hexsha
stringlengths
40
40
size
int64
3
1.03M
content
stringlengths
3
1.03M
avg_line_length
float64
1.33
100
max_line_length
int64
2
1k
alphanum_fraction
float64
0.25
0.99
46a1d6698867362a8fd1252d36345993b0f4cd41
12,971
// // MockSixInternal.swift // MockSix // // The MIT License (MIT) // // Copyright (c) 2017 Tamas Lustyik // Portions copyright (c) 2015-2016 Daniel Burbank // // 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 Dispatch // MARK: - common stuff extension Mock where Self : AnyObject { public var mockSixLock: String { let ptr = Unmanaged.passUnretained(self).toOpaque() let address = Int(bitPattern: ptr) return "\(address)" } } extension Mock where MockMethod.RawValue == Int { private(set) public var invocations: [MockInvocation] { get { return mockQueue.sync { mockRecords[mockSixLock] ?? [] } } set { mockQueue.sync { mockRecords[mockSixLock] = newValue } } } public func resetMock() { mockQueue.sync { mockRecords[mockSixLock] = [] mockBlocks[mockSixLock] = [:] } } } // MARK: - stubbing methods extension Mock where MockMethod.RawValue == Int { fileprivate func identifier(for method: MockMethod) -> String { return "method-\(method.rawValue)" } private func registerStub<T>(for method: MockMethod, withBlock block: @escaping ([Any?]) throws -> T) { let id = identifier(for: method) mockQueue.sync { var blocks = mockBlocks[mockSixLock] ?? [:] as [String: Any] blocks[id] = block mockBlocks[mockSixLock] = blocks } } private func registerStub<T>(for method: MockMethod, withBlock block: @escaping ([Any?]) throws -> T?) { let id = identifier(for: method) mockQueue.sync { var blocks = mockBlocks[mockSixLock] ?? [:] as [String: Any] blocks[id] = block mockBlocks[mockSixLock] = blocks } } public func unstub(_ method: MockMethod) { let id = identifier(for: method) mockQueue.sync { var blocks = mockBlocks[mockSixLock] ?? [:] as [String: Any] blocks.removeValue(forKey: id) mockBlocks[mockSixLock] = blocks } } public func stub<T>(_ method: MockMethod, withBlock block: @escaping ([Any?]) throws -> T) { registerStub(for: method, withBlock: block) } public func stub<T>(_ method: MockMethod, withBlock block: @escaping ([Any?]) throws -> T?) { registerStub(for: method, withBlock: block) } public func stub<T>(_ method: MockMethod, andReturn value: T) { registerStub(for: method, withBlock: { _ in value }) } public func stub<T>(_ method: MockMethod, andReturn value: T?) { registerStub(for: method, withBlock: { _ in value }) } public func stub<T>(_ method: MockMethod, andReturn firstValue: T, times: Int, afterwardsReturn secondValue: T) { var count = 0 registerStub(for: method, withBlock: { _ -> T in defer { count += 1 } return count < times ? firstValue : secondValue }) } public func stub<T>(_ method: MockMethod, andReturn firstValue: T?, times: Int, afterwardsReturn secondValue: T?) { var count = 0 registerStub(for: method, withBlock: { _ -> T? in defer { count += 1 } return count < times ? firstValue : secondValue }) } } // MARK: - invocation proxies extension Mock where MockMethod.RawValue == Int { private func registerInvocation<T>(for method: MockMethod, function: String = #function, args: [Any?], returns: ([Any?]) throws -> T? = { _ in nil }) throws -> T? { logInvocation(method: method, functionName: function, arguments: args) let id = identifier(for: method) let registeredStub = mockQueue.sync { mockBlocks[mockSixLock]?[id] } if let registeredStub = registeredStub { guard let typedStub = registeredStub as? ([Any?]) throws -> T? else { fatalError("MockSix: Incompatible block of type '\(type(of: registeredStub))' registered for function '\(function)' requiring block type '([Any?]) -> \(T.self)'") } return try typedStub(args) } else { return try returns(args) } } private func registerInvocation<T>(for method: MockMethod, function: String = #function, args: [Any?], returns: ([Any?]) throws -> T) throws -> T { logInvocation(method: method, functionName: function, arguments: args) let id = identifier(for: method) let registeredStub = mockQueue.sync { mockBlocks[mockSixLock]?[id] } if let registeredStub = registeredStub { guard let typedStub = registeredStub as? ([Any?]) throws -> T else { fatalError("MockSix: Incompatible block of type '\(type(of: registeredStub))' registered for function '\(function)' requiring block type '([Any?]) -> \(T.self)'") } return try typedStub(args) } else { return try returns(args) } } public func registerThrowingInvocation<T>(for method: MockMethod, function: String = #function, args: Any?..., returns: ([Any?]) throws -> T? = { _ in nil }) throws -> T? { return try registerInvocation(for: method, function: function, args: args, returns: returns) } public func registerThrowingInvocation<T>(for method: MockMethod, function: String = #function, args: Any?..., returns: ([Any?]) throws -> T) throws -> T { return try registerInvocation(for: method, function: function, args: args, returns: returns) } public func registerThrowingInvocation<T>(for method: MockMethod, function: String = #function, args: Any?..., andReturn value: T?) throws -> T? { return try registerInvocation(for: method, function: function, args: args, returns: { _ -> T? in value }) } public func registerThrowingInvocation<T>(for method: MockMethod, function: String = #function, args: Any?..., andReturn value: T) throws -> T { return try registerInvocation(for: method, function: function, args: args, returns: { _ -> T in value }) } public func registerThrowingInvocation(for method: MockMethod, function: String = #function, args: Any?..., returns: ([Any?]) throws -> Void = { _ in }) throws { logInvocation(method: method, functionName: function, arguments: args) let id = identifier(for: method) let registeredStub = mockQueue.sync { mockBlocks[mockSixLock]?[id] } if let registeredStub = registeredStub { guard let typedStub = registeredStub as? ([Any?]) throws -> Void else { fatalError("MockSix: Incompatible block of type '\(type(of: registeredStub))' registered for function '\(function)' requiring block type '([Any?]) -> ()'") } try typedStub(args) } else { try returns(args) } } public func registerInvocation<T>(for method: MockMethod, function: String = #function, args: Any?..., returns: ([Any?]) throws -> T? = { _ in nil }) -> T? { return try! registerInvocation(for: method, function: function, args: args, returns: returns) } public func registerInvocation<T>(for method: MockMethod, function: String = #function, args: Any?..., returns: ([Any?]) throws -> T) -> T { return try! registerInvocation(for: method, function: function, args: args, returns: returns) } public func registerInvocation<T>(for method: MockMethod, function: String = #function, args: Any?..., andReturn value: T?) -> T? { return try! registerInvocation(for: method, function: function, args: args, returns: { _ -> T? in value }) } public func registerInvocation<T>(for method: MockMethod, function: String = #function, args: Any?..., andReturn value: T) -> T { return try! registerInvocation(for: method, function: function, args: args, returns: { _ -> T in value }) } public func registerInvocation(for method: MockMethod, function: String = #function, args: Any?..., returns: ([Any?]) throws -> Void = { _ in }) { logInvocation(method: method, functionName: function, arguments: args) let id = identifier(for: method) let registeredStub = mockQueue.sync { mockBlocks[mockSixLock]?[id] } if let registeredStub = registeredStub { guard let typedStub = registeredStub as? ([Any?]) throws -> Void else { fatalError("MockSix: Incompatible block of type '\(type(of: registeredStub))' registered for function '\(function)' requiring block type '([Any?]) -> ()'") } try! typedStub(args) } else { try! returns(args) } } // Utility stuff private func logInvocation(method: MockMethod, functionName: String, arguments: [Any?]) { var invocations = [MockInvocation]() invocations.append(MockInvocation(methodID: method.rawValue, functionName: functionName, args: arguments)) mockQueue.sync { if let existingInvocations = mockRecords[mockSixLock] { invocations = existingInvocations + invocations } mockRecords[mockSixLock] = invocations } } } public func resetMockSix() { mockQueue.sync { globalObjectIDIndex = 0 mockRecords = [:] mockBlocks = [:] } } public func lock(prefix: String = #file + ":\(#line):") -> String { let suffix = mockQueue.sync { () -> String in globalObjectIDIndex += 1 return "\(globalObjectIDIndex)" } return prefix + suffix } private var mockQueue: DispatchQueue = DispatchQueue(label: "MockSix") private var globalObjectIDIndex: Int32 = 0 private var mockRecords: [String: [MockInvocation]] = [:] private var mockBlocks: [String: [String: Any]] = [:] // Testing func fatalError(message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Never { FatalErrorUtil.fatalErrorClosure(message(), file, line) } struct FatalErrorUtil { static var fatalErrorClosure: (String, StaticString, UInt) -> Never = defaultFatalErrorClosure private static let defaultFatalErrorClosure = { Swift.fatalError($0, file: $1, line: $2) } static func replaceFatalError(closure: @escaping (String, StaticString, UInt) -> Never) { fatalErrorClosure = closure } static func restoreFatalError() { fatalErrorClosure = defaultFatalErrorClosure } }
41.177778
178
0.562563
4634d1af9b26dc07e69fb96eb59827cc13a0d153
1,021
// // DataHeaderFooter.swift // SwiftDataTables // // Created by Pavan Kataria on 22/02/2017. // Copyright © 2017 Pavan Kataria. All rights reserved. // import UIKit class DataHeaderFooter: UICollectionReusableView { //MARK: - Properties @IBOutlet var titleLabel: UILabel! @IBOutlet var sortingImageView: UIImageView! //MARK: - Events var didTapEvent: (() -> Void)? = nil //MARK: - Lifecycle override func awakeFromNib() { super.awakeFromNib() let tapGesture = UITapGestureRecognizer.init(target: self, action: #selector(DataHeaderFooter.didTapView)) self.addGestureRecognizer(tapGesture) } func setup(viewModel: DataHeaderFooterViewModel) { self.titleLabel.text = viewModel.data self.sortingImageView.image = viewModel.imageForSortingElement self.sortingImageView.tintColor = viewModel.tintColorForSortingElement self.backgroundColor = .white } @objc func didTapView(){ self.didTapEvent?() } }
27.594595
114
0.68952
29449373a9582d4d905213bd0d2209a15cccb4e3
5,512
// // ChaCha20.swift // CryptoSwift // // Created by Marcin Krzyzanowski on 25/08/14. // Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved. // final public class ChaCha20 { public enum Error: ErrorType { case MissingContext } static let blockSize = 64 // 512 / 8 private let stateSize = 16 private var context:Context? final private class Context { var input:[UInt32] = [UInt32](count: 16, repeatedValue: 0) deinit { for i in 0..<input.count { input[i] = 0x00; } } } public init?(key:[UInt8], iv:[UInt8]) { if let c = contextSetup(iv: iv, key: key) { context = c } else { return nil } } public func encrypt(bytes:[UInt8]) throws -> [UInt8] { guard context != nil else { throw Error.MissingContext } return try encryptBytes(bytes) } public func decrypt(bytes:[UInt8]) throws -> [UInt8] { return try encrypt(bytes) } private final func wordToByte(input:[UInt32] /* 64 */) -> [UInt8]? /* 16 */ { if (input.count != stateSize) { return nil; } var x = input for _ in 0..<10 { quarterround(&x[0], &x[4], &x[8], &x[12]) quarterround(&x[1], &x[5], &x[9], &x[13]) quarterround(&x[2], &x[6], &x[10], &x[14]) quarterround(&x[3], &x[7], &x[11], &x[15]) quarterround(&x[0], &x[5], &x[10], &x[15]) quarterround(&x[1], &x[6], &x[11], &x[12]) quarterround(&x[2], &x[7], &x[8], &x[13]) quarterround(&x[3], &x[4], &x[9], &x[14]) } var output = [UInt8]() output.reserveCapacity(16) for i in 0..<16 { x[i] = x[i] &+ input[i] output.appendContentsOf(x[i].bytes().reverse()) } return output; } private func contextSetup(iv iv:[UInt8], key:[UInt8]) -> Context? { let ctx = Context() let kbits = key.count * 8 if (kbits != 128 && kbits != 256) { return nil } // 4 - 8 for i in 0..<4 { let start = i * 4 ctx.input[i + 4] = wordNumber(key[start..<(start + 4)]) } var addPos = 0; switch (kbits) { case 256: addPos += 16 // sigma ctx.input[0] = 0x61707865 //apxe ctx.input[1] = 0x3320646e //3 dn ctx.input[2] = 0x79622d32 //yb-2 ctx.input[3] = 0x6b206574 //k et default: // tau ctx.input[0] = 0x61707865 //apxe ctx.input[1] = 0x3620646e //6 dn ctx.input[2] = 0x79622d31 //yb-1 ctx.input[3] = 0x6b206574 //k et break; } // 8 - 11 for i in 0..<4 { let start = addPos + (i*4) let bytes = key[start..<(start + 4)] ctx.input[i + 8] = wordNumber(bytes) } // iv ctx.input[12] = 0 ctx.input[13] = 0 ctx.input[14] = wordNumber(iv[0..<4]) ctx.input[15] = wordNumber(iv[4..<8]) return ctx } private final func encryptBytes(message:[UInt8]) throws -> [UInt8] { guard let ctx = context else { throw Error.MissingContext } var c:[UInt8] = [UInt8](count: message.count, repeatedValue: 0) var cPos:Int = 0 var mPos:Int = 0 var bytes = message.count while (true) { if let output = wordToByte(ctx.input) { ctx.input[12] = ctx.input[12] &+ 1 if (ctx.input[12] == 0) { ctx.input[13] = ctx.input[13] &+ 1 /* stopping at 2^70 bytes per nonce is user's responsibility */ } if (bytes <= ChaCha20.blockSize) { for i in 0..<bytes { c[i + cPos] = message[i + mPos] ^ output[i] } return c } for i in 0..<ChaCha20.blockSize { c[i + cPos] = message[i + mPos] ^ output[i] } bytes -= ChaCha20.blockSize cPos += ChaCha20.blockSize mPos += ChaCha20.blockSize } } } private final func quarterround(inout a:UInt32, inout _ b:UInt32, inout _ c:UInt32, inout _ d:UInt32) { a = a &+ b d = rotateLeft((d ^ a), 16) //FIXME: WAT? n: c = c &+ d b = rotateLeft((b ^ c), 12); a = a &+ b d = rotateLeft((d ^ a), 8); c = c &+ d b = rotateLeft((b ^ c), 7); } } // MARK: - Cipher extension ChaCha20: Cipher { public func cipherEncrypt(bytes:[UInt8]) throws -> [UInt8] { return try self.encrypt(bytes) } public func cipherDecrypt(bytes: [UInt8]) throws -> [UInt8] { return try self.decrypt(bytes) } } // MARK: Helpers /// Change array to number. It's here because arrayOfBytes is too slow private func wordNumber(bytes:ArraySlice<UInt8>) -> UInt32 { var value:UInt32 = 0 for i:UInt32 in 0..<4 { let j = bytes.startIndex + Int(i) value = value | UInt32(bytes[j]) << (8 * i) } return value}
27.422886
107
0.45918
8fe98b94384aa572065ac828c3ded8d283ac46bf
2,322
// // CV // // Copyright 2022 - Grzegorz Wikiera - https://github.com/gwikiera // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import XCTest import Nimble import Logging import Logger @testable import LoggerLive class LoggerLiveTests: XCTestCase { func testTrace() { test( method: LoggerType.trace, logLevel: .trace ) } func testDebug() { test( method: LoggerType.debug, logLevel: .debug ) } func testInfo() { test( method: LoggerType.info, logLevel: .info ) } func testNotice() { test( method: LoggerType.notice, logLevel: .notice ) } func testWarning() { test( method: LoggerType.warning, logLevel: .warning ) } func testError() { test( method: LoggerType.error, logLevel: .error ) } func testCritical() { test( method: LoggerType.critical, logLevel: .critical ) } // MARK: - private func test( method: (LoggerType) -> (@autoclosure () -> String, String, String, UInt) -> Void, logLevel: Logger.Level, function: String = #function, file: FileString = #file, line: UInt = #line ) { let mock = LogHandlerMock() mock.logLevel = logLevel let logger = Logger(label: function) { _ in mock } let sut = LoggerType(logger: logger) let message = logLevel.rawValue // When method(sut)(message, function, file.description, line) // Then expect(file: file, line: line, mock.logs.last) == (logLevel, message, function, file.description, line) } }
24.442105
111
0.578381
e476584ec75fe06f2ed680eb3a47f214d7cbf636
8,304
//****************************************************************************** // Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation //============================================================================== // DeviceQueue functions with default cpu delegation extension CpuQueue { //-------------------------------------------------------------------------- @inlinable func fill<S, E>( _ out: inout Tensor<S, E>, with element: E.Value ) { cpu_fill(&out, with: element) } //-------------------------------------------------------------------------- @inlinable func fill<S, E>( _ out: inout Tensor<S, E>, from first: E.Value, to last: E.Value, by step: E.Value ) where E.Value: Numeric { cpu_fill(&out, from: first, to: last, by: step) } //-------------------------------------------------------------------------- @inlinable func eye<S, E: StorageElement>( _ out: inout Tensor<S, E>, offset: Int ) where E.Value: Numeric { cpu_eye(&out, offset: offset) } //-------------------------------------------------------------------------- @inlinable func fill<S, E>( randomUniform out: inout Tensor<S, E>, _ lower: E.Value, _ upper: E.Value, _ seed: RandomSeed ) where E.Value: BinaryFloatingPoint { cpu_fill(randomUniform: &out, lower, upper, seed) } //-------------------------------------------------------------------------- @inlinable func fill<S, E>( randomNormal out: inout Tensor<S, E>, _ mean: E.Value, _ standardDeviation: E.Value, _ seed: RandomSeed ) where E.Value: BinaryFloatingPoint { cpu_fill(randomNormal: &out, mean, standardDeviation, seed) } //-------------------------------------------------------------------------- // case where the mean and stddev are not static scalars, // but tensor results from previous ops @inlinable func fill<S, E>( randomNormal out: inout Tensor<S, E>, _ mean: Tensor<S, E>, _ standardDeviation: Tensor<S, E>, _ seed: RandomSeed ) where E.Value: BinaryFloatingPoint { cpu_fill(randomNormal: &out, mean, standardDeviation, seed) } //-------------------------------------------------------------------------- @inlinable func fill<S, E>( randomTruncatedNormal out: inout Tensor<S, E>, _ mean: E.Value, _ standardDeviation: E.Value, _ seed: RandomSeed ) where E.Value: BinaryFloatingPoint { cpu_fill(randomTruncatedNormal: &out, mean, standardDeviation, seed) } //-------------------------------------------------------------------------- @inlinable func fill<S, E>( randomTruncatedNormal out: inout Tensor<S, E>, _ mean: Tensor<S, E>, _ standardDeviation: Tensor<S, E>, _ seed: RandomSeed ) where E.Value: BinaryFloatingPoint { cpu_fill(randomTruncatedNormal: &out, mean, standardDeviation, seed) } } //============================================================================== // Cpu device queue function implementations extension CpuFunctions where Self: DeviceQueue { //-------------------------------------------------------------------------- @inlinable func cpu_eye<S, E>( _ out: inout Tensor<S, E>, offset: Int ) where E.Value: Numeric { diagnostic( .queueCpu, "eye(\(out.name)) on \(name)", categories: .queueCpu) mapOp(&out) { 0 } } //-------------------------------------------------------------------------- @inlinable func cpu_fill<S, E>( _ out: inout Tensor<S, E>, with element: E.Value ) { diagnostic( .queueCpu, "fill(\(out.name), with: \(element)) on \(name)", categories: .queueCpu) mapOp(&out) { element } } //-------------------------------------------------------------------------- @inlinable func cpu_fill<S, E>( _ out: inout Tensor<S, E>, from first: E.Value, to last: E.Value, by step: E.Value ) where E.Value: Numeric { diagnostic( .queueCpu, "fill(\(out.name), from: \(first), to: \(last)," + " by: \(step)) on \(name)", categories: .queueCpu) mapOp(from: first, to: last, by: step, &out) } //-------------------------------------------------------------------------- @inlinable func cpu_fill<S, E>( randomUniform out: inout Tensor<S, E>, _ lower: E.Value, _ upper: E.Value, _ seed: RandomSeed ) where E.Value: BinaryFloatingPoint { diagnostic( .queueCpu, "fill(randomUniform: \(out.name), lower: " + "\(lower), upper: \(upper), seed: \(seed)) on \(name)", categories: .queueCpu) let scale = Double(upper - lower) / Double(UInt64.max) var generator = Platform.createRandomNumberGenerator(using: seed) mapOp(&out) { E.Value(Double(generator.next()) * scale) + lower } } //-------------------------------------------------------------------------- @inlinable func cpu_fill<S, E>( randomNormal out: inout Tensor<S, E>, _ mean: E.Value, _ std: E.Value, _ seed: RandomSeed ) where E.Value: BinaryFloatingPoint { diagnostic( .queueCpu, "fill(randomNormal: \(out.name), mean: " + "\(mean), std: \(std), seed: \(seed)) on \(name)", categories: .queueCpu) let scale = Double(std) / Double(UInt64.max) var generator = Platform.createRandomNumberGenerator(using: seed) mapOp(&out) { E.Value(Double(generator.next()) * scale) + mean } } //-------------------------------------------------------------------------- // case where the mean and stddev are not static scalars, // but tensor results from previous ops @inlinable func cpu_fill<S, E>( randomNormal out: inout Tensor<S, E>, _ mean: Tensor<S, E>, _ std: Tensor<S, E>, _ seed: RandomSeed ) where E.Value: BinaryFloatingPoint { assert(std.count == 1 && mean.count == 1) diagnostic( .queueCpu, "fill(randomNormal: \(out.name), mean: " + "\(mean.name), std: \(std.name), seed: \(seed)) on \(name)", categories: .queueCpu) let scale = Double(std.element) / Double(UInt64.max) var generator = Platform.createRandomNumberGenerator(using: seed) mapOp(&out) { E.Value(Double(generator.next()) * scale) + mean.element } } //-------------------------------------------------------------------------- @inlinable func cpu_fill<S, E>( randomTruncatedNormal out: inout Tensor<S, E>, _ mean: E.Value, _ std: E.Value, _ seed: RandomSeed ) where E.Value: BinaryFloatingPoint { diagnostic( .queueCpu, "fill(randomTruncatedNormal: \(out.name), mean: " + "\(mean), std: \(std), seed: \(seed)) on \(name)", categories: .queueCpu) let std2x = std * 2 let scale = Double(std) / Double(UInt64.max) var generator = Platform.createRandomNumberGenerator(using: seed) mapOp(&out) { let a = Double(generator.next()) * scale return E.Value(a).clamped(to: -std2x...std2x) + mean } } //-------------------------------------------------------------------------- @inlinable func cpu_fill<S, E>( randomTruncatedNormal out: inout Tensor<S, E>, _ mean: Tensor<S, E>, _ std: Tensor<S, E>, _ seed: RandomSeed ) where E.Value: BinaryFloatingPoint { assert(std.count == 1 && mean.count == 1) diagnostic( .queueCpu, "fill(randomTruncatedNormal: \(out.name), " + "mean: \(mean.name), std: \(std.name), seed: \(seed)) on \(name)", categories: .queueCpu) let std2x = std.element * 2 let scale = Double(std.element) / Double(UInt64.max) var generator = Platform.createRandomNumberGenerator(using: seed) mapOp(&out) { let a = Double(generator.next()) * scale return E.Value(a).clamped(to: -std2x...std2x) + mean.element } } }
34.6
99
0.520472
6430771f9778499e181228951f3483edcb9714e1
2,592
// // JSObject.swift // // The MIT License // Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // extension JSObject { /// Calls an object as a function. /// /// - Parameters: /// - arguments: The arguments pass to the function. /// - this: The object to use as `this`, or `nil` to use the global object as `this`. /// /// - Returns: The object that results from calling object as a function @discardableResult public func call(withArguments arguments: [Json], this: JSObject? = nil) -> JSObject { return self.call(withArguments: arguments.map { JSObject(json: $0, in: context) }, this: this) } /// Calls an object as a constructor. /// /// - Parameters: /// - arguments: The arguments pass to the function. /// /// - Returns: The object that results from calling object as a constructor. public func construct(withArguments arguments: [Json]) -> JSObject { return self.construct(withArguments: arguments.map { JSObject(json: $0, in: context) }) } /// Invoke an object's method. /// /// - Parameters: /// - name: The name of method. /// - arguments: The arguments pass to the function. /// /// - Returns: The object that results from calling the method. @discardableResult public func invokeMethod(_ name: String, withArguments arguments: [Json]) -> JSObject { return self[name].call(withArguments: arguments, this: self) } }
41.806452
102
0.680556
56b63fb276ad9c463afc21f678e90f63ba518aad
324
// swift-tools-version:5.1 import PackageDescription let package = Package( name: "CodableFirebase", products: [ .library(name: "CodableFirebase", targets: ["CodableFirebase"]) ], targets: [ .target( name: "CodableFirebase", path: "CodableFirebase" ) ] )
20.25
71
0.574074
38e5000645c42f8f661189b16bb6100ddd5126e9
16,470
// // AlertEngine.swift // SwiftTool // // Created by liujun on 2021/5/24. // Copyright © 2021 yinhe. All rights reserved. // import Foundation import UIKit import SnapKit fileprivate struct Keys { static var associatedKey = "com.galaxy.alertengine.key" } @available(iOSApplicationExtension, unavailable, message: "This method is NS_EXTENSION_UNAVAILABLE.") public class AlertEngine { public class Options { public var fromPosition: AlertEngine.FromPosition = .rightCenter(left: .zero) public var toPosition: AlertEngine.ToPostion = .center public var dismissPosition: AlertEngine.FromPosition = .none // public var enableMask: Bool = true public var shouldResignOnTouchOutside: Bool = true // public var duration: TimeInterval = 0.25 public var translucentColor: UIColor = UIColor(red: 0, green: 0, blue: 0, alpha: 1).withAlphaComponent(0.6) public var animationOptions: UIView.AnimationOptions = [.curveEaseInOut] // public init() {} } public enum FromPosition: Equatable { case topLeft(bottom: CGFloat, left: CGFloat) case topCenter(bottom: CGFloat) case topRight(bottom: CGFloat, right: CGFloat) // case leftTop(right: CGFloat, top: CGFloat) case leftCenter(right: CGFloat) case leftBottom(right: CGFloat, bottom: CGFloat) // case bottomLeft(top: CGFloat, left: CGFloat) case bottomCenter(top: CGFloat) case bottomRight(top: CGFloat, right: CGFloat) // case rightTop(left: CGFloat, top: CGFloat) case rightCenter(left: CGFloat) case rightBottom(left: CGFloat, bottom: CGFloat) // case center // case none } public enum ToPostion { case topLeft(top: CGFloat, left: CGFloat) case topCenter(top: CGFloat) case topRight(top: CGFloat, right: CGFloat) case leftCenter(left: CGFloat) case bottomLeft(bottom: CGFloat, left: CGFloat) case bottomCenter(bottom: CGFloat) case bottomRight(bottom: CGFloat, right: CGFloat) case rightCenter(right: CGFloat) case center } private let defaultUsingSpringWithDamping: CGFloat = 0.75 private let defaultInitialSpringVelocity: CGFloat = 7.0 public static let `default` = AlertEngine() private var backgroundView: UIView? private var maskView: UIView? private var currentAlertView: UIView? private init() { } } @available(iOSApplicationExtension, unavailable, message: "This method is NS_EXTENSION_UNAVAILABLE.") extension AlertEngine { public func show(parentView: UIView?, alertView: UIView?, options: AlertEngine.Options) { // guard let alertView = alertView else { return } // var tempParentView: UIView? if parentView != nil { tempParentView = parentView } else if let keyWindow = UIApplication.shared.keyWindow { tempParentView = keyWindow } if tempParentView == nil { return } // self.release() // if options.enableMask { let backgroundView = UIView() backgroundView.isUserInteractionEnabled = true let maskView = UIView() maskView.backgroundColor = options.translucentColor.withAlphaComponent(0) if options.shouldResignOnTouchOutside { let tap = UITapGestureRecognizer(target: self, action: #selector(tapDismissAction)) maskView.addGestureRecognizer(tap) } tempParentView!.addSubview(backgroundView) backgroundView.addSubview(maskView) tempParentView!.addSubview(alertView) backgroundView.snp.makeConstraints { make in make.edges.equalToSuperview() } maskView.snp.makeConstraints { make in make.edges.equalToSuperview() } self.backgroundView = backgroundView self.maskView = maskView self.currentAlertView = alertView } else { tempParentView!.addSubview(alertView) self.currentAlertView = alertView } // NotificationCenter.default.addObserver(self, selector: #selector(refreshWhenOrientationDidChange), name: UIApplication.didChangeStatusBarOrientationNotification, object: nil) // objc_setAssociatedObject(alertView, &Keys.associatedKey, options, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) // if options.fromPosition == .none { self.maskView?.backgroundColor = options.translucentColor setToPositionConstraints(view: alertView, toPosition: options.toPosition) return } // setFromPositionConstraints(view: alertView, fromPosition: options.fromPosition) alertView.superview?.layoutIfNeeded() alertView.layoutIfNeeded() // self.maskView?.isUserInteractionEnabled = false // setToPositionConstraints(view: alertView, toPosition: options.toPosition) // UIView.animate(withDuration: options.duration, delay: 0, usingSpringWithDamping: defaultUsingSpringWithDamping, initialSpringVelocity: defaultInitialSpringVelocity, options: options.animationOptions) { self.maskView?.backgroundColor = options.translucentColor alertView.superview?.layoutIfNeeded() } completion: { (_) in self.maskView?.isUserInteractionEnabled = true } } public func refresh() { refreshWhenOrientationDidChange() } public func dismiss() { if let currentAlertView = self.currentAlertView, let options = objc_getAssociatedObject(currentAlertView, &Keys.associatedKey) as? AlertEngine.Options, options.dismissPosition != .none { self.maskView?.isUserInteractionEnabled = false setDismissPositionConstraints(view: currentAlertView, dismissPosition: options.dismissPosition) UIView.animate(withDuration: options.duration, delay: 0, options: options.animationOptions) { self.maskView?.backgroundColor = options.translucentColor.withAlphaComponent(0) currentAlertView.superview?.layoutIfNeeded() } completion: { (_) in self.maskView?.isUserInteractionEnabled = true self.release() } } else { self.release() } } } @available(iOSApplicationExtension, unavailable, message: "This method is NS_EXTENSION_UNAVAILABLE.") extension AlertEngine { @objc private func tapDismissAction() { dismiss() } @objc private func refreshWhenOrientationDidChange() { backgroundView?.snp.remakeConstraints { make in make.edges.equalToSuperview() } maskView?.snp.remakeConstraints { make in make.edges.equalToSuperview() } if let currentAlertView = currentAlertView, let options = objc_getAssociatedObject(currentAlertView, &Keys.associatedKey) as? AlertEngine.Options { setToPositionConstraints(view: currentAlertView, toPosition: options.toPosition) } } } @available(iOSApplicationExtension, unavailable, message: "This method is NS_EXTENSION_UNAVAILABLE.") extension AlertEngine { private func release() { if let currentAlertView = self.currentAlertView { objc_setAssociatedObject(currentAlertView, &Keys.associatedKey, nil, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } NotificationCenter.default.removeObserver(self, name: UIApplication.didChangeStatusBarOrientationNotification, object: nil) self.currentAlertView?.removeFromSuperview() self.maskView?.isUserInteractionEnabled = false self.maskView?.removeFromSuperview() self.backgroundView?.removeFromSuperview() self.currentAlertView = nil self.maskView = nil self.backgroundView = nil } } @available(iOSApplicationExtension, unavailable, message: "This method is NS_EXTENSION_UNAVAILABLE.") private func setFromPositionConstraints(view: UIView?, fromPosition: AlertEngine.FromPosition) { guard let view = view else { return } guard let superview = view.superview else { return } switch fromPosition { case .topLeft(let bottom, let left): view.snp.makeConstraints({ (make) in make.left.equalToSuperview().offset(left) make.bottom.equalTo(superview.snp.top).offset(-bottom) }) case .topCenter(let bottom): view.snp.makeConstraints({ (make) in make.centerX.equalToSuperview() make.bottom.equalTo(superview.snp.top).offset(-bottom) }) case .topRight(let bottom, let right): view.snp.makeConstraints({ (make) in make.right.equalToSuperview().offset(-right) make.bottom.equalTo(superview.snp.top).offset(-bottom) }) case .leftTop(let right, let top): view.snp.makeConstraints({ (make) in make.top.equalToSuperview().offset(top) make.right.equalTo(superview.snp.left).offset(-right) }) case .leftCenter(let right): view.snp.makeConstraints({ (make) in make.centerY.equalToSuperview() make.right.equalTo(superview.snp.left).offset(-right) }) case .leftBottom(let right, let bottom): view.snp.makeConstraints({ (make) in make.bottom.equalToSuperview().offset(-bottom) make.right.equalTo(superview.snp.left).offset(-right) }) case .bottomLeft(let top, let left): view.snp.makeConstraints({ (make) in make.top.equalTo(superview.snp.bottom).offset(top) make.left.equalToSuperview().offset(left) }) case .bottomCenter(let top): view.snp.makeConstraints({ (make) in make.top.equalTo(superview.snp.bottom).offset(top) make.centerX.equalToSuperview() }) case .bottomRight(let top, let right): view.snp.makeConstraints({ (make) in make.top.equalTo(superview.snp.bottom).offset(top) make.right.equalToSuperview().offset(-right) }) case .rightTop(let left, let top): view.snp.makeConstraints({ (make) in make.top.equalTo(superview.snp.bottom).offset(top) make.left.equalTo(superview.snp.right).offset(left) }) case .rightCenter(let left): view.snp.makeConstraints({ (make) in make.centerY.equalToSuperview() make.left.equalTo(superview.snp.right).offset(left) }) case .rightBottom(let left, let bottom): view.snp.makeConstraints({ (make) in make.bottom.equalToSuperview().offset(-bottom) make.left.equalTo(superview.snp.right).offset(left) }) case .center: view.snp.makeConstraints({ (make) in make.centerX.equalToSuperview() make.centerY.equalToSuperview() }) case .none: fatalError() } } @available(iOSApplicationExtension, unavailable, message: "This method is NS_EXTENSION_UNAVAILABLE.") private func setToPositionConstraints(view: UIView?, toPosition: AlertEngine.ToPostion) { guard let view = view else { return } guard let _ = view.superview else { return } switch toPosition { case .topLeft(let top, let left): view.snp.remakeConstraints { (make) in make.top.equalToSuperview().offset(top) make.left.equalToSuperview().offset(left) } case .topCenter(let top): view.snp.remakeConstraints { (make) in make.top.equalToSuperview().offset(top) make.centerX.equalToSuperview() } case .topRight(let top, let right): view.snp.remakeConstraints { (make) in make.top.equalToSuperview().offset(top) make.right.equalToSuperview().offset(-right) } case .leftCenter(let left): view.snp.remakeConstraints { (make) in make.centerY.equalToSuperview() make.left.equalToSuperview().offset(left) } case .bottomLeft(let bottom, let left): view.snp.remakeConstraints { (make) in make.bottom.equalToSuperview().offset(-bottom) make.left.equalToSuperview().offset(left) } case .bottomCenter(let bottom): view.snp.remakeConstraints { (make) in make.centerX.equalToSuperview() make.bottom.equalToSuperview().offset(-bottom) } case .bottomRight(let bottom, let right): view.snp.remakeConstraints { (make) in make.right.equalToSuperview().offset(-right) make.bottom.equalToSuperview().offset(-bottom) } case .rightCenter(let right): view.snp.remakeConstraints { (make) in make.centerY.equalToSuperview() make.right.equalToSuperview().offset(-right) } case .center: view.snp.remakeConstraints { (make) in make.centerX.equalToSuperview() make.centerY.equalToSuperview() } } } @available(iOSApplicationExtension, unavailable, message: "This method is NS_EXTENSION_UNAVAILABLE.") private func setDismissPositionConstraints(view: UIView?, dismissPosition: AlertEngine.FromPosition) { guard let view = view else { return } guard let superview = view.superview else { return } switch dismissPosition { case .topLeft(let bottom, let left): view.snp.remakeConstraints({ (make) in make.left.equalToSuperview().offset(left) make.bottom.equalTo(superview.snp.top).offset(-bottom) }) case .topCenter(let bottom): view.snp.remakeConstraints({ (make) in make.centerX.equalToSuperview() make.bottom.equalTo(superview.snp.top).offset(-bottom) }) case .topRight(let bottom, let right): view.snp.remakeConstraints({ (make) in make.right.equalToSuperview().offset(-right) make.bottom.equalTo(superview.snp.top).offset(-bottom) }) case .leftTop(let right, let top): view.snp.remakeConstraints({ (make) in make.top.equalToSuperview().offset(top) make.right.equalTo(superview.snp.left).offset(-right) }) case .leftCenter(let right): view.snp.remakeConstraints({ (make) in make.centerY.equalToSuperview() make.right.equalTo(superview.snp.left).offset(-right) }) case .leftBottom(let right, let bottom): view.snp.remakeConstraints({ (make) in make.bottom.equalToSuperview().offset(-bottom) make.right.equalTo(superview.snp.left).offset(-right) }) case .bottomLeft(let top, let left): view.snp.remakeConstraints({ (make) in make.top.equalTo(superview.snp.bottom).offset(top) make.left.equalToSuperview().offset(left) }) case .bottomCenter(let top): view.snp.remakeConstraints({ (make) in make.top.equalTo(superview.snp.bottom).offset(top) make.centerX.equalToSuperview() }) case .bottomRight(let top, let right): view.snp.remakeConstraints({ (make) in make.top.equalTo(superview.snp.bottom).offset(top) make.right.equalToSuperview().offset(-right) }) case .rightTop(let left, let top): view.snp.remakeConstraints({ (make) in make.top.equalTo(superview.snp.bottom).offset(top) make.left.equalTo(superview.snp.right).offset(left) }) case .rightCenter(let left): view.snp.remakeConstraints({ (make) in make.centerY.equalToSuperview() make.left.equalTo(superview.snp.right).offset(left) }) case .rightBottom(let left, let bottom): view.snp.remakeConstraints({ (make) in make.bottom.equalToSuperview().offset(-bottom) make.left.equalTo(superview.snp.right).offset(left) }) case .center: view.snp.remakeConstraints({ (make) in make.centerX.equalToSuperview() make.centerY.equalToSuperview() }) case .none: fatalError() } }
39.401914
209
0.63813
4ad53bdf04f62cbd786990f0a14ac2fc9744458e
43,582
//===--- RangeReplaceableCollection.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 // //===----------------------------------------------------------------------===// // // A Collection protocol with replaceSubrange. // //===----------------------------------------------------------------------===// /// A type that supports replacement of an arbitrary subrange of elements with /// the elements of another collection. /// /// In most cases, it's best to ignore this protocol and use the /// `RangeReplaceableCollection` protocol instead, because it has a more /// complete interface. @available(*, deprecated, message: "it will be removed in Swift 4.0. Please use 'RandomAccessCollection' instead") public typealias RangeReplaceableIndexable = RangeReplaceableCollection /// A collection that supports replacement of an arbitrary subrange of elements /// with the elements of another collection. /// /// Range-replaceable collections provide operations that insert and remove /// elements. For example, you can add elements to an array of strings by /// calling any of the inserting or appending operations that the /// `RangeReplaceableCollection` protocol defines. /// /// var bugs = ["Aphid", "Damselfly"] /// bugs.append("Earwig") /// bugs.insert(contentsOf: ["Bumblebee", "Cicada"], at: 1) /// print(bugs) /// // Prints "["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"]" /// /// Likewise, `RangeReplaceableCollection` types can remove one or more /// elements using a single operation. /// /// bugs.removeLast() /// bugs.removeSubrange(1...2) /// print(bugs) /// // Prints "["Aphid", "Damselfly"]" /// /// bugs.removeAll() /// print(bugs) /// // Prints "[]" /// /// Lastly, use the eponymous `replaceSubrange(_:with:)` method to replace /// a subrange of elements with the contents of another collection. Here, /// three elements in the middle of an array of integers are replaced by the /// five elements of a `Repeated<Int>` instance. /// /// var nums = [10, 20, 30, 40, 50] /// nums.replaceSubrange(1...3, with: repeatElement(1, count: 5)) /// print(nums) /// // Prints "[10, 1, 1, 1, 1, 1, 50]" /// /// Conforming to the RangeReplaceableCollection Protocol /// ===================================================== /// /// To add `RangeReplaceableCollection` conformance to your custom collection, /// add an empty initializer and the `replaceSubrange(_:with:)` method to your /// custom type. `RangeReplaceableCollection` provides default implementations /// of all its other methods using this initializer and method. For example, /// the `removeSubrange(_:)` method is implemented by calling /// `replaceSubrange(_:with:)` with an empty collection for the `newElements` /// parameter. You can override any of the protocol's required methods to /// provide your own custom implementation. public protocol RangeReplaceableCollection : Collection where SubSequence : RangeReplaceableCollection { // FIXME(ABI): Associated type inference requires this. associatedtype SubSequence //===--- Fundamental Requirements ---------------------------------------===// /// Creates a new, empty collection. init() /// Replaces the specified subrange of elements with the given collection. /// /// This method has the effect of removing the specified range of elements /// from the collection and inserting the new elements at the same location. /// The number of new elements need not match the number of elements being /// removed. /// /// In this example, three elements in the middle of an array of integers are /// replaced by the five elements of a `Repeated<Int>` instance. /// /// var nums = [10, 20, 30, 40, 50] /// nums.replaceSubrange(1...3, with: repeatElement(1, count: 5)) /// print(nums) /// // Prints "[10, 1, 1, 1, 1, 1, 50]" /// /// If you pass a zero-length range as the `subrange` parameter, this method /// inserts the elements of `newElements` at `subrange.startIndex`. Calling /// the `insert(contentsOf:at:)` method instead is preferred. /// /// Likewise, if you pass a zero-length collection as the `newElements` /// parameter, this method removes the elements in the given subrange /// without replacement. Calling the `removeSubrange(_:)` method instead is /// preferred. /// /// Calling this method may invalidate any existing indices for use with this /// collection. /// /// - Parameters: /// - subrange: The subrange of the collection to replace. The bounds of /// the range must be valid indices of the collection. /// - newElements: The new elements to add to the collection. /// /// - Complexity: O(*m*), where *m* is the combined length of the collection /// and `newElements`. If the call to `replaceSubrange` simply appends the /// contents of `newElements` to the collection, the complexity is O(*n*), /// where *n* is the length of `newElements`. mutating func replaceSubrange<C>( _ subrange: Range<Index>, with newElements: C ) where C : Collection, C.Element == Element /// Prepares the collection to store the specified number of elements, when /// doing so is appropriate for the underlying type. /// /// If you are adding a known number of elements to a collection, use this /// method to avoid multiple reallocations. A type that conforms to /// `RangeReplaceableCollection` can choose how to respond when this method /// is called. Depending on the type, it may make sense to allocate more or /// less storage than requested, or to take no action at all. /// /// - Parameter n: The requested number of elements to store. mutating func reserveCapacity(_ n: Int) //===--- Derivable Requirements -----------------------------------------===// /// Creates a new collection containing the specified number of a single, /// repeated value. /// /// The following example creates an array initialized with five strings /// containing the letter *Z*. /// /// let fiveZs = Array(repeating: "Z", count: 5) /// print(fiveZs) /// // Prints "["Z", "Z", "Z", "Z", "Z"]" /// /// - Parameters: /// - repeatedValue: The element to repeat. /// - count: The number of times to repeat the value passed in the /// `repeating` parameter. `count` must be zero or greater. init(repeating repeatedValue: Element, count: Int) /// Creates a new instance of a collection containing the elements of a /// sequence. /// /// - Parameter elements: The sequence of elements for the new collection. /// `elements` must be finite. init<S : Sequence>(_ elements: S) where S.Element == Element /// Adds an element to the end of the collection. /// /// If the collection does not have sufficient capacity for another element, /// additional storage is allocated before appending `newElement`. The /// following example adds a new number to an array of integers: /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.append(100) /// /// print(numbers) /// // Prints "[1, 2, 3, 4, 5, 100]" /// /// - Parameter newElement: The element to append to the collection. /// /// - Complexity: O(1) on average, over many additions to the same /// collection. mutating func append(_ newElement: Element) /// Adds the elements of a sequence or collection to the end of this /// collection. /// /// The collection being appended to allocates any additional necessary /// storage to hold the new elements. /// /// The following example appends the elements of a `Range<Int>` instance to /// an array of integers: /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.append(contentsOf: 10...15) /// print(numbers) /// // Prints "[1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15]" /// /// - Parameter newElements: The elements to append to the collection. /// /// - Complexity: O(*n*), where *n* is the length of the resulting /// collection. // FIXME(ABI)#166 (Evolution): Consider replacing .append(contentsOf) with += // suggestion in SE-91 mutating func append<S : Sequence>(contentsOf newElements: S) where S.Element == Element /// Inserts a new element into the collection at the specified position. /// /// The new element is inserted before the element currently at the /// specified index. If you pass the collection's `endIndex` property as /// the `index` parameter, the new element is appended to the /// collection. /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.insert(100, at: 3) /// numbers.insert(200, at: numbers.endIndex) /// /// print(numbers) /// // Prints "[1, 2, 3, 100, 4, 5, 200]" /// /// Calling this method may invalidate any existing indices for use with this /// collection. /// /// - Parameter newElement: The new element to insert into the collection. /// - Parameter i: The position at which to insert the new element. /// `index` must be a valid index into the collection. /// /// - Complexity: O(*n*), where *n* is the length of the collection. mutating func insert(_ newElement: Element, at i: Index) /// Inserts the elements of a sequence into the collection at the specified /// position. /// /// The new elements are inserted before the element currently at the /// specified index. If you pass the collection's `endIndex` property as the /// `index` parameter, the new elements are appended to the collection. /// /// Here's an example of inserting a range of integers into an array of the /// same type: /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.insert(contentsOf: 100...103, at: 3) /// print(numbers) /// // Prints "[1, 2, 3, 100, 101, 102, 103, 4, 5]" /// /// Calling this method may invalidate any existing indices for use with this /// collection. /// /// - Parameter newElements: The new elements to insert into the collection. /// - Parameter i: The position at which to insert the new elements. `index` /// must be a valid index of the collection. /// /// - Complexity: O(*m*), where *m* is the combined length of the collection /// and `newElements`. If `i` is equal to the collection's `endIndex` /// property, the complexity is O(*n*), where *n* is the length of /// `newElements`. mutating func insert<S : Collection>(contentsOf newElements: S, at i: Index) where S.Element == Element /// Removes and returns the element at the specified position. /// /// All the elements following the specified position are moved to close the /// gap. This example removes the middle element from an array of /// measurements. /// /// var measurements = [1.2, 1.5, 2.9, 1.2, 1.6] /// let removed = measurements.remove(at: 2) /// print(measurements) /// // Prints "[1.2, 1.5, 1.2, 1.6]" /// /// Calling this method may invalidate any existing indices for use with this /// collection. /// /// - Parameter i: The position of the element to remove. `index` must be /// a valid index of the collection that is not equal to the collection's /// end index. /// - Returns: The removed element. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @discardableResult mutating func remove(at i: Index) -> Element /// Removes the specified subrange of elements from the collection. /// /// var bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"] /// bugs.removeSubrange(1...3) /// print(bugs) /// // Prints "["Aphid", "Earwig"]" /// /// Calling this method may invalidate any existing indices for use with this /// collection. /// /// - Parameter bounds: The subrange of the collection to remove. The bounds /// of the range must be valid indices of the collection. /// /// - Complexity: O(*n*), where *n* is the length of the collection. mutating func removeSubrange(_ bounds: Range<Index>) /// Customization point for `removeLast()`. Implement this function if you /// want to replace the default implementation. /// /// - Returns: A non-nil value if the operation was performed. mutating func _customRemoveLast() -> Element? /// Customization point for `removeLast(_:)`. Implement this function if you /// want to replace the default implementation. /// /// - Returns: `true` if the operation was performed. mutating func _customRemoveLast(_ n: Int) -> Bool /// Removes and returns the first element of the collection. /// /// The collection must not be empty. /// /// var bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"] /// bugs.removeFirst() /// print(bugs) /// // Prints "["Bumblebee", "Cicada", "Damselfly", "Earwig"]" /// /// Calling this method may invalidate any existing indices for use with this /// collection. /// /// - Returns: The removed element. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @discardableResult mutating func removeFirst() -> Element /// Removes the specified number of elements from the beginning of the /// collection. /// /// var bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"] /// bugs.removeFirst(3) /// print(bugs) /// // Prints "["Damselfly", "Earwig"]" /// /// Calling this method may invalidate any existing indices for use with this /// collection. /// /// - Parameter n: The number of elements to remove from the collection. /// `n` must be greater than or equal to zero and must not exceed the /// number of elements in the collection. /// /// - Complexity: O(*n*), where *n* is the length of the collection. mutating func removeFirst(_ n: Int) /// Removes all elements from the collection. /// /// Calling this method may invalidate any existing indices for use with this /// collection. /// /// - Parameter keepCapacity: Pass `true` to request that the collection /// avoid releasing its storage. Retaining the collection's storage can /// be a useful optimization when you're planning to grow the collection /// again. The default value is `false`. /// /// - Complexity: O(*n*), where *n* is the length of the collection. mutating func removeAll(keepingCapacity keepCapacity: Bool /*= false*/) /// Removes from the collection all elements that satisfy the given predicate. /// /// - Parameter predicate: A closure that takes an element of the /// sequence as its argument and returns a Boolean value indicating /// whether the element should be removed from the collection. /// /// - Complexity: O(*n*), where *n* is the length of the collection. mutating func removeAll(where predicate: (Element) throws -> Bool) rethrows // FIXME(ABI): Associated type inference requires this. subscript(bounds: Index) -> Element { get } // FIXME(ABI): Associated type inference requires this. subscript(bounds: Range<Index>) -> SubSequence { get } } //===----------------------------------------------------------------------===// // Default implementations for RangeReplaceableCollection //===----------------------------------------------------------------------===// extension RangeReplaceableCollection { /// Creates a new collection containing the specified number of a single, /// repeated value. /// /// Here's an example of creating an array initialized with five strings /// containing the letter *Z*. /// /// let fiveZs = Array(repeating: "Z", count: 5) /// print(fiveZs) /// // Prints "["Z", "Z", "Z", "Z", "Z"]" /// /// - Parameters: /// - repeatedValue: The element to repeat. /// - count: The number of times to repeat the value passed in the /// `repeating` parameter. `count` must be zero or greater. @inlinable public init(repeating repeatedValue: Element, count: Int) { self.init() if count != 0 { let elements = Repeated(_repeating: repeatedValue, count: count) append(contentsOf: elements) } } /// Creates a new instance of a collection containing the elements of a /// sequence. /// /// - Parameter elements: The sequence of elements for the new collection. @inlinable public init<S : Sequence>(_ elements: S) where S.Element == Element { self.init() append(contentsOf: elements) } /// Adds an element to the end of the collection. /// /// If the collection does not have sufficient capacity for another element, /// additional storage is allocated before appending `newElement`. The /// following example adds a new number to an array of integers: /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.append(100) /// /// print(numbers) /// // Prints "[1, 2, 3, 4, 5, 100]" /// /// - Parameter newElement: The element to append to the collection. /// /// - Complexity: O(1) on average, over many additions to the same /// collection. @inlinable public mutating func append(_ newElement: Element) { insert(newElement, at: endIndex) } /// Adds the elements of a sequence or collection to the end of this /// collection. /// /// The collection being appended to allocates any additional necessary /// storage to hold the new elements. /// /// The following example appends the elements of a `Range<Int>` instance to /// an array of integers: /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.append(contentsOf: 10...15) /// print(numbers) /// // Prints "[1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15]" /// /// - Parameter newElements: The elements to append to the collection. /// /// - Complexity: O(*n*), where *n* is the length of the resulting /// collection. @inlinable public mutating func append<S : Sequence>(contentsOf newElements: S) where S.Element == Element { let approximateCapacity = self.count + numericCast(newElements.underestimatedCount) self.reserveCapacity(approximateCapacity) for element in newElements { append(element) } } /// Inserts a new element into the collection at the specified position. /// /// The new element is inserted before the element currently at the /// specified index. If you pass the collection's `endIndex` property as /// the `index` parameter, the new element is appended to the /// collection. /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.insert(100, at: 3) /// numbers.insert(200, at: numbers.endIndex) /// /// print(numbers) /// // Prints "[1, 2, 3, 100, 4, 5, 200]" /// /// Calling this method may invalidate any existing indices for use with this /// collection. /// /// - Parameter newElement: The new element to insert into the collection. /// - Parameter i: The position at which to insert the new element. /// `index` must be a valid index into the collection. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @inlinable public mutating func insert( _ newElement: Element, at i: Index ) { replaceSubrange(i..<i, with: CollectionOfOne(newElement)) } /// Inserts the elements of a sequence into the collection at the specified /// position. /// /// The new elements are inserted before the element currently at the /// specified index. If you pass the collection's `endIndex` property as the /// `index` parameter, the new elements are appended to the collection. /// /// Here's an example of inserting a range of integers into an array of the /// same type: /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.insert(contentsOf: 100...103, at: 3) /// print(numbers) /// // Prints "[1, 2, 3, 100, 101, 102, 103, 4, 5]" /// /// Calling this method may invalidate any existing indices for use with this /// collection. /// /// - Parameter newElements: The new elements to insert into the collection. /// - Parameter i: The position at which to insert the new elements. `index` /// must be a valid index of the collection. /// /// - Complexity: O(*m*), where *m* is the combined length of the collection /// and `newElements`. If `i` is equal to the collection's `endIndex` /// property, the complexity is O(*n*), where *n* is the length of /// `newElements`. @inlinable public mutating func insert<C : Collection>( contentsOf newElements: C, at i: Index ) where C.Element == Element { replaceSubrange(i..<i, with: newElements) } /// Removes and returns the element at the specified position. /// /// All the elements following the specified position are moved to close the /// gap. This example removes the middle element from an array of /// measurements. /// /// var measurements = [1.2, 1.5, 2.9, 1.2, 1.6] /// let removed = measurements.remove(at: 2) /// print(measurements) /// // Prints "[1.2, 1.5, 1.2, 1.6]" /// /// Calling this method may invalidate any existing indices for use with this /// collection. /// /// - Parameter position: The position of the element to remove. `position` must be /// a valid index of the collection that is not equal to the collection's /// end index. /// - Returns: The removed element. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @inlinable @discardableResult public mutating func remove(at position: Index) -> Element { _precondition(!isEmpty, "Can't remove from an empty collection") let result: Element = self[position] replaceSubrange(position..<index(after: position), with: EmptyCollection()) return result } /// Removes the elements in the specified subrange from the collection. /// /// All the elements following the specified position are moved to close the /// gap. This example removes three elements from the middle of an array of /// measurements. /// /// var measurements = [1.2, 1.5, 2.9, 1.2, 1.5] /// measurements.removeSubrange(1..<4) /// print(measurements) /// // Prints "[1.2, 1.5]" /// /// Calling this method may invalidate any existing indices for use with this /// collection. /// /// - Parameter bounds: The range of the collection to be removed. The /// bounds of the range must be valid indices of the collection. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @inlinable public mutating func removeSubrange(_ bounds: Range<Index>) { replaceSubrange(bounds, with: EmptyCollection()) } /// Removes the specified number of elements from the beginning of the /// collection. /// /// var bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"] /// bugs.removeFirst(3) /// print(bugs) /// // Prints "["Damselfly", "Earwig"]" /// /// Calling this method may invalidate any existing indices for use with this /// collection. /// /// - Parameter n: The number of elements to remove from the collection. /// `n` must be greater than or equal to zero and must not exceed the /// number of elements in the collection. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @inlinable public mutating func removeFirst(_ n: Int) { if n == 0 { return } _precondition(n >= 0, "Number of elements to remove should be non-negative") _precondition(count >= numericCast(n), "Can't remove more items from a collection than it has") let end = index(startIndex, offsetBy: numericCast(n)) removeSubrange(startIndex..<end) } /// Removes and returns the first element of the collection. /// /// The collection must not be empty. /// /// var bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"] /// bugs.removeFirst() /// print(bugs) /// // Prints "["Bumblebee", "Cicada", "Damselfly", "Earwig"]" /// /// Calling this method may invalidate any existing indices for use with this /// collection. /// /// - Returns: The removed element. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @inlinable @discardableResult public mutating func removeFirst() -> Element { _precondition(!isEmpty, "Can't remove first element from an empty collection") let firstElement = first! removeFirst(1) return firstElement } /// Removes all elements from the collection. /// /// Calling this method may invalidate any existing indices for use with this /// collection. /// /// - Parameter keepCapacity: Pass `true` to request that the collection /// avoid releasing its storage. Retaining the collection's storage can /// be a useful optimization when you're planning to grow the collection /// again. The default value is `false`. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @inlinable public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) { if !keepCapacity { self = Self() } else { replaceSubrange(startIndex..<endIndex, with: EmptyCollection()) } } /// Prepares the collection to store the specified number of elements, when /// doing so is appropriate for the underlying type. /// /// If you will be adding a known number of elements to a collection, use /// this method to avoid multiple reallocations. A type that conforms to /// `RangeReplaceableCollection` can choose how to respond when this method /// is called. Depending on the type, it may make sense to allocate more or /// less storage than requested or to take no action at all. /// /// - Parameter n: The requested number of elements to store. @inlinable public mutating func reserveCapacity(_ n: Int) {} } extension RangeReplaceableCollection where SubSequence == Self { /// Removes and returns the first element of the collection. /// /// The collection must not be empty. /// /// Calling this method may invalidate all saved indices of this /// collection. Do not rely on a previously stored index value after /// altering a collection with any operation that can change its length. /// /// - Returns: The first element of the collection. /// /// - Complexity: O(1) /// - Precondition: `!self.isEmpty`. @inlinable @discardableResult public mutating func removeFirst() -> Element { _precondition(!isEmpty, "Can't remove items from an empty collection") let element = first! self = self[index(after: startIndex)..<endIndex] return element } /// Removes the specified number of elements from the beginning of the /// collection. /// /// Attempting to remove more elements than exist in the collection /// triggers a runtime error. /// /// Calling this method may invalidate all saved indices of this /// collection. Do not rely on a previously stored index value after /// altering a collection with any operation that can change its length. /// /// - Parameter n: The number of elements to remove from the collection. /// `n` must be greater than or equal to zero and must not exceed the /// number of elements in the collection. /// /// - Complexity: O(1) @inlinable public mutating func removeFirst(_ n: Int) { if n == 0 { return } _precondition(n >= 0, "Number of elements to remove should be non-negative") _precondition(count >= numericCast(n), "Can't remove more items from a collection than it contains") self = self[index(startIndex, offsetBy: numericCast(n))..<endIndex] } } extension RangeReplaceableCollection { /// Replaces the specified subrange of elements with the given collection. /// /// This method has the effect of removing the specified range of elements /// from the collection and inserting the new elements at the same location. /// The number of new elements need not match the number of elements being /// removed. /// /// In this example, three elements in the middle of an array of integers are /// replaced by the five elements of a `Repeated<Int>` instance. /// /// var nums = [10, 20, 30, 40, 50] /// nums.replaceSubrange(1...3, with: repeatElement(1, count: 5)) /// print(nums) /// // Prints "[10, 1, 1, 1, 1, 1, 50]" /// /// If you pass a zero-length range as the `subrange` parameter, this method /// inserts the elements of `newElements` at `subrange.startIndex`. Calling /// the `insert(contentsOf:at:)` method instead is preferred. /// /// Likewise, if you pass a zero-length collection as the `newElements` /// parameter, this method removes the elements in the given subrange /// without replacement. Calling the `removeSubrange(_:)` method instead is /// preferred. /// /// Calling this method may invalidate any existing indices for use with this /// collection. /// /// - Parameters: /// - subrange: The subrange of the collection to replace. The bounds of /// the range must be valid indices of the collection. /// - newElements: The new elements to add to the collection. /// /// - Complexity: O(*m*), where *m* is the combined length of the collection /// and `newElements`. If the call to `replaceSubrange` simply appends the /// contents of `newElements` to the collection, the complexity is O(*n*), /// where *n* is the length of `newElements`. @inlinable public mutating func replaceSubrange<C: Collection, R: RangeExpression>( _ subrange: R, with newElements: C ) where C.Element == Element, R.Bound == Index { self.replaceSubrange(subrange.relative(to: self), with: newElements) } /// Removes the elements in the specified subrange from the collection. /// /// All the elements following the specified position are moved to close the /// gap. This example removes three elements from the middle of an array of /// measurements. /// /// var measurements = [1.2, 1.5, 2.9, 1.2, 1.5] /// measurements.removeSubrange(1..<4) /// print(measurements) /// // Prints "[1.2, 1.5]" /// /// Calling this method may invalidate any existing indices for use with this /// collection. /// /// - Parameter bounds: The range of the collection to be removed. The /// bounds of the range must be valid indices of the collection. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @inlinable public mutating func removeSubrange<R: RangeExpression>( _ bounds: R ) where R.Bound == Index { removeSubrange(bounds.relative(to: self)) } } extension RangeReplaceableCollection { @inlinable public mutating func _customRemoveLast() -> Element? { return nil } @inlinable public mutating func _customRemoveLast(_ n: Int) -> Bool { return false } } extension RangeReplaceableCollection where Self : BidirectionalCollection, SubSequence == Self { @inlinable public mutating func _customRemoveLast() -> Element? { let element = last! self = self[startIndex..<index(before: endIndex)] return element } @inlinable public mutating func _customRemoveLast(_ n: Int) -> Bool { self = self[startIndex..<index(endIndex, offsetBy: numericCast(-n))] return true } } extension RangeReplaceableCollection where Self : BidirectionalCollection { /// Removes and returns the last element of the collection. /// /// Calling this method may invalidate all saved indices of this /// collection. Do not rely on a previously stored index value after /// altering a collection with any operation that can change its length. /// /// - Returns: The last element of the collection if the collection is not /// empty; otherwise, `nil`. /// /// - Complexity: O(1) @inlinable public mutating func popLast() -> Element? { if isEmpty { return nil } // duplicate of removeLast logic below, to avoid redundant precondition if let result = _customRemoveLast() { return result } return remove(at: index(before: endIndex)) } /// Removes and returns the last element of the collection. /// /// The collection must not be empty. /// /// Calling this method may invalidate all saved indices of this /// collection. Do not rely on a previously stored index value after /// altering a collection with any operation that can change its length. /// /// - Returns: The last element of the collection. /// /// - Complexity: O(1) @inlinable @discardableResult public mutating func removeLast() -> Element { _precondition(!isEmpty, "Can't remove last element from an empty collection") // NOTE if you change this implementation, change popLast above as well // AND change the tie-breaker implementations in the next extension if let result = _customRemoveLast() { return result } return remove(at: index(before: endIndex)) } /// Removes the specified number of elements from the end of the /// collection. /// /// Attempting to remove more elements than exist in the collection /// triggers a runtime error. /// /// Calling this method may invalidate all saved indices of this /// collection. Do not rely on a previously stored index value after /// altering a collection with any operation that can change its length. /// /// - Parameter n: The number of elements to remove from the collection. /// `n` must be greater than or equal to zero and must not exceed the /// number of elements in the collection. /// /// - Complexity: O(*n*), where *n* is the specified number of elements. @inlinable public mutating func removeLast(_ n: Int) { if n == 0 { return } _precondition(n >= 0, "Number of elements to remove should be non-negative") _precondition(count >= numericCast(n), "Can't remove more items from a collection than it contains") if _customRemoveLast(n) { return } let end = endIndex removeSubrange(index(end, offsetBy: numericCast(-n))..<end) } } /// Ambiguity breakers. extension RangeReplaceableCollection where Self : BidirectionalCollection, SubSequence == Self { /// Removes and returns the last element of the collection. /// /// Calling this method may invalidate all saved indices of this /// collection. Do not rely on a previously stored index value after /// altering a collection with any operation that can change its length. /// /// - Returns: The last element of the collection if the collection is not /// empty; otherwise, `nil`. /// /// - Complexity: O(1) @inlinable public mutating func popLast() -> Element? { if isEmpty { return nil } // duplicate of removeLast logic below, to avoid redundant precondition if let result = _customRemoveLast() { return result } return remove(at: index(before: endIndex)) } /// Removes and returns the last element of the collection. /// /// The collection must not be empty. /// /// Calling this method may invalidate all saved indices of this /// collection. Do not rely on a previously stored index value after /// altering a collection with any operation that can change its length. /// /// - Returns: The last element of the collection. /// /// - Complexity: O(1) @inlinable @discardableResult public mutating func removeLast() -> Element { _precondition(!isEmpty, "Can't remove last element from an empty collection") // NOTE if you change this implementation, change popLast above as well if let result = _customRemoveLast() { return result } return remove(at: index(before: endIndex)) } /// Removes the specified number of elements from the end of the /// collection. /// /// Attempting to remove more elements than exist in the collection /// triggers a runtime error. /// /// Calling this method may invalidate all saved indices of this /// collection. Do not rely on a previously stored index value after /// altering a collection with any operation that can change its length. /// /// - Parameter n: The number of elements to remove from the collection. /// `n` must be greater than or equal to zero and must not exceed the /// number of elements in the collection. /// /// - Complexity: O(*n*), where *n* is the specified number of elements. @inlinable public mutating func removeLast(_ n: Int) { if n == 0 { return } _precondition(n >= 0, "Number of elements to remove should be non-negative") _precondition(count >= numericCast(n), "Can't remove more items from a collection than it contains") if _customRemoveLast(n) { return } let end = endIndex removeSubrange(index(end, offsetBy: numericCast(-n))..<end) } } extension RangeReplaceableCollection { /// Creates a new collection by concatenating the elements of a collection and /// a sequence. /// /// The two arguments must have the same `Element` type. For example, you can /// concatenate the elements of an integer array and a `Range<Int>` instance. /// /// let numbers = [1, 2, 3, 4] /// let moreNumbers = numbers + 5...10 /// print(moreNumbers) /// // Prints "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]" /// /// The resulting collection has the type of the argument on the left-hand /// side. In the example above, `moreNumbers` has the same type as `numbers`, /// which is `[Int]`. /// /// - Parameters: /// - lhs: A range-replaceable collection. /// - rhs: A collection or finite sequence. @inlinable public static func + < Other : Sequence >(lhs: Self, rhs: Other) -> Self where Element == Other.Element { var lhs = lhs // FIXME: what if lhs is a reference type? This will mutate it. lhs.append(contentsOf: rhs) return lhs } /// Creates a new collection by concatenating the elements of a sequence and a /// collection. /// /// The two arguments must have the same `Element` type. For example, you can /// concatenate the elements of a `Range<Int>` instance and an integer array. /// /// let numbers = [7, 8, 9, 10] /// let moreNumbers = 1...6 + numbers /// print(moreNumbers) /// // Prints "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]" /// /// The resulting collection has the type of argument on the right-hand side. /// In the example above, `moreNumbers` has the same type as `numbers`, which /// is `[Int]`. /// /// - Parameters: /// - lhs: A collection or finite sequence. /// - rhs: A range-replaceable collection. @inlinable public static func + < Other : Sequence >(lhs: Other, rhs: Self) -> Self where Element == Other.Element { var result = Self() result.reserveCapacity(rhs.count + numericCast(lhs.underestimatedCount)) result.append(contentsOf: lhs) result.append(contentsOf: rhs) return result } /// Appends the elements of a sequence to a range-replaceable collection. /// /// Use this operator to append the elements of a sequence to the end of /// range-replaceable collection with same `Element` type. This example appends /// the elements of a `Range<Int>` instance to an array of integers. /// /// var numbers = [1, 2, 3, 4, 5] /// numbers += 10...15 /// print(numbers) /// // Prints "[1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15]" /// /// - Parameters: /// - lhs: The array to append to. /// - rhs: A collection or finite sequence. /// /// - Complexity: O(*n*), where *n* is the length of the resulting array. @inlinable public static func += < Other : Sequence >(lhs: inout Self, rhs: Other) where Element == Other.Element { lhs.append(contentsOf: rhs) } /// Creates a new collection by concatenating the elements of two collections. /// /// The two arguments must have the same `Element` type. For example, you can /// concatenate the elements of two integer arrays. /// /// let lowerNumbers = [1, 2, 3, 4] /// let higherNumbers: ContiguousArray = [5, 6, 7, 8, 9, 10] /// let allNumbers = lowerNumbers + higherNumbers /// print(allNumbers) /// // Prints "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]" /// /// The resulting collection has the type of the argument on the left-hand /// side. In the example above, `moreNumbers` has the same type as `numbers`, /// which is `[Int]`. /// /// - Parameters: /// - lhs: A range-replaceable collection. /// - rhs: Another range-replaceable collection. @inlinable public static func + < Other : RangeReplaceableCollection >(lhs: Self, rhs: Other) -> Self where Element == Other.Element { var lhs = lhs // FIXME: what if lhs is a reference type? This will mutate it. lhs.append(contentsOf: rhs) return lhs } } extension RangeReplaceableCollection { /// Returns a new collection of the same type containing, in order, the /// elements of the original collection that satisfy the given predicate. /// /// In this example, `filter(_:)` is used to include only names shorter than /// five characters. /// /// let cast = ["Vivien", "Marlon", "Kim", "Karl"] /// let shortNames = cast.filter { $0.count < 5 } /// print(shortNames) /// // Prints "["Kim", "Karl"]" /// /// - Parameter isIncluded: A closure that takes an element of the /// sequence as its argument and returns a Boolean value indicating /// whether the element should be included in the returned array. /// - Returns: An array of the elements that `isIncluded` allowed. @inlinable @available(swift, introduced: 4.0) public func filter( _ isIncluded: (Element) throws -> Bool ) rethrows -> Self { return try Self(self.lazy.filter(isIncluded)) } } extension RangeReplaceableCollection where Self: MutableCollection { /// Removes from the collection all elements that satisfy the given predicate. /// /// - Parameter predicate: A closure that takes an element of the /// sequence as its argument and returns a Boolean value indicating /// whether the element should be removed from the collection. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @inlinable public mutating func removeAll( where predicate: (Element) throws -> Bool ) rethrows { if var i = try firstIndex(where: predicate) { var j = index(after: i) while j != endIndex { if try !predicate(self[j]) { swapAt(i, j) formIndex(after: &i) } formIndex(after: &j) } removeSubrange(i...) } } } extension RangeReplaceableCollection { /// Removes from the collection all elements that satisfy the given predicate. /// /// - Parameter predicate: A closure that takes an element of the /// sequence as its argument and returns a Boolean value indicating /// whether the element should be removed from the collection. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @inlinable public mutating func removeAll( where predicate: (Element) throws -> Bool ) rethrows { // FIXME: Switch to using RRC.filter once stdlib is compiled for 4.0 // self = try filter { try !predicate($0) } self = try Self(self.lazy.filter { try !predicate($0) }) } }
38.534041
115
0.653435
4a6067fc0bd6e922ced789e5879a3381773b1684
500
// // ChatModel.swift // ZYBaseDemo // // Created by Mzywx on 2017/2/4. // Copyright © 2017年 Mzywx. All rights reserved. // import UIKit class ChatModel: ZYDataModel { var senderimg : String! var content : String! var createdate : Double! required init(fromJson json: JSON!) { super.init(fromJson: json) senderimg = json["senderimg"].stringValue content = json["content"].stringValue createdate = json["createdate"].doubleValue } }
20.833333
51
0.634
ab7eb6f230feb2809f42015cf2068299ab970f48
257
// // UITableViewCell+identifier.swift // TravelMap // // Created by Даниил Петров on 30.07.2021. // import Foundation import UIKit extension UITableViewCell { static var reusableIdentifier: String { return String(describing: self) } }
16.0625
43
0.700389
cc1d75abc9785e8d1c06dcbdb0ad694b3c0ca6e6
2,565
#if MIXBOX_ENABLE_IN_APP_SERVICES public final class MultipleDependenciesRegistrationContinuation<T> { private let dependencyRegisterer: DependencyRegisterer private let scope: Scope public init(dependencyRegisterer: DependencyRegisterer, scope: Scope) { self.dependencyRegisterer = dependencyRegisterer self.scope = scope } // NOTE: Reregistering can be tricky. // // You may want to register your stateless classes as `.single`, but you // also may want to reregister them as `.unique`. This is because you // probably want to just reference registered type, not registered instance, // which will occur because `.single` dependencies are cached. // // For example: // // ``` // di.registerMultiple(scope: .single, type: Employee.self) { _ in Alice() } // .reregister(scope: .unique) { $0 as Colleague } // ``` // // If you want to replace `Alice` with `Bob` for whatever reasons, you may also want to // resolve `Bob` as `Collegue` instead of `Alice`. But if you reregister her as `.single`, // then she will be cached forever and `Bob` will never be resolved as `Collegue`. // // This will only happen if `Alice` was resolved once. Otherwise `Bob` will just be resolved // in any case. // // And keep in mind that resolving a `.single` dependency will store it somewhere, which can // be unexpected for you if you override dependency later after resolve. You may think // that it will be changed everywhere where it was resolved, but it will not. // @discardableResult public func reregister<U>( scope: Scope, type: U.Type = U.self, transform: @escaping (T) -> U) -> MultipleDependenciesRegistrationContinuation<T> { dependencyRegisterer.register( scope: scope, type: type, factory: { di in transform(try di.resolve() as T) } ) return MultipleDependenciesRegistrationContinuation<T>( dependencyRegisterer: dependencyRegisterer, scope: scope ) } // Reregisters with same scope that was in a root object. @discardableResult public func reregister<U>( type: U.Type = U.self, transform: @escaping (T) -> U) -> MultipleDependenciesRegistrationContinuation<T> { return reregister( scope: scope, type: type, transform: transform ) } } #endif
34.662162
96
0.62768
144b0ef3bf91cb44b30d729de5ba6b7dac5aeeb6
21,016
import Foundation import Prelude import ReactiveSwift public enum Mailbox: String { case inbox case sent } /* * A type that knows how to perform requests for Kickstarter data. */ public protocol ServiceType { var appId: String { get } var serverConfig: ServerConfigType { get } var oauthToken: OauthTokenAuthType? { get } var language: String { get } var currency: String { get } var buildVersion: String { get } var deviceIdentifier: String { get } var perimeterXClient: PerimeterXClientType? { get } init( appId: String, serverConfig: ServerConfigType, oauthToken: OauthTokenAuthType?, language: String, currency: String, buildVersion: String, deviceIdentifier: String, perimeterXClient: PerimeterXClientType? ) /// Returns a new service with the oauth token replaced. func login(_ oauthToken: OauthTokenAuthType) -> Self /// Returns a new service with the oauth token set to `nil`. func logout() -> Self /// Request to connect user to Facebook with access token. func facebookConnect(facebookAccessToken token: String) -> SignalProducer<User, ErrorEnvelope> /// Uploads and attaches an image to the draft of a project update. func addImage(file fileURL: URL, toDraft draft: UpdateDraft) -> SignalProducer<UpdateDraft.Image, ErrorEnvelope> /// Cancels a backing func cancelBacking(input: CancelBackingInput) -> SignalProducer<GraphMutationEmptyResponseEnvelope, GraphError> func changeEmail(input: ChangeEmailInput) -> SignalProducer<GraphMutationEmptyResponseEnvelope, GraphError> func changePassword(input: ChangePasswordInput) -> SignalProducer<GraphMutationEmptyResponseEnvelope, GraphError> func changeCurrency(input: ChangeCurrencyInput) -> SignalProducer<GraphMutationEmptyResponseEnvelope, GraphError> /// Clears the user's unseen activity count. func clearUserUnseenActivity(input: EmptyInput) -> SignalProducer<ClearUserUnseenActivityEnvelope, GraphError> func createBacking(input: CreateBackingInput) -> SignalProducer<CreateBackingEnvelope, GraphError> func createPassword(input: CreatePasswordInput) -> SignalProducer<GraphMutationEmptyResponseEnvelope, GraphError> func addNewCreditCard(input: CreatePaymentSourceInput) -> SignalProducer<CreatePaymentSourceEnvelope, GraphError> /// Deletes a payment method func deletePaymentMethod(input: PaymentSourceDeleteInput) -> SignalProducer<DeletePaymentMethodEnvelope, GraphError> /// Removes an image from a project update draft. func delete(image: UpdateDraft.Image, fromDraft draft: UpdateDraft) -> SignalProducer<UpdateDraft.Image, ErrorEnvelope> func exportData() -> SignalProducer<VoidEnvelope, ErrorEnvelope> func exportDataState() -> SignalProducer<ExportDataEnvelope, ErrorEnvelope> /// Fetch a page of activities. func fetchActivities(count: Int?) -> SignalProducer<ActivityEnvelope, ErrorEnvelope> /// Fetch activities from a pagination URL func fetchActivities(paginationUrl: String) -> SignalProducer<ActivityEnvelope, ErrorEnvelope> /// Fetches the current user's backing for the project, if it exists. func fetchBacking(forProject project: Project, forUser user: User) -> SignalProducer<Backing, ErrorEnvelope> /// Fetch comments from a pagination url. func fetchComments(paginationUrl url: String) -> SignalProducer<CommentsEnvelope, ErrorEnvelope> /// Fetch comments for a project. func fetchComments(project: Project) -> SignalProducer<CommentsEnvelope, ErrorEnvelope> /// Fetch comments for an update. func fetchComments(update: Update) -> SignalProducer<CommentsEnvelope, ErrorEnvelope> /// Fetch the config. func fetchConfig() -> SignalProducer<Config, ErrorEnvelope> /// Fetch discovery envelope with a pagination url. func fetchDiscovery(paginationUrl: String) -> SignalProducer<DiscoveryEnvelope, ErrorEnvelope> /// Fetch the full discovery envelope with specified discovery params. func fetchDiscovery(params: DiscoveryParams) -> SignalProducer<DiscoveryEnvelope, ErrorEnvelope> /// Fetch friends for a user. func fetchFriends() -> SignalProducer<FindFriendsEnvelope, ErrorEnvelope> /// Fetch friends from a pagination url. func fetchFriends(paginationUrl: String) -> SignalProducer<FindFriendsEnvelope, ErrorEnvelope> /// Fetch friend stats. func fetchFriendStats() -> SignalProducer<FriendStatsEnvelope, ErrorEnvelope> /// Fetch Categories objects using graphQL. func fetchGraphCategories(query: NonEmptySet<Query>) -> SignalProducer<RootCategoriesEnvelope, GraphError> /// Fetch Category objects using graphQL. func fetchGraphCategory(query: NonEmptySet<Query>) -> SignalProducer<CategoryEnvelope, GraphError> /// Fetch User's stored cards. func fetchGraphCreditCards(query: NonEmptySet<Query>) -> SignalProducer<UserEnvelope<GraphUserCreditCard>, GraphError> /// Fetch a User's account fields func fetchGraphUserAccountFields(query: NonEmptySet<Query>) -> SignalProducer<UserEnvelope<GraphUser>, GraphError> /// Fetch User's backings with a specific status. func fetchGraphUserBackings(query: NonEmptySet<Query>) -> SignalProducer<BackingsEnvelope, ErrorEnvelope> /// Fetch User's email fields object using graphQL. func fetchGraphUserEmailFields(query: NonEmptySet<Query>) -> SignalProducer<UserEnvelope<UserEmailFields>, GraphError> /// Fetch Backing data for ManagePledgeViewController func fetchManagePledgeViewBacking(query: NonEmptySet<Query>) -> SignalProducer<ProjectAndBackingEnvelope, ErrorEnvelope> /// Fetches all of the messages in a particular message thread. func fetchMessageThread(messageThreadId: Int) -> SignalProducer<MessageThreadEnvelope, ErrorEnvelope> /// Fetches all of the messages related to a particular backing. func fetchMessageThread(backing: Backing) -> SignalProducer<MessageThreadEnvelope?, ErrorEnvelope> /// Fetches all of the messages in a particular mailbox and specific to a particular project. func fetchMessageThreads(mailbox: Mailbox, project: Project?) -> SignalProducer<MessageThreadsEnvelope, ErrorEnvelope> /// Fetches more messages threads from a pagination URL. func fetchMessageThreads(paginationUrl: String) -> SignalProducer<MessageThreadsEnvelope, ErrorEnvelope> /// Fetch the newest data for a particular project from its id. func fetchProject(param: Param) -> SignalProducer<Project, ErrorEnvelope> /// Fetch a single project with the specified discovery params. func fetchProject(_ params: DiscoveryParams) -> SignalProducer<DiscoveryEnvelope, ErrorEnvelope> /// Fetch the newest data for a particular project from its project value. func fetchProject(project: Project) -> SignalProducer<Project, ErrorEnvelope> /// Fetch a page of activities for a project. func fetchProjectActivities(forProject project: Project) -> SignalProducer<ProjectActivityEnvelope, ErrorEnvelope> /// Fetch a page of activities for a project from a pagination url. func fetchProjectActivities(paginationUrl: String) -> SignalProducer<ProjectActivityEnvelope, ErrorEnvelope> /// Fetch the user's project notifications. func fetchProjectNotifications() -> SignalProducer<[ProjectNotification], ErrorEnvelope> /// Fetches the projects that the current user is a member of. func fetchProjects(member: Bool) -> SignalProducer<ProjectsEnvelope, ErrorEnvelope> /// Fetches more projects from a pagination URL. func fetchProjects(paginationUrl: String) -> SignalProducer<ProjectsEnvelope, ErrorEnvelope> /// Fetches the stats for a particular project. func fetchProjectStats(projectId: Int) -> SignalProducer<ProjectStatsEnvelope, ErrorEnvelope> /// Fetch the add-on rewards for the add-on selection view with a given query. func fetchRewardAddOnsSelectionViewRewards(query: NonEmptySet<Query>) -> SignalProducer<Project, ErrorEnvelope> /// Fetches a reward for a project and reward id. func fetchRewardShippingRules(projectId: Int, rewardId: Int) -> SignalProducer<ShippingRulesEnvelope, ErrorEnvelope> /// Fetches a survey response belonging to the current user. func fetchSurveyResponse(surveyResponseId: Int) -> SignalProducer<SurveyResponse, ErrorEnvelope> /// Fetches all of the user's unanswered surveys. func fetchUnansweredSurveyResponses() -> SignalProducer<[SurveyResponse], ErrorEnvelope> /// Fetches an update from its id and project. func fetchUpdate(updateId: Int, projectParam: Param) -> SignalProducer<Update, ErrorEnvelope> /// Fetches a project update draft. func fetchUpdateDraft(forProject project: Project) -> SignalProducer<UpdateDraft, ErrorEnvelope> /// Fetches more user backed projects. func fetchUserProjectsBacked(paginationUrl url: String) -> SignalProducer<ProjectsEnvelope, ErrorEnvelope> /// Fetch the newest data for a particular user. func fetchUser(_ user: User) -> SignalProducer<User, ErrorEnvelope> /// Fetch a user. func fetchUser(userId: Int) -> SignalProducer<User, ErrorEnvelope> /// Fetch the logged-in user's data. func fetchUserSelf() -> SignalProducer<User, ErrorEnvelope> /// Mark reward received. func backingUpdate(forProject project: Project, forUser user: User, received: Bool) -> SignalProducer<Backing, ErrorEnvelope> /// Follow all friends of current user. func followAllFriends() -> SignalProducer<VoidEnvelope, ErrorEnvelope> /// Follow a user with their id. func followFriend(userId id: Int) -> SignalProducer<User, ErrorEnvelope> /// Increment the video complete stat for a project. func incrementVideoCompletion(forProject project: Project) -> SignalProducer<VoidEnvelope, ErrorEnvelope> /// Increment the video start stat for a project. func incrementVideoStart(forProject project: Project) -> SignalProducer<VoidEnvelope, ErrorEnvelope> /// Attempt a login with an email, password and optional code. func login(email: String, password: String, code: String?) -> SignalProducer<AccessTokenEnvelope, ErrorEnvelope> /// Attempt a login with Facebook access token and optional code. func login(facebookAccessToken: String, code: String?) -> SignalProducer<AccessTokenEnvelope, ErrorEnvelope> /// Marks all the messages in a particular thread as read. func markAsRead(messageThread: MessageThread) -> SignalProducer<MessageThread, ErrorEnvelope> /// Posts a comment to a project. func postComment(_ body: String, toProject project: Project) -> SignalProducer<Comment, ErrorEnvelope> /// Posts a comment to an update. func postComment(_ body: String, toUpdate update: Update) -> SignalProducer<Comment, ErrorEnvelope> /// Returns a project update preview URL. func previewUrl(forDraft draft: UpdateDraft) -> URL? /// Publishes a project update draft. func publish(draft: UpdateDraft) -> SignalProducer<Update, ErrorEnvelope> /// Registers a push token. func register(pushToken: String) -> SignalProducer<VoidEnvelope, ErrorEnvelope> /// Reset user password with email address. func resetPassword(email: String) -> SignalProducer<User, ErrorEnvelope> /// Searches all of the messages, (optionally) bucketed to a specific project. func searchMessages(query: String, project: Project?) -> SignalProducer<MessageThreadsEnvelope, ErrorEnvelope> /// Sends a message to a subject, i.e. creator project, message thread, backer of backing. func sendMessage(body: String, toSubject subject: MessageSubject) -> SignalProducer<Message, ErrorEnvelope> /// Sends a verification email (after updating the email from account settings). func sendVerificationEmail(input: EmptyInput) -> SignalProducer<GraphMutationEmptyResponseEnvelope, GraphError> /// Signin with Apple func signInWithApple(input: SignInWithAppleInput) -> SignalProducer<SignInWithAppleEnvelope, GraphError> /// Signup with email. func signup( name: String, email: String, password: String, passwordConfirmation: String, sendNewsletters: Bool ) -> SignalProducer<AccessTokenEnvelope, ErrorEnvelope> /// Signup with Facebook access token and newsletter bool. func signup(facebookAccessToken: String, sendNewsletters: Bool) -> SignalProducer<AccessTokenEnvelope, ErrorEnvelope> /// Unfollow a user with their id. func unfollowFriend(userId id: Int) -> SignalProducer<VoidEnvelope, ErrorEnvelope> /// Updates a backing func updateBacking(input: UpdateBackingInput) -> SignalProducer<UpdateBackingEnvelope, GraphError> /// Update the project notification setting. func updateProjectNotification(_ notification: ProjectNotification) -> SignalProducer<ProjectNotification, ErrorEnvelope> /// Update the current user with settings attributes. func updateUserSelf(_ user: User) -> SignalProducer<User, ErrorEnvelope> /// Updates the draft of a project update. func update(draft: UpdateDraft, title: String, body: String, isPublic: Bool) -> SignalProducer<UpdateDraft, ErrorEnvelope> func unwatchProject(input: WatchProjectInput) -> SignalProducer<GraphMutationWatchProjectResponseEnvelope, GraphError> /// Verifies an email address with a given access token. func verifyEmail(withToken token: String) -> SignalProducer<EmailVerificationResponseEnvelope, ErrorEnvelope> func watchProject(input: WatchProjectInput) -> SignalProducer<GraphMutationWatchProjectResponseEnvelope, GraphError> } extension ServiceType { /// Returns `true` if an oauth token is present, and `false` otherwise. public var isAuthenticated: Bool { return self.oauthToken != nil } } public func == (lhs: ServiceType, rhs: ServiceType) -> Bool { return type(of: lhs) == type(of: rhs) && lhs.serverConfig == rhs.serverConfig && lhs.oauthToken == rhs.oauthToken && lhs.language == rhs.language && lhs.buildVersion == rhs.buildVersion } public func != (lhs: ServiceType, rhs: ServiceType) -> Bool { return !(lhs == rhs) } extension ServiceType { /** Prepares a URL request to be sent to the server. - parameter originalRequest: The request that should be prepared. - parameter query: Additional query params that should be attached to the request. - returns: A new URL request that is properly configured for the server. */ public func preparedRequest(forRequest originalRequest: URLRequest, query: [String: Any] = [:]) -> URLRequest { var request = originalRequest guard let URL = request.url else { return originalRequest } var headers = self.defaultHeaders let method = request.httpMethod?.uppercased() var components = URLComponents(url: URL, resolvingAgainstBaseURL: false)! var queryItems = components.queryItems ?? [] queryItems.append(contentsOf: self.defaultQueryParams.map(URLQueryItem.init(name:value:))) if method == .some("POST") || method == .some("PUT") { if request.httpBody == nil { headers["Content-Type"] = "application/json; charset=utf-8" request.httpBody = try? JSONSerialization.data(withJSONObject: query, options: []) } } else { queryItems.append( contentsOf: query .flatMap(self.queryComponents) .map(URLQueryItem.init(name:value:)) ) } components.queryItems = queryItems.sorted { $0.name < $1.name } request.url = components.url let currentHeaders = request.allHTTPHeaderFields ?? [:] request.allHTTPHeaderFields = currentHeaders.withAllValuesFrom(headers) return request } /** Prepares a request to be sent to the server. - parameter URL: The URL to turn into a request and prepare. - parameter method: The HTTP verb to use for the request. - parameter query: Additional query params that should be attached to the request. - returns: A new URL request that is properly configured for the server. */ public func preparedRequest(forURL url: URL, method: Method = .GET, query: [String: Any] = [:]) -> URLRequest { var request = URLRequest(url: url) request.httpMethod = method.rawValue return self.preparedRequest(forRequest: request, query: query) } /** Prepares a URL request to be sent to the server. - parameter originalRequest: The request that should be prepared. - parameter queryString: The GraphQL query string for the request. - returns: A new URL request that is properly configured for the server. */ public func preparedRequest(forRequest originalRequest: URLRequest, queryString: String) -> URLRequest { var request = originalRequest guard let URL = request.url else { return originalRequest } request.httpBody = "query=\(queryString)".data(using: .utf8) let components = URLComponents(url: URL, resolvingAgainstBaseURL: false)! request.url = components.url request.allHTTPHeaderFields = self.defaultHeaders return request } public func preparedRequest(forURL url: URL, queryString: String) -> URLRequest { var request = URLRequest(url: url) request.httpMethod = Method.POST.rawValue return self.preparedRequest(forRequest: request, queryString: queryString) } /** Prepares a URL request to be sent to the server. - parameter originalRequest: The request that should be prepared - parameter queryString: The GraphQL mutation string description - parameter input: The input for the mutation - returns: A new URL request that is properly configured for the server **/ public func preparedGraphRequest( forURL url: URL, queryString: String, input: [String: Any] ) throws -> URLRequest { var request = URLRequest(url: url) request.httpMethod = Method.POST.rawValue guard let URL = request.url else { return request } let requestBody = self.graphMutationRequestBody(mutation: queryString, input: input) let jsonData = try JSONSerialization.data(withJSONObject: requestBody, options: []) request.httpBody = jsonData var headers = self.defaultHeaders headers["Content-Type"] = "application/json; charset=utf-8" let components = URLComponents(url: URL, resolvingAgainstBaseURL: false)! request.url = components.url request.allHTTPHeaderFields = headers return request } public func isPrepared(request: URLRequest) -> Bool { return request.value(forHTTPHeaderField: "Authorization") == self.authorizationHeader && request.value(forHTTPHeaderField: "Kickstarter-iOS-App") != nil } fileprivate var defaultHeaders: [String: String] { var headers: [String: String] = [:] headers["Accept-Language"] = self.language headers["Authorization"] = self.authorizationHeader headers["Kickstarter-App-Id"] = self.appId headers["Kickstarter-iOS-App"] = self.buildVersion headers["User-Agent"] = Self.userAgent headers["X-KICKSTARTER-CLIENT"] = self.serverConfig.apiClientAuth.clientId headers["Kickstarter-iOS-App-UUID"] = self.deviceIdentifier return headers.withAllValuesFrom(self.pxHeaders) } // PerimeterX authorization header fileprivate var pxHeaders: [String: String] { return self.perimeterXClient?.headers() ?? [:] } func graphMutationRequestBody(mutation: String, input: [String: Any]) -> [String: Any] { return [ "query": mutation, "variables": ["input": input] ] } public static var userAgent: String { let executable = Bundle.main.infoDictionary?["CFBundleExecutable"] as? String let bundleIdentifier = Bundle.main.infoDictionary?["CFBundleIdentifier"] as? String let app: String = executable ?? bundleIdentifier ?? "Kickstarter" let bundleVersion: String = (Bundle.main.infoDictionary?["CFBundleVersion"] as? String) ?? "1" let model = UIDevice.current.model let systemVersion = UIDevice.current.systemVersion let scale = UIScreen.main.scale return "\(app)/\(bundleVersion) (\(model); iOS \(systemVersion) Scale/\(scale))" } fileprivate var authorizationHeader: String? { if let token = self.oauthToken?.token { return "token \(token)" } else { return self.serverConfig.basicHTTPAuth?.authorizationHeader } } fileprivate var defaultQueryParams: [String: String] { var query: [String: String] = [:] query["client_id"] = self.serverConfig.apiClientAuth.clientId query["currency"] = self.currency query["oauth_token"] = self.oauthToken?.token return query } fileprivate func queryComponents(_ key: String, _ value: Any) -> [(String, String)] { var components: [(String, String)] = [] if let dictionary = value as? [String: Any] { for (nestedKey, value) in dictionary { components += self.queryComponents("\(key)[\(nestedKey)]", value) } } else if let array = value as? [Any] { for value in array { components += self.queryComponents("\(key)[]", value) } } else { components.append((key, String(describing: value))) } return components } }
38.350365
108
0.741054
5d78f259748797294973cb01d702d6e6ddf8cadf
3,141
// // AppDelegate.swift // ZafeplaceSDK // // Created by Dmitriy Zhyzhko on 03.05.2018. // Copyright © 2018 Z4. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Set the window to the dimensions of the device self.window = UIWindow(frame: UIScreen.main.bounds) // Grab a reference to whichever storyboard you have the ViewController within let storyboard = UIStoryboard(name: "Main", bundle: nil) // Grab a reference to the ViewController you want to show 1st. var initialViewController = storyboard.instantiateViewController(withIdentifier: "ViewController") if UserDefaults.standard.integer(forKey: "pin") != 0 { initialViewController = storyboard.instantiateViewController(withIdentifier: "MainViewController") } // Set that ViewController as the rootViewController self.window?.rootViewController = initialViewController // Sets our window up in front self.window?.makeKeyAndVisible() let zafepalce = Zafeplace.default //Zafeplace.generateAccessToken(appId: "291377603636896", appSecret: "698940504ca9c2353f2494299926694f") return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
47.590909
285
0.731933
23096401fb7b85393d111aedef5bf5cc2c00d966
5,813
import Foundation final class Box { init<T>(value: T) { self.value = value } func wrap<T>(value: T) { self.value = value } func unwrap<T>() -> T? { return value as? T } private var value: Any } final class ReducerBox { init<S: State, A: Action>(reducer: @escaping Reducer<S, A>) { box = Box(value: reducer) perform = { box, state, action, observe in guard let reducer: Reducer<S, A> = box.unwrap() else { return [] } guard var state = state as? S else { return [] } guard let action = action as? A else { return [] } var effects: [Action] = [] switch try reducer(&state, action) { case .unmodified: break case let .modified(newState): try observe(newState) case let .effect(newState, action): try observe(newState) effects.append(action) case let .effects(newState, actions): try observe(newState) effects += actions } return effects } } func apply(state: State, action: Action, observe: (State) throws -> Void) throws -> [Action] { return try perform(box, state, action, observe) } private let box: Box private let perform: (Box, State, Action, (State) throws -> Void) throws -> [Action] } final class StateBox { init<S: State>(state: S) { box = Box(value: state) perform = { box, action, reducers, observers, middlewares in guard let state: S = box.unwrap() else { return [] } var effects: [Action] = [] for reducer in reducers { effects += try reducer.apply(state: state, action: action) { newState in guard var newState = newState as? S else { return } // State has changed box.wrap(value: newState) // Notify observers try observers.forEach { try $0.apply(state: newState, reason: .modified) } // Notify middlewares var changes = false try middlewares.forEach { if let state = try $0.apply(state: newState) { // State has changed again box.wrap(value: state) newState = state changes = true } } if changes { // Notify observers try observers.forEach { try $0.apply(state: newState, reason: .middleware) } } } } return effects } } func apply(action: Action, reducers: [ReducerBox], observers: [ObserverBox], middlewares: [MiddlewareBox]) throws -> [Action] { return try perform(box, action, reducers, observers, middlewares) } func apply<S: State>(observer: Observer<S>) throws { guard let state: S = box.unwrap() else { return } try observer(state, .subscribed) } private var box: Box private var perform: (Box, Action, [ReducerBox], [ObserverBox], [MiddlewareBox]) throws -> [Action] } /* final class MiddlewareBox { init(middleware: Middleware) { box = Box(value: middleware) } func apply(action: Action) throws { guard let middleware: Middleware = box.unwrap() else { return } if case let .action(f) = middleware { try f(action) } } func apply(state: State) throws -> State? { guard let middleware: Middleware = box.unwrap() else { return nil } if case let .state(f) = middleware { return try f(state) } return nil } private var box: Box } */ final class MiddlewareBox { init(_ f: @escaping (Action) throws -> [Action]) { perform = { action, _ in guard let action = action else { return (nil, nil) } return (nil, try f(action)) } } init<S: State>(_ f: @escaping (inout S) throws -> Reduction<S>) { perform = { action, state in guard var newState = state as? S else { return (nil, nil) } switch try f(&newState) { case .unmodified: return (nil, nil) case let .effect(newState, _): return (newState, nil) case let .modified(newState): return (newState, nil) case let .effects(newState, _): return (newState, nil) } } } func apply(action: Action) throws -> [Action] { guard let actions = try perform(action, nil).1 else { return [] } return actions } func apply<S: State>(state: S) throws -> S? { guard let state = try perform(nil, state).0 as? S else { return nil } return state } private var perform: (Action?, State?) throws -> (State?, [Action]?) } final class ObserverBox { let priority: Priority init<S: State>(priority: Priority, observer: @escaping Observer<S>) { self.priority = priority box = Box(value: observer) } func apply<S: State>(state: S, reason: Reason) throws { guard let observer: Observer<S> = box.unwrap() else { return } try observer(state, reason) } func apply<S: State>(state: S) throws { guard let observer: Observer<S> = box.unwrap() else { return } try observer(state, .subscribed) } private var box: Box }
32.294444
131
0.512472
4abffc41788f0cb848059c26daf0cd6bd6b5ccbe
9,856
/* Copyright (c) 2019, Apple Inc. 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 CoreData import Foundation extension OCKStore { public func fetchCarePlans(_ anchor: OCKCarePlanAnchor? = nil, query: OCKCarePlanQuery? = nil, queue: DispatchQueue = .main, completion: @escaping (Result<[OCKCarePlan], OCKStoreError>) -> Void) { context.perform { do { let predicate = try self.buildPredicate(for: anchor, query: query) let persistedPlans = OCKCDCarePlan.fetchFromStore(in: self.context, where: predicate) { fetchRequest in fetchRequest.fetchLimit = query?.limit ?? 0 fetchRequest.fetchOffset = query?.offset ?? 0 fetchRequest.sortDescriptors = self.buildSortDescriptors(from: query) } let plans = persistedPlans.map(self.makePlan) queue.async { completion(.success(plans)) } } catch { self.context.rollback() queue.async { completion(.failure(.fetchFailed(reason: "Building predicate failed: \(error.localizedDescription)"))) } } } } public func addCarePlans(_ plans: [OCKCarePlan], queue: DispatchQueue = .main, completion: ((Result<[OCKCarePlan], OCKStoreError>) -> Void)? = nil) { context.perform { do { try OCKCDCarePlan.validateNewIdentifiers(plans.map { $0.identifier }, in: self.context) let persistablePlans = plans.map { self.addCarePlan($0) } try self.context.save() let addedPlans = persistablePlans.map(self.makePlan) queue.async { self.delegate?.store(self, didAddCarePlans: addedPlans) completion?(.success(addedPlans)) } } catch { self.context.rollback() queue.async { completion?(.failure(.addFailed(reason: "Failed to add OCKCarePlans: [\(plans)]. \(error.localizedDescription)"))) } } } } public func updateCarePlans(_ plans: [OCKCarePlan], queue: DispatchQueue = .main, completion: ((Result<[OCKCarePlan], OCKStoreError>) -> Void)? = nil) { context.perform { do { let identifiers = plans.map { $0.identifier } try OCKCDCarePlan.validateUpdateIdentifiers(identifiers, in: self.context) let updatedPlans = self.configuration.updatesCreateNewVersions ? try self.performVersionedUpdate(values: plans, addNewVersion: self.addCarePlan) : try self.performUnversionedUpdate(values: plans, update: self.copyPlan) try self.context.save() let plans = updatedPlans.map(self.makePlan) queue.async { self.delegate?.store(self, didUpdateCarePlans: plans) completion?(.success(updatedPlans.map(self.makePlan))) } } catch { self.context.rollback() queue.async { completion?(.failure(.updateFailed(reason: "Failed to update OCKCarePlans: \(plans). \(error.localizedDescription)"))) } } } } public func deleteCarePlans(_ plans: [OCKCarePlan], queue: DispatchQueue = .main, completion: ((Result<[OCKCarePlan], OCKStoreError>) -> Void)? = nil) { context.perform { do { let deletedPlans = try self.performUnversionedUpdate(values: plans) { _, persistablePlan in persistablePlan.deletedAt = Date() }.map(self.makePlan) try self.context.save() queue.async { self.delegate?.store(self, didDeleteCarePlans: deletedPlans) completion?(.success(deletedPlans)) } } catch { self.context.rollback() queue.async { completion?(.failure(.deleteFailed(reason: "Failed to update OCKCarePlans: [\(plans)]. \(error.localizedDescription)"))) } } } } // MARK: Private /// - Remark: This does not commit the transaction. After calling this function one or more times, you must call `context.save()` in order to /// persist the changes to disk. This is an optimization to allow batching. /// - Remark: You should verify that the object does not already exist in the database and validate its values before calling this method. private func addCarePlan(_ plan: OCKCarePlan) -> OCKCDCarePlan { let persistablePlan = OCKCDCarePlan(context: context) copyPlan(plan, to: persistablePlan) return persistablePlan } /// - Remark: This method is intended to create a value type struct from a *persisted* NSManagedObject. Calling this method with an /// object that is not yet commited is a programmer error. private func makePlan(from object: OCKCDCarePlan) -> OCKCarePlan { assert(object.versionID != nil, "Don't this method with an object that isn't saved yet") var plan = OCKCarePlan(identifier: object.identifier, title: object.title, patientID: object.patient?.versionID) plan.copyVersionedValues(from: object) return plan } private func copyPlan(_ plan: OCKCarePlan, to object: OCKCDCarePlan) { object.copyVersionInfo(from: plan) object.allowsMissingRelationships = allowsEntitiesWithMissingRelationships object.title = plan.title if let patientId = plan.patientID { object.patient = try? fetchObject(havingLocalID: patientId) } } private func buildPredicate(for anchor: OCKCarePlanAnchor?, query: OCKCarePlanQuery?) throws -> NSPredicate { return NSCompoundPredicate(andPredicateWithSubpredicates: [ try buildSubPredicate(for: anchor), buildSubPredicate(for: query), NSPredicate(format: "%K == nil", #keyPath(OCKCDVersionedObject.deletedAt)) ]) } private func buildSubPredicate(for anchor: OCKCarePlanAnchor?) throws -> NSPredicate { guard let anchor = anchor else { return NSPredicate(value: true) } switch anchor { case .carePlanIdentifiers(let planIdentifiers): return NSPredicate(format: "%K IN %@", #keyPath(OCKCDVersionedObject.identifier), planIdentifiers) case .carePlanVersions(let planVersionIDs): return NSPredicate(format: "self IN %@", try planVersionIDs.map(objectID)) case .patientVersions(let patientVersionIDs): return NSPredicate(format: "%K IN %@", #keyPath(OCKCDCarePlan.patient), try patientVersionIDs.map(objectID)) case .patientIdentifiers(let patientIdentifiers): return NSPredicate(format: "%K IN %@", #keyPath(OCKCDCarePlan.patient.identifier), patientIdentifiers) } } private func buildSubPredicate(for query: OCKCarePlanQuery? = nil) -> NSPredicate { var predicate = NSPredicate(value: true) if let interval = query?.dateInterval { let datePredicate = OCKCDVersionedObject.newestVersionPredicate(in: interval) predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [predicate, datePredicate]) } if let groupIdentifiers = query?.groupIdentifiers { predicate = predicate.including(groupIdentifiers: groupIdentifiers) } if let tags = query?.tags { predicate = predicate.including(tags: tags) } return predicate } private func buildSortDescriptors(from query: OCKCarePlanQuery?) -> [NSSortDescriptor] { guard let orders = query?.sortDescriptors else { return [] } return orders.map { order -> NSSortDescriptor in switch order { case .effectiveAt(let ascending): return NSSortDescriptor(keyPath: \OCKCDCarePlan.effectiveAt, ascending: ascending) case .title(let ascending): return NSSortDescriptor(keyPath: \OCKCDCarePlan.title, ascending: ascending) } } } }
49.034826
145
0.644176
7aca903d63f61ac7844c4cda590ac17661cf509a
901
// // MainListViewModel.swift // Shakespeare (iOS) // // Created by Roschaun Johnson on 7/31/21. // import Foundation import Combine class MainListViewModel: ViewModel { @Published var listViewState = ListViewState() func getQuoteReviews() { listViewState.isLoading = true cancellationToken = networkRepository.getQuoteReviews() .mapError({ [weak self] (error) -> Error in self?.listViewState.showError = true self?.listViewState.isLoading = false return error }) .sink(receiveCompletion: { _ in }, receiveValue: { [weak self] reviews in self?.listViewState = ListViewStateReducer.reduceToState(reviews) self?.listViewState.isLoading = false self?.listViewState.showError = false }) } }
30.033333
85
0.589345
486fff634e0bdbfedcd988390fdbbcfa6707242c
2,245
// // BackupViewController.swift // xdag-ios // // Created by yangyin on 2018/8/26. // Copyright © 2018年 xdag.org. All rights reserved. // import UIKit import Telegraph class BackupViewController: UIViewController { var httpServer:Server! @IBOutlet weak var httpUrlLabel: UIButton! override func viewDidLoad() { super.viewDidLoad() let reachability = Reachability()! if (reachability.connection == .wifi) { initHttpServer() } // Do any additional setup after loading the view. } @IBAction func copyUrl(_ sender: Any) { UIPasteboard.general.string = httpUrlLabel.titleLabel?.text self.noticeSuccess("copy success!", autoClear: true,autoClearTime:1) } func initHttpServer() { httpServer = Server() let documentsDirectory = FileManager.default.urls(for:.documentDirectory, in: .userDomainMask)[0] httpServer.serveDirectory(documentsDirectory) try! httpServer.start(onPort: 8099) httpUrlLabel.setTitle("http://\(Util.GetIPAddresses()!):\(httpServer.port)/wallet.zip", for: UIControlState.normal) } @IBAction func closeView(_ sender: Any) { self.dismiss(animated: true, completion: nil) } override func viewWillAppear(_ animated: Bool) { UIApplication.shared.statusBarStyle = .lightContent } override func viewWillDisappear(_ animated: Bool) { UIApplication.shared.statusBarStyle = .default if (httpServer != nil) { httpServer.stop() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } /* // 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. } */ }
28.0625
123
0.647216
790e17bbb7f3ca8193dcafbe2d8384c5d5db1e2a
5,102
// // RNGoogleSignIn.swift // // Created by Joon Ho Cho on 1/16/17. // Copyright © 2017 Facebook. All rights reserved. // import Foundation @objc(RNGoogleSignIn) class RNGoogleSignIn: NSObject, GIDSignInUIDelegate { static let sharedInstance = RNGoogleSignIn() weak var events: RNGoogleSignInEvents? override init() { super.init() GIDSignIn.sharedInstance().uiDelegate = self } // @objc func addEvent(_ name: String, location: String, date: NSNumber, callback: @escaping (Array<String>) -> ()) -> Void { // NSLog("%@ %@ %@", name, location, date) // self.callback = callback // } @objc func configureGIDSignIn() { if let filePath = Bundle.main.path(forResource: "GoogleService-Info", ofType: "plist") { if let plistDict = NSDictionary(contentsOfFile: filePath) { if let clientID = plistDict["CLIENT_ID"] as? String { GIDSignIn.sharedInstance().clientID = clientID } else { print("RNGoogleSignIn Error: CLIENT_ID is invalid in GoogleService-Info.plist") } } else { print("RNGoogleSignIn Error: GoogleService-Info.plist is malformed") } } else { print("RNGoogleSignIn Error: GoogleService-Info.plist not found") } } @objc func configure(_ config: [String: Any]) { if let instance = GIDSignIn.sharedInstance() { if let clientID = config["clientID"] as? String { instance.clientID = clientID } if let scopes = config["scopes"] as? [String] { instance.scopes = scopes } if let shouldFetchBasicProfile = config["shouldFetchBasicProfile"] as? Bool { instance.shouldFetchBasicProfile = shouldFetchBasicProfile } if let language = config["language"] as? String { instance.language = language } if let loginHint = config["loginHint"] as? String { instance.loginHint = loginHint } if let serverClientID = config["serverClientID"] as? String { instance.serverClientID = serverClientID } if let openIDRealm = config["openIDRealm"] as? String { instance.openIDRealm = openIDRealm } if let hostedDomain = config["hostedDomain"] as? String { instance.hostedDomain = hostedDomain } } } @objc func signIn() { DispatchQueue.main.async { GIDSignIn.sharedInstance().signIn() } } @objc func signOut(_ resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { GIDSignIn.sharedInstance().signOut() if GIDSignIn.sharedInstance().currentUser == nil { resolve(nil) } else { reject("SignOutFailed", "Failed to sign out", nil) } } @objc func signInSilently() { DispatchQueue.main.async { GIDSignIn.sharedInstance().signInSilently() } } @objc func disconnect() { DispatchQueue.main.async { GIDSignIn.sharedInstance().disconnect() } } @objc func currentUser(_ resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { resolve(RNGoogleSignInEvents.userToJSON(GIDSignIn.sharedInstance().currentUser)) } @objc func hasAuthInKeychain(_ resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { resolve(GIDSignIn.sharedInstance().hasAuthInKeychain()) } @objc func constantsToExport() -> [String: Any] { return [ "dark": "dark", "light": "light", "iconOnly": "iconOnly", "standard": "standard", "wide": "wide", "ErrorCode": [ "unknown": GIDSignInErrorCode.unknown.rawValue, "keychain": GIDSignInErrorCode.keychain.rawValue, "noSignInHandlersInstalled": GIDSignInErrorCode.noSignInHandlersInstalled.rawValue, "hasNoAuthInKeychain": GIDSignInErrorCode.hasNoAuthInKeychain.rawValue, "canceled": GIDSignInErrorCode.canceled.rawValue, ], ] } // START: GIDSignInUIDelegate func sign(inWillDispatch signIn: GIDSignIn!, error: Error?) { events?.dispatch(error: error) } func sign(_ signIn: GIDSignIn!, dismiss viewController: UIViewController!) { viewController.dismiss(animated: true, completion: nil) } func sign(_ signIn: GIDSignIn!, present viewController: UIViewController!) { let _ = present(viewController: viewController) } func getTopViewController(window: UIWindow?) -> UIViewController? { if let window = window { var top = window.rootViewController while true { if let presented = top?.presentedViewController { top = presented } else if let nav = top as? UINavigationController { top = nav.visibleViewController } else if let tab = top as? UITabBarController { top = tab.selectedViewController } else { break } } return top } return nil } func present(viewController: UIViewController) -> Bool { if let topVc = getTopViewController(window: UIApplication.shared.keyWindow) { topVc.present(viewController, animated: true, completion: nil) return true } return false } // END: GIDSignInUIDelegate }
30.189349
128
0.656605
d661f9c1d2671a870afe03aae7164cb3671cb881
5,673
/* SmartcarAuth.swift SmartcarAuth Copyright (c) 2017-present, Smartcar, Inc. All rights reserved. You are hereby granted a limited, non-exclusive, worldwide, royalty-free license to use, copy, modify, and distribute this software in source code or binary form, for the limited purpose of this software's use in connection with the web services and APIs provided by Smartcar. As with any software that integrates with the Smartcar platform, your use of this software is subject to the Smartcar Developer Agreement. This copyright notice shall be included in all copies or substantial portions of the software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import UIKit import SafariServices let domain = "connect.smartcar.com" /** Smartcar Authentication SDK for iOS written in Swift 3. - Facilitates the flow with a SFSafariViewController to redirect to Smartcar and retrieve an authorization code */ public class SmartcarAuth: NSObject { var clientId: String var redirectUri: String var scope: [String] var completion: (Error?, String?, String?) -> Any? var development: Bool /** Constructor for the SmartcarAuth - parameters: - clientId: app client id - redirectUri: app redirect uri - scope: app oauth scope - development: optional, shows the mock OEM for testing, defaults to false - completion: callback function called upon the completion of the OAuth flow with the error, the auth code, and the state string */ public init(clientId: String, redirectUri: String, scope: [String] = [], development: Bool = false, completion: @escaping (Error?, String?, String?) -> Any?) { self.clientId = clientId self.redirectUri = redirectUri self.scope = scope self.completion = completion self.development = development } /** Presents a SFSafariViewController with the initial authorization url - parameters: - state: optional, oauth state - forcePrompt: optional, forces permission screen if set to true, defaults to false - viewController: the viewController responsible for presenting the SFSafariView */ public func launchAuthFlow(state: String? = nil, forcePrompt: Bool = false, viewController: UIViewController) { let safariVC = SFSafariViewController(url: URL(string: generateUrl(state: state, forcePrompt: forcePrompt))!) viewController.present(safariVC, animated: true, completion: nil) } /** Generates the authorization request URL from the authorization parameters - parameters: - state: optional, oauth state - forcePrompt: optional, forces permission screen if set to true, defaults to false - returns: authorization request URL */ public func generateUrl(state: String? = nil, forcePrompt: Bool = false) -> String { var components = URLComponents(string: "https://\(domain)/oauth/authorize")! var queryItems: [URLQueryItem] = [] queryItems.append(URLQueryItem(name: "response_type", value: "code")) queryItems.append(URLQueryItem(name: "client_id", value: self.clientId)) if let redirectUri = self.redirectUri.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) { queryItems.append(URLQueryItem(name: "redirect_uri", value: redirectUri)) } if !scope.isEmpty { if let scopeString = self.scope.joined(separator: " ").addingPercentEncoding( withAllowedCharacters: .urlQueryAllowed) { queryItems.append(URLQueryItem(name: "scope", value: scopeString)) } } queryItems.append(URLQueryItem(name: "approval_prompt", value: forcePrompt ? "force" : "auto")) if let stateString = state?.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) { queryItems.append(URLQueryItem(name: "state", value: stateString)) } queryItems.append(URLQueryItem(name: "mock", value: String(self.development))) components.queryItems = queryItems return components.url!.absoluteString } /** Authorization callback function. Verifies that no error occured during the OAuth process and extracts the auth code and state string. Invokes the completion function with the appropriate parameters. - parameters: - url: callback URL containing authorization code - returns: the output of the executed completion function */ public func handleCallback(with url: URL) -> Any? { let urlComp = URLComponents(url: url, resolvingAgainstBaseURL: false) guard let query = urlComp?.queryItems else { return completion(AuthorizationError.missingQueryParameters, nil, nil) } let queryState = query.filter({ $0.name == "state"}).first?.value if query.filter({ $0.name == "error"}).first?.value != nil { return completion(AuthorizationError.accessDenied, nil, queryState) } guard let code = query.filter({ $0.name == "code"}).first?.value else { return completion(AuthorizationError.missingAuthCode, nil, queryState) } return completion(nil, code, queryState) } }
38.856164
202
0.69963
ef0cc42c0e2c0a3766029e003cd10886d2f94047
140
import Bugsnag public enum CrashReporter { public static func initialize() { Bugsnag.start(withApiKey: Secrets.Bugsnag.apiKey) } }
17.5
53
0.742857
010bbe2409670df9dd633d29cb972eb620c1292b
1,899
// From: https://github.com/myfreeweb/SwiftCBOR // License: Public Domain import Foundation public class CodableCBOREncoder { public init() {} public func encode(_ value: Encodable) throws -> Data { let encoder = _CBOREncoder() if let dateVal = value as? Date { return Data(CBOR.encodeDate(dateVal)) } else if let dataVal = value as? Data { return Data(CBOR.encodeData(dataVal)) } try value.encode(to: encoder) return encoder.data } } final class _CBOREncoder { var codingPath: [CodingKey] = [] var userInfo: [CodingUserInfoKey : Any] = [:] fileprivate var container: CBOREncodingContainer? { willSet { precondition(self.container == nil) } } var data: Data { return container?.data ?? Data() } } extension _CBOREncoder: Encoder { fileprivate func assertCanCreateContainer() { precondition(self.container == nil) } func container<Key: CodingKey>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> { assertCanCreateContainer() let container = KeyedContainer<Key>(codingPath: self.codingPath, userInfo: self.userInfo) self.container = container return KeyedEncodingContainer(container) } func unkeyedContainer() -> UnkeyedEncodingContainer { assertCanCreateContainer() let container = UnkeyedContainer(codingPath: self.codingPath, userInfo: self.userInfo) self.container = container return container } func singleValueContainer() -> SingleValueEncodingContainer { assertCanCreateContainer() let container = SingleValueContainer(codingPath: self.codingPath, userInfo: self.userInfo) self.container = container return container } } protocol CBOREncodingContainer: class { var data: Data { get } }
26.013699
98
0.656135
11753c2b3b67f6742482986a41a9507db4dd0b7a
831
//// // 🦠 Corona-Warn-App // import Foundation import HealthCertificateToolkit extension Name { var fullName: String { var givenName = self.givenName var familyName = self.familyName if givenName == nil || givenName?.trimmingCharacters(in: .whitespacesAndNewlines) == "" { givenName = standardizedGivenName } if familyName == nil || familyName?.trimmingCharacters(in: .whitespacesAndNewlines) == "" { familyName = standardizedFamilyName } return [givenName, familyName] .compactMap { $0 } .filter { $0.trimmingCharacters(in: .whitespacesAndNewlines) != "" } .joined(separator: " ") } var standardizedName: String { [standardizedGivenName, standardizedFamilyName] .compactMap { $0 } .filter { $0.trimmingCharacters(in: .whitespacesAndNewlines) != "" } .joined(separator: " ") } }
23.083333
93
0.695548
e4d17c0fe7dc95582e8739d74dc12c64a1905036
776
// // InstructionsViewController.swift // TrashProject // // Created by Jack Palevich on 8/9/18. // Copyright © 2018 Sydrah Al-saegh. All rights reserved. // import UIKit class InstructionsViewController: UIViewController { @IBOutlet weak var textView: UITextView! override func viewDidLoad() { super.viewDidLoad() if let aboutPath = Bundle.main.path(forResource: "Instructions", ofType: "html") { if let aboutData = NSData(contentsOfFile: aboutPath) { do { try textView.attributedText = NSAttributedString( data: aboutData as Data, options:[.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) } catch { // Do nothing. } } } } }
23.515152
86
0.643041
16c1dc09ca80fdaea82c4f32f157ec7e40cb5213
1,495
// // ViewController.swift // TrueVolumeControls // // Created by wizage on 5/4/16. // Copyright © 2016 wizage. All rights reserved. // import UIKit import MediaPlayer class ViewController: UIViewController { @IBOutlet weak var label : UILabel! override func viewDidLoad() { super.viewDidLoad() let vc = VolumeControl.sharedInstance /* This dispatch after is because the application is adding the volume control and not allowing enought time for the system to get the actual volume so it returns 0.0 which is incorrect. */ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.01*Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { self.label.text = String(format: "Current Volume: %.3f", vc.getCurrentVolume()) } // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func turnUp() { let vc = VolumeControl.sharedInstance vc.turnUp() label.text = String(format: "Current Volume: %.3f", vc.getCurrentVolume()) } @IBAction func turnDown() { let vc = VolumeControl.sharedInstance vc.turnDown() label.text = String(format: "Current Volume: %.3f", vc.getCurrentVolume()) } }
26.696429
117
0.6301
18422e60979e74f76e339567f8d1392b73cb5a05
2,330
/* Copyright (c) 2021, Hippocrates Technologies S.r.l.. 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 contributor(s) 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. 4. Commercial redistribution in any form requires an explicit license agreement with the copyright holder(s). Please contact [email protected] for further information regarding licensing. 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 SwiftUI extension Font { static var basicFontStyle: Font { return .system(size: 20, weight: .regular, design: .default) } static var subHeaderFontStyle: Font { return .system(size: 20, weight: .bold, design: .default) } static var headerFontStyle: Font { return .system(size: 25, weight: .bold, design: .default) } static var titleFontStyle: Font { return .system(size: 35, weight: .bold, design: .default) } }
40.877193
88
0.770386
c176431c6e549d57ef4c21f447981d0de7fea9dc
1,635
// // UIViewController+Helpers.swift // OnionBrowser2 // // Created by Benjamin Erhart on 16.12.19. // Copyright (c) 2012-2019, Tigas Ventures, LLC (Mike Tigas) // // This file is part of Onion Browser. See LICENSE file for redistribution terms. // import Foundation extension UIViewController { public var top: UIViewController { if let vc = subViewController { return vc.top } return self } public var subViewController: UIViewController? { if let vc = self as? UINavigationController { return vc.topViewController } if let vc = self as? UISplitViewController { return vc.viewControllers.last } if let vc = self as? UITabBarController { return vc.selectedViewController } if let vc = presentedViewController { return vc } return nil } /** Presents a view controller modally animated. Does it as a popover, when a `sender` object is provided. - parameter vc: The view controller to present. - parameter sender: The `UIView` with which the user triggered this operation. */ func present(_ vc: UIViewController, _ sender: UIView? = nil) { if let sender = sender { vc.modalPresentationStyle = .popover vc.popoverPresentationController?.sourceView = sender.superview vc.popoverPresentationController?.sourceRect = sender.frame if let delegate = vc as? UIPopoverPresentationControllerDelegate { vc.popoverPresentationController?.delegate = delegate } } present(vc, animated: true) } }
25.153846
82
0.654434
0afa54c294865a5a9b994011f76518b7878d82c5
207
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing {{ let:d<c} class d{class case c,let f
25.875
87
0.753623
26e131e09f457af7c7cee4e433e3dd6972a770e8
1,250
// // AssessmentQuestionScore.swift // // Generated by swagger-codegen // https://github.com/swagger-api/swagger-codegen // import Foundation public class AssessmentQuestionScore: Codable { /** True if this was a failed Kill question */ public var failedKillQuestion: Bool? /** Comments provided for the answer */ public var comments: String? /** The ID of the question */ public var questionId: String? /** The ID of the selected answer */ public var answerId: String? /** The score received for this question */ public var score: Int? /** True if this question was marked as NA */ public var markedNA: Bool? /** Answer for free text answer type */ public var freeTextAnswer: String? public init(failedKillQuestion: Bool?, comments: String?, questionId: String?, answerId: String?, score: Int?, markedNA: Bool?, freeTextAnswer: String?) { self.failedKillQuestion = failedKillQuestion self.comments = comments self.questionId = questionId self.answerId = answerId self.score = score self.markedNA = markedNA self.freeTextAnswer = freeTextAnswer } }
25
158
0.6352
1c02c103184b83113ef1b48f6bd24d9713a74a08
532
// // UILabelExtensions.swift // VelocityRaptorCore // // Created by Nicholas Bonatsakis on 7/22/20. // Copyright © 2020 Velocity Raptor Incorporated All rights reserved. // import UIKit public extension UILabel { // Font reference; https://gist.github.com/zacwest/916d31da5d03405809c4 convenience init(labelText: String?, textStyle: UIFont.TextStyle) { self.init() font = .preferredFont(forTextStyle: textStyle) textColor = .label text = labelText numberOfLines = 0 } }
22.166667
75
0.680451
db72cf9012ee91212a04b712ba90726b9ad73f40
410
// // ContentView.swift // AppL10n // // Created by Rafael Fernandez Alvarez on 19/10/20. // Copyright © 2020 Rafael Fernandez Alvarez. All rights reserved. // import SwiftUI struct ContentView: View { var body: some View { Text("Hello, world!") .padding() } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
17.826087
67
0.636585
bfaf322d93dc449772caa7e0f53a447999660787
2,392
// // ExScrollView.swift // Swift-Extensionn // // Created by Anand Nimje on 27/01/18. // Copyright © 2018 Anand. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit extension UIScrollView { // Scroll to a specific view so that it's top is at the top our scrollview func scrollToView(view:UIView, animated: Bool) { if let origin = view.superview { UIView.animate(withDuration: 0.4, animations: { // Get the Y position of your child view let childStartPoint = origin.convert(view.frame.origin, to: self) // Scroll to a rectangle starting at the Y of your subview, with a height of the scrollview self.scrollRectToVisible(CGRect(x:0, y:childStartPoint.y, width:1, height:self.frame.height), animated: animated) }) } } // Bonus: Scroll to top func scrollToTop(animated: Bool) { let topOffset = CGPoint(x: 0, y: -contentInset.top) setContentOffset(topOffset, animated: animated) } // Bonus: Scroll to bottom func scrollToBottom() { let bottomOffset = CGPoint(x: 0, y: contentSize.height - bounds.size.height + contentInset.bottom) if(bottomOffset.y > 0) { setContentOffset(bottomOffset, animated: true) } } }
41.241379
129
0.686037
e0edbd3e301594ef1f5d13dc36634314d9472452
8,541
// Document.swift // Copyright (c) 2015 Ce Zheng // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import libxml2 /// XML document which can be searched and queried. open class XMLDocument { // MARK: - Document Attributes /// The XML version. open fileprivate(set) lazy var version: String? = { return ^-^self.cDocument.pointee.version }() /// The string encoding for the document. This is NSUTF8StringEncoding if no encoding is set, or it cannot be calculated. open fileprivate(set) lazy var encoding: String.Encoding = { if let encodingName = ^-^self.cDocument.pointee.encoding { let encoding = CFStringConvertIANACharSetNameToEncoding(encodingName as CFString?) if encoding != kCFStringEncodingInvalidId { return String.Encoding(rawValue: UInt(CFStringConvertEncodingToNSStringEncoding(encoding))) } } return String.Encoding.utf8 }() // MARK: - Accessing the Root Element /// The root element of the document. open fileprivate(set) var root: XMLElement? // MARK: - Accessing & Setting Document Formatters /// The formatter used to determine `numberValue` for elements in the document. By default, this is an `NSNumberFormatter` instance with `NSNumberFormatterDecimalStyle`. open lazy var numberFormatter: NumberFormatter = { let formatter = NumberFormatter() formatter.numberStyle = .decimal return formatter }() /// The formatter used to determine `dateValue` for elements in the document. By default, this is an `NSDateFormatter` instance configured to accept ISO 8601 formatted timestamps. open lazy var dateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.locale = Locale(identifier: "en_US_POSIX") formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ" return formatter }() // MARK: - Creating XML Documents internal let cDocument: xmlDocPtr /** Creates and returns an instance of XMLDocument from an XML string, throwing XMLError if an error occured while parsing the XML. - parameter string: The XML string. - parameter encoding: The string encoding. - throws: `XMLError` instance if an error occurred - returns: An `XMLDocument` with the contents of the specified XML string. */ public convenience init(string: String, encoding: String.Encoding = String.Encoding.utf8) throws { guard let cChars = string.cString(using: encoding) else { throw XMLError.invalidData } try self.init(cChars: cChars) } /** Creates and returns an instance of XMLDocument from XML data, throwing XMLError if an error occured while parsing the XML. - parameter data: The XML data. - throws: `XMLError` instance if an error occurred - returns: An `XMLDocument` with the contents of the specified XML string. */ public convenience init(data: Data) throws { let buffer = data.withUnsafeBytes { $0.bindMemory(to: Int8.self) } try self.init(buffer: buffer) } /** Creates and returns an instance of XMLDocument from C char array, throwing XMLError if an error occured while parsing the XML. - parameter cChars: cChars The XML data as C char array - throws: `XMLError` instance if an error occurred - returns: An `XMLDocument` with the contents of the specified XML string. */ public convenience init(cChars: [CChar]) throws { let buffer: UnsafeBufferPointer<CChar> = cChars.withUnsafeBufferPointer { (buffer) -> UnsafeBufferPointer<CChar> in return UnsafeBufferPointer(rebasing: buffer[0 ..< buffer.count]) } try self.init(buffer: buffer) } /** Creates and returns an instance of XMLDocument from C char buffer, throwing XMLError if an error occured while parsing the XML. - parameter buffer: The XML data as C char buffer - throws: `XMLError` instance if an error occurred - returns: An `XMLDocument` with the contents of the specified XML string. */ public convenience init(buffer: UnsafeBufferPointer<Int8>) throws { let options = Int32(XML_PARSE_NOWARNING.rawValue | XML_PARSE_NOERROR.rawValue | XML_PARSE_RECOVER.rawValue) try self.init(buffer: buffer, options: options) } fileprivate convenience init(buffer: UnsafeBufferPointer<Int8>, options: Int32) throws { guard let document = type(of: self).parse(buffer: buffer, options: options) else { throw XMLError.lastError(defaultError: .parserFailure) } xmlResetLastError() self.init(cDocument: document) } fileprivate class func parse(buffer: UnsafeBufferPointer<Int8>, options: Int32) -> xmlDocPtr? { return xmlReadMemory(buffer.baseAddress, Int32(buffer.count), "", nil, options) } fileprivate init(cDocument: xmlDocPtr) { self.cDocument = cDocument if let cRoot = xmlDocGetRootElement(cDocument) { root = XMLElement(cNode: cRoot, document: self) } } deinit { xmlFreeDoc(cDocument) } // MARK: - XML Namespaces var namespaces = [String: String]() // prefix -> URI /** Defines a new prefix for the given namespace in XPath expressions. - parameter prefix: The prefix name - parameter ns: The namespace URI declared in the XML Document */ open func definePrefix(_ prefix: String, forNamespace ns: String) { namespaces[prefix] = ns } /** Define a prefix for a default namespace. - parameter prefix: The prefix name - parameter ns: The default namespace URI that declared in XML Document */ @available(*, deprecated, renamed: "definePrefix(_:forNamespace:)", message: "This API will be removed in version 4.") open func definePrefix(_ prefix: String, defaultNamespace ns: String) { definePrefix(prefix, forNamespace: ns) } } extension XMLDocument: Equatable {} /** Determine whether two documents are the same - parameter lhs: XMLDocument on the left - parameter rhs: XMLDocument on the right - returns: whether lhs and rhs are equal */ public func ==(lhs: XMLDocument, rhs: XMLDocument) -> Bool { return lhs.cDocument == rhs.cDocument } /// HTML document which can be searched and queried. open class HTMLDocument: XMLDocument { // MARK: - Convenience Accessors /// HTML title of current document open var title: String? { return root?.firstChildElement(tag: "head")?.firstChildElement(tag: "title")?.stringValue } /// HTML head element of current document open var head: XMLElement? { return root?.firstChildElement(tag: "head") } /// HTML body element of current document open var body: XMLElement? { return root?.firstChildElement(tag: "body") } fileprivate override class func parse(buffer: UnsafeBufferPointer<Int8>, options: Int32) -> xmlDocPtr? { return htmlReadMemory(buffer.baseAddress, Int32(buffer.count), "", nil, options) } } // MARK: Element Creation extension HTMLDocument { open func createElement(withTag tag: String) -> XMLElement { return XMLElement(cNode: xmlNewDocNode(self.cDocument, nil, tag, nil), document: self) } }
38.647059
183
0.679429
dd67c27706d25734c3725a4bdeb2f43f4c03e600
3,372
// // CastlePics.swift // iOS Workshop App // // Created by Elysia Lock on 7/13/19. // Copyright © 2019 Elysia Lock. All rights reserved. // import UIKit struct Item { var imageName: String } class CastlePics: UIViewController { @IBOutlet weak var castleCollectionView: UICollectionView! var items: [Item] = [Item(imageName: "castle1"), Item(imageName: "castle2"), Item(imageName: "castle3"), Item(imageName: "castle4"), Item(imageName: "castle5"), Item(imageName: "castle6"), Item(imageName: "castle7"), Item(imageName: "castle8"), Item(imageName: "castle9"), Item(imageName: "castle10"), Item(imageName: "castle11"), Item(imageName: "castle12")] var collectionViewFlowLayout: UICollectionViewFlowLayout! let cellIdentifier = "CastleCollectionViewCell" override func viewDidLoad() { super.viewDidLoad() setupCollectionView() } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() setupCollectionViewItemsSize() } private func setupCollectionView() { castleCollectionView.delegate = self castleCollectionView.dataSource = self let nib = UINib(nibName: "CastleCollectionViewCell", bundle: nil) castleCollectionView.register(nib, forCellWithReuseIdentifier: cellIdentifier) } private func setupCollectionViewItemsSize() { if collectionViewFlowLayout == nil { let numberOfItemsPerRow: CGFloat = 3 let lineSpacing: CGFloat = 5 let interItemSpacing: CGFloat = 5 let width = (castleCollectionView.frame.width - (numberOfItemsPerRow - 1) * interItemSpacing) / numberOfItemsPerRow let height = width collectionViewFlowLayout = UICollectionViewFlowLayout() collectionViewFlowLayout.itemSize = CGSize(width: width, height: height) collectionViewFlowLayout.sectionInset = UIEdgeInsets.zero collectionViewFlowLayout.scrollDirection = .vertical collectionViewFlowLayout.minimumLineSpacing = lineSpacing collectionViewFlowLayout.minimumInteritemSpacing = interItemSpacing castleCollectionView.setCollectionViewLayout(collectionViewFlowLayout, animated: true) } } } extension CastlePics: UICollectionViewDelegate, UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return items.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! CastleCollectionViewCell cell.castleImageView.image = UIImage(named: items[indexPath.item].imageName) return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { print("didSelectItemAt \(indexPath)") } }
37.054945
136
0.638197
4a9f903d3763aca8b2262d7cb5e94f532c006970
13,889
// // Network.swift // Amber Electric // // Created by Rowan Willson on 31/8/19. // Copyright © 2019 Rowan Willson. All rights reserved. // import Foundation /* How did our API request finish */ enum NetworkResult { case successFromNetwork, successFromCache, failWrongCredentials, failOther } /* JSON mapping from Auth API */ struct AuthData : Decodable, BinaryCodable { struct AuthPersonalData : Decodable, BinaryCodable { let name : String let postcode : String let email : String let idToken : String let refreshToken : String } let data : AuthPersonalData let serviceResponseType : Int let message : String? } /* JSON mapping from GetPriceList API */ struct CurrentPriceData : Decodable, BinaryCodable { struct PriceData : Decodable, BinaryCodable { struct Price : Decodable, BinaryCodable { let period : Date // ISO-8601 e.g. 2019-08-31T22:00:00Z let priceKWH : Double let renewableInGrid : Double let color : String } let currentPriceKWH : Double let currentRenewableInGrid : Double let currentPriceColor : String let currentPricePeriod : Date // ISO-8601 let forecastPrices : [Price] let previousPrices : [Price] } let data : PriceData let serviceResponseType : Int let message : String? } /* JSON mapping from GetUsageForHub API */ struct HistoricalHubData : Decodable { struct HistData : Decodable { struct LongTermUsage : Decodable { let totalUsageInCertainPeriod : Double let totalUsageCostInCertainPeriod : Double let lessThanAverageCost : Double let lessThanAverageUsage : Double let savedCost : Double let usedPriceSpikesInCertainPeriod : Double let lessThanAveragePrice : Double } struct DailyUsage : Decodable { let date : Date // ISO 8601 let usageType : String //e.g. "ACTUAL" let usageCost : Double let usageKWH : Double let usageAveragePrice : Double let usagePriceSpikes : Double let dailyFixedCost : Double let meterSuffix : String //e.g. "E1" } let currentNEMtime : Date // ISO-8601 let thisWeekUsage : [String:LongTermUsage] let lastWeekUsage : [String:LongTermUsage] let lastMonthUsage: [String:LongTermUsage] let thisWeekDailyUsage : [DailyUsage] let lastWeekDailyUsage : [DailyUsage] let lastMonthDailyUsage : [DailyUsage] let usageDataTypes : [String] // e.g. "E1" } let data : HistData let serviceResponseType : Int let message : String? } /* Delegate callbacks for various network completion events */ protocol AmberAPIDelegate : class { func updateLoginDetails(requiresNewUserCredentials : Bool) func updatePrices() func updateHistoricalUsage() } /* Implement empty updateHistoricalUsage here. Override to implement */ extension AmberAPIDelegate { func updateHistoricalUsage() { } } /* Singleton network class. Call AmberAPI.shared.update() to use it. Will login, download prices and call delegate throughout. Data is serialised and cached to disk via UserDefaults. This class will update itself every half hour with a timer (e.g. as Kiosk). Note: iOS Background app refresh should also call update() */ class AmberAPI { private static let authURL = "https://api-bff.amberelectric.com.au/api/v1.0/Authentication/SignIn" private static let priceURL = "https://api-bff.amberelectric.com.au/api/v1.0/Price/GetPriceList" private static let usageURL = "https://api-bff.amberelectric.com.au/api/v1.0/UsageHub/GetUsageForHub" private let jsonDecoder = JSONDecoder() /* Singleton: access as AmberAPI.shared */ static let shared = AmberAPI() private init() { //Decode non-standard Amber API dates that are hard-coded to Brisbane timezone with incorrect 'Z' timezone. jsonDecoder.dateDecodingStrategy = .formatted(.amberDateFormatter) // Load some old currentPriceData from Defaults if it exists if let data = UserDefaults.shared.object(forKey: DefaultsKeys.lastSavedPriceKey) as? [UInt8] { currentPriceData = try? BinaryDecoder.decode(CurrentPriceData.self, data: data) } if let data = UserDefaults.shared.object(forKey: DefaultsKeys.lastSavedAuthKey) as? [UInt8] { authData = try? BinaryDecoder.decode(AuthData.self, data: data) } } deinit { timer?.invalidate() timer = nil } weak var delegate : AmberAPIDelegate? private var timer : Timer? //every 5 mins at xx:00:15 and xx:05:15 /* Downloaded Data */ var authData : AuthData? var currentPriceData : CurrentPriceData? var historicalHubData : HistoricalHubData? /* Update() - sets up timer. Will grab cached data if able. Signals delegate and completionHandler with result(s). */ func update(completionHandler : ((_ result: NetworkResult) -> Void)?) { /* 15 minute timer */ if timer == nil { timer = Timer(fire: Date().nextMinutes(minutes: 5, plusSeconds: 15), interval: 60*5, repeats: true, block: { (_) in self.login(completionHandler: nil) //login again on next half hour boundary }) } login(completionHandler: completionHandler) } /* Attempt Login. Upon successful login, calls prices. Optional completion handler is called upon successful login AND download of price data. Or upon return of cache results. Note: We always call login API and refresh token. With HTTP/2, this is a small time burden. */ private func login(completionHandler : ((_ result: NetworkResult) -> Void)?) { let defaults = UserDefaults.shared /* Firstly check cached currentPriceData for a result in the current time block and return that if appropriate (avoid unnecessary network calls). Assumes data does not change in each 5 minute time period. */ if let currentCachedTime = currentPriceData?.data.currentPricePeriod { let nextValidTimePeriod = currentCachedTime.nextMinutes(minutes: 5) if nextValidTimePeriod.timeIntervalSinceNow > 0 { #if DEBUG print("\(Date().description): Returning Cached Data: " + currentCachedTime.description + " \(currentPriceData?.data.currentPriceKWH ?? 0)c") #endif delegate?.updateLoginDetails(requiresNewUserCredentials: false) delegate?.updatePrices() completionHandler?(.successFromCache) return } } guard let authURL = URL(string: AmberAPI.authURL) else { completionHandler?(.failOther) return } // Get saved user credentials from UserDefaults guard let username = defaults.string(forKey: DefaultsKeys.usernameKey), let password = defaults.string(forKey: DefaultsKeys.passwordKey) else { delegate?.updateLoginDetails(requiresNewUserCredentials: true) completionHandler?(.failWrongCredentials) return } var request = URLRequest(url: authURL) request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.httpMethod = "POST" request.httpBody = "{\"username\":\"\(username)\",\"password\":\"\(password)\"}".data(using: .utf8) let dataTask = URLSession.shared.dataTask(with: request) { (data, response, error) in guard let data = data, let _ = response as? HTTPURLResponse, error == nil else { #if DEBUG print("error", error ?? "Network error in Auth") #endif completionHandler?(.failOther) return } if let auth = try? self.jsonDecoder.decode(AuthData.self, from: data), auth.serviceResponseType == 1 { DispatchQueue.main.async { self.authData = auth self.delegate?.updateLoginDetails(requiresNewUserCredentials: false) // Serialise to Defaults (cache) for next time. let defaults = UserDefaults.shared do { let bytes = try BinaryEncoder.encode(auth) defaults.set(bytes, forKey: DefaultsKeys.lastSavedAuthKey) defaults.synchronize() } catch { #if DEBUG print(error.localizedDescription) #endif } // Now we are logged in, next step is to get price data from API. self.getPrices(completionHandler: completionHandler) } } else { DispatchQueue.main.async { self.delegate?.updateLoginDetails(requiresNewUserCredentials: true) completionHandler?(.failOther) } } } dataTask.resume() } /* Get Prices. Upon successful completion, calls history API */ private func getPrices(completionHandler : ((_ result: NetworkResult) -> Void)?) { guard let priceURL = URL(string: AmberAPI.priceURL) else { completionHandler?(.failOther) return } guard let idToken = authData?.data.idToken, let refreshToken = authData?.data.refreshToken, let email = authData?.data.email else { completionHandler?(.failOther) return } var request = URLRequest(url: priceURL) request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.setValue("application/json", forHTTPHeaderField: "Accept") request.setValue(idToken, forHTTPHeaderField: "authorization") request.setValue(email, forHTTPHeaderField: "email") request.setValue(refreshToken, forHTTPHeaderField: "refreshtoken") request.httpMethod = "POST" request.httpBody = "{\"headers\":{\"normalizedNames\":{},\"lazyUpdate\":null,\"headers\":{}}}" .data(using: .utf8) let dataTask = URLSession.shared.dataTask(with: request) { (data, response, error) in guard let data = data, let _ = response as? HTTPURLResponse, error == nil else { #if DEBUG print("error", error ?? "Network error in Prices") #endif completionHandler?(.failOther) return } if let prices = try? self.jsonDecoder.decode(CurrentPriceData.self, from: data) { DispatchQueue.main.async { self.currentPriceData = prices self.delegate?.updatePrices() // Serialise to Defaults (cache) for next time. let defaults = UserDefaults.shared do { let bytes = try BinaryEncoder.encode(prices) defaults.set(bytes, forKey: DefaultsKeys.lastSavedPriceKey) defaults.synchronize() } catch { #if DEBUG print(error.localizedDescription) #endif } //self.getHistory() // Enable once implemented in UI completionHandler?(.successFromNetwork) } } else { completionHandler?(.failOther) } } dataTask.resume() } /* Get Prices. Upon successful completion, calls history */ private func getHistory(completionHandler : ((_ result: NetworkResult) -> Void)?) { guard let usageURL = URL(string: AmberAPI.usageURL) else { completionHandler?(.failOther) return } guard let idToken = authData?.data.idToken, let refreshToken = authData?.data.refreshToken, let email = authData?.data.email else { completionHandler?(.failOther) return } var request = URLRequest(url: usageURL) request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.setValue("application/json", forHTTPHeaderField: "Accept") request.setValue(idToken, forHTTPHeaderField: "authorization") request.setValue(email, forHTTPHeaderField: "email") request.setValue(refreshToken, forHTTPHeaderField: "refreshtoken") request.httpMethod = "POST" request.httpBody = "{\"email\":\"\(email)\"}" .data(using: .utf8) let dataTask = URLSession.shared.dataTask(with: request) { (data, response, error) in guard let data = data, let _ = response as? HTTPURLResponse, error == nil else { #if DEBUG print("error", error ?? "Network error in History") #endif completionHandler?(.failOther) return } if let hubData = try? self.jsonDecoder.decode(HistoricalHubData.self, from: data) { DispatchQueue.main.async { self.historicalHubData = hubData self.delegate?.updateHistoricalUsage() completionHandler?(.successFromNetwork) } } else { completionHandler?(.failOther) } } dataTask.resume() } }
40.730205
215
0.597523
f860277a99f92ffbf12d97ba4bb0637ef6908cfe
2,791
// // AppDelegate.swift // Books // // Created by Yogesh Bhople on 13/05/21. // Copyright © 2021 SOMEONE. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var navigationController:UINavigationController? var books:[Book]? = [] func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. let _ = loadData() return true } func loadData() -> Bool { let urlPath = Bundle.main.url(forResource: "booksdata", withExtension: "json")! guard let json = try? Data(contentsOf: urlPath) else { return true } let decoder = JSONDecoder() if let jsonPetitions = try? decoder.decode(Welcome.self, from: json) { for item in jsonPetitions.items { books?.append(item.volumeInfo) } } return true } func loadDataAsync(completionHandler: @escaping () -> Void) { DispatchQueue.global().async { [weak self] in let urlPath = Bundle.main.url(forResource: "booksdata", withExtension: "json")! guard let json = try? Data(contentsOf: urlPath) else { return } let decoder = JSONDecoder() if let jsonPetitions = try? decoder.decode(Welcome.self, from: json) { for item in jsonPetitions.items { self?.books?.append(item.volumeInfo) } } completionHandler() } } // MARK: UISceneSession Lifecycle @available(iOS 13.0, *) func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } @available(iOS 13.0, *) func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } }
34.8875
179
0.632032
5d84739fabff7b3da1fbd64ced90f8fb756891f0
194
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing {t{}{ enum e{class case,
24.25
87
0.752577
621a5da62cf4c6d9c0095a68736dbfd07d9401db
2,231
// // 🦠 Corona-Warn-App // import XCTest import OpenCombine import ZIPFoundation @testable import ENA class CacheAppConfigMockTests: XCTestCase { func testDefaultConfig() throws { let url = try XCTUnwrap(Bundle.main.url(forResource: "default_app_config_115", withExtension: "")) let data = try Data(contentsOf: url) let zip = try XCTUnwrap(Archive(data: data, accessMode: .read)) let staticConfig = try zip.extractAppConfiguration() let onFetch = expectation(description: "config fetched") let subscription = CachedAppConfigurationMock().appConfiguration().sink { config in XCTAssertEqual(config, staticConfig) onFetch.fulfill() } waitForExpectations(timeout: .medium) subscription.cancel() } func testCustomConfig() throws { var customConfig = SAP_Internal_V2_ApplicationConfigurationIOS() customConfig.supportedCountries = ["foo", "bar", "baz"] let onFetch = expectation(description: "config fetched") let subscription = CachedAppConfigurationMock(with: customConfig).appConfiguration().sink { config in XCTAssertEqual(config, customConfig) XCTAssertEqual(config.supportedCountries, customConfig.supportedCountries) onFetch.fulfill() } waitForExpectations(timeout: .medium) subscription.cancel() } func testCacheSupportedCountries() throws { var config = SAP_Internal_V2_ApplicationConfigurationIOS() config.supportedCountries = ["DE", "ES", "FR", "IT", "IE", "DK"] let gotValue = expectation(description: "got countries list") let subscription = CachedAppConfigurationMock(with: config) .supportedCountries() .sink { countries in XCTAssertEqual(countries.count, 6) gotValue.fulfill() } waitForExpectations(timeout: .medium) subscription.cancel() } func testCacheEmptySupportedCountries() throws { let config = SAP_Internal_V2_ApplicationConfigurationIOS() let gotValue = expectation(description: "got countries list") let subscription = CachedAppConfigurationMock(with: config) .supportedCountries() .sink { countries in XCTAssertEqual(countries.count, 1) XCTAssertEqual(countries.first, .defaultCountry()) gotValue.fulfill() } waitForExpectations(timeout: .medium) subscription.cancel() } }
27.54321
103
0.753026
f8d7f561cbe5f4610b033118eafdc7a4a6f49a7c
57,472
//===--- ArraySlice.swift -------------------------------------*- swift -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // - `ArraySlice<Element>` presents an arbitrary subsequence of some // contiguous sequence of `Element`s. // //===----------------------------------------------------------------------===// /// A slice of an `Array`, `ContiguousArray`, or `ArraySlice` instance. /// /// The `ArraySlice` type makes it fast and efficient for you to perform /// operations on sections of a larger array. Instead of copying over the /// elements of a slice to new storage, an `ArraySlice` instance presents a /// view onto the storage of a larger array. And because `ArraySlice` /// presents the same interface as `Array`, you can generally perform the /// same operations on a slice as you could on the original array. /// /// For more information about using arrays, see `Array` and `ContiguousArray`, /// with which `ArraySlice` shares most properties and methods. /// /// Slices Are Views onto Arrays /// ============================ /// /// For example, suppose you have an array holding the number of absences /// from each class during a session. /// /// let absences = [0, 2, 0, 4, 0, 3, 1, 0] /// /// You want to compare the absences in the first half of the session with /// those in the second half. To do so, start by creating two slices of the /// `absences` array. /// /// let midpoint = absences.count / 2 /// /// let firstHalf = absences[..<midpoint] /// let secondHalf = absences[midpoint...] /// /// Neither the `firstHalf` nor `secondHalf` slices allocate any new storage /// of their own. Instead, each presents a view onto the storage of the /// `absences` array. /// /// You can call any method on the slices that you might have called on the /// `absences` array. To learn which half had more absences, use the /// `reduce(_:_:)` method to calculate each sum. /// /// let firstHalfSum = firstHalf.reduce(0, +) /// let secondHalfSum = secondHalf.reduce(0, +) /// /// if firstHalfSum > secondHalfSum { /// print("More absences in the first half.") /// } else { /// print("More absences in the second half.") /// } /// // Prints "More absences in the first half." /// /// - Important: Long-term storage of `ArraySlice` instances is discouraged. A /// slice holds a reference to the entire storage of a larger array, not /// just to the portion it presents, even after the original array's lifetime /// ends. Long-term storage of a slice may therefore prolong the lifetime of /// elements that are no longer otherwise accessible, which can appear to be /// memory and object leakage. /// /// Slices Maintain Indices /// ======================= /// /// Unlike `Array` and `ContiguousArray`, the starting index for an /// `ArraySlice` instance isn't always zero. Slices maintain the same /// indices of the larger array for the same elements, so the starting /// index of a slice depends on how it was created, letting you perform /// index-based operations on either a full array or a slice. /// /// Sharing indices between collections and their subsequences is an important /// part of the design of Swift's collection algorithms. Suppose you are /// tasked with finding the first two days with absences in the session. To /// find the indices of the two days in question, follow these steps: /// /// 1) Call `firstIndex(where:)` to find the index of the first element in the /// `absences` array that is greater than zero. /// 2) Create a slice of the `absences` array starting after the index found in /// step 1. /// 3) Call `firstIndex(where:)` again, this time on the slice created in step /// 2. Where in some languages you might pass a starting index into an /// `indexOf` method to find the second day, in Swift you perform the same /// operation on a slice of the original array. /// 4) Print the results using the indices found in steps 1 and 3 on the /// original `absences` array. /// /// Here's an implementation of those steps: /// /// if let i = absences.firstIndex(where: { $0 > 0 }) { // 1 /// let absencesAfterFirst = absences[(i + 1)...] // 2 /// if let j = absencesAfterFirst.firstIndex(where: { $0 > 0 }) { // 3 /// print("The first day with absences had \(absences[i]).") // 4 /// print("The second day with absences had \(absences[j]).") /// } /// } /// // Prints "The first day with absences had 2." /// // Prints "The second day with absences had 4." /// /// In particular, note that `j`, the index of the second day with absences, /// was found in a slice of the original array and then used to access a value /// in the original `absences` array itself. /// /// - Note: To safely reference the starting and ending indices of a slice, /// always use the `startIndex` and `endIndex` properties instead of /// specific values. @_fixed_layout public struct ArraySlice<Element>: _DestructorSafeContainer { @usableFromInline internal typealias _Buffer = _SliceBuffer<Element> @usableFromInline internal var _buffer: _Buffer /// Initialization from an existing buffer does not have "array.init" /// semantics because the caller may retain an alias to buffer. @inlinable internal init(_buffer: _Buffer) { self._buffer = _buffer } /// Initialization from an existing buffer does not have "array.init" /// semantics because the caller may retain an alias to buffer. @inlinable internal init(_buffer buffer: _ContiguousArrayBuffer<Element>) { self.init(_buffer: _Buffer(_buffer: buffer, shiftedToStartIndex: 0)) } } //===--- private helpers---------------------------------------------------===// extension ArraySlice { /// Returns `true` if the array is native and does not need a deferred /// type check. May be hoisted by the optimizer, which means its /// results may be stale by the time they are used if there is an /// inout violation in user code. @inlinable @_semantics("array.props.isNativeTypeChecked") public // @testable func _hoistableIsNativeTypeChecked() -> Bool { return _buffer.arrayPropertyIsNativeTypeChecked } @inlinable @_semantics("array.get_count") internal func _getCount() -> Int { return _buffer.count } @inlinable @_semantics("array.get_capacity") internal func _getCapacity() -> Int { return _buffer.capacity } @inlinable @_semantics("array.make_mutable") internal mutating func _makeMutableAndUnique() { if _slowPath(!_buffer.isMutableAndUniquelyReferenced()) { _buffer = _Buffer(copying: _buffer) } } /// Check that the given `index` is valid for subscripting, i.e. /// `0 ≤ index < count`. @inlinable @inline(__always) internal func _checkSubscript_native(_ index: Int) { _buffer._checkValidSubscript(index) } /// Check that the given `index` is valid for subscripting, i.e. /// `0 ≤ index < count`. @inlinable @_semantics("array.check_subscript") public // @testable func _checkSubscript( _ index: Int, wasNativeTypeChecked: Bool ) -> _DependenceToken { #if _runtime(_ObjC) _buffer._checkValidSubscript(index) #else _buffer._checkValidSubscript(index) #endif return _DependenceToken() } /// Check that the specified `index` is valid, i.e. `0 ≤ index ≤ count`. @inlinable @_semantics("array.check_index") internal func _checkIndex(_ index: Int) { _precondition(index <= endIndex, "ArraySlice index is out of range") _precondition(index >= startIndex, "ArraySlice index is out of range (before startIndex)") } @_semantics("array.get_element") @inline(__always) public // @testable func _getElement( _ index: Int, wasNativeTypeChecked: Bool, matchingSubscriptCheck: _DependenceToken ) -> Element { #if false return _buffer.getElement(index, wasNativeTypeChecked: wasNativeTypeChecked) #else return _buffer.getElement(index) #endif } @inlinable @_semantics("array.get_element_address") internal func _getElementAddress(_ index: Int) -> UnsafeMutablePointer<Element> { return _buffer.subscriptBaseAddress + index } } extension ArraySlice: _ArrayProtocol { /// The total number of elements that the array can contain without /// allocating new storage. /// /// Every array reserves a specific amount of memory to hold its contents. /// When you add elements to an array and that array begins to exceed its /// reserved capacity, the array allocates a larger region of memory and /// copies its elements into the new storage. The new storage is a multiple /// of the old storage's size. This exponential growth strategy means that /// appending an element happens in constant time, averaging the performance /// of many append operations. Append operations that trigger reallocation /// have a performance cost, but they occur less and less often as the array /// grows larger. /// /// The following example creates an array of integers from an array literal, /// then appends the elements of another collection. Before appending, the /// array allocates new storage that is large enough store the resulting /// elements. /// /// var numbers = [10, 20, 30, 40, 50] /// // numbers.count == 5 /// // numbers.capacity == 5 /// /// numbers.append(contentsOf: stride(from: 60, through: 100, by: 10)) /// // numbers.count == 10 /// // numbers.capacity == 12 @inlinable public var capacity: Int { return _getCapacity() } /// An object that guarantees the lifetime of this array's elements. @inlinable public // @testable var _owner: AnyObject? { return _buffer.owner } /// If the elements are stored contiguously, a pointer to the first /// element. Otherwise, `nil`. @inlinable public var _baseAddressIfContiguous: UnsafeMutablePointer<Element>? { @inline(__always) // FIXME(TODO: JIRA): Hack around test failure get { return _buffer.firstElementAddressIfContiguous } } @inlinable internal var _baseAddress: UnsafeMutablePointer<Element> { return _buffer.firstElementAddress } } extension ArraySlice: RandomAccessCollection, MutableCollection { /// The index type for arrays, `Int`. /// /// `ArraySlice` instances are not always indexed from zero. Use `startIndex` /// and `endIndex` as the bounds for any element access, instead of `0` and /// `count`. public typealias Index = Int /// The type that represents the indices that are valid for subscripting an /// array, in ascending order. public typealias Indices = Range<Int> /// The type that allows iteration over an array's elements. public typealias Iterator = IndexingIterator<ArraySlice> /// The position of the first element in a nonempty array. /// /// `ArraySlice` instances are not always indexed from zero. Use `startIndex` /// and `endIndex` as the bounds for any element access, instead of `0` and /// `count`. /// /// If the array is empty, `startIndex` is equal to `endIndex`. @inlinable public var startIndex: Int { return _buffer.startIndex } /// The array's "past the end" position---that is, the position one greater /// than the last valid subscript argument. /// /// When you need a range that includes the last element of an array, use the /// half-open range operator (`..<`) with `endIndex`. The `..<` operator /// creates a range that doesn't include the upper bound, so it's always /// safe to use with `endIndex`. For example: /// /// let numbers = [10, 20, 30, 40, 50] /// if let i = numbers.firstIndex(of: 30) { /// print(numbers[i ..< numbers.endIndex]) /// } /// // Prints "[30, 40, 50]" /// /// If the array is empty, `endIndex` is equal to `startIndex`. @inlinable public var endIndex: Int { return _buffer.endIndex } /// Returns the position immediately after the given index. /// /// - Parameter i: A valid index of the collection. `i` must be less than /// `endIndex`. /// - Returns: The index immediately after `i`. @inlinable public func index(after i: Int) -> Int { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. return i + 1 } /// Replaces the given index with its successor. /// /// - Parameter i: A valid index of the collection. `i` must be less than /// `endIndex`. @inlinable public func formIndex(after i: inout Int) { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. i += 1 } /// Returns the position immediately before the given index. /// /// - Parameter i: A valid index of the collection. `i` must be greater than /// `startIndex`. /// - Returns: The index immediately before `i`. @inlinable public func index(before i: Int) -> Int { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. return i - 1 } /// Replaces the given index with its predecessor. /// /// - Parameter i: A valid index of the collection. `i` must be greater than /// `startIndex`. @inlinable public func formIndex(before i: inout Int) { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. i -= 1 } /// Returns an index that is the specified distance from the given index. /// /// The following example obtains an index advanced four positions from an /// array's starting index and then prints the element at that position. /// /// let numbers = [10, 20, 30, 40, 50] /// let i = numbers.index(numbers.startIndex, offsetBy: 4) /// print(numbers[i]) /// // Prints "50" /// /// The value passed as `distance` must not offset `i` beyond the bounds of /// the collection. /// /// - Parameters: /// - i: A valid index of the array. /// - distance: The distance to offset `i`. /// - Returns: An index offset by `distance` from the index `i`. If /// `distance` is positive, this is the same value as the result of /// `distance` calls to `index(after:)`. If `distance` is negative, this /// is the same value as the result of `abs(distance)` calls to /// `index(before:)`. @inlinable public func index(_ i: Int, offsetBy distance: Int) -> Int { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. return i + distance } /// Returns an index that is the specified distance from the given index, /// unless that distance is beyond a given limiting index. /// /// The following example obtains an index advanced four positions from an /// array's starting index and then prints the element at that position. The /// operation doesn't require going beyond the limiting `numbers.endIndex` /// value, so it succeeds. /// /// let numbers = [10, 20, 30, 40, 50] /// if let i = numbers.index(numbers.startIndex, /// offsetBy: 4, /// limitedBy: numbers.endIndex) { /// print(numbers[i]) /// } /// // Prints "50" /// /// The next example attempts to retrieve an index ten positions from /// `numbers.startIndex`, but fails, because that distance is beyond the /// index passed as `limit`. /// /// let j = numbers.index(numbers.startIndex, /// offsetBy: 10, /// limitedBy: numbers.endIndex) /// print(j) /// // Prints "nil" /// /// The value passed as `distance` must not offset `i` beyond the bounds of /// the collection, unless the index passed as `limit` prevents offsetting /// beyond those bounds. /// /// - Parameters: /// - i: A valid index of the array. /// - distance: The distance to offset `i`. /// - limit: A valid index of the collection to use as a limit. If /// `distance > 0`, `limit` has no effect if it is less than `i`. /// Likewise, if `distance < 0`, `limit` has no effect if it is greater /// than `i`. /// - Returns: An index offset by `distance` from the index `i`, unless that /// index would be beyond `limit` in the direction of movement. In that /// case, the method returns `nil`. /// /// - Complexity: O(1) @inlinable public func index( _ i: Int, offsetBy distance: Int, limitedBy limit: Int ) -> Int? { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. let l = limit - i if distance > 0 ? l >= 0 && l < distance : l <= 0 && distance < l { return nil } return i + distance } /// Returns the distance between two indices. /// /// - Parameters: /// - start: A valid index of the collection. /// - end: Another valid index of the collection. If `end` is equal to /// `start`, the result is zero. /// - Returns: The distance between `start` and `end`. @inlinable public func distance(from start: Int, to end: Int) -> Int { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. return end - start } @inlinable public func _failEarlyRangeCheck(_ index: Int, bounds: Range<Int>) { // NOTE: This method is a no-op for performance reasons. } @inlinable public func _failEarlyRangeCheck(_ range: Range<Int>, bounds: Range<Int>) { // NOTE: This method is a no-op for performance reasons. } /// Accesses the element at the specified position. /// /// The following example uses indexed subscripting to update an array's /// second element. After assigning the new value (`"Butler"`) at a specific /// position, that value is immediately available at that same position. /// /// var streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] /// streets[1] = "Butler" /// print(streets[1]) /// // Prints "Butler" /// /// - Parameter index: The position of the element to access. `index` must be /// greater than or equal to `startIndex` and less than `endIndex`. /// /// - Complexity: Reading an element from an array is O(1). Writing is O(1) /// unless the array's storage is shared with another array or uses a /// bridged `NSArray` instance as its storage, in which case writing is /// O(*n*), where *n* is the length of the array. @inlinable public subscript(index: Int) -> Element { get { // This call may be hoisted or eliminated by the optimizer. If // there is an inout violation, this value may be stale so needs to be // checked again below. let wasNativeTypeChecked = _hoistableIsNativeTypeChecked() // Make sure the index is in range and wasNativeTypeChecked is // still valid. let token = _checkSubscript( index, wasNativeTypeChecked: wasNativeTypeChecked) return _getElement( index, wasNativeTypeChecked: wasNativeTypeChecked, matchingSubscriptCheck: token) } _modify { _makeMutableAndUnique() // makes the array native, too _checkSubscript_native(index) let address = _buffer.subscriptBaseAddress + index yield &address.pointee } } /// Accesses a contiguous subrange of the array's elements. /// /// The returned `ArraySlice` instance uses the same indices for the same /// elements as the original array. In particular, that slice, unlike an /// array, may have a nonzero `startIndex` and an `endIndex` that is not /// equal to `count`. Always use the slice's `startIndex` and `endIndex` /// properties instead of assuming that its indices start or end at a /// particular value. /// /// This example demonstrates getting a slice of an array of strings, finding /// the index of one of the strings in the slice, and then using that index /// in the original array. /// /// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] /// let streetsSlice = streets[2 ..< streets.endIndex] /// print(streetsSlice) /// // Prints "["Channing", "Douglas", "Evarts"]" /// /// let i = streetsSlice.firstIndex(of: "Evarts") // 4 /// print(streets[i!]) /// // Prints "Evarts" /// /// - Parameter bounds: A range of integers. The bounds of the range must be /// valid indices of the array. @inlinable public subscript(bounds: Range<Int>) -> ArraySlice<Element> { get { _checkIndex(bounds.lowerBound) _checkIndex(bounds.upperBound) return ArraySlice(_buffer: _buffer[bounds]) } set(rhs) { _checkIndex(bounds.lowerBound) _checkIndex(bounds.upperBound) // If the replacement buffer has same identity, and the ranges match, // then this was a pinned in-place modification, nothing further needed. if self[bounds]._buffer.identity != rhs._buffer.identity || bounds != rhs.startIndex..<rhs.endIndex { self.replaceSubrange(bounds, with: rhs) } } } /// The number of elements in the array. @inlinable public var count: Int { return _getCount() } } extension ArraySlice: ExpressibleByArrayLiteral { /// Creates an array from the given array literal. /// /// Do not call this initializer directly. It is used by the compiler when /// you use an array literal. Instead, create a new array by using an array /// literal as its value. To do this, enclose a comma-separated list of /// values in square brackets. /// /// Here, an array of strings is created from an array literal holding only /// strings: /// /// let ingredients: ArraySlice = /// ["cocoa beans", "sugar", "cocoa butter", "salt"] /// /// - Parameter elements: A variadic list of elements of the new array. @inlinable public init(arrayLiteral elements: Element...) { self.init(_buffer: ContiguousArray(elements)._buffer) } } extension ArraySlice: RangeReplaceableCollection { /// Creates a new, empty array. /// /// This is equivalent to initializing with an empty array literal. /// For example: /// /// var emptyArray = Array<Int>() /// print(emptyArray.isEmpty) /// // Prints "true" /// /// emptyArray = [] /// print(emptyArray.isEmpty) /// // Prints "true" @inlinable @_semantics("array.init") public init() { _buffer = _Buffer() } /// Creates an array containing the elements of a sequence. /// /// You can use this initializer to create an array from any other type that /// conforms to the `Sequence` protocol. For example, you might want to /// create an array with the integers from 1 through 7. Use this initializer /// around a range instead of typing all those numbers in an array literal. /// /// let numbers = Array(1...7) /// print(numbers) /// // Prints "[1, 2, 3, 4, 5, 6, 7]" /// /// You can also use this initializer to convert a complex sequence or /// collection type back to an array. For example, the `keys` property of /// a dictionary isn't an array with its own storage, it's a collection /// that maps its elements from the dictionary only when they're /// accessed, saving the time and space needed to allocate an array. If /// you need to pass those keys to a method that takes an array, however, /// use this initializer to convert that list from its type of /// `LazyMapCollection<Dictionary<String, Int>, Int>` to a simple /// `[String]`. /// /// func cacheImagesWithNames(names: [String]) { /// // custom image loading and caching /// } /// /// let namedHues: [String: Int] = ["Vermillion": 18, "Magenta": 302, /// "Gold": 50, "Cerise": 320] /// let colorNames = Array(namedHues.keys) /// cacheImagesWithNames(colorNames) /// /// print(colorNames) /// // Prints "["Gold", "Cerise", "Magenta", "Vermillion"]" /// /// - Parameter s: The sequence of elements to turn into an array. @inlinable public init<S: Sequence>(_ s: S) where S.Element == Element { self = ArraySlice( _buffer: _Buffer( _buffer: s._copyToContiguousArray()._buffer, shiftedToStartIndex: 0)) } /// Creates a new array containing the specified number of a single, repeated /// value. /// /// Here's an example of creating an array initialized with five strings /// containing the letter *Z*. /// /// let fiveZs = Array(repeating: "Z", count: 5) /// print(fiveZs) /// // Prints "["Z", "Z", "Z", "Z", "Z"]" /// /// - Parameters: /// - repeatedValue: The element to repeat. /// - count: The number of times to repeat the value passed in the /// `repeating` parameter. `count` must be zero or greater. @inlinable @_semantics("array.init") public init(repeating repeatedValue: Element, count: Int) { var p: UnsafeMutablePointer<Element> (self, p) = ArraySlice._allocateUninitialized(count) for _ in 0..<count { p.initialize(to: repeatedValue) p += 1 } } @inline(never) @usableFromInline internal static func _allocateBufferUninitialized( minimumCapacity: Int ) -> _Buffer { let newBuffer = _ContiguousArrayBuffer<Element>( _uninitializedCount: 0, minimumCapacity: minimumCapacity) return _Buffer(_buffer: newBuffer, shiftedToStartIndex: 0) } /// Construct a ArraySlice of `count` uninitialized elements. @inlinable internal init(_uninitializedCount count: Int) { _precondition(count >= 0, "Can't construct ArraySlice with count < 0") // Note: Sinking this constructor into an else branch below causes an extra // Retain/Release. _buffer = _Buffer() if count > 0 { // Creating a buffer instead of calling reserveCapacity saves doing an // unnecessary uniqueness check. We disable inlining here to curb code // growth. _buffer = ArraySlice._allocateBufferUninitialized(minimumCapacity: count) _buffer.count = count } // Can't store count here because the buffer might be pointing to the // shared empty array. } /// Entry point for `Array` literal construction; builds and returns /// a ArraySlice of `count` uninitialized elements. @inlinable @_semantics("array.uninitialized") internal static func _allocateUninitialized( _ count: Int ) -> (ArraySlice, UnsafeMutablePointer<Element>) { let result = ArraySlice(_uninitializedCount: count) return (result, result._buffer.firstElementAddress) } //===--- basic mutations ------------------------------------------------===// /// Reserves enough space to store the specified number of elements. /// /// If you are adding a known number of elements to an array, use this method /// to avoid multiple reallocations. This method ensures that the array has /// unique, mutable, contiguous storage, with space allocated for at least /// the requested number of elements. /// /// Calling the `reserveCapacity(_:)` method on an array with bridged storage /// triggers a copy to contiguous storage even if the existing storage /// has room to store `minimumCapacity` elements. /// /// For performance reasons, the size of the newly allocated storage might be /// greater than the requested capacity. Use the array's `capacity` property /// to determine the size of the new storage. /// /// Preserving an Array's Geometric Growth Strategy /// =============================================== /// /// If you implement a custom data structure backed by an array that grows /// dynamically, naively calling the `reserveCapacity(_:)` method can lead /// to worse than expected performance. Arrays need to follow a geometric /// allocation pattern for appending elements to achieve amortized /// constant-time performance. The `Array` type's `append(_:)` and /// `append(contentsOf:)` methods take care of this detail for you, but /// `reserveCapacity(_:)` allocates only as much space as you tell it to /// (padded to a round value), and no more. This avoids over-allocation, but /// can result in insertion not having amortized constant-time performance. /// /// The following code declares `values`, an array of integers, and the /// `addTenQuadratic()` function, which adds ten more values to the `values` /// array on each call. /// /// var values: [Int] = [0, 1, 2, 3] /// /// // Don't use 'reserveCapacity(_:)' like this /// func addTenQuadratic() { /// let newCount = values.count + 10 /// values.reserveCapacity(newCount) /// for n in values.count..<newCount { /// values.append(n) /// } /// } /// /// The call to `reserveCapacity(_:)` increases the `values` array's capacity /// by exactly 10 elements on each pass through `addTenQuadratic()`, which /// is linear growth. Instead of having constant time when averaged over /// many calls, the function may decay to performance that is linear in /// `values.count`. This is almost certainly not what you want. /// /// In cases like this, the simplest fix is often to simply remove the call /// to `reserveCapacity(_:)`, and let the `append(_:)` method grow the array /// for you. /// /// func addTen() { /// let newCount = values.count + 10 /// for n in values.count..<newCount { /// values.append(n) /// } /// } /// /// If you need more control over the capacity of your array, implement your /// own geometric growth strategy, passing the size you compute to /// `reserveCapacity(_:)`. /// /// - Parameter minimumCapacity: The requested number of elements to store. /// /// - Complexity: O(*n*), where *n* is the number of elements in the array. @inlinable @_semantics("array.mutate_unknown") public mutating func reserveCapacity(_ minimumCapacity: Int) { if _buffer.requestUniqueMutableBackingBuffer( minimumCapacity: minimumCapacity) == nil { let newBuffer = _ContiguousArrayBuffer<Element>( _uninitializedCount: count, minimumCapacity: minimumCapacity) _buffer._copyContents( subRange: _buffer.indices, initializing: newBuffer.firstElementAddress) _buffer = _Buffer( _buffer: newBuffer, shiftedToStartIndex: _buffer.startIndex) } _sanityCheck(capacity >= minimumCapacity) } /// Copy the contents of the current buffer to a new unique mutable buffer. /// The count of the new buffer is set to `oldCount`, the capacity of the /// new buffer is big enough to hold 'oldCount' + 1 elements. @inline(never) @inlinable // @specializable internal mutating func _copyToNewBuffer(oldCount: Int) { let newCount = oldCount + 1 var newBuffer = _buffer._forceCreateUniqueMutableBuffer( countForNewBuffer: oldCount, minNewCapacity: newCount) _buffer._arrayOutOfPlaceUpdate( &newBuffer, oldCount, 0) } @inlinable @_semantics("array.make_mutable") internal mutating func _makeUniqueAndReserveCapacityIfNotUnique() { if _slowPath(!_buffer.isMutableAndUniquelyReferenced()) { _copyToNewBuffer(oldCount: _buffer.count) } } @inlinable @_semantics("array.mutate_unknown") internal mutating func _reserveCapacityAssumingUniqueBuffer(oldCount: Int) { // This is a performance optimization. This code used to be in an || // statement in the _sanityCheck below. // // _sanityCheck(_buffer.capacity == 0 || // _buffer.isMutableAndUniquelyReferenced()) // // SR-6437 let capacity = _buffer.capacity == 0 // Due to make_mutable hoisting the situation can arise where we hoist // _makeMutableAndUnique out of loop and use it to replace // _makeUniqueAndReserveCapacityIfNotUnique that preceeds this call. If the // array was empty _makeMutableAndUnique does not replace the empty array // buffer by a unique buffer (it just replaces it by the empty array // singleton). // This specific case is okay because we will make the buffer unique in this // function because we request a capacity > 0 and therefore _copyToNewBuffer // will be called creating a new buffer. _sanityCheck(capacity || _buffer.isMutableAndUniquelyReferenced()) if _slowPath(oldCount + 1 > _buffer.capacity) { _copyToNewBuffer(oldCount: oldCount) } } @inlinable @_semantics("array.mutate_unknown") internal mutating func _appendElementAssumeUniqueAndCapacity( _ oldCount: Int, newElement: __owned Element ) { _sanityCheck(_buffer.isMutableAndUniquelyReferenced()) _sanityCheck(_buffer.capacity >= _buffer.count + 1) _buffer.count = oldCount + 1 (_buffer.firstElementAddress + oldCount).initialize(to: newElement) } /// Adds a new element at the end of the array. /// /// Use this method to append a single element to the end of a mutable array. /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.append(100) /// print(numbers) /// // Prints "[1, 2, 3, 4, 5, 100]" /// /// Because arrays increase their allocated capacity using an exponential /// strategy, appending a single element to an array is an O(1) operation /// when averaged over many calls to the `append(_:)` method. When an array /// has additional capacity and is not sharing its storage with another /// instance, appending an element is O(1). When an array needs to /// reallocate storage before appending or its storage is shared with /// another copy, appending is O(*n*), where *n* is the length of the array. /// /// - Parameter newElement: The element to append to the array. /// /// - Complexity: O(1) on average, over many calls to `append(_:)` on the /// same array. @inlinable @_semantics("array.append_element") public mutating func append(_ newElement: __owned Element) { _makeUniqueAndReserveCapacityIfNotUnique() let oldCount = _getCount() _reserveCapacityAssumingUniqueBuffer(oldCount: oldCount) _appendElementAssumeUniqueAndCapacity(oldCount, newElement: newElement) } /// Adds the elements of a sequence to the end of the array. /// /// Use this method to append the elements of a sequence to the end of this /// array. This example appends the elements of a `Range<Int>` instance /// to an array of integers. /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.append(contentsOf: 10...15) /// print(numbers) /// // Prints "[1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15]" /// /// - Parameter newElements: The elements to append to the array. /// /// - Complexity: O(*m*) on average, where *m* is the length of /// `newElements`, over many calls to `append(contentsOf:)` on the same /// array. @inlinable @_semantics("array.append_contentsOf") public mutating func append<S: Sequence>(contentsOf newElements: __owned S) where S.Element == Element { let newElementsCount = newElements.underestimatedCount reserveCapacityForAppend(newElementsCount: newElementsCount) let oldCount = self.count let startNewElements = _buffer.firstElementAddress + oldCount let buf = UnsafeMutableBufferPointer( start: startNewElements, count: self.capacity - oldCount) let (remainder,writtenUpTo) = buf.initialize(from: newElements) // trap on underflow from the sequence's underestimate: let writtenCount = buf.distance(from: buf.startIndex, to: writtenUpTo) _precondition(newElementsCount <= writtenCount, "newElements.underestimatedCount was an overestimate") // can't check for overflow as sequences can underestimate _buffer.count += writtenCount if writtenUpTo == buf.endIndex { // there may be elements that didn't fit in the existing buffer, // append them in slow sequence-only mode _buffer._arrayAppendSequence(IteratorSequence(remainder)) } } @inlinable @_semantics("array.reserve_capacity_for_append") internal mutating func reserveCapacityForAppend(newElementsCount: Int) { let oldCount = self.count let oldCapacity = self.capacity let newCount = oldCount + newElementsCount // Ensure uniqueness, mutability, and sufficient storage. Note that // for consistency, we need unique self even if newElements is empty. self.reserveCapacity( newCount > oldCapacity ? Swift.max(newCount, _growArrayCapacity(oldCapacity)) : newCount) } @inlinable public mutating func _customRemoveLast() -> Element? { _precondition(count > 0, "Can't removeLast from an empty ArraySlice") // FIXME(performance): if `self` is uniquely referenced, we should remove // the element as shown below (this will deallocate the element and // decrease memory use). If `self` is not uniquely referenced, the code // below will make a copy of the storage, which is wasteful. Instead, we // should just shrink the view without allocating new storage. let i = endIndex // We don't check for overflow in `i - 1` because `i` is known to be // positive. let result = self[i &- 1] self.replaceSubrange((i &- 1)..<i, with: EmptyCollection()) return result } /// Removes and returns the element at the specified position. /// /// All the elements following the specified position are moved up to /// close the gap. /// /// var measurements: [Double] = [1.1, 1.5, 2.9, 1.2, 1.5, 1.3, 1.2] /// let removed = measurements.remove(at: 2) /// print(measurements) /// // Prints "[1.1, 1.5, 1.2, 1.5, 1.3, 1.2]" /// /// - Parameter index: The position of the element to remove. `index` must /// be a valid index of the array. /// - Returns: The element at the specified index. /// /// - Complexity: O(*n*), where *n* is the length of the array. @inlinable @discardableResult public mutating func remove(at index: Int) -> Element { let result = self[index] self.replaceSubrange(index..<(index + 1), with: EmptyCollection()) return result } /// Inserts a new element at the specified position. /// /// The new element is inserted before the element currently at the specified /// index. If you pass the array's `endIndex` property as the `index` /// parameter, the new element is appended to the array. /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.insert(100, at: 3) /// numbers.insert(200, at: numbers.endIndex) /// /// print(numbers) /// // Prints "[1, 2, 3, 100, 4, 5, 200]" /// /// - Parameter newElement: The new element to insert into the array. /// - Parameter i: The position at which to insert the new element. /// `index` must be a valid index of the array or equal to its `endIndex` /// property. /// /// - Complexity: O(*n*), where *n* is the length of the array. If /// `i == endIndex`, this method is equivalent to `append(_:)`. @inlinable public mutating func insert(_ newElement: __owned Element, at i: Int) { _checkIndex(i) self.replaceSubrange(i..<i, with: CollectionOfOne(newElement)) } /// Removes all elements from the array. /// /// - Parameter keepCapacity: Pass `true` to keep the existing capacity of /// the array after removing its elements. The default value is /// `false`. /// /// - Complexity: O(*n*), where *n* is the length of the array. @inlinable public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) { if !keepCapacity { _buffer = _Buffer() } else { self.replaceSubrange(indices, with: EmptyCollection()) } } //===--- algorithms -----------------------------------------------------===// @inlinable public mutating func _withUnsafeMutableBufferPointerIfSupported<R>( _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R? { return try withUnsafeMutableBufferPointer { (bufferPointer) -> R in return try body(&bufferPointer) } } @inlinable public __consuming func _copyToContiguousArray() -> ContiguousArray<Element> { if let n = _buffer.requestNativeBuffer() { return ContiguousArray(_buffer: n) } return _copyCollectionToContiguousArray(_buffer) } } extension ArraySlice: CustomReflectable { /// A mirror that reflects the array. public var customMirror: Mirror { return Mirror( self, unlabeledChildren: self, displayStyle: .collection) } } extension ArraySlice: CustomStringConvertible, CustomDebugStringConvertible { /// A textual representation of the array and its elements. public var description: String { return _makeCollectionDescription() } /// A textual representation of the array and its elements, suitable for /// debugging. public var debugDescription: String { return _makeCollectionDescription(withTypeName: "ArraySlice") } } extension ArraySlice { @usableFromInline @_transparent internal func _cPointerArgs() -> (AnyObject?, UnsafeRawPointer?) { let p = _baseAddressIfContiguous if _fastPath(p != nil || isEmpty) { return (_owner, UnsafeRawPointer(p)) } let n = ContiguousArray(self._buffer)._buffer return (n.owner, UnsafeRawPointer(n.firstElementAddress)) } } extension ArraySlice { /// Calls a closure with a pointer to the array's contiguous storage. /// /// Often, the optimizer can eliminate bounds checks within an array /// algorithm, but when that fails, invoking the same algorithm on the /// buffer pointer passed into your closure lets you trade safety for speed. /// /// The following example shows how you can iterate over the contents of the /// buffer pointer: /// /// let numbers = [1, 2, 3, 4, 5] /// let sum = numbers.withUnsafeBufferPointer { buffer -> Int in /// var result = 0 /// for i in stride(from: buffer.startIndex, to: buffer.endIndex, by: 2) { /// result += buffer[i] /// } /// return result /// } /// // 'sum' == 9 /// /// The pointer passed as an argument to `body` is valid only during the /// execution of `withUnsafeBufferPointer(_:)`. Do not store or return the /// pointer for later use. /// /// - Parameter body: A closure with an `UnsafeBufferPointer` parameter that /// points to the contiguous storage for the array. If /// `body` has a return value, that value is also used as the return value /// for the `withUnsafeBufferPointer(_:)` method. The pointer argument is /// valid only for the duration of the method's execution. /// - Returns: The return value, if any, of the `body` closure parameter. @inlinable public func withUnsafeBufferPointer<R>( _ body: (UnsafeBufferPointer<Element>) throws -> R ) rethrows -> R { return try _buffer.withUnsafeBufferPointer(body) } /// Calls the given closure with a pointer to the array's mutable contiguous /// storage. /// /// Often, the optimizer can eliminate bounds checks within an array /// algorithm, but when that fails, invoking the same algorithm on the /// buffer pointer passed into your closure lets you trade safety for speed. /// /// The following example shows how modifying the contents of the /// `UnsafeMutableBufferPointer` argument to `body` alters the contents of /// the array: /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.withUnsafeMutableBufferPointer { buffer in /// for i in stride(from: buffer.startIndex, to: buffer.endIndex - 1, by: 2) { /// buffer.swapAt(i, i + 1) /// } /// } /// print(numbers) /// // Prints "[2, 1, 4, 3, 5]" /// /// The pointer passed as an argument to `body` is valid only during the /// execution of `withUnsafeMutableBufferPointer(_:)`. Do not store or /// return the pointer for later use. /// /// - Warning: Do not rely on anything about the array that is the target of /// this method during execution of the `body` closure; it might not /// appear to have its correct value. Instead, use only the /// `UnsafeMutableBufferPointer` argument to `body`. /// /// - Parameter body: A closure with an `UnsafeMutableBufferPointer` /// parameter that points to the contiguous storage for the array. /// If `body` has a return value, that value is also /// used as the return value for the `withUnsafeMutableBufferPointer(_:)` /// method. The pointer argument is valid only for the duration of the /// method's execution. /// - Returns: The return value, if any, of the `body` closure parameter. @_semantics("array.withUnsafeMutableBufferPointer") @inline(__always) // Performance: This method should get inlined into the // caller such that we can combine the partial apply with the apply in this // function saving on allocating a closure context. This becomes unnecessary // once we allocate noescape closures on the stack. public mutating func withUnsafeMutableBufferPointer<R>( _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R { let count = self.count // Ensure unique storage _buffer._outlinedMakeUniqueBuffer(bufferCount: count) // Ensure that body can't invalidate the storage or its bounds by // moving self into a temporary working array. // NOTE: The stack promotion optimization that keys of the // "array.withUnsafeMutableBufferPointer" semantics annotation relies on the // array buffer not being able to escape in the closure. It can do this // because we swap the array buffer in self with an empty buffer here. Any // escape via the address of self in the closure will therefore escape the // empty array. var work = ArraySlice() (work, self) = (self, work) // Create an UnsafeBufferPointer over work that we can pass to body let pointer = work._buffer.firstElementAddress var inoutBufferPointer = UnsafeMutableBufferPointer( start: pointer, count: count) // Put the working array back before returning. defer { _precondition( inoutBufferPointer.baseAddress == pointer && inoutBufferPointer.count == count, "ArraySlice withUnsafeMutableBufferPointer: replacing the buffer is not allowed") (work, self) = (self, work) } // Invoke the body. return try body(&inoutBufferPointer) } @inlinable public __consuming func _copyContents( initializing buffer: UnsafeMutableBufferPointer<Element> ) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index) { guard !self.isEmpty else { return (makeIterator(),buffer.startIndex) } // It is not OK for there to be no pointer/not enough space, as this is // a precondition and Array never lies about its count. guard var p = buffer.baseAddress else { _preconditionFailure("Attempt to copy contents into nil buffer pointer") } _precondition(self.count <= buffer.count, "Insufficient space allocated to copy array contents") if let s = _baseAddressIfContiguous { p.initialize(from: s, count: self.count) // Need a _fixLifetime bracketing the _baseAddressIfContiguous getter // and all uses of the pointer it returns: _fixLifetime(self._owner) } else { for x in self { p.initialize(to: x) p += 1 } } var it = IndexingIterator(_elements: self) it._position = endIndex return (it,buffer.index(buffer.startIndex, offsetBy: self.count)) } } extension ArraySlice { /// Replaces a range of elements with the elements in the specified /// collection. /// /// This method has the effect of removing the specified range of elements /// from the array and inserting the new elements at the same location. The /// number of new elements need not match the number of elements being /// removed. /// /// In this example, three elements in the middle of an array of integers are /// replaced by the five elements of a `Repeated<Int>` instance. /// /// var nums = [10, 20, 30, 40, 50] /// nums.replaceSubrange(1...3, with: repeatElement(1, count: 5)) /// print(nums) /// // Prints "[10, 1, 1, 1, 1, 1, 50]" /// /// If you pass a zero-length range as the `subrange` parameter, this method /// inserts the elements of `newElements` at `subrange.startIndex`. Calling /// the `insert(contentsOf:at:)` method instead is preferred. /// /// Likewise, if you pass a zero-length collection as the `newElements` /// parameter, this method removes the elements in the given subrange /// without replacement. Calling the `removeSubrange(_:)` method instead is /// preferred. /// /// - Parameters: /// - subrange: The subrange of the array to replace. The start and end of /// a subrange must be valid indices of the array. /// - newElements: The new elements to add to the array. /// /// - Complexity: O(*n* + *m*), where *n* is length of the array and /// *m* is the length of `newElements`. If the call to this method simply /// appends the contents of `newElements` to the array, this method is /// equivalent to `append(contentsOf:)`. @inlinable @_semantics("array.mutate_unknown") public mutating func replaceSubrange<C>( _ subrange: Range<Int>, with newElements: __owned C ) where C: Collection, C.Element == Element { _precondition(subrange.lowerBound >= _buffer.startIndex, "ArraySlice replace: subrange start is before the startIndex") _precondition(subrange.upperBound <= _buffer.endIndex, "ArraySlice replace: subrange extends past the end") let oldCount = _buffer.count let eraseCount = subrange.count let insertCount = newElements.count let growth = insertCount - eraseCount if _buffer.requestUniqueMutableBackingBuffer( minimumCapacity: oldCount + growth) != nil { _buffer.replaceSubrange( subrange, with: insertCount, elementsOf: newElements) } else { _buffer._arrayOutOfPlaceReplace(subrange, with: newElements, count: insertCount) } } } extension ArraySlice: Equatable where Element: Equatable { /// Returns a Boolean value indicating whether two arrays contain the same /// elements in the same order. /// /// You can use the equal-to operator (`==`) to compare any two arrays /// that store the same, `Equatable`-conforming element type. /// /// - Parameters: /// - lhs: An array to compare. /// - rhs: Another array to compare. @inlinable public static func ==(lhs: ArraySlice<Element>, rhs: ArraySlice<Element>) -> Bool { let lhsCount = lhs.count if lhsCount != rhs.count { return false } // Test referential equality. if lhsCount == 0 || lhs._buffer.identity == rhs._buffer.identity { return true } var streamLHS = lhs.makeIterator() var streamRHS = rhs.makeIterator() var nextLHS = streamLHS.next() while nextLHS != nil { let nextRHS = streamRHS.next() if nextLHS != nextRHS { return false } nextLHS = streamLHS.next() } return true } } extension ArraySlice: Hashable where Element: Hashable { /// Hashes the essential components of this value by feeding them into the /// given hasher. /// /// - Parameter hasher: The hasher to use when combining the components /// of this instance. @inlinable public func hash(into hasher: inout Hasher) { hasher.combine(count) // discriminator for element in self { hasher.combine(element) } } } extension ArraySlice { /// Calls the given closure with a pointer to the underlying bytes of the /// array's mutable contiguous storage. /// /// The array's `Element` type must be a *trivial type*, which can be copied /// with just a bit-for-bit copy without any indirection or /// reference-counting operations. Generally, native Swift types that do not /// contain strong or weak references are trivial, as are imported C structs /// and enums. /// /// The following example copies bytes from the `byteValues` array into /// `numbers`, an array of `Int`: /// /// var numbers: [Int32] = [0, 0] /// var byteValues: [UInt8] = [0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00] /// /// numbers.withUnsafeMutableBytes { destBytes in /// byteValues.withUnsafeBytes { srcBytes in /// destBytes.copyBytes(from: srcBytes) /// } /// } /// // numbers == [1, 2] /// /// The pointer passed as an argument to `body` is valid only for the /// lifetime of the closure. Do not escape it from the closure for later /// use. /// /// - Warning: Do not rely on anything about the array that is the target of /// this method during execution of the `body` closure; it might not /// appear to have its correct value. Instead, use only the /// `UnsafeMutableRawBufferPointer` argument to `body`. /// /// - Parameter body: A closure with an `UnsafeMutableRawBufferPointer` /// parameter that points to the contiguous storage for the array. /// If no such storage exists, it is created. If `body` has a return value, that value is also /// used as the return value for the `withUnsafeMutableBytes(_:)` method. /// The argument is valid only for the duration of the closure's /// execution. /// - Returns: The return value, if any, of the `body` closure parameter. @inlinable public mutating func withUnsafeMutableBytes<R>( _ body: (UnsafeMutableRawBufferPointer) throws -> R ) rethrows -> R { return try self.withUnsafeMutableBufferPointer { return try body(UnsafeMutableRawBufferPointer($0)) } } /// Calls the given closure with a pointer to the underlying bytes of the /// array's contiguous storage. /// /// The array's `Element` type must be a *trivial type*, which can be copied /// with just a bit-for-bit copy without any indirection or /// reference-counting operations. Generally, native Swift types that do not /// contain strong or weak references are trivial, as are imported C structs /// and enums. /// /// The following example copies the bytes of the `numbers` array into a /// buffer of `UInt8`: /// /// var numbers = [1, 2, 3] /// var byteBuffer: [UInt8] = [] /// numbers.withUnsafeBytes { /// byteBuffer.append(contentsOf: $0) /// } /// // byteBuffer == [1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, ...] /// /// - Parameter body: A closure with an `UnsafeRawBufferPointer` parameter /// that points to the contiguous storage for the array. /// If no such storage exists, it is created. If `body` has a return value, that value is also /// used as the return value for the `withUnsafeBytes(_:)` method. The /// argument is valid only for the duration of the closure's execution. /// - Returns: The return value, if any, of the `body` closure parameter. @inlinable public func withUnsafeBytes<R>( _ body: (UnsafeRawBufferPointer) throws -> R ) rethrows -> R { return try self.withUnsafeBufferPointer { try body(UnsafeRawBufferPointer($0)) } } } extension ArraySlice { @inlinable public // @testable init(_startIndex: Int) { self.init( _buffer: _Buffer( _buffer: ContiguousArray()._buffer, shiftedToStartIndex: _startIndex)) } }
38.832432
99
0.663854
8aa345687812575d0a766c1d3c987d4f311a1f51
818
// // InterestingCell.swift // Flickrrr // // Created by Kedar Sukerkar on 30/07/18. // Copyright © 2018 Kedar Sukerkar. All rights reserved. // import UIKit class InterestingCell: UICollectionViewCell{ @IBOutlet weak var interestingImageView: UIImageView! func setData(photo: Photo ){ if interestingImageView.image == nil{ interestingImageView.sd_setImage(with: URL(string: "http://farm\(photo.farm).staticflickr.com/\(photo.server)/\(photo.id)_\(photo.secret)_t_d.jpg" ) ) }else{ interestingImageView.image = nil interestingImageView.sd_setImage(with: URL(string: "http://farm\(photo.farm).staticflickr.com/\(photo.server)/\(photo.id)_\(photo.secret)_t_d.jpg" )) } } }
26.387097
160
0.619804
feda3c484187df80e28a41736c6801b244a397cc
525
// // ViewController.swift // HelloWorld // // Created by Massimiliano Bigatti on 19/10/15. // Copyright © 2015 Massimiliano Bigatti. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
20.192308
80
0.68
099c6ccf8fa57990a843bceef8eec8f216f43a75
1,462
//: Playground - noun: a place where people can play import Cocoa var str = "Hello, playground" protocol Writer{ func write(s:String) } class SystemOutNewPrinter{ func newPrintToSystemOut(s:String){ print(s) } } class SystemOutPrinter{ func printToSystemOut(s:String){ print(s) } } class PrinterAdapter : Writer{ var adaptee:SystemOutPrinter init(adaptee:SystemOutPrinter){ self.adaptee = adaptee } func write(s: String) { adaptee.printToSystemOut(s); } } class NewPrinterAdapter : Writer{ var adaptee:SystemOutNewPrinter init(adaptee:SystemOutNewPrinter){ self.adaptee = adaptee } func write(s: String) { adaptee.newPrintToSystemOut(s); } } print("Creating the Adaptees...") let adaptee = SystemOutPrinter(); let newAdaptee = SystemOutNewPrinter(); print("issuing the request to the Adaptees") adaptee.printToSystemOut("Test successful") newAdaptee.newPrintToSystemOut("Test successful") print("Now generate the same output, but using Adapters...") print("Creating the Adapers...") let myTarget = PrinterAdapter(adaptee: adaptee) let myNewTarget = NewPrinterAdapter(adaptee: newAdaptee) print("Each pair of Adapter and Adaptee are the same object?") print(myTarget === adaptee) print(myNewTarget === newAdaptee) print("issuing the request to the Adapters...") myTarget.write("Test successful") myNewTarget.write("Test successful")
22.492308
62
0.708618
db1952a98db39aaefa56b682bcdadd29c5c5fd0e
10,115
// // SAWebJSManager.swift // SAWebBridgeDemo // // Created by Sarkizz on 2019/12/17. // Copyright © 2019 Sarkizz. All rights reserved. // import Foundation /// Keys for js message object which from web calling jssdk api. public enum SAJSMessageKey: String { case sessionId case action case params } /// Callback object keys. When web call jssdk api, native must callback immediately. public enum SAJSCallbackKey: String { case code case sessionId case action case from case progress case data } /// Callback object types. public enum SAJSCallbackType: String { case normal case promise case promise_result case progress case exec } /// JS event actions that parse from SAWebJSManager public enum SAJSActionType { public enum NotificationType { case register(key: String) case unregister(key: String) case notify(key: String) case resolve case reject } public enum EventType { case sync(_ name: String) case async(_ name: String) } case none case event(_ type: EventType) case notification(_ type: NotificationType) case localStorage(action: SALocalStorage.SALocalStorageAction) } /// The default return codes. You can define your codes for yourself. public enum SAReturnCode: String { case success = "SUCCESS" case failed = "FAILED" case cancel = "CANCEL" case missSessionId = "ERR_MISS_SESSIONID" case missAction = "ERR_MISS_ACTION" case invaildAction = "ERR_INVAILD_ACTION" case invaildParams = "ERR_INVAILD_PARAMS" case noData = "ERR_NO_DATA" case notFound = "ERR_NOT_FOUND" case unsupport = "ERR_NOT_SUPPORT" case timeout = "ERR_TIMEOUT" case permission = "ERR_NO_PERMISSION" case authorization = "ERR_AUTHORIZATION" case unknow = "ERR_UNKNOW" } public enum SAJSHandleResult { case sync(code: String = SAReturnCode.success.rawValue, data: Any? = nil) case promise case promiseResult(code: String = SAReturnCode.success.rawValue, data: Any? = nil) case progress(Double)// 0-1 case notify(key: String, data: Any? = nil, context: [String: Any]? = nil) } open class SAWebJSManager { public static let `default` = SAWebJSManager(Setting()) public var setting: Setting public struct Setting { let jssdkFlag = "jssdk." let syncEventFlag = "jssdk.sync." let asyncEventFlag = "jssdk.async." let registerFlag = "jssdk_register." let unregisterFlag = "jssdk_unregister." let resolveFlag = "jssdk_exec_resolve" let rejectFlag = "jssdk_exec_reject" let localStorageFlag = "jssdk.localStorage." var notifyAPIFlag = "api." var notifyEventFlag = "event." } public required init(_ setting: Setting) { self.setting = setting } public typealias CallbackResult = String public enum ResultType { case normal case missAction case invaildAction case missSessionId case unknow } public struct SAWebJSScriptInfo: Equatable { public static func == (lhs: SAWebJSManager.SAWebJSScriptInfo, rhs: SAWebJSManager.SAWebJSScriptInfo) -> Bool { return lhs.type == rhs.type && lhs.sessionId == rhs.sessionId } public static let failedSessionId = -99998 public static let missActionInfo = SAWebJSScriptInfo.init(type: .missAction, sessionId: failedSessionId, action: .none) public static let invaildActionInfo = SAWebJSScriptInfo.init(type: .invaildAction, sessionId: failedSessionId, action: .none) public static let missSessionId = SAWebJSScriptInfo.init(type: .missSessionId, sessionId: failedSessionId, action: .none) public static let unknowInfo = SAWebJSScriptInfo.init(type: .unknow, sessionId: failedSessionId, action: .none) public var type: ResultType public var sessionId: Int public var action: SAJSActionType public var params: Any? public static func normal(sessionId: Int, action: SAJSActionType, params: Any?) -> SAWebJSScriptInfo { return .init(type: .normal, sessionId: sessionId, action: action, params: params) } } open func shouldHandleScript(_ msg: String) -> Bool { return msg.hasPrefix("{\"type\": \"bridge\"") } open func parseScript(_ script: String) -> SAWebJSScriptInfo? { guard shouldHandleScript(script), let body = scriptToDic(script) else { return .unknowInfo } guard let id = body[.sessionId] as? Int else { return .missSessionId } guard let action = body[.action] as? String else { return .missActionInfo } let params = body[.params] if let key = registerKey(action) { return .normal(sessionId: id, action: .notification(.register(key: key)), params: params) } else if let key = unregisterKey(action) { return .normal(sessionId: id, action: .notification(.unregister(key: key)), params: params) } else if let event = syncEvent(action) { return .normal(sessionId: id, action: .event(.sync(event)), params: params) } else if let event = asyncEvent(action) { return .normal(sessionId: id, action: .event(.async(event)), params: params) } else if let key = notifyKey(action) { return .normal(sessionId: id, action: .notification(.notify(key: key)), params: params) } else if resolve(action) { return .normal(sessionId: id, action: .notification(.resolve), params: params) } else if reject(action) { return .normal(sessionId: id, action: .notification(.reject), params: params) } else if let type = localstorageType(action) { return .normal(sessionId: id, action: .localStorage(action: type), params: params) } else { return .invaildActionInfo } } } extension SAWebJSManager { private func scriptToDic(_ script: String) -> [SAJSMessageKey: Any]? { guard let data = script.data(using: .utf8) else { return nil } do { let obj = try JSONSerialization.jsonObject(with: data, options: .allowFragments) if let dict = obj as? [String: Any], let body = dict["body"] as? [String: Any] { let rs = Dictionary(uniqueKeysWithValues: body.map({k, v in (SAJSMessageKey(rawValue: k), v) }).compactMap({ t in t.0 == nil ? nil : (t.0!, t.1) })) return rs } } catch {} return nil } private func registerKey(_ messageAction: String) -> String? { if messageAction.hasPrefix(setting.registerFlag) { return messageAction.replacingOccurrences(of: setting.registerFlag, with: "") } return nil } private func unregisterKey(_ messageAction: String) -> String? { if messageAction.hasPrefix(setting.unregisterFlag) { return messageAction.replacingOccurrences(of: setting.unregisterFlag, with: "") } return nil } private func syncEvent(_ messageAction: String) -> String? { if messageAction.hasPrefix(setting.syncEventFlag) { let action = messageAction.replacingOccurrences(of: setting.syncEventFlag, with: "") return action } return nil } private func asyncEvent(_ messageAction: String) -> String? { if messageAction.hasPrefix(setting.asyncEventFlag) { let action = messageAction.replacingOccurrences(of: setting.asyncEventFlag, with: "") return action } return nil } private func localstorageType(_ messageAction: String) -> SALocalStorage.SALocalStorageAction? { if messageAction.hasPrefix(setting.localStorageFlag) { let action = messageAction.replacingOccurrences(of: setting.localStorageFlag, with: "") return SALocalStorage.SALocalStorageAction(rawValue: action) } return nil } private func notifyKey(_ messageAction: String) -> String? { if messageAction.hasPrefix(setting.jssdkFlag+setting.notifyAPIFlag) || messageAction.hasPrefix(setting.jssdkFlag+setting.notifyEventFlag) { return messageAction.replacingOccurrences(of: setting.jssdkFlag, with: "") } return nil } private func resolve(_ messageAction: String) -> Bool { return messageAction == setting.resolveFlag } private func reject(_ messageAction: String) -> Bool { return messageAction == setting.rejectFlag } } extension Dictionary { public var jsonString: String? { do { let data = try JSONSerialization.data(withJSONObject: self, options: []) return String(data: data, encoding: .utf8) } catch let e { SADLog("Parse json error: \n\(e)") } return nil } } extension SAWebJSManager.CallbackResult { public static func rs(type: SAJSCallbackType, code: String? = nil, id: Int? = nil, key: String? = nil, data: Any? = nil, context: [String: Any]? = nil) -> Self? { var rs: [String: Any] = ["type": type.rawValue] rs["code"] = code rs["sessionId"] = id rs["action"] = key if type == .progress { rs["progress"] = data } else { if let str = data as? String, str.contains("\"") && str.hasPrefix("{") { rs["data"] = str.replacingOccurrences(of: "\"", with: "\\\"") } else { rs["data"] = data } } if let context = context { rs["context"] = context } return rs.jsonString } }
34.75945
133
0.613841
1cb02bf415de40c3c82c947592806a3eb00738ef
1,301
// // AppDelegate.swift // Lines // // Created by David Rönnqvist on 2017-03-23. // Copyright © 2017 David Rönnqvist // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { }
40.65625
82
0.753267
4b449281110cee4a5b52b44927d3c3a1f1a98720
1,797
import UIKit import Carbon import MagazineLayout final class KyotoViewController: UIViewController { enum ID { case top case photo } @IBOutlet var collectionView: UICollectionView! private let renderer = Renderer( adapter: KyotoMagazineLayoutAdapter(), updater: UICollectionViewUpdater() ) override var supportedInterfaceOrientations: UIInterfaceOrientationMask { .portrait } override func viewDidLoad() { super.viewDidLoad() title = "Kyoto" let layout = MagazineLayout() collectionView.collectionViewLayout = layout renderer.target = collectionView renderer.render { Section( id: ID.top, header: KyotoTop() ) Section( id: ID.photo, header: Header("PHOTOS"), footer: KyotoLicense { let url = URL(string: "https://unsplash.com/")! UIApplication.shared.open(url) }, cells: { KyotoImage(title: "Fushimi Inari-taisha", image: #imageLiteral(resourceName: "KyotoFushimiInari")) KyotoImage(title: "Arashiyama", image: #imageLiteral(resourceName: "KyotoArashiyama")) KyotoImage(title: "Byōdō-in", image: #imageLiteral(resourceName: "KyotoByōdōIn")) KyotoImage(title: "Gion", image: #imageLiteral(resourceName: "KyotoGion")) KyotoImage(title: "Kiyomizu-dera", image: #imageLiteral(resourceName: "KyotoKiyomizuDera")) }) } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() collectionView.performBatchUpdates(nil) } }
30.457627
118
0.582638
18415727603aa6829af3bc3d499a454f3a603f83
1,846
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // // EchoServerClientTest+XCTest.swift // import XCTest /// /// NOTE: This file was generated by generate_linux_tests.rb /// /// Do NOT edit this file directly as it will be regenerated automatically when needed. /// extension EchoServerClientTest { static var allTests : [(String, (EchoServerClientTest) -> () throws -> Void)] { return [ ("testEcho", testEcho), ("testLotsOfUnflushedWrites", testLotsOfUnflushedWrites), ("testEchoUnixDomainSocket", testEchoUnixDomainSocket), ("testConnectUnixDomainSocket", testConnectUnixDomainSocket), ("testChannelActiveOnConnect", testChannelActiveOnConnect), ("testWriteThenRead", testWriteThenRead), ("testCloseInInactive", testCloseInInactive), ("testFlushOnEmpty", testFlushOnEmpty), ("testWriteOnConnect", testWriteOnConnect), ("testWriteOnAccept", testWriteOnAccept), ("testWriteAfterChannelIsDead", testWriteAfterChannelIsDead), ("testPendingReadProcessedAfterWriteError", testPendingReadProcessedAfterWriteError), ("testChannelErrorEOFNotFiredThroughPipeline", testChannelErrorEOFNotFiredThroughPipeline), ("testPortNumbers", testPortNumbers), ] } }
39.276596
107
0.615385
d589e7215fdd6cdd0e95263c50be278ca253af69
2,936
// // DeviceView.swift // Patriot // // Displays a single device & state // // Created by Ron Lisle on 7/10/21. // import SwiftUI extension String { func camelCaseToWords() -> String { return unicodeScalars.dropFirst().reduce(String(prefix(1))) { return CharacterSet.uppercaseLetters.contains($1) ? $0 + " " + String($1) : $0 + String($1) } } } struct DeviceView: View { @EnvironmentObject var model: PatriotModel @ObservedObject var device: Device @State var brighten = false var body: some View { GeometryReader { geometry in ZStack { VStack { Image(device.percent > 0 ? device.onImageName : device.offImageName) .resizable() .scaledToFit() .padding(0) .opacity(brighten ? 1.0 : 0.8) .onTapGesture { device.manualToggle() } .onLongPressGesture(minimumDuration: 1.0, perform: { model.selectedDevice = self.device model.showingDetails = true }, onPressingChanged: { pressed in brighten = pressed }) Spacer() } VStack { HStack { Spacer() Button(action: device.flipFavorite) { Image(systemName: device.isFavorite ? "star.fill" : "star") .renderingMode(.template) .resizable() .foregroundColor(device.isFavorite ? .yellow : .gray) .padding(4) .frame(width: geometry.size.width/4, height: geometry.size.width/4) } } Spacer() Text(device.name.camelCaseToWords()) .font(.subheadline) .foregroundColor(.white) } } .frame(width: geometry.size.width, height: geometry.size.width) .background(Color.black) } } } struct DeviceView_Previews: PreviewProvider { static var previews: some View { Group { DeviceView(device: Device(name: "LeftTrim", type: .Light, percent: 0, isFavorite: false)) .previewLayout(PreviewLayout.fixed(width: 100, height: 100)) .previewDisplayName("Device Off") DeviceView(device: Device(name: "KitchenCeiling", type: .Light, percent: 100, isFavorite: true)) .previewLayout(PreviewLayout.fixed(width: 100, height: 100)) .previewDisplayName("Device Favorite On") } } }
34.139535
108
0.474114
1a937cf929fa93895acd3560518d1bb4f985e72d
1,413
// // Tests_iOS.swift // Tests iOS // // Copyright © 2021 Xmartlabs SRL. All rights reserved. // import XCTest class Tests_iOS: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // UI tests must launch the application that they test. let app = XCUIApplication() app.launch() // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testLaunchPerformance() throws { if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) { // This measures how long it takes to launch your application. measure(metrics: [XCTApplicationLaunchMetric()]) { XCUIApplication().launch() } } } }
32.860465
182
0.65322
ff67db50f737e3522f517b372cd1ff9ef10bc58b
469
// // URLHelper.swift // SpacePhoto // // Created by Guillermo Alcalá Gamero on 21/8/17. // Copyright © 2017 Guillermo Alcalá Gamero. All rights reserved. // import Foundation extension URL { func withQueries(_ queries: [String: String]) -> URL? { var components = URLComponents(url: self, resolvingAgainstBaseURL: true) components?.queryItems = queries.flatMap { URLQueryItem(name: $0.0, value: $0.1) } return components?.url } }
26.055556
90
0.673774
ddc06a8a49619555301d07fb68f78fd9033c4f32
1,865
/* Typealiases START */ public typealias NetworkAPIValidationType = ValidationType public typealias NetworkAPITask = Task public typealias NetworkAPIMethod = Method public typealias NetworkParameterEncoding = ParameterEncoding public typealias NetworkJSONEncoding = JSONEncoding public typealias NetworkURLEncoding = URLEncoding public typealias NetworkResponseValidationType = ValidationType public typealias NetworkResponse = MResponse public typealias NetworkCompletionClosure<T: Codable> = (Result<T, Error>) -> () /* Typealiases END */ /* Network Target Protocols START */ public protocol NetworkAPITarget: TargetType { var parameterEncoding: ParameterEncoding { get } var parameters: [String: Any] { get } } public protocol NetworkAPIAuthenticatedTarget: NetworkAPITarget { var shouldAuthenticate: Bool { get } } public protocol NetworkAPIRefreshesToken { static var refreshTokenEndpoint: NetworkAPITarget { get } } public protocol NetworkTargetWithHeaderResult { var resultCodeHeaderKey: String { get } var resultMessageHeaderKey: String { get } } public protocol NetworkAPIRefreshesTokenWithHeaderCode: NetworkAPIRefreshesToken { var accessTokenExpiredResultCode: Int { get } var refreshTokenExpiredResultCode: Int { get } } public protocol GazelRestAPITarget: NetworkAPIAuthenticatedTarget, NetworkAPIRefreshesTokenWithHeaderCode, NetworkTargetWithHeaderResult {} /* Network Target Protocols END */ /* Network Adapter Protocols START */ public struct RefreshTokensResponseModel: Codable { public var userToken: String public var refreshToken: String } public protocol NetworkAuthenticationTokenProvider { var accessToken: String? { get set } var refreshToken: String? { get set } } public enum NetworkAuthenticationProvider { case Gazel } /* Network Adapter Protocols END */
23.607595
139
0.78874
f9e97d84da74acd7ff45b9af52bc8f0712decd95
2,021
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. import Foundation import azureSwiftRuntime internal struct CredentialUpdatePropertiesData : CredentialUpdatePropertiesProtocol { public var userName: String? public var password: String? public var description: String? enum CodingKeys: String, CodingKey {case userName = "userName" case password = "password" case description = "description" } public init() { } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) if container.contains(.userName) { self.userName = try container.decode(String?.self, forKey: .userName) } if container.contains(.password) { self.password = try container.decode(String?.self, forKey: .password) } if container.contains(.description) { self.description = try container.decode(String?.self, forKey: .description) } if var pageDecoder = decoder as? PageDecoder { if pageDecoder.isPagedData, let nextLinkName = pageDecoder.nextLinkName { pageDecoder.nextLink = try UnknownCodingKey.decodeStringForKey(decoder: decoder, keyForDecode: nextLinkName) } } } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) if self.userName != nil {try container.encode(self.userName, forKey: .userName)} if self.password != nil {try container.encode(self.password, forKey: .password)} if self.description != nil {try container.encode(self.description, forKey: .description)} } } extension DataFactory { public static func createCredentialUpdatePropertiesProtocol() -> CredentialUpdatePropertiesProtocol { return CredentialUpdatePropertiesData() } }
38.865385
119
0.701633
0984d00d4fd02a52ff83a9ae3ee5d28a5deebf0f
2,347
// // PMGNavigationController.swift // PMG // // Created by Erik Mai on 25/5/20. // Copyright © 2020 Erik Mai. All rights reserved. // import UIKit class PMGNavigationController: UINavigationController { var landscapeLocked = false var portraitLocked = false override init(rootViewController: UIViewController) { super.init(rootViewController: rootViewController) self.navigationBar.barTintColor = UIColor(pmg: .primary) self.navigationBar.tintColor = UIColor(pmg: .white) self.navigationBar.titleTextAttributes = [.foregroundColor: UIColor(pmg: .white)] self.navigationBar.isTranslucent = false } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) self.navigationBar.barTintColor = UIColor(pmg: .primary) self.navigationBar.tintColor = UIColor(pmg: .white) self.navigationBar.isTranslucent = false } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: UIViewController Orientations override var shouldAutorotate: Bool { return true } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { if self.portraitLocked { return .portrait } if !self.landscapeLocked { return super.supportedInterfaceOrientations } return UIInterfaceOrientationMask.landscape } override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation { if self.portraitLocked { return .portrait } if !self.landscapeLocked { return super.preferredInterfaceOrientationForPresentation } if UIDevice.current.orientation == UIDeviceOrientation.landscapeLeft { return UIInterfaceOrientation.landscapeRight } else if UIDevice.current.orientation == UIDeviceOrientation.landscapeRight { return UIInterfaceOrientation.landscapeLeft } return UIInterfaceOrientation.landscapeRight } override var preferredStatusBarStyle: UIStatusBarStyle { return topViewController?.preferredStatusBarStyle ?? .default } }
32.150685
89
0.680869
e08a335791d32737862b680e5c8cbb7b21900871
914
public struct TMDBTVEpisode: Codable { public let airDate: String public let episodeNumber, id: Int public let name, overview, productionCode: String public let seasonNumber: Int public let showID: Int? public let stillPath: String? public let voteAverage: Double public let voteCount: Int public let crew: [TMDBCrew]? public let guestStars: [TMDBCast]? public let rating: Double? public enum CodingKeys: String, CodingKey { case airDate = "air_date" case episodeNumber = "episode_number" case id, name, overview case productionCode = "production_code" case seasonNumber = "season_number" case showID = "show_id" case stillPath = "still_path" case voteAverage = "vote_average" case voteCount = "vote_count" case crew case guestStars = "guest_stars" case rating } }
31.517241
53
0.658643
2972e37a51b6186da95fde24fd63e1039ec30a0d
302
// // MacOSOutputViewController.swift // APIconizer // // Created by Warren Gavin on 02/08/2017. // Copyright © 2017 Apokrupto. All rights reserved. // import Cocoa class MacOSOutputViewController: GeneratedImageViewController { override var iconSet: AppIconSet { return .mac } }
18.875
63
0.711921
89769ed65da302394f07ac5865425e2de5acd7af
312
// // AdjustmentDirection.swift // ODScrollView // // Created by Orçun Deniz on 07.03.2020. // Copyright © 2020 Orçun Deniz. All rights reserved. // import Foundation /// Default value is `.bottom` public enum AdjustmentDirection { /// case top /// case center /// case bottom }
13.565217
54
0.63141
1aab5b8d03e0f5efaf79f8f40e09c2f2bdfaf016
4,331
/// - Important: to make `@Environment` properties (e.g. `horizontalSizeClass`), internally accessible /// to extensions, add as sourcery annotation in `FioriSwiftUICore/Models/ModelDefinitions.swift` /// to declare a wrapped property /// e.g.: `// sourcery: add_env_props = ["horizontalSizeClass"]` import SwiftUI extension Fiori { enum ActivationScreen { struct Title: ViewModifier { func body(content: Content) -> some View { content .font(.system(size: 28, weight: .thin, design: .default)) .foregroundColor(.preferredColor(.primary1)) .multilineTextAlignment(.center) } } typealias TitleCumulative = EmptyModifier struct DescriptionText: ViewModifier { func body(content: Content) -> some View { content .font(.system(size: 17)) .foregroundColor(.preferredColor(.primary1)) .multilineTextAlignment(.center) } } typealias DescriptionTextCumulative = EmptyModifier struct TextInput: ViewModifier { func body(content: Content) -> some View { content .font(.system(size: 15)) .foregroundColor(.preferredColor(.primary1)) .multilineTextAlignment(.center) .keyboardType(.emailAddress) .disableAutocorrection(true) } } typealias TextInputCumulative = EmptyModifier struct Action: ViewModifier { func body(content: Content) -> some View { content .frame(minWidth: 169.0, minHeight: 20.0) } } typealias ActionCumulative = EmptyModifier struct Footnote: ViewModifier { func body(content: Content) -> some View { content .font(.system(size: 15)) .foregroundColor(.preferredColor(.primary1)) } } typealias FootnoteCumulative = EmptyModifier struct SecondaryAction: ViewModifier { func body(content: Content) -> some View { content .font(.system(size: 15)) .foregroundColor(.preferredColor(.primary1)) } } typealias SecondaryActionCumulative = EmptyModifier static let title = Title() static let descriptionText = DescriptionText() static let textInput = TextInput() static let action = Action() static let footnote = Footnote() static let secondaryAction = SecondaryAction() static let titleCumulative = TitleCumulative() static let descriptionTextCumulative = DescriptionTextCumulative() static let textInputCumulative = TextInputCumulative() static let actionCumulative = ActionCumulative() static let footnoteCumulative = FootnoteCumulative() static let secondaryActionCumulative = SecondaryActionCumulative() } } extension ActivationScreen: View { public var body: some View { VStack { title .padding(.top, 80) .padding(.bottom, 40) descriptionText .padding(.bottom, 56) textInput .padding(.bottom, 30) action .buttonStyle(StatefulButtonStyle()) .padding(.bottom, 16) footnote .padding(.bottom, 16) secondaryAction .buttonStyle(StatefulButtonStyle()) Spacer() } .padding(.leading, 32) .padding(.trailing, 32) } } @available(iOS 14.0, *) struct ActivationScreenLibraryContent: LibraryContentProvider { @LibraryContentBuilder var views: [LibraryItem] { LibraryItem(ActivationScreen(title: "Activation", descriptionText: "If you received a welcome email, follow the activation link in the email.Otherwise, enter your email address or scan the QR code to start onboarding. ", footnote: "Or", action: Action(actionText: "Next"), secondaryAction: Action(actionText: "Scan")), category: .control) } }
36.091667
326
0.57631
ffbf07ebbad8fb005dfdaac34bf9f4cce3bf39af
9,535
//===----------------------------------------------------------------------===// // // 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 http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // Implementation Note: Because StaticString is used in the // implementation of _precondition(), _fatalErrorMessage(), etc., we // keep it extremely close to the bare metal. In particular, because // we store only Builtin types, we are guaranteed that no assertions // are involved in its construction. This feature is crucial for // preventing infinite recursion even in non-asserting cases. /// A string type designed to represent text that is known at compile time. /// /// Instances of the `StaticString` type are immutable. `StaticString` provides /// limited, pointer-based access to its contents, unlike Swift's more /// commonly used `String` type. A static string can store its value as a /// pointer to an ASCII code unit sequence, as a pointer to a UTF-8 code unit /// sequence, or as a single Unicode scalar value. @_fixed_layout public struct StaticString : _ExpressibleByBuiltinUnicodeScalarLiteral, _ExpressibleByBuiltinExtendedGraphemeClusterLiteral, _ExpressibleByBuiltinStringLiteral, ExpressibleByUnicodeScalarLiteral, ExpressibleByExtendedGraphemeClusterLiteral, ExpressibleByStringLiteral, CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable { /// Either a pointer to the start of UTF-8 data, represented as an integer, /// or an integer representation of a single Unicode scalar. internal var _startPtrOrData: Builtin.Word /// If `_startPtrOrData` is a pointer, contains the length of the UTF-8 data /// in bytes. internal var _utf8CodeUnitCount: Builtin.Word /// Extra flags: /// /// - bit 0: set to 0 if `_startPtrOrData` is a pointer, or to 1 if it is a /// Unicode scalar. /// /// - bit 1: set to 1 if `_startPtrOrData` is a pointer and string data is /// ASCII. internal var _flags: Builtin.Int8 /// A pointer to the beginning of the string's UTF-8 encoded representation. /// /// The static string must store a pointer to either ASCII or UTF-8 code /// units. Accessing this property when `hasPointerRepresentation` is /// `false` triggers a runtime error. @_transparent public var utf8Start: UnsafePointer<UInt8> { _precondition( hasPointerRepresentation, "StaticString should have pointer representation") return UnsafePointer(bitPattern: UInt(_startPtrOrData))! } /// The stored Unicode scalar value. /// /// The static string must store a single Unicode scalar value. Accessing /// this property when `hasPointerRepresentation` is `true` triggers a /// runtime error. @_transparent public var unicodeScalar: UnicodeScalar { _precondition( !hasPointerRepresentation, "StaticString should have Unicode scalar representation") return UnicodeScalar(UInt32(UInt(_startPtrOrData)))! } /// The length in bytes of the static string's ASCII or UTF-8 representation. /// /// - Warning: If the static string stores a single Unicode scalar value, the /// value of `utf8CodeUnitCount` is unspecified. @_transparent public var utf8CodeUnitCount: Int { _precondition( hasPointerRepresentation, "StaticString should have pointer representation") return Int(_utf8CodeUnitCount) } /// A Boolean value indicating whether the static string stores a pointer to /// ASCII or UTF-8 code units. @_transparent public var hasPointerRepresentation: Bool { return (UInt8(_flags) & 0x1) == 0 } /// A Boolean value that is `true` if the static string stores a pointer to /// ASCII code units. /// /// Use this property in conjunction with `hasPointerRepresentation` to /// determine whether a static string with pointer representation stores an /// ASCII or UTF-8 code unit sequence. /// /// - Warning: If the static string stores a single Unicode scalar value, the /// value of `isASCII` is unspecified. @_transparent public var isASCII: Bool { return (UInt8(_flags) & 0x2) != 0 } /// Invokes the given closure with a buffer containing the static string's /// UTF-8 code unit sequence. /// /// This method works regardless of whether the static string stores a /// pointer or a single Unicode scalar value. /// /// The pointer argument to `body` is valid only for the lifetime of the /// closure. Do not escape it from the closure for later use. /// /// - Parameter body: A closure that takes a buffer pointer to the static /// string's UTF-8 code unit sequence as its sole argument. If the closure /// has a return value, it is used as the return value of the /// `withUTF8Buffer(invoke:)` method. The pointer argument is valid only /// for the duration of the closure's execution. /// - Returns: The return value of the `body` closure, if any. public func withUTF8Buffer<R>( _ body: (UnsafeBufferPointer<UInt8>) -> R) -> R { if hasPointerRepresentation { return body(UnsafeBufferPointer( start: utf8Start, count: Int(utf8CodeUnitCount))) } else { var buffer: UInt64 = 0 var i = 0 let sink: (UInt8) -> Void = { #if _endian(little) buffer = buffer | (UInt64($0) << (UInt64(i) * 8)) #else buffer = buffer | (UInt64($0) << (UInt64(7-i) * 8)) #endif i += 1 } UTF8.encode(unicodeScalar, into: sink) return body(UnsafeBufferPointer( start: UnsafePointer(Builtin.addressof(&buffer)), count: i)) } } /// Creates an empty static string. @_transparent public init() { self = "" } @_versioned @_transparent internal init( _start: Builtin.RawPointer, utf8CodeUnitCount: Builtin.Word, isASCII: Builtin.Int1 ) { // We don't go through UnsafePointer here to make things simpler for alias // analysis. A higher-level algorithm may be trying to make sure an // unrelated buffer is not accessed or freed. self._startPtrOrData = Builtin.ptrtoint_Word(_start) self._utf8CodeUnitCount = utf8CodeUnitCount self._flags = Bool(isASCII) ? (0x2 as UInt8)._value : (0x0 as UInt8)._value } @_versioned @_transparent internal init( unicodeScalar: Builtin.Int32 ) { self._startPtrOrData = UInt(UInt32(unicodeScalar))._builtinWordValue self._utf8CodeUnitCount = 0._builtinWordValue self._flags = UnicodeScalar(_builtinUnicodeScalarLiteral: unicodeScalar).isASCII ? (0x3 as UInt8)._value : (0x1 as UInt8)._value } @effects(readonly) @_transparent public init(_builtinUnicodeScalarLiteral value: Builtin.Int32) { self = StaticString(unicodeScalar: value) } /// Creates an instance initialized to a single Unicode scalar. /// /// Do not call this initializer directly. It may be used by the compiler /// when you initialize a static string with a Unicode scalar. @effects(readonly) @_transparent public init(unicodeScalarLiteral value: StaticString) { self = value } @effects(readonly) @_transparent public init( _builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer, utf8CodeUnitCount: Builtin.Word, isASCII: Builtin.Int1 ) { self = StaticString( _builtinStringLiteral: start, utf8CodeUnitCount: utf8CodeUnitCount, isASCII: isASCII ) } /// Creates an instance initialized to a single character that is made up of /// one or more Unicode code points. /// /// Do not call this initializer directly. It may be used by the compiler /// when you initialize a static string using an extended grapheme cluster. @effects(readonly) @_transparent public init(extendedGraphemeClusterLiteral value: StaticString) { self = value } @effects(readonly) @_transparent public init( _builtinStringLiteral start: Builtin.RawPointer, utf8CodeUnitCount: Builtin.Word, isASCII: Builtin.Int1 ) { self = StaticString( _start: start, utf8CodeUnitCount: utf8CodeUnitCount, isASCII: isASCII) } /// Creates an instance initialized to the value of a string literal. /// /// Do not call this initializer directly. It may be used by the compiler /// when you initialize a static string using a string literal. @effects(readonly) @_transparent public init(stringLiteral value: StaticString) { self = value } /// A string representation of the static string. public var description: String { return withUTF8Buffer { (buffer) in return String._fromWellFormedCodeUnitSequence(UTF8.self, input: buffer) } } /// A textual representation of the static string, suitable for debugging. public var debugDescription: String { return self.description.debugDescription } } extension StaticString { public var customMirror: Mirror { return Mirror(reflecting: description) } } extension StaticString { @available(*, unavailable, renamed: "utf8CodeUnitCount") public var byteSize: Int { Builtin.unreachable() } @available(*, unavailable, message: "use the 'String(_:)' initializer") public var stringValue: String { Builtin.unreachable() } }
33.812057
84
0.697116
c1c781f44945933916a1779499dbf2677a665fca
706
import Foundation import UIKit final class Section: RowType { var text: String init() { text = "" } convenience init(_ initializer: (Section) -> Void) { self.init() initializer(self) } var view: UIView { let container = UIView() if #available(iOS 13.0, *) { container.backgroundColor = .systemGray5 } else { container.backgroundColor = .lightGray } let label = UILabel() label.text = text label.font = .preferredFont(forTextStyle: .title2) label.embed(in: container, insets: UIEdgeInsets(top: 0, left: 16, bottom: 0, right: -16)) return container } }
21.393939
97
0.565156
698386a833f471123cf0ddc28f0bdb977edd0574
1,142
// // ChartView.swift // BTCTracker // // Created by Pasquale Vittoriosi for the Developer Academy on 18/02/22. // // import SwiftUI struct ChartView: View { let coin: Coin var body: some View { let data = coin.sparklineIn7d.price GeometryReader { proxy in Path { path in for index in data.indices { let xPos = proxy.size.width / CGFloat(data.count) * CGFloat(index + 1) let yAxis = (data.max() ?? 0) - (data.min() ?? 0) let yPos = (1 - CGFloat((data[index] - (data.min() ?? 0)) / yAxis)) * proxy.size.height if index == 0 { path.move(to: CGPoint(x: xPos, y:yPos)) } path.addLine(to: CGPoint(x: xPos, y:yPos)) } } .stroke(coin.priceChangePercentage24h > 0 ? Color.green: Color.red, style: StrokeStyle(lineWidth: CGFloat(2))) } } } struct ChartView_Previews: PreviewProvider { static var previews: some View { ChartView(coin: Coin.previewData) } }
27.190476
122
0.515762
034946a338350f7702b10eed4f1dffd6a484fa80
5,841
// // SwiftDate, Full featured Swift date library for parsing, validating, manipulating, and formatting dates and timezones. // Created by: Daniele Margutti // Main contributors: Jeroen Houtzager // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation // MARK: - DateInRegion Private Extension extension DateInRegion { /// Return a `DateComponent` object from a given set of `Calendar.Component` object with associated values and a specific region /// /// - parameter values: calendar components to set (with their values) /// - parameter multipler: optional multipler (by default is nil; to make an inverse component value it should be multipled by -1) /// - parameter region: optional region to set /// /// - returns: a `DateComponents` object internal static func componentsFrom(values: [Calendar.Component : Int], multipler: Int? = nil, setRegion region: Region? = nil) -> DateComponents { var cmps = DateComponents() if region != nil { cmps.calendar = region!.calendar cmps.calendar!.locale = region!.locale cmps.timeZone = region!.timeZone } values.forEach { key,value in if key != .timeZone && key != .calendar { cmps.setValue( (multipler == nil ? value : value * multipler!), for: key) } } return cmps } /// Create a new DateInRegion by adding specified DateComponents to self. /// If fails it return `nil`o object. /// /// - Parameter dateComponents: date components to add /// - Returns: a new instance of DateInRegion expressed in same region public func add(components dateComponents: DateComponents) -> DateInRegion? { let newDate = self.region.calendar.date(byAdding: dateComponents, to: self.absoluteDate) if newDate == nil { return nil } return DateInRegion(absoluteDate: newDate!, in: self.region) } /// Enumerate dates between two intervals by adding specified time components and return an array of dates. /// `startDate` interval will be the first item of the resulting array. The last item of the array is evaluated automatically. /// /// - Parameters: /// - startDate: starting date /// - endDate: ending date /// - components: components to add /// - normalize: normalize both start and end date at the start of the specified component (if nil, normalization is skipped) /// - Returns: an array of DateInRegion objects public static func dates(between startDate: DateInRegion, and endDate: DateInRegion, increment components: DateComponents) -> [DateInRegion]? { guard startDate.region.calendar == endDate.region.calendar else { return nil } var dates: [DateInRegion] = [] var currentDate = startDate while (currentDate <= endDate) { dates.append(currentDate) guard let c_date = currentDate.add(components: components) else { return nil } currentDate = c_date } return dates } /// Adjust time of the date by rounding to the next `value` interval. /// Interval can be `seconds` or `minutes` and you can specify the type of rounding function to use. /// /// - Parameters: /// - value: value to round /// - type: type of rounding public func roundAt(_ value: IntervalType, type: IntervalRoundingType = .ceil) { var roundedInterval: TimeInterval = 0 let rounded_abs_date = self.absoluteDate let seconds = value.seconds switch type { case .round: roundedInterval = (rounded_abs_date.timeIntervalSinceReferenceDate / seconds).rounded() * seconds case .ceil: roundedInterval = ceil(rounded_abs_date.timeIntervalSinceReferenceDate / seconds) * seconds case .floor: roundedInterval = floor(rounded_abs_date.timeIntervalSinceReferenceDate / seconds) * seconds } self.absoluteDate = Date(timeIntervalSinceReferenceDate: roundedInterval) } } // MARK: - DateInRegion Support for math operation // These functions allows us to make something like // `let newDate = (date - 3.days + 3.months)` // We can sum algebrically a `DateInRegion` object with a calendar component. public func + (lhs: DateInRegion, rhs: DateComponents) -> DateInRegion { let nextDate = lhs.region.calendar.date(byAdding: rhs, to: lhs.absoluteDate) return DateInRegion(absoluteDate: nextDate!, in: lhs.region) } public func - (lhs: DateInRegion, rhs: DateComponents) -> DateInRegion { return lhs + (-rhs) } public func + (lhs: DateInRegion, rhs: [Calendar.Component : Int]) -> DateInRegion { let cmps = DateInRegion.componentsFrom(values: rhs) return lhs + cmps } public func - (lhs: DateInRegion, rhs: [Calendar.Component : Int]) -> DateInRegion { var invertedCmps: [Calendar.Component : Int] = [:] rhs.forEach { invertedCmps[$0] = -$1 } return lhs + invertedCmps } public func - (lhs: DateInRegion, rhs: DateInRegion) -> TimeInterval { return DateTimeInterval(start: rhs.absoluteDate, end: lhs.absoluteDate).duration }
39.466216
148
0.729841
89a471ec2200d601dea3850635f19f02f2bade2d
8,067
// // TetrisScene.swift // ARTetris // // Created by Yuri Strot on 6/29/17. // Copyright © 2017 Exyte. All rights reserved. // import Foundation import SceneKit class TetrisScene { private static let colors : [UIColor] = [ UIColor(red:1.00, green:0.23, blue:0.19, alpha:1.0), UIColor(red:1.00, green:0.18, blue:0.33, alpha:1.0), UIColor(red:1.00, green:0.58, blue:0.00, alpha:1.0), UIColor(red:1.00, green:0.80, blue:0.00, alpha:1.0), UIColor(red:0.35, green:0.34, blue:0.84, alpha:1.0), UIColor(red:0.20, green:0.67, blue:0.86, alpha:1.0), UIColor(red:0.56, green:0.56, blue:0.58, alpha:1.0)] private static let wellColor = UIColor(red:0, green:0, blue:0, alpha:0.3) private static let floorColor = UIColor(red:0, green:0, blue:0, alpha:0) private static let scoresColor = UIColor(red:0.30, green:0.85, blue:0.39, alpha:1.0) private static let titleColor = UIColor(red:0.35, green:0.34, blue:0.84, alpha:1.0) private let cell: Float = 0.05 private let config: TetrisConfig private let scene: SCNScene private let x: Float private let y: Float private let z: Float private var blocksByLine: [[SCNNode]] = [] private var recent: SCNNode! private var frame: SCNNode! init(_ config: TetrisConfig, _ scene: SCNScene, _ x: Float, _ y: Float, _ z: Float) { self.config = config self.scene = scene self.x = x self.y = y self.z = z self.frame = createWellFrame(config.width, config.height) scene.rootNode.addChildNode(self.frame) } func show(_ current: TetrisState) { recent?.removeFromParentNode() recent = SCNNode() let tetromino = current.tetromino() for i in 0...3 { recent.addChildNode(block(current, tetromino.x(i), tetromino.y(i))) } scene.rootNode.addChildNode(recent) } func addToWell(_ current: TetrisState) { recent?.removeFromParentNode() let tetromino = current.tetromino() for i in 0...3 { let box = block(current, tetromino.x(i), tetromino.y(i)) scene.rootNode.addChildNode(box) let row = tetromino.y(i) + current.y while(blocksByLine.count <= row) { blocksByLine.append([]) } blocksByLine[row].append(box) } } func removeLines(_ lines: [Int], _ scores: Int) -> CFTimeInterval { let time = 0.2 // hide blocks in removed lines for line in lines { for block in blocksByLine[line] { animate(block, "opacity", from: 1, to: 0, during: time) } } Timer.scheduledTimer(withTimeInterval: time, repeats: false) { _ in self.showLinesScores(Float(lines.first!), scores) // drop blocks down to fill empty spaces of removed lines for (index, line) in lines.reversed().enumerated() { let nextLine = index + 1 < lines.count ? lines[index + 1] : self.blocksByLine.count if (nextLine > line + 1) { for j in line + 1..<nextLine { for block in self.blocksByLine[j] { let y1 = self.y + Float(j) * self.cell - self.cell / 2 let y2 = y1 - self.cell * Float(index + 1) self.animate(block, "position.y", from: y1, to: y2, during: time) } } } } // remove filled lines from the scene for line in lines { for block in self.blocksByLine[line] { block.removeFromParentNode() } self.blocksByLine.remove(at: line) } } return time * 2 } func drop(from: TetrisState, to: TetrisState) -> CFTimeInterval { // use animation time from 0.1 to 0.4 seconds depending on distance let delta = from.y - to.y let percent = Double(delta - 1) / Double(config.height - 1) let time = percent * 0.3 + 0.1 animate(recent, "position.y", from: 0, to: Float(-delta) * cell, during: time) return time } func showGameOver(_ scores: Int) { // Remove well frame from the scene self.frame.removeFromParentNode() // Use Moon gravity to make effect slower scene.physicsWorld.gravity = SCNVector3Make(0, -1.6, 0) // SCNPlanes are vertically oriented in their local coordinate space let matrix = SCNMatrix4Mult(SCNMatrix4MakeRotation(-Float.pi / 2, 1, 0, 0), translate(0, 0)) let floor = createNode(SCNPlane(width: 10, height: 10), matrix, TetrisScene.floorColor) floor.physicsBody = SCNPhysicsBody(type: .static, shape: nil) scene.rootNode.addChildNode(floor) for i in 0..<blocksByLine.count { // Apply little impulse to all boxes in a random direction. // This will force our Tetris "pyramid" to break up. let z = Float((Int(arc4random_uniform(3)) - 1) * i) * -0.01 let x = Float((Int(arc4random_uniform(3)) - 1) * i) * -0.01 let direction = SCNVector3Make(x, 0, z) for item in blocksByLine[i] { item.physicsBody = SCNPhysicsBody(type: .dynamic, shape: nil) // use 0.9 angular damping to prevents boxes from rotating like a crazy item.physicsBody!.angularDamping = 0.9 item.physicsBody!.applyForce(direction, asImpulse: true) } } Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false) { _ in self.showFinalScores(scores) } } private func showLinesScores(_ line: Float, _ scores: Int) { let node = createNode(text("+\(scores)"), translate(5, line, 2).scale(0.001), TetrisScene.scoresColor) let y = node.position.y animate(node, "position.y", from: y, to: y + cell * 4, during: 2) animate(node, "opacity", from: 1, to: 0, during: 2) self.scene.rootNode.addChildNode(node) } private func showFinalScores(_ scores: Int) { let x = Float(config.width / 2 - 2) let y = Float(config.height / 2) let node = createNode(text("Scores: \(scores)"), translate(x, y).scale(0.003), TetrisScene.titleColor) self.scene.rootNode.addChildNode(node) } private func createWellFrame(_ width: Int, _ height: Int) -> SCNNode { let node = SCNNode() for i in 1...width + 1 { addLine(to: node, 0.001, cell * Float(height + 3), 0.001, Float(i), 0, 0) addLine(to: node, 0.001, cell * Float(height + 3), 0.001, Float(i), 0, 1) } for i in 0...height + 3 { addLine(to: node, cell * Float(width), 0.001, 0.001, 1, Float(i), 0) addLine(to: node, cell * Float(width), 0.001, 0.001, 1, Float(i), 1) } for i in 1...width + 1 { for j in 0...height + 3 { addLine(to: node, 0.001, 0.001, cell, Float(i), Float(j), 1) } } return node } private func text(_ string: String) -> SCNText { let text = SCNText(string: string, extrusionDepth: 1) text.font = UIFont.systemFont(ofSize: 20) return text } private func block(_ state: TetrisState, _ x: Int, _ y: Int) -> SCNNode { let cell = cg(self.cell) let box = SCNBox(width: cell, height: cell, length: cell, chamferRadius: cell / 10) let matrix = translate(Float(state.x + x), Float(state.y + y) - 0.5) return createNode(box, matrix, TetrisScene.colors[state.index]) } private func addLine(to node: SCNNode, _ w: Float, _ h: Float, _ l: Float, _ x: Float, _ y: Float, _ z: Float) { let line = SCNBox(width: cg(w), height: cg(h), length: cg(l), chamferRadius: 0) let matrix = SCNMatrix4Translate(translate(x - 0.5, y, z - 0.5), w / 2, h / 2, -l / 2) node.addChildNode(createNode(line, matrix, TetrisScene.wellColor)) } private func animate(_ node: SCNNode, _ path: String, from: Any, to: Any, during: CFTimeInterval) { let animation = CABasicAnimation(keyPath: path) animation.fromValue = from animation.toValue = to animation.duration = during animation.fillMode = kCAFillModeForwards animation.isRemovedOnCompletion = false node.addAnimation(animation, forKey: nil) } private func createNode(_ geometry: SCNGeometry, _ matrix: SCNMatrix4, _ color: UIColor) -> SCNNode { let material = SCNMaterial() material.diffuse.contents = color // use the same material for all geometry elements geometry.firstMaterial = material let node = SCNNode(geometry: geometry) node.transform = matrix return node } private func translate(_ x: Float, _ y: Float, _ z: Float = 0) -> SCNMatrix4 { return SCNMatrix4MakeTranslation(self.x + x * cell, self.y + y * cell, self.z + z * cell) } private func cg(_ f: Float) -> CGFloat { return CGFloat(f) } } extension SCNMatrix4 { func scale(_ s: Float) -> SCNMatrix4 { return SCNMatrix4Scale(self, s, s, s) } }
34.922078
113
0.671377
18fa00dabb13a5b1452480f567de9b7c2aef0fb3
19,238
// // TheZygonInvasion.swift // DW Episode Guide // // Created by Mark Howard on 17/11/2021. // import SwiftUI import UniformTypeIdentifiers struct TheZygonInvasion: View { @Environment(\.managedObjectContext) private var viewContext @FetchRequest(entity: TheZygonInvasionClass.entity(), sortDescriptors: [], animation: .default) private var items: FetchedResults<TheZygonInvasionClass> @State var showingShare = false @AppStorage("TheZygonInvasionNotes") var notes = "" #if os(iOS) @Environment(\.horizontalSizeClass) var horizontalSizeClass @FocusState private var isFocused: Bool #endif var body: some View { #if os(macOS) ForEach(items) { item in ScrollView { HStack { Spacer() Image("TheZygonInvasion") .resizable() .scaledToFill() .cornerRadius(25) .frame(width: 130, height: 130) .contextMenu { Button(action: {let pasteboard = NSPasteboard.general pasteboard.clearContents() pasteboard.writeObjects([NSImage(named: "TheZygonInvasion")!]) }) { Text("Copy") } } .onDrag { let data = NSImage(named: "TheZygonInvasion")?.tiffRepresentation let provider = NSItemProvider(item: data as NSSecureCoding?, typeIdentifier: UTType.tiff.identifier as String) provider.previewImageHandler = { (handler, _, _) -> Void in handler?(data as NSSecureCoding?, nil) } return provider } Spacer() VStack { Text("\(item.title!)") .bold() .font(.title) .padding() Text("Story No. 258a") .font(.title3) Text("Written By - Peter Harness") .font(.title3) } Spacer() } .padding() Divider() HStack { Spacer() GroupBox(label: Label("Broadcast", systemImage: "dot.radiowaves.left.and.right")) { VStack { Spacer() HStack { Spacer() Text("\(item.broadcast!)") Spacer() } Spacer() } } Spacer() GroupBox(label: Label("Companions", systemImage: "person.2.fill")) { VStack { Spacer() HStack { Spacer() Text("\(item.companions!)") Spacer() } Spacer() } } Spacer() } .padding() Divider() HStack { Spacer() GroupBox(label: Label("Director", systemImage: "camera.fill")) { VStack { Spacer() HStack { Spacer() Text("\(item.director!)") Spacer() } Spacer() } } Spacer() GroupBox(label: Label("Producer", systemImage: "person.text.rectangle")) { VStack { Spacer() HStack { Spacer() Text("\(item.producer!)") Spacer() } Spacer() } } Spacer() } .padding() Divider() HStack { Spacer() GroupBox(label: Label("Doctor", systemImage: "person.crop.square.filled.and.at.rectangle")) { VStack { Spacer() HStack { Spacer() Text("\(item.doctor!)") Spacer() } Spacer() } } Spacer() GroupBox(label: Label("Length", systemImage: "clock.arrow.circlepath")) { VStack { Spacer() HStack { Spacer() Text("\(item.length!)") Spacer() } Spacer() } } Spacer() } .padding() Divider() HStack { Spacer() GroupBox(label: Label("Notes", systemImage: "note.text")) { TextEditor(text: $notes) .frame(height: 200) } Spacer() } .padding() } .toolbar { ToolbarItem(placement: .primaryAction) { Button(action: {self.showingShare = true}) { Image(systemName: "square.and.arrow.up") } .background(SharingsPicker(isPresented: $showingShare, sharingItems: [URL(string: "https://en.wikipedia.org/wiki/The_Zygon_Invasion")!])) } } .textSelection(.enabled) .navigationTitle("\(item.title!)") } #elseif os(iOS) if horizontalSizeClass == .compact { ForEach(items) { item in Form { HStack { Spacer() Image("TheZygonInvasion") .resizable() .scaledToFill() .frame(width: 150, height: 150) .contextMenu { Button(action: {let pasteboard = UIPasteboard.general pasteboard.image = UIImage(named: "TheZygonInvasion") }) { Label("Copy", systemImage: "doc.on.doc") } } .onDrag { return NSItemProvider(object: UIImage(named: "TheZygonInvasion")! as UIImage) } Spacer() } Text("Story No. 258a") .onDrag { return NSItemProvider(object: String("Story No. 258a") as NSString) } Text("Written By - Peter Harness") .onDrag { return NSItemProvider(object: String("Written By - Peter Harness") as NSString) } Section(header: Label("Broadcast", systemImage: "dot.radiowaves.left.and.right")) { Text("\(item.broadcast!)") .onDrag { return NSItemProvider(object: String("\(item.broadcast!)") as NSString) } } Section(header: Label("Companions", systemImage: "person.2.fill")) { Text("\(item.companions!)") .onDrag { return NSItemProvider(object: String("\(item.companions!)") as NSString) } } Section(header: Label("Director", systemImage: "camera.fill")) { Text("\(item.director!)") .onDrag { return NSItemProvider(object: String("\(item.director!)") as NSString) } } Section(header: Label("Producer", systemImage: "person.text.rectangle")) { Text("\(item.producer!)") .onDrag { return NSItemProvider(object: String("\(item.producer!)") as NSString) } } Section(header: Label("Doctor", systemImage: "person.crop.square.filled.and.at.rectangle")) { Text("\(item.doctor!)") .onDrag { return NSItemProvider(object: String("\(item.doctor!)") as NSString) } } Section(header: Label("Length", systemImage: "clock.arrow.circlepath")) { Text("\(item.length!)") .onDrag { return NSItemProvider(object: String("\(item.length!)") as NSString) } } Section(header: Label("Notes", systemImage: "note.text")) { TextEditor(text: $notes) .frame(height: 200) .focused($isFocused) } } .textSelection(.enabled) .navigationTitle("\(item.title!)") .navigationBarTitleDisplayMode(.inline) .toolbar { ToolbarItem(placement: .navigationBarTrailing) { Button(action: {self.showingShare = true}) { Image(systemName: "square.and.arrow.up") } .sheet(isPresented: $showingShare) { ActivityView(activityItems: [URL(string: "https://en.wikipedia.org/wiki/The_Zygon_Invasion")!], applicationActivities: nil) } } ToolbarItemGroup(placement: .keyboard) { Spacer() Button("Done") { isFocused = false } } } } } else { ForEach(items) { item in ScrollView { HStack { Spacer() Image("TheZygonInvasion") .resizable() .scaledToFill() .cornerRadius(25) .frame(width: 150, height: 150) .contextMenu { Button(action: {let pasteboard = UIPasteboard.general pasteboard.image = UIImage(named: "TheZygonInvasion") }) { Label("Copy", systemImage: "doc.on.doc") } } .onDrag { return NSItemProvider(object: UIImage(named: "TheZygonInvasion")! as UIImage) } Spacer() VStack { Text("\(item.title!)") .bold() .font(.title) .padding() Text("Story No. 258a") .font(.title3) .onDrag { return NSItemProvider(object: String("Story No. 258a") as NSString) } Text("Written By - Peter Harness") .font(.title3) .onDrag { return NSItemProvider(object: String("Written By - Peter Harness") as NSString) } } Spacer() } .padding() Divider() HStack { Spacer() GroupBox(label: Label("Broadcast", systemImage: "dot.radiowaves.left.and.right")) { VStack { Spacer() HStack { Spacer() Text("\(item.broadcast!)") Spacer() } Spacer() } } .onDrag { return NSItemProvider(object: String("\(item.broadcast!)") as NSString) } Spacer() GroupBox(label: Label("Companions", systemImage: "person.2.fill")) { VStack { Spacer() HStack { Spacer() Text("\(item.companions!)") Spacer() } Spacer() } } .onDrag { return NSItemProvider(object: String("\(item.companions!)") as NSString) } Spacer() } .padding() Divider() HStack { Spacer() GroupBox(label: Label("Director", systemImage: "camera.fill")) { VStack { Spacer() HStack { Spacer() Text("\(item.director!)") Spacer() } Spacer() } } .onDrag { return NSItemProvider(object: String("\(item.director!)") as NSString) } Spacer() GroupBox(label: Label("Producer", systemImage: "person.text.rectangle")) { VStack { Spacer() HStack { Spacer() Text("\(item.producer!)") Spacer() } Spacer() } } .onDrag { return NSItemProvider(object: String("\(item.producer!)") as NSString) } Spacer() } .padding() Divider() HStack { Spacer() GroupBox(label: Label("Doctor", systemImage: "person.crop.square.filled.and.at.rectangle")) { VStack { Spacer() HStack { Spacer() Text("\(item.doctor!)") Spacer() } Spacer() } } .onDrag { return NSItemProvider(object: String("\(item.doctor!)") as NSString) } Spacer() GroupBox(label: Label("Length", systemImage: "clock.arrow.circlepath")) { VStack { Spacer() HStack { Spacer() Text("\(item.length!)") Spacer() } Spacer() } } .onDrag { return NSItemProvider(object: String("\(item.length!)") as NSString) } Spacer() } .padding() Divider() HStack { Spacer() GroupBox(label: Label("Notes", systemImage: "note.text")) { TextEditor(text: $notes) .frame(height: 200) .focused($isFocused) } Spacer() } .padding() } .toolbar { ToolbarItem(placement: .primaryAction) { Button(action: {self.showingShare = true}) { Image(systemName: "square.and.arrow.up") } .sheet(isPresented: $showingShare) { ActivityView(activityItems: [URL(string: "https://en.wikipedia.org/wiki/The_Zygon_Invasion")!], applicationActivities: nil) } } ToolbarItemGroup(placement: .keyboard) { Spacer() Button("Done") { isFocused = false } } } .textSelection(.enabled) .navigationTitle("\(item.title!)") .navigationBarTitleDisplayMode(.inline) } } #endif } } struct TheZygonInvasion_Previews: PreviewProvider { static var previews: some View { TheZygonInvasion() } }
42.467991
157
0.326489
032f705b914eba7db0815d99a31853fbab5e2111
2,192
// // CurrentWeather.swift // weatherInfo // // Created by Macbook Pro on 1/17/2560 BE. // Copyright © 2560 Student. All rights reserved. // import Foundation import Alamofire class CurrentWeather{ var _cityName : String! var _date : String! var _weatherType : String! var _currentTemp : String! var cityName: String{ if(_cityName == nil){ _cityName = "" } return _cityName } var date: String{ if(_date == nil){ _date = "" } let dateFormatter = DateFormatter() dateFormatter.dateStyle = .long dateFormatter.timeStyle = .none let currentDate = dateFormatter.string(from: Date()) self._date = "Today \(currentDate)" return _date } var weatherType: String{ if(_weatherType == nil){ _weatherType = "" } return _weatherType } var currentTemp: String{ if(_currentTemp == nil){ _currentTemp = "" } return _currentTemp } func downloadWeatherDetails(completed: @escaping () -> () ){ Alamofire.request(CURRENT_WEATHER_URL).responseJSON { response in let result = response.result if let dict = result.value as? Dictionary<String, AnyObject >{ if let name = dict["name"] as? String{ self._cityName = name.uppercased() } if let main = dict["main"] as? Dictionary<String, AnyObject >{ if let currentTemparature = main["temp"] as? Double{ let kelvinToCelcius = Double(round(currentTemparature-273.15)) self._currentTemp = String(kelvinToCelcius) } } if let weather = dict["weather"] as? [Dictionary<String, AnyObject>]{ if let weatherType = weather[0]["main"] as? String{ self._weatherType = weatherType } } } completed() } } }
26.409639
86
0.507299
ff3155408fb001864459fb9593c46ec77f8822d8
879
// // ViewController.swift // IOS10BlurEffectTutorial // // Created by Arthur Knopper on 02/06/2017. // Copyright © 2017 Arthur Knopper. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var imageView: UIImageView! @IBAction func blurImage(_ sender: Any) { // 1 let darkBlur = UIBlurEffect(style: UIBlurEffectStyle.dark) // 2 let blurView = UIVisualEffectView(effect: darkBlur) blurView.frame = imageView.bounds // 3 imageView.addSubview(blurView) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
23.756757
80
0.65529
622390ab0cf01aba0caa6506d0d6937ac421116c
307
// // LiveView.swift // Book_Sources // // Created by 白梵 on 2019/3/16. // import UIKit import PlaygroundSupport // Instantiate a new instance of the live view from the book's auxiliary sources and pass it to PlaygroundSupport. PlaygroundPage.current.liveView = LiveViewController(sceneName: "welcome")
23.615385
114
0.762215
289e91d0ba46ba83d9974abcbbfb363cd8087ffa
1,050
// // AnyHeaderFooterConvertible.swift // ListableUI // // Created by Kyle Van Essen on 9/28/21. // import Foundation /// A type which can be converted into a `HeaderFooter`, so you /// do not need to explicitly wrap / convert your `HeaderFooterContent` /// in a `HeaderFooter` when providing an header or footer to a list or section: /// /// ``` /// Section("id") { section in /// section.header = MyHeaderContent(title: "Hello, World!") /// } /// /// struct MyHeaderContent : HeaderFooterContent { /// var title : String /// ... /// } /// ``` /// /// Only two types conform to this protocol: /// /// ### `HeaderFooter` /// The `HeaderFooter` conformance simply returns self. /// /// ### `HeaderFooterContent` /// The `HeaderFooterContent` conformance returns `HeaderFooter(self)`, /// utilizing the default values from the `HeaderFooter` initializer. /// public protocol AnyHeaderFooterConvertible { /// Converts the object into a type-erased `AnyHeaderFooter` instance. func asAnyHeaderFooter() -> AnyHeaderFooter }
25
80
0.67619
337535caa9c3dcf5586e54cc93a0370c93e36e68
22,124
// // HomeView.swift // EhPanda // // Created by 荒木辰造 on R 2/10/28. // import SwiftUI import TTProgressHUD struct HomeView: View, StoreAccessor { @EnvironmentObject var store: Store @Environment(\.colorScheme) private var colorScheme @State private var clipboardJumpID: String? @State private var isJumpNavActive = false @State private var greeting: Greeting? @State private var hudVisible = false @State private var hudConfig = TTProgressHUDConfig( hapticsEnabled: false ) // MARK: HomeView var body: some View { NavigationView { ZStack { NavigationLink( "", destination: DetailView( gid: clipboardJumpID ?? "", depth: 1 ), isActive: $isJumpNavActive ) conditionalList .onChange( of: environment.homeListType, perform: onHomeListTypeChange ) .onChange( of: environment.favoritesIndex, perform: onFavoritesIndexChange ) .onChange( of: user?.greeting, perform: onReceiveGreeting ) .onAppear(perform: onListAppear) .navigationBarTitle(navigationBarTitle) .navigationBarItems(trailing: navigationBarItem ) TTProgressHUD($hudVisible, config: hudConfig) } } .navigationViewStyle(StackNavigationViewStyle()) .sheet(item: environmentBinding.homeViewSheetState) { item in switch item { case .setting: SettingView() .environmentObject(store) .accentColor(accentColor) .preferredColorScheme(colorScheme) .blur(radius: environment.blurRadius) .allowsHitTesting(environment.isAppUnlocked) case .filter: FilterView() .environmentObject(store) .accentColor(accentColor) .preferredColorScheme(colorScheme) .blur(radius: environment.blurRadius) .allowsHitTesting(environment.isAppUnlocked) case .newDawn: NewDawnView(greeting: greeting) .preferredColorScheme(colorScheme) .blur(radius: environment.blurRadius) .allowsHitTesting(environment.isAppUnlocked) } } .onAppear(perform: onAppear) .onReceive( NotificationCenter.default.publisher( for: UIApplication.didBecomeActiveNotification ) ) { _ in onBecomeActive() } .onChange( of: environment.mangaItemReverseID, perform: onJumpIDChange ) .onChange( of: environment.mangaItemReverseLoading, perform: onFetchFinish ) } } private extension HomeView { var environmentBinding: Binding<AppState.Environment> { $store.appState.environment } var historyItems: [Manga] { var items = homeInfo.historyItems? .compactMap({ $0.value }) .filter({ $0.lastOpenTime != nil }) items?.sort { $0.lastOpenTime ?? Date() > $1.lastOpenTime ?? Date() } return items ?? [] } var navigationBarTitle: String { if let user = settings.user, environment.favoritesIndex != -1, environment.homeListType == .favorites { return user.getFavNameFrom(environment.favoritesIndex) } else { return environment.homeListType.rawValue.localized() } } var hasJumpPermission: Bool { viewControllersCount == 1 && isTokenMatched && setting?.detectGalleryFromPasteboard == true } var conditionalList: some View { Group { switch environment.homeListType { case .search: GenericList( items: homeInfo.searchItems, loadingFlag: homeInfo.searchLoading, notFoundFlag: homeInfo.searchNotFound, loadFailedFlag: homeInfo.searchLoadFailed, moreLoadingFlag: homeInfo.moreSearchLoading, moreLoadFailedFlag: homeInfo.moreSearchLoadFailed, fetchAction: fetchSearchItems, loadMoreAction: fetchMoreSearchItems ) case .frontpage: GenericList( items: homeInfo.frontpageItems, loadingFlag: homeInfo.frontpageLoading, notFoundFlag: homeInfo.frontpageNotFound, loadFailedFlag: homeInfo.frontpageLoadFailed, moreLoadingFlag: homeInfo.moreFrontpageLoading, moreLoadFailedFlag: homeInfo.moreFrontpageLoadFailed, fetchAction: fetchFrontpageItems, loadMoreAction: fetchMoreFrontpageItems ) case .popular: GenericList( items: homeInfo.popularItems, loadingFlag: homeInfo.popularLoading, notFoundFlag: homeInfo.popularNotFound, loadFailedFlag: homeInfo.popularLoadFailed, moreLoadingFlag: false, moreLoadFailedFlag: false, fetchAction: fetchPopularItems ) case .watched: GenericList( items: homeInfo.watchedItems, loadingFlag: homeInfo.watchedLoading, notFoundFlag: homeInfo.watchedNotFound, loadFailedFlag: homeInfo.watchedLoadFailed, moreLoadingFlag: homeInfo.moreWatchedLoading, moreLoadFailedFlag: homeInfo.moreWatchedLoadFailed, fetchAction: fetchWatchedItems, loadMoreAction: fetchMoreWatchedItems ) case .favorites: GenericList( items: homeInfo.favoritesItems[ environment.favoritesIndex ], loadingFlag: homeInfo.favoritesLoading[ environment.favoritesIndex ] ?? false, notFoundFlag: homeInfo.favoritesNotFound[ environment.favoritesIndex ] ?? false, loadFailedFlag: homeInfo.favoritesLoadFailed[ environment.favoritesIndex ] ?? false, moreLoadingFlag: homeInfo.moreFavoritesLoading[ environment.favoritesIndex ] ?? false, moreLoadFailedFlag: homeInfo.moreFavoritesLoadFailed[ environment.favoritesIndex ] ?? false, fetchAction: fetchFavoritesItems, loadMoreAction: fetchMoreFavoritesItems ) case .downloaded: NotFoundView(retryAction: nil) case .history: GenericList( items: historyItems, loadingFlag: false, notFoundFlag: historyItems.isEmpty, loadFailedFlag: false, moreLoadingFlag: false, moreLoadFailedFlag: false ) } } } var navigationBarItem: some View { Group { if let user = settings.user, let names = user.favoriteNames, environment.homeListType == .favorites { Menu { ForEach(-1..<names.count - 1) { index in Button(action: { onFavMenuSelect(index) }, label: { HStack { Text(user.getFavNameFrom(index)) if index == environment.favoritesIndex { Image(systemName: "checkmark") } } }) } } label: { Image(systemName: "square.2.stack.3d.top.fill") .foregroundColor(.primary) } } } } func onAppear() { detectPasteboard() fetchGreetingIfNeeded() } func onListAppear() { if settings.user == nil { store.dispatch(.initiateUser) } if setting == nil { store.dispatch(.initiateSetting) } if settings.user?.displayName?.isEmpty != false { fetchUserInfo() } fetchFavoriteNames() fetchFrontpageItemsIfNeeded() } func onBecomeActive() { if viewControllersCount == 1 { detectPasteboard() fetchGreetingIfNeeded() } } func onHomeListTypeChange(_ type: HomeListType) { switch type { case .frontpage: fetchFrontpageItemsIfNeeded() case .popular: fetchPopularItemsIfNeeded() case .watched: fetchWatchedItemsIfNeeded() case .favorites: fetchFavoritesItemsIfNeeded() case .downloaded: print(type) case .search: print(type) case .history: print(type) } } func onReceiveGreeting(_ greeting: Greeting?) { if let greeting = greeting, !greeting.gainedNothing { self.greeting = greeting toggleNewDawn() } } func onFavoritesIndexChange(_ : Int) { fetchFavoritesItemsIfNeeded() } func onFavMenuSelect(_ index: Int) { store.dispatch(.toggleFavoriteIndex(index: index)) } func onJumpIDChange(_ value: String?) { if value != nil, hasJumpPermission { clipboardJumpID = value isJumpNavActive = true replaceMangaCommentJumpID(gid: nil) } } func onFetchFinish(_ value: Bool) { if !value, hasJumpPermission { dismissHUD() } } func showHUD() { hudConfig = TTProgressHUDConfig( type: .loading, title: "Loading...".localized() ) hudVisible = true } func dismissHUD() { hudVisible = false hudConfig = TTProgressHUDConfig( hapticsEnabled: false ) } func detectPasteboard() { if hasJumpPermission { if let link = getPasteboardLinkIfAllowed(), isValidDetailURL(url: link) { let gid = link.pathComponents[2] if cachedList.hasCached(gid: gid) { replaceMangaCommentJumpID(gid: gid) } else { fetchMangaWithDetailURL(link.absoluteString) showHUD() } clearPasteboard() clearObstruction() } } } func getPasteboardLinkIfAllowed() -> URL? { if setting?.allowsDetectionWhenNoChange == true { return getPasteboardLink() } else { let currentChangeCount = UIPasteboard.general.changeCount if pasteboardChangeCount != currentChangeCount { setPasteboardChangeCount(with: currentChangeCount) return getPasteboardLink() } else { return nil } } } func clearObstruction() { if environment.homeViewSheetState != nil { store.dispatch(.toggleHomeViewSheetNil) } if environment.isSlideMenuClosed != true { postSlideMenuShouldCloseNotification() } } func fetchGreeting() { store.dispatch(.fetchGreeting) } func fetchUserInfo() { if let uid = settings.user?.apiuid, !uid.isEmpty { store.dispatch(.fetchUserInfo(uid: uid)) } } func fetchFavoriteNames() { store.dispatch(.fetchFavoriteNames) } func fetchSearchItems() { store.dispatch(.fetchSearchItems(keyword: homeInfo.searchKeyword)) } func fetchFrontpageItems() { store.dispatch(.fetchFrontpageItems) } func fetchPopularItems() { store.dispatch(.fetchPopularItems) } func fetchWatchedItems() { store.dispatch(.fetchWatchedItems) } func fetchFavoritesItems() { store.dispatch(.fetchFavoritesItems(index: environment.favoritesIndex)) } func fetchMoreSearchItems() { store.dispatch(.fetchMoreSearchItems(keyword: homeInfo.searchKeyword)) } func fetchMoreFrontpageItems() { store.dispatch(.fetchMoreFrontpageItems) } func fetchMoreWatchedItems() { store.dispatch(.fetchMoreWatchedItems) } func fetchMoreFavoritesItems() { store.dispatch(.fetchMoreFavoritesItems(index: environment.favoritesIndex)) } func fetchMangaWithDetailURL(_ detailURL: String) { store.dispatch(.fetchMangaItemReverse(detailURL: detailURL)) } func replaceMangaCommentJumpID(gid: String?) { store.dispatch(.replaceMangaCommentJumpID(gid: gid)) } func toggleNewDawn() { store.dispatch(.toggleHomeViewSheetState(state: .newDawn)) } func updateViewControllersCount() { store.dispatch(.updateViewControllersCount) } func fetchGreetingIfNeeded() { func verifyDate(with updateTime: Date?) -> Bool { guard let updateTime = updateTime else { return false } let currentTime = Date() let formatter = DateFormatter() formatter.dateFormat = "dd MMMM yyyy" formatter.locale = Locale.current formatter.timeZone = TimeZone(secondsFromGMT: 0) let currentTimeString = formatter.string(from: currentTime) if let currDay = formatter.date(from: currentTimeString) { return currentTime > currDay && updateTime < currDay } return false } if setting?.showNewDawnGreeting == true { if let greeting = user?.greeting { if verifyDate(with: greeting.updateTime) { fetchGreeting() } } else { fetchGreeting() } } } func fetchFrontpageItemsIfNeeded() { if homeInfo.frontpageItems?.isEmpty != false { fetchFrontpageItems() } } func fetchPopularItemsIfNeeded() { if homeInfo.popularItems?.isEmpty != false { fetchPopularItems() } } func fetchWatchedItemsIfNeeded() { if homeInfo.watchedItems?.isEmpty != false { fetchWatchedItems() } } func fetchFavoritesItemsIfNeeded() { if homeInfo.favoritesItems[environment.favoritesIndex]?.isEmpty != false { fetchFavoritesItems() } } } // MARK: GenericList private struct GenericList: View, StoreAccessor { @EnvironmentObject var store: Store private let items: [Manga]? private let loadingFlag: Bool private let notFoundFlag: Bool private let loadFailedFlag: Bool private let moreLoadingFlag: Bool private let moreLoadFailedFlag: Bool private let fetchAction: (() -> Void)? private let loadMoreAction: (() -> Void)? init( items: [Manga]?, loadingFlag: Bool, notFoundFlag: Bool, loadFailedFlag: Bool, moreLoadingFlag: Bool, moreLoadFailedFlag: Bool, fetchAction: (() -> Void)? = nil, loadMoreAction: (() -> Void)? = nil ) { self.items = items self.loadingFlag = loadingFlag self.notFoundFlag = notFoundFlag self.loadFailedFlag = loadFailedFlag self.moreLoadingFlag = moreLoadingFlag self.moreLoadFailedFlag = moreLoadFailedFlag self.fetchAction = fetchAction self.loadMoreAction = loadMoreAction UIScrollView.appearance().keyboardDismissMode = .onDrag } var body: some View { KRefreshScrollView( progressTint: .gray, arrowTint: .primary, onUpdate: onUpdate ) { if isTokenMatched { SearchBar( keyword: homeInfoBinding.searchKeyword, commitAction: searchBarCommit, filterAction: searchBarFilter ) .padding(.horizontal) .padding(.bottom, 10) } if !didLogin && isTokenMatched { NotLoginView(loginAction: toggleSetting) .padding(.top, 30) } else if loadingFlag { LoadingView() .padding(.top, 30) } else if loadFailedFlag { NetworkErrorView(retryAction: fetchAction) .padding(.top, 30) } else if notFoundFlag { NotFoundView(retryAction: fetchAction) .padding(.top, 30) } else { ForEach(items ?? []) { item in NavigationLink(destination: DetailView(gid: item.id, depth: 0)) { MangaSummaryRow(manga: item) .onAppear { onRowAppear(item) } } } .padding(.horizontal) .transition( AnyTransition .opacity .animation(.default) ) if moreLoadingFlag { LoadingView(isCompact: true) .padding() } else if moreLoadFailedFlag { NetworkErrorView( isCompact: true, retryAction: loadMoreAction ) .padding() } } } } } private extension GenericList { var homeInfoBinding: Binding<AppState.HomeInfo> { $store.appState.homeInfo } func onUpdate() { if let action = fetchAction { action() } } func onRowAppear(_ item: Manga) { if let action = loadMoreAction, item == items?.last { action() } } func searchBarCommit() { hideKeyboard() if environment.homeListType != .search { store.dispatch(.toggleHomeListType(type: .search)) } fetchSearchItems() } func searchBarFilter() { toggleFilter() } func fetchSearchItems() { store.dispatch(.fetchSearchItems(keyword: homeInfo.searchKeyword)) } func toggleSetting() { store.dispatch(.toggleHomeViewSheetState(state: .setting)) } func toggleFilter() { store.dispatch(.toggleHomeViewSheetState(state: .filter)) } } // MARK: SearchBar private struct SearchBar: View { @Binding private var keyword: String private var commitAction: () -> Void private var filterAction: () -> Void init( keyword: Binding<String>, commitAction: @escaping () -> Void, filterAction: @escaping () -> Void ) { _keyword = keyword self.commitAction = commitAction self.filterAction = filterAction } var body: some View { HStack { Image(systemName: "magnifyingglass") .foregroundColor(.gray) TextField("Search", text: $keyword, onCommit: commitAction) .disableAutocorrection(true) .autocapitalization(.none) HStack { Group { if !keyword.isEmpty { Button(action: onClearButtonTap) { Image(systemName: "xmark.circle.fill") .foregroundColor(.gray) } } Button(action: filterAction) { Image(systemName: "slider.horizontal.3") .foregroundColor(.gray) .padding(.vertical, 13) .padding(.trailing, 10) } } } } .padding(.leading, 10) .background(Color(.systemGray6)) .cornerRadius(8) } private func onClearButtonTap() { keyword = "" } } // MARK: Definition enum HomeListType: String, Identifiable, CaseIterable { var id: Int { hashValue } case search = "Search" case frontpage = "Frontpage" case popular = "Popular" case watched = "Watched" case favorites = "Favorites" case downloaded = "Downloaded" case history = "History" var symbolName: String { switch self { case .search: return "magnifyingglass.circle" case .frontpage: return "house" case .popular: return "flame" case .watched: return "tag.circle" case .favorites: return "heart.circle" case .downloaded: return "arrow.down.circle" case .history: return "clock.arrow.circlepath" } } } enum HomeViewSheetState: Identifiable { var id: Int { hashValue } case setting case filter case newDawn }
32.156977
85
0.524408
dbd4321475aa4cf9e4be6fc0ee617e2ce9015c36
1,052
// swift-tools-version:5.5 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "SwiftyInjection", products: [ // Products define the executables and libraries a package produces, and make them visible to other packages. .library( name: "SwiftyInjection", targets: ["SwiftyInjection"]), ], dependencies: [ // Dependencies declare other packages that this package depends on. // .package(url: /* package url */, from: "1.0.0"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages this package depends on. .target( name: "SwiftyInjection", dependencies: []), .testTarget( name: "SwiftyInjectionTests", dependencies: ["SwiftyInjection"]), ] )
36.275862
117
0.632129
f81950af7c94d75e5365347700beffd376c21bb8
1,306
// // DashboardModel.swift // RCCariOSController // // Created by Michal Fousek on 17/07/2020. // Copyright © 2020 Chlup. All rights reserved. // import Foundation import RxSwift protocol DashboardModel { var accelerometerDataStream: Observable<(Int, Int)> { get } func start() func stop() } class DashboardModelImpl { struct Dependencies { let accelerometerManager = DI.getAccelerometerDataManager() let btManager = DI.getBTManager() } let deps = Dependencies() init() { } } extension DashboardModelImpl: DashboardModel { var accelerometerDataStream: Observable<(Int, Int)> { return deps.accelerometerManager.accelerometerDataStream .map { x, y in let angleX = x.interpolate(fromLow: 0, fromHigh: 200, toLow: 0, toHigh: 180) - 90 let angleY = y.interpolate(fromLow: 0, fromHigh: 200, toLow: 0, toHigh: 180) - 90 return (angleX, angleY) } } func start() { deps.accelerometerManager.start() } func stop() { deps.accelerometerManager.stop() } } private extension Int { func interpolate(fromLow: Int, fromHigh: Int, toLow: Int, toHigh: Int) -> Int { return toLow + (toHigh - toLow) * (self - fromLow) / (fromHigh - fromLow) } }
25.607843
97
0.635528
f862416f17c6ed61705825432f1a2a326b240e84
644
// // UIBarButtonItem-Extention.swift // weibo // // Created by 2020 on 2020/7/26. // Copyright © 2020 2020. All rights reserved. // import UIKit extension UIBarButtonItem { convenience init(image:String,heightImg:String = "") { let btn = UIButton() btn.setImage(UIImage(named: image), for: .normal) if heightImg == "" { btn.setImage(UIImage(named: image + "_highlighted"), for: .highlighted) }else { btn.setImage(UIImage(named: heightImg), for: .highlighted) } btn.sizeToFit() self.init(customView:btn) // self.customView = btn } }
24.769231
83
0.593168
d6f9baf4a34c349b62636ae5e2a08ad4d2d93d3f
652
import Foundation extension Int { public func timesRepeat(_ block: () -> Void) { if self > 0 { (0 ..< self).forEach { _ in block() } } } } public func random(_ max: Double) -> Double { let upperBound = UInt32(Swift.min(Swift.max(Int64(max), 0), Int64(UInt32.max))) return Double(arc4random_uniform(upperBound)) } public func degrees() { Angle.currentUnit = .degree } public func radians() { Angle.currentUnit = .radian } public func colorMode(_ mode: Int) { Color.currentMode = Color.Mode(rawValue: mode) ?? .range255 } public var colorMode: Int { return Color.currentMode.rawValue }
19.757576
83
0.639571
9ca73a7640d2f0ea159383373bd3843eec716ab5
2,499
import Foundation import XCTest @testable import InclusiveColor extension ICTestCases.TextColors { static let test1: [ICTextBGFontTriplet] = [ ICTextBGFontTriplet(text: ICSRGBA(1, 2, 3), font: ICFontStyle(pointSize: 18, isBold: true), bg: ICSRGBA(2, 3, 4), indexText: 7, indexFont: 8, indexBG: 9), ICTextBGFontTriplet(text: ICSRGBA(50, 222, 233), font: ICFontStyle(pointSize: 18, isBold: true), bg: ICSRGBA(60, 3, 4), indexText: 10, indexFont: 8, indexBG: 12) ] static let test1Text = [ICSRGBA(1, 2, 3), ICSRGBA(50, 222, 233)] static let test1Bg = [ICSRGBA(2, 3, 4), ICSRGBA(60, 3, 4)] static let test1Font = [ICFontStyle(pointSize: 18, isBold: true)] static func case1() -> [ICColorVisionType : [ICAssessment.TextColors<ICSRGBA>.Comparison]] { let c1 = [ ICAssessment.TextColors.Comparison(text: test1[0].text, bg: test1[0].bg, font: test1[0].font, score: 1.0060028, didPass: false, indexText: test1[0].indexText, indexBG: test1[0].indexBG, indexFont: test1[0].indexFont), ICAssessment.TextColors.Comparison(text: test1[1].text, bg: test1[1].bg, font: test1[1].font, score: 10.573096, didPass: true, indexText: test1[1].indexText, indexBG: test1[1].indexBG, indexFont: test1[1].indexFont) ] var comparisons: [ICColorVisionType : [ICAssessment.TextColors<ICSRGBA>.Comparison]] = [:] ICColorVisionType.allCases.forEach { comparisons.updateValue(c1, forKey: $0) } return comparisons } }
44.625
98
0.410564
71e57cab81f93e1b18c7cb7cb959520b2ce67d77
1,698
// // Stage.swift // TheGreatGame // // Created by Олег on 10.05.17. // Copyright © 2017 The Great Game. All rights reserved. // import Foundation public struct Stage : Model { public let title: String public var matches: [Match.Compact] } extension Stage : CustomStringConvertible { public var description: String { return "Stage: \(title), \(matches)" } } extension Stage : Mappable { public enum MappingKeys : String, IndexPathElement { case title, matches } public init<Source>(mapper: InMapper<Source, MappingKeys>) throws { self.title = try mapper.map(from: .title) self.matches = try mapper.map(from: .matches) } public func outMap<Destination>(mapper: inout OutMapper<Destination, MappingKeys>) throws { try mapper.map(self.title, to: .title) try mapper.map(self.matches, to: .matches) } } public struct Stages : Model { public let stages: [Stage] } extension Stages : ArrayMappableBox { public init(_ values: [Stage]) { self.stages = values } public var values: [Stage] { return stages } } extension Stage : MappableBoxable { public typealias Box = Stages } extension Stages : Mappable { public enum MappingKeys : String, IndexPathElement { case stages } public init<Source>(mapper: InMapper<Source, MappingKeys>) throws { self.stages = try mapper.map(from: .stages) } public func outMap<Destination>(mapper: inout OutMapper<Destination, MappingKeys>) throws { try mapper.map(self.stages, to: .stages) } }
20.457831
95
0.620141
5bd779781278eb468668831b75d2fb78a74fdb20
3,960
// // MyProfileViewController.swift // Cactacea_Example // // Created by TAKESHI SHIMADA on 2018/12/09. // Copyright © 2018 Cactacea. All rights reserved. // import UIKit import Cactacea import RxSwift class MyProfileViewController: UIViewController { @IBOutlet weak var collectionView: UICollectionView! var posts: [Feed] = [] var delegate: MyProfileHeaderReusableViewDelegate? override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) fetchUser() fetchPosts() } func fetchUser() { if let user = Session.user { self.navigationItem.title = user.userName SessionAPI.findSession() { [weak self] (user, _) in guard let weakSelf = self else { return } guard let user = user else { return } Session.user = user weakSelf.collectionView.reloadData() } } } func fetchPosts() { SessionAPI.findSessionFeeds(since: nil, offset: nil, feedPrivacyType: nil, feedType: SessionAPI.FeedType_findSessionFeeds.posted, count: nil) { [weak self] (result, error) in guard let weakSelf = self else { return } if let error = error { Session.showError(error) } else if let result = result { weakSelf.posts = result // .append(contentsOf: result) weakSelf.collectionView.reloadData() } } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { } } extension MyProfileViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return posts.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ProfilePhotoCell", for: indexPath) as! ProfilePhotoCell let post = posts[indexPath.row] cell.post = post cell.delegate = self return cell } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let headerViewCell = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "MyProfileHeaderReusableView", for: indexPath) as! MyProfileHeaderReusableView if let user = Session.user { headerViewCell.user = user headerViewCell.delegate = self } return headerViewCell } } extension MyProfileViewController: MyProfileHeaderReusableViewDelegate { func tappedEditButton() { performSegue(withIdentifier: "setting", sender: nil) } } extension MyProfileViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 2 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 0 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: collectionView.frame.size.width / 3 - 1, height: collectionView.frame.size.width / 3 - 1) } } extension MyProfileViewController: PhotoCollectionViewCellDelegate { func tappedPhoto(postId: Int64) { performSegue(withIdentifier: "ProfileUser_DetailSegue", sender: postId) } }
35.357143
227
0.684596
626757a71615aa81363a52a5d1944f4281205984
27,134
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// /// A Swift Array or Dictionary of types conforming to /// `_ObjectiveCBridgeable` can be passed to Objective-C as an NSArray or /// NSDictionary, respectively. The elements of the resulting NSArray /// or NSDictionary will be the result of calling `_bridgeToObjectiveC` /// on each element of the source container. public protocol _ObjectiveCBridgeable { associatedtype _ObjectiveCType: AnyObject /// Convert `self` to Objective-C. func _bridgeToObjectiveC() -> _ObjectiveCType /// Bridge from an Objective-C object of the bridged class type to a /// value of the Self type. /// /// This bridging operation is used for forced downcasting (e.g., /// via as), and may defer complete checking until later. For /// example, when bridging from `NSArray` to `Array<Element>`, we can defer /// the checking for the individual elements of the array. /// /// - parameter result: The location where the result is written. The optional /// will always contain a value. static func _forceBridgeFromObjectiveC( _ source: _ObjectiveCType, result: inout Self? ) /// Try to bridge from an Objective-C object of the bridged class /// type to a value of the Self type. /// /// This conditional bridging operation is used for conditional /// downcasting (e.g., via as?) and therefore must perform a /// complete conversion to the value type; it cannot defer checking /// to a later time. /// /// - parameter result: The location where the result is written. /// /// - Returns: `true` if bridging succeeded, `false` otherwise. This redundant /// information is provided for the convenience of the runtime's `dynamic_cast` /// implementation, so that it need not look into the optional representation /// to determine success. @discardableResult static func _conditionallyBridgeFromObjectiveC( _ source: _ObjectiveCType, result: inout Self? ) -> Bool /// Bridge from an Objective-C object of the bridged class type to a /// value of the Self type. /// /// This bridging operation is used for unconditional bridging when /// interoperating with Objective-C code, either in the body of an /// Objective-C thunk or when calling Objective-C code, and may /// defer complete checking until later. For example, when bridging /// from `NSArray` to `Array<Element>`, we can defer the checking /// for the individual elements of the array. /// /// \param source The Objective-C object from which we are /// bridging. This optional value will only be `nil` in cases where /// an Objective-C method has returned a `nil` despite being marked /// as `_Nonnull`/`nonnull`. In most such cases, bridging will /// generally force the value immediately. However, this gives /// bridging the flexibility to substitute a default value to cope /// with historical decisions, e.g., an existing Objective-C method /// that returns `nil` to for "empty result" rather than (say) an /// empty array. In such cases, when `nil` does occur, the /// implementation of `Swift.Array`'s conformance to /// `_ObjectiveCBridgeable` will produce an empty array rather than /// dynamically failing. @_effects(readonly) static func _unconditionallyBridgeFromObjectiveC(_ source: _ObjectiveCType?) -> Self } #if _runtime(_ObjC) // Note: This function is not intended to be called from Swift. The // availability information here is perfunctory; this function isn't considered // part of the Stdlib's Swift ABI. @available(SwiftStdlib 5.2, *) @_cdecl("_SwiftCreateBridgedArray") @usableFromInline internal func _SwiftCreateBridgedArray_DoNotCall( values: UnsafePointer<AnyObject>, numValues: Int ) -> Unmanaged<AnyObject> { let bufPtr = UnsafeBufferPointer(start: values, count: numValues) let bridged = Array(bufPtr)._bridgeToObjectiveCImpl() return Unmanaged<AnyObject>.passRetained(bridged) } // Note: This function is not intended to be called from Swift. The // availability information here is perfunctory; this function isn't considered // part of the Stdlib's Swift ABI. @available(SwiftStdlib 5.2, *) @_cdecl("_SwiftCreateBridgedMutableArray") @usableFromInline internal func _SwiftCreateBridgedMutableArray_DoNotCall( values: UnsafePointer<AnyObject>, numValues: Int ) -> Unmanaged<AnyObject> { let bufPtr = UnsafeBufferPointer(start: values, count: numValues) let bridged = _SwiftNSMutableArray(Array(bufPtr)) return Unmanaged<AnyObject>.passRetained(bridged) } @_silgen_name("swift_stdlib_connectNSBaseClasses") internal func _connectNSBaseClasses() -> Bool private let _bridgeInitializedSuccessfully = _connectNSBaseClasses() internal var _orphanedFoundationSubclassesReparented: Bool = false /// Reparents the SwiftNativeNS*Base classes to be subclasses of their respective /// Foundation types, or is false if they couldn't be reparented. Must be run /// in order to bridge Swift Strings, Arrays, Dictionarys, Sets, or Enumerators to ObjC. internal func _connectOrphanedFoundationSubclassesIfNeeded() -> Void { let bridgeWorks = _bridgeInitializedSuccessfully _debugPrecondition(bridgeWorks) _orphanedFoundationSubclassesReparented = true } //===--- Bridging for metatypes -------------------------------------------===// /// A stand-in for a value of metatype type. /// /// The language and runtime do not yet support protocol conformances for /// structural types like metatypes. However, we can use a struct that contains /// a metatype, make it conform to _ObjectiveCBridgeable, and its witness table /// will be ABI-compatible with one that directly provided conformance to the /// metatype type itself. public struct _BridgeableMetatype: _ObjectiveCBridgeable { internal var value: AnyObject.Type internal init(value: AnyObject.Type) { self.value = value } public typealias _ObjectiveCType = AnyObject public func _bridgeToObjectiveC() -> AnyObject { return value } public static func _forceBridgeFromObjectiveC( _ source: AnyObject, result: inout _BridgeableMetatype? ) { result = _BridgeableMetatype(value: source as! AnyObject.Type) } public static func _conditionallyBridgeFromObjectiveC( _ source: AnyObject, result: inout _BridgeableMetatype? ) -> Bool { if let type = source as? AnyObject.Type { result = _BridgeableMetatype(value: type) return true } result = nil return false } @_effects(readonly) public static func _unconditionallyBridgeFromObjectiveC(_ source: AnyObject?) -> _BridgeableMetatype { var result: _BridgeableMetatype? _forceBridgeFromObjectiveC(source!, result: &result) return result! } } //===--- Bridging facilities written in Objective-C -----------------------===// // Functions that must discover and possibly use an arbitrary type's // conformance to a given protocol. See ../runtime/Casting.cpp for // implementations. //===----------------------------------------------------------------------===// /// Bridge an arbitrary value to an Objective-C object. /// /// - If `T` is a class type, it is always bridged verbatim, the function /// returns `x`; /// /// - otherwise, if `T` conforms to `_ObjectiveCBridgeable`, /// returns the result of `x._bridgeToObjectiveC()`; /// /// - otherwise, we use **boxing** to bring the value into Objective-C. /// The value is wrapped in an instance of a private Objective-C class /// that is `id`-compatible and dynamically castable back to the type of /// the boxed value, but is otherwise opaque. /// // COMPILER_INTRINSIC @inlinable public func _bridgeAnythingToObjectiveC<T>(_ x: T) -> AnyObject { if _fastPath(_isClassOrObjCExistential(T.self)) { return unsafeBitCast(x, to: AnyObject.self) } return _bridgeAnythingNonVerbatimToObjectiveC(x) } @_silgen_name("") public // @testable func _bridgeAnythingNonVerbatimToObjectiveC<T>(_ x: __owned T) -> AnyObject /// Convert a purportedly-nonnull `id` value from Objective-C into an Any. /// /// Since Objective-C APIs sometimes get their nullability annotations wrong, /// this includes a failsafe against nil `AnyObject`s, wrapping them up as /// a nil `AnyObject?`-inside-an-`Any`. /// // COMPILER_INTRINSIC public func _bridgeAnyObjectToAny(_ possiblyNullObject: AnyObject?) -> Any { if let nonnullObject = possiblyNullObject { return nonnullObject // AnyObject-in-Any } return possiblyNullObject as Any } /// Convert `x` from its Objective-C representation to its Swift /// representation. /// /// - If `T` is a class type: /// - if the dynamic type of `x` is `T` or a subclass of it, it is bridged /// verbatim, the function returns `x`; /// - otherwise, if `T` conforms to `_ObjectiveCBridgeable`: /// + if the dynamic type of `x` is not `T._ObjectiveCType` /// or a subclass of it, trap; /// + otherwise, returns the result of `T._forceBridgeFromObjectiveC(x)`; /// - otherwise, trap. @inlinable public func _forceBridgeFromObjectiveC<T>(_ x: AnyObject, _: T.Type) -> T { if _fastPath(_isClassOrObjCExistential(T.self)) { return x as! T } var result: T? _bridgeNonVerbatimFromObjectiveC(x, T.self, &result) return result! } /// Convert `x` from its Objective-C representation to its Swift /// representation. // COMPILER_INTRINSIC @inlinable public func _forceBridgeFromObjectiveC_bridgeable<T:_ObjectiveCBridgeable> ( _ x: T._ObjectiveCType, _: T.Type ) -> T { var result: T? T._forceBridgeFromObjectiveC(x, result: &result) return result! } /// Attempt to convert `x` from its Objective-C representation to its Swift /// representation. /// /// - If `T` is a class type: /// - if the dynamic type of `x` is `T` or a subclass of it, it is bridged /// verbatim, the function returns `x`; /// - otherwise, if `T` conforms to `_ObjectiveCBridgeable`: /// + otherwise, if the dynamic type of `x` is not `T._ObjectiveCType` /// or a subclass of it, the result is empty; /// + otherwise, returns the result of /// `T._conditionallyBridgeFromObjectiveC(x)`; /// - otherwise, the result is empty. @inlinable public func _conditionallyBridgeFromObjectiveC<T>( _ x: AnyObject, _: T.Type ) -> T? { if _fastPath(_isClassOrObjCExistential(T.self)) { return x as? T } var result: T? _ = _bridgeNonVerbatimFromObjectiveCConditional(x, T.self, &result) return result } /// Attempt to convert `x` from its Objective-C representation to its Swift /// representation. // COMPILER_INTRINSIC @inlinable public func _conditionallyBridgeFromObjectiveC_bridgeable<T:_ObjectiveCBridgeable>( _ x: T._ObjectiveCType, _: T.Type ) -> T? { var result: T? T._conditionallyBridgeFromObjectiveC (x, result: &result) return result } @_silgen_name("") @usableFromInline internal func _bridgeNonVerbatimFromObjectiveC<T>( _ x: AnyObject, _ nativeType: T.Type, _ result: inout T? ) /// Helper stub to upcast to Any and store the result to an inout Any? /// on the C++ runtime's behalf. @_silgen_name("_bridgeNonVerbatimFromObjectiveCToAny") internal func _bridgeNonVerbatimFromObjectiveCToAny( _ x: AnyObject, _ result: inout Any? ) { result = x as Any } /// Helper stub to upcast to Optional on the C++ runtime's behalf. @_silgen_name("_bridgeNonVerbatimBoxedValue") internal func _bridgeNonVerbatimBoxedValue<NativeType>( _ x: UnsafePointer<NativeType>, _ result: inout NativeType? ) { result = x.pointee } /// Runtime optional to conditionally perform a bridge from an object to a value /// type. /// /// - parameter result: Will be set to the resulting value if bridging succeeds, and /// unchanged otherwise. /// /// - Returns: `true` to indicate success, `false` to indicate failure. @_silgen_name("") public func _bridgeNonVerbatimFromObjectiveCConditional<T>( _ x: AnyObject, _ nativeType: T.Type, _ result: inout T? ) -> Bool /// Determines if values of a given type can be converted to an Objective-C /// representation. /// /// - If `T` is a class type, returns `true`; /// - otherwise, returns whether `T` conforms to `_ObjectiveCBridgeable`. public func _isBridgedToObjectiveC<T>(_: T.Type) -> Bool { if _fastPath(_isClassOrObjCExistential(T.self)) { return true } return _isBridgedNonVerbatimToObjectiveC(T.self) } @_silgen_name("") public func _isBridgedNonVerbatimToObjectiveC<T>(_: T.Type) -> Bool /// A type that's bridged "verbatim" does not conform to /// `_ObjectiveCBridgeable`, and can have its bits reinterpreted as an /// `AnyObject`. When this function returns true, the storage of an /// `Array<T>` can be `unsafeBitCast` as an array of `AnyObject`. @inlinable // FIXME(sil-serialize-all) public func _isBridgedVerbatimToObjectiveC<T>(_: T.Type) -> Bool { return _isClassOrObjCExistential(T.self) } /// Retrieve the Objective-C type to which the given type is bridged. @inlinable // FIXME(sil-serialize-all) public func _getBridgedObjectiveCType<T>(_: T.Type) -> Any.Type? { if _fastPath(_isClassOrObjCExistential(T.self)) { return T.self } return _getBridgedNonVerbatimObjectiveCType(T.self) } @_silgen_name("") public func _getBridgedNonVerbatimObjectiveCType<T>(_: T.Type) -> Any.Type? // -- Pointer argument bridging /// A mutable pointer addressing an Objective-C reference that doesn't own its /// target. /// /// `Pointee` must be a class type or `Optional<C>` where `C` is a class. /// /// This type has implicit conversions to allow passing any of the following /// to a C or ObjC API: /// /// - `nil`, which gets passed as a null pointer, /// - an inout argument of the referenced type, which gets passed as a pointer /// to a writeback temporary with autoreleasing ownership semantics, /// - an `UnsafeMutablePointer<Pointee>`, which is passed as-is. /// /// Passing pointers to mutable arrays of ObjC class pointers is not /// directly supported. Unlike `UnsafeMutablePointer<Pointee>`, /// `AutoreleasingUnsafeMutablePointer<Pointee>` must reference storage that /// does not own a reference count to the referenced /// value. UnsafeMutablePointer's operations, by contrast, assume that /// the referenced storage owns values loaded from or stored to it. /// /// This type does not carry an owner pointer unlike the other C*Pointer types /// because it only needs to reference the results of inout conversions, which /// already have writeback-scoped lifetime. @frozen public struct AutoreleasingUnsafeMutablePointer<Pointee /* TODO : class */> : _Pointer { public let _rawValue: Builtin.RawPointer @_transparent public // COMPILER_INTRINSIC init(_ _rawValue: Builtin.RawPointer) { self._rawValue = _rawValue } /// Retrieve or set the `Pointee` instance referenced by `self`. /// /// `AutoreleasingUnsafeMutablePointer` is assumed to reference a value with /// `__autoreleasing` ownership semantics, like `NSFoo **` declarations in /// ARC. Setting the pointee autoreleases the new value before trivially /// storing it in the referenced memory. /// /// - Precondition: the pointee has been initialized with an instance of type /// `Pointee`. @inlinable public var pointee: Pointee { @_transparent get { // The memory addressed by this pointer contains a non-owning reference, // therefore we *must not* point an `UnsafePointer<AnyObject>` to // it---otherwise we would allow the compiler to assume it has a +1 // refcount, enabling some optimizations that wouldn't be valid. // // Instead, we need to load the pointee as a +0 unmanaged reference. For // an extra twist, `Pointee` is allowed (but not required) to be an // optional type, so we actually need to load it as an optional, and // explicitly handle the nil case. let unmanaged = UnsafePointer<Optional<Unmanaged<AnyObject>>>(_rawValue).pointee return _unsafeReferenceCast( unmanaged?.takeUnretainedValue(), to: Pointee.self) } @_transparent nonmutating set { // Autorelease the object reference. let object = _unsafeReferenceCast(newValue, to: Optional<AnyObject>.self) Builtin.retain(object) Builtin.autorelease(object) // Convert it to an unmanaged reference and trivially assign it to the // memory addressed by this pointer. let unmanaged: Optional<Unmanaged<AnyObject>> if let object = object { unmanaged = Unmanaged.passUnretained(object) } else { unmanaged = nil } UnsafeMutablePointer<Optional<Unmanaged<AnyObject>>>(_rawValue).pointee = unmanaged } } /// Access the `i`th element of the raw array pointed to by /// `self`. /// /// - Precondition: `self != nil`. @inlinable // unsafe-performance public subscript(i: Int) -> Pointee { @_transparent get { return self.advanced(by: i).pointee } } /// Explicit construction from an UnsafeMutablePointer. /// /// This is inherently unsafe; UnsafeMutablePointer assumes the /// referenced memory has +1 strong ownership semantics, whereas /// AutoreleasingUnsafeMutablePointer implies +0 semantics. /// /// - Warning: Accessing `pointee` as a type that is unrelated to /// the underlying memory's bound type is undefined. @_transparent public init<U>(@_nonEphemeral _ from: UnsafeMutablePointer<U>) { self._rawValue = from._rawValue } /// Explicit construction from an UnsafeMutablePointer. /// /// Returns nil if `from` is nil. /// /// This is inherently unsafe; UnsafeMutablePointer assumes the /// referenced memory has +1 strong ownership semantics, whereas /// AutoreleasingUnsafeMutablePointer implies +0 semantics. /// /// - Warning: Accessing `pointee` as a type that is unrelated to /// the underlying memory's bound type is undefined. @_transparent public init?<U>(@_nonEphemeral _ from: UnsafeMutablePointer<U>?) { guard let unwrapped = from else { return nil } self.init(unwrapped) } /// Explicit construction from a UnsafePointer. /// /// This is inherently unsafe because UnsafePointers do not imply /// mutability. /// /// - Warning: Accessing `pointee` as a type that is unrelated to /// the underlying memory's bound type is undefined. @usableFromInline @_transparent internal init<U>( @_nonEphemeral _ from: UnsafePointer<U> ) { self._rawValue = from._rawValue } /// Explicit construction from a UnsafePointer. /// /// Returns nil if `from` is nil. /// /// This is inherently unsafe because UnsafePointers do not imply /// mutability. /// /// - Warning: Accessing `pointee` as a type that is unrelated to /// the underlying memory's bound type is undefined. @usableFromInline @_transparent internal init?<U>( @_nonEphemeral _ from: UnsafePointer<U>? ) { guard let unwrapped = from else { return nil } self.init(unwrapped) } } extension UnsafeMutableRawPointer { /// Creates a new raw pointer from an `AutoreleasingUnsafeMutablePointer` /// instance. /// /// - Parameter other: The pointer to convert. @_transparent public init<T>( @_nonEphemeral _ other: AutoreleasingUnsafeMutablePointer<T> ) { _rawValue = other._rawValue } /// Creates a new raw pointer from an `AutoreleasingUnsafeMutablePointer` /// instance. /// /// - Parameter other: The pointer to convert. If `other` is `nil`, the /// result is `nil`. @_transparent public init?<T>( @_nonEphemeral _ other: AutoreleasingUnsafeMutablePointer<T>? ) { guard let unwrapped = other else { return nil } self.init(unwrapped) } } extension UnsafeRawPointer { /// Creates a new raw pointer from an `AutoreleasingUnsafeMutablePointer` /// instance. /// /// - Parameter other: The pointer to convert. @_transparent public init<T>( @_nonEphemeral _ other: AutoreleasingUnsafeMutablePointer<T> ) { _rawValue = other._rawValue } /// Creates a new raw pointer from an `AutoreleasingUnsafeMutablePointer` /// instance. /// /// - Parameter other: The pointer to convert. If `other` is `nil`, the /// result is `nil`. @_transparent public init?<T>( @_nonEphemeral _ other: AutoreleasingUnsafeMutablePointer<T>? ) { guard let unwrapped = other else { return nil } self.init(unwrapped) } } extension AutoreleasingUnsafeMutablePointer { } internal struct _CocoaFastEnumerationStackBuf { // Clang uses 16 pointers. So do we. internal var _item0: UnsafeRawPointer? internal var _item1: UnsafeRawPointer? internal var _item2: UnsafeRawPointer? internal var _item3: UnsafeRawPointer? internal var _item4: UnsafeRawPointer? internal var _item5: UnsafeRawPointer? internal var _item6: UnsafeRawPointer? internal var _item7: UnsafeRawPointer? internal var _item8: UnsafeRawPointer? internal var _item9: UnsafeRawPointer? internal var _item10: UnsafeRawPointer? internal var _item11: UnsafeRawPointer? internal var _item12: UnsafeRawPointer? internal var _item13: UnsafeRawPointer? internal var _item14: UnsafeRawPointer? internal var _item15: UnsafeRawPointer? @_transparent internal var count: Int { return 16 } internal init() { _item0 = nil _item1 = _item0 _item2 = _item0 _item3 = _item0 _item4 = _item0 _item5 = _item0 _item6 = _item0 _item7 = _item0 _item8 = _item0 _item9 = _item0 _item10 = _item0 _item11 = _item0 _item12 = _item0 _item13 = _item0 _item14 = _item0 _item15 = _item0 _internalInvariant(MemoryLayout.size(ofValue: self) >= MemoryLayout<Optional<UnsafeRawPointer>>.size * count) } } /// Get the ObjC type encoding for a type as a pointer to a C string. /// /// This is used by the Foundation overlays. The compiler will error if the /// passed-in type is generic or not representable in Objective-C @_transparent public func _getObjCTypeEncoding<T>(_ type: T.Type) -> UnsafePointer<Int8> { // This must be `@_transparent` because `Builtin.getObjCTypeEncoding` is // only supported by the compiler for concrete types that are representable // in ObjC. return UnsafePointer(Builtin.getObjCTypeEncoding(type)) } #endif //===--- Bridging without the ObjC runtime --------------------------------===// #if !_runtime(_ObjC) /// Convert `x` from its Objective-C representation to its Swift /// representation. // COMPILER_INTRINSIC @inlinable public func _forceBridgeFromObjectiveC_bridgeable<T:_ObjectiveCBridgeable> ( _ x: T._ObjectiveCType, _: T.Type ) -> T { var result: T? T._forceBridgeFromObjectiveC(x, result: &result) return result! } /// Attempt to convert `x` from its Objective-C representation to its Swift /// representation. // COMPILER_INTRINSIC @inlinable public func _conditionallyBridgeFromObjectiveC_bridgeable<T:_ObjectiveCBridgeable>( _ x: T._ObjectiveCType, _: T.Type ) -> T? { var result: T? T._conditionallyBridgeFromObjectiveC (x, result: &result) return result } public // SPI(Foundation) protocol _NSSwiftValue: AnyObject { init(_ value: Any) var value: Any { get } static var null: AnyObject { get } } @usableFromInline internal class __SwiftValue { @usableFromInline let value: Any @usableFromInline init(_ value: Any) { self.value = value } @usableFromInline static let null = __SwiftValue(Optional<Any>.none as Any) } // Internal stdlib SPI @_silgen_name("swift_unboxFromSwiftValueWithType") public func swift_unboxFromSwiftValueWithType<T>( _ source: inout AnyObject, _ result: UnsafeMutablePointer<T> ) -> Bool { if source === _nullPlaceholder { if let unpacked = Optional<Any>.none as? T { result.initialize(to: unpacked) return true } } if let box = source as? __SwiftValue { if let value = box.value as? T { result.initialize(to: value) return true } } else if let box = source as? _NSSwiftValue { if let value = box.value as? T { result.initialize(to: value) return true } } return false } // Internal stdlib SPI @_silgen_name("swift_swiftValueConformsTo") public func _swiftValueConformsTo<T>(_ type: T.Type) -> Bool { if let foundationType = _foundationSwiftValueType { return foundationType is T.Type } else { return __SwiftValue.self is T.Type } } @_silgen_name("_swift_extractDynamicValue") public func _extractDynamicValue<T>(_ value: T) -> AnyObject? @_silgen_name("_swift_bridgeToObjectiveCUsingProtocolIfPossible") public func _bridgeToObjectiveCUsingProtocolIfPossible<T>(_ value: T) -> AnyObject? internal protocol _Unwrappable { func _unwrap() -> Any? } extension Optional: _Unwrappable { internal func _unwrap() -> Any? { return self } } private let _foundationSwiftValueType = _typeByName("Foundation.__SwiftValue") as? _NSSwiftValue.Type @usableFromInline internal var _nullPlaceholder: AnyObject { if let foundationType = _foundationSwiftValueType { return foundationType.null } else { return __SwiftValue.null } } @usableFromInline func _makeSwiftValue(_ value: Any) -> AnyObject { if let foundationType = _foundationSwiftValueType { return foundationType.init(value) } else { return __SwiftValue(value) } } /// Bridge an arbitrary value to an Objective-C object. /// /// - If `T` is a class type, it is always bridged verbatim, the function /// returns `x`; /// /// - otherwise, if `T` conforms to `_ObjectiveCBridgeable`, /// returns the result of `x._bridgeToObjectiveC()`; /// /// - otherwise, we use **boxing** to bring the value into Objective-C. /// The value is wrapped in an instance of a private Objective-C class /// that is `id`-compatible and dynamically castable back to the type of /// the boxed value, but is otherwise opaque. /// // COMPILER_INTRINSIC public func _bridgeAnythingToObjectiveC<T>(_ x: T) -> AnyObject { var done = false var result: AnyObject! let source: Any = x if let dynamicSource = _extractDynamicValue(x) { result = dynamicSource as AnyObject done = true } if !done, let wrapper = source as? _Unwrappable { if let value = wrapper._unwrap() { result = value as AnyObject } else { result = _nullPlaceholder } done = true } if !done { if type(of: source) as? AnyClass != nil { result = unsafeBitCast(x, to: AnyObject.self) } else if let object = _bridgeToObjectiveCUsingProtocolIfPossible(source) { result = object } else { result = _makeSwiftValue(source) } } return result } #endif // !_runtime(_ObjC)
32.691566
101
0.705314
48c898459816b1188884a35265b2893ed4eed087
270
// // Copyright 2018-2019 Amazon.com, // Inc. or its affiliates. All Rights Reserved. // // SPDX-License-Identifier: Apache-2.0 // public typealias HubPayloadEventName = String public protocol HubPayloadEventNameable { var eventName: HubPayloadEventName { get } }
20.769231
47
0.744444
0e2449ad57554927adc07a9d9f335c73b92544ad
434
// MARK: - InAppMessageKey /// A safer alternative to typing "string" types. Declared as `String` type to query the key name via `rawValue`. enum InAppMessageKey: String { case viewType = "view_type" case attributeKey = "attribute_key" } // MARK: - InAppMessageViewType /// Represents the `view_type` key in your In-App Message key-value pairs. enum InAppMessageViewType: String { case picker case tableList = "table_list" }
31
113
0.739631
643751577a294fe087ba9529d202cb9db4a49c9f
2,490
// // SceneDelegate.swift // MovieList // // Created by Ayşe Nur Bakırcı on 27.07.2021. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). guard let _ = (scene as? UIWindowScene) else { return } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. // Save changes in the application's managed object context when the application transitions to the background. (UIApplication.shared.delegate as? AppDelegate)?.saveContext() } }
44.464286
147
0.715663
7a4b5cd119a7b7847ef56b996587b67ac93cf010
1,438
// // CodePathPreworkUITests.swift // CodePathPreworkUITests // // Created by Misael Guijarro on 1/26/21. // import XCTest class CodePathPreworkUITests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // UI tests must launch the application that they test. let app = XCUIApplication() app.launch() // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testLaunchPerformance() throws { if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) { // This measures how long it takes to launch your application. measure(metrics: [XCTApplicationLaunchMetric()]) { XCUIApplication().launch() } } } }
33.44186
182
0.661335
b9b41f7ed786f4219a5bddf373b5ba5951707459
1,074
// // Observer.swift // KWFoundation // // Created by Kamil Wyszomierski on 30/11/2019. // Copyright © 2019 Kamil Wyszomierski. All rights reserved. // import Foundation public class Observer<T> { public private(set) var current: T { didSet { subscribers.forEach { $0.operation(current) } } } private(set) var subscribers = Set<Subscriber<T>>() public init(value: T) { current = value } public func bind<O>(to object: O, for key: ReferenceWritableKeyPath<O, T>) -> CancellationToken where O: AnyObject { let completion: ValueClosure<T> = { [weak object, weak key] (value) in guard let key = key else { return } object?[keyPath: key] = value } return onCurrent(completion: completion) } public func onCurrent(completion: @escaping ValueClosure<T>) -> CancellationToken { let subscriber = Subscriber(operation: completion) subscriber.operation(current) subscribers.insert(subscriber) return CancellationToken { [weak self] in self?.subscribers.remove(subscriber) } } public func set(value: T) { current = value } }
22.375
117
0.701117
767f1283311e3673fa8f2b6e34c60838ec5ec034
3,530
// // Directory.swift // import Foundation public class ToolDirectory : DirectoryItem { // MARK: instance variables public fileprivate(set) var dirPath: ToolPath // MARK: initializer public init(_ path: ToolPath ) { self.dirPath = path } public init?(_ pathString: String, expandTilde: Bool = false ) { let p = ToolPath(pathString, expandTilde: expandTilde) guard p.isDirectory else { return nil } self.dirPath = p } public var path : ToolPath { return self.dirPath } public func setDirectoryName(_ newValue: String) -> ToolDirectory { return ToolDirectory( self.parent().path + newValue ) } public func parent() -> DirectoryItem { return ToolDirectory(self.path.parent) } public func subItem(_ name: String, type: FSItemType ) -> FileSystemItem { switch type { case FSItemType.DIRECTORY: return ToolDirectory(self.path + name) default: return ToolFile(self, name) } } public func subdirectory(_ name: String) -> ToolDirectory { return subItem(name, type: FSItemType.DIRECTORY) as! ToolDirectory } public func file(_ name: String) -> ToolFile { return subItem(name, type: FSItemType.FILE) as! ToolFile } public func children() throws -> [FileSystemItem] { return try FileManager.default.contentsOfDirectory(atPath: path.string).map { let childPath = path + $0 if ( childPath.isDirectory ) { return ToolDirectory(childPath) } else { return ToolFile(ToolDirectory(path), $0) } } } public func recursiveChildren() throws -> [FileSystemItem] { return try FileManager.default.subpathsOfDirectory(atPath: path.string).map { let childPath = path + $0 if ( childPath.isDirectory ) { return ToolDirectory(childPath) } else { return ToolFile(ToolDirectory(path), $0) } } } } extension ToolDirectory { // MARK: common paths public static var currentWorkingDirectory : ToolDirectory { return ToolDirectory(ToolPath.cwd) } public static var home: ToolDirectory { return ToolDirectory(ToolPath(NSHomeDirectory())) } public static var systemTmp: ToolDirectory { return ToolDirectory(ToolPath("/private/tmp")) } public static var temporary: ToolDirectory { return ToolDirectory(ToolPath(NSTemporaryDirectory())) } public static func processUniqueTemporary() throws -> ToolDirectory { let dir = temporary.subdirectory(ProcessInfo.processInfo.globallyUniqueString) if !dir.path.exists { try dir.mkdir() } return dir } public static func uniqueTemporary() throws -> ToolDirectory { let dir = try processUniqueTemporary().subdirectory(UUID().uuidString) try dir.mkdir() return dir } } extension ToolDirectory : CustomStringConvertible { public var description: String { return "\(self.path.description)" } public var debugDescription: String { return "File: \(self.path.debugDescription)" } } extension ToolDirectory : Equatable { // MARK: Equatable public static func == (lhs: ToolDirectory, rhs: ToolDirectory) -> Bool { return lhs.path == rhs.path } }
28.467742
88
0.615014
33fb53fba9bc6ba656ea157b044bf9dea2a7e10b
903
// // CrackleLocalOptimizer.swift // SnapCore // // Created by Andrew Fox on 10/27/20. // Copyright © 2020 Andrew Fox. All rights reserved. // public class CrackleLocalOptimizer: NSObject { public var unoptimizedProgram = CrackleBasicBlock() public var optimizedProgram = CrackleBasicBlock() public func optimize() { optimizedProgram = unoptimizedProgram let constantPropagation = CrackleConstantPropagationOptimizationPass() constantPropagation.unoptimizedProgram = optimizedProgram constantPropagation.optimize() optimizedProgram = constantPropagation.optimizedProgram let deadCodeElimination = CrackleDeadCodeEliminationOptimizationPass() deadCodeElimination.unoptimizedProgram = optimizedProgram deadCodeElimination.optimize() optimizedProgram = deadCodeElimination.optimizedProgram } }
33.444444
78
0.738649
46d4d209d18ef61245017c1d424b9a50a6bba0e5
3,453
// // HomeViewController.swift // DYLive_Swift // // Created by qujiahong on 2018/6/11. // Copyright © 2018年 瞿嘉洪. All rights reserved. // import UIKit let kTitleViewH : CGFloat = 40 class HomeViewController: UIViewController { // MARK: - 懒加载属性 lazy var pageTitleView : PageTitleView = {[weak self] in let titleFrame = CGRect(x: 0, y: kStatusBarH+kNavigationBarH, width: kScreenW, height: kTitleViewH) let titles = ["推荐","游戏","娱乐","趣玩"] let titleView = PageTitleView(frame: titleFrame, titles: titles) titleView.pageDelegate = self return titleView }() lazy var pageContentView : PageContentView = {[weak self] in let contentH = kScreenH - kStatusBarH - kNavigationBarH - kTitleViewH - kTabBarH let contentFrame = CGRect(x: 0, y: kStatusBarH+kNavigationBarH+kTitleViewH, width: kScreenW, height: contentH) var childVCs = [UIViewController]() childVCs.append(RecommendViewController()) for _ in 0..<3 { let vc = UIViewController() vc.view.backgroundColor = UIColor.randomcolor() childVCs.append(vc) } let contentView = PageContentView(frame: contentFrame, childVCs: childVCs, presentViewController: self) contentView.pageDelegate = self return contentView }() override func viewDidLoad() { super.viewDidLoad() setupUI() } } // MARK: - extension - 设置UI界面 extension HomeViewController { func setupUI() { //0.不需要调整UIScrollView的内边距 automaticallyAdjustsScrollViewInsets = false //1.导航 setupNavigationBar() //2.titleView view.addSubview(pageTitleView) //3.pageContentVC view.addSubview(pageContentView) } private func setupNavigationBar() { //左 let leftBtn = UIButton() leftBtn.setImage(UIImage(named: "logo"), for: .normal) leftBtn.sizeToFit() navigationItem.leftBarButtonItem = UIBarButtonItem(customView: leftBtn) //右 let btnSize = CGSize(width: 40, height: 40) /* //类方法 let historyItem = UIBarButtonItem.createItem(imageName: "Image_my_history", highImageName: "Image_my_history_click", itemSize: btnSize) */ //构造方法 let historyItem = UIBarButtonItem(imageName: "image_my_history", highImageName: "Image_my_history_click", itemSize: btnSize) let searchItem = UIBarButtonItem(imageName: "btn_search", highImageName: "btn_search_clicked", itemSize: btnSize) let qrcodeItem = UIBarButtonItem(imageName: "Image_scan", highImageName: "Image_scan_click", itemSize: btnSize) navigationItem.rightBarButtonItems = [historyItem, searchItem, qrcodeItem] } } // MARK: - 遵守PageTitleView的代理 extension HomeViewController : PageTitleViewDelegate { func pageTitleView(titleView: PageTitleView, selectIndex index: Int) { pageContentView.setCurrentIndex(currentIndex: index) } } // MARK: - 遵守PageContentView的代理 extension HomeViewController : PageContentViewDelegate { func pageContentView(contentView: PageContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int) { pageTitleView.setTitleWithProgress(progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex) } }
30.830357
144
0.653055
2f3b781fa5fdecd7a26a0b422d1771e4c1630037
1,021
/* Copyright 2020 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation /// Defines a visitor identifier @objc(AEPIdentifiable) public protocol Identifiable { /// Origin of the identifier var origin: String? { get } /// Type of the identifier var type: String? { get } /// The identifier var identifier: String? { get } /// The authentication state for the identifier var authenticationState: MobileVisitorAuthenticationState { get } }
36.464286
87
0.745348
dbd032d2d53a463c3faae01636b52df0eb3f81b9
23,280
// // Created by Shin Yamamoto on 2018/09/27. // Copyright © 2018 Shin Yamamoto. All rights reserved. // import UIKit /// FloatingPanelFullScreenLayout /// /// Use the layout protocol if you configure full, half and tip insets from the superview, not the safe area. /// It can't be used with FloatingPanelIntrinsicLayout. public protocol FloatingPanelFullScreenLayout: FloatingPanelLayout { } public extension FloatingPanelFullScreenLayout { var positionReference: FloatingPanelLayoutReference { return .fromSuperview } } /// FloatingPanelIntrinsicLayout /// /// Use the layout protocol if you want to layout a panel using the intrinsic height. /// It can't be used with `FloatingPanelFullScreenLayout`. /// /// - Attention: /// `insetFor(position:)` must return `nil` for the full position. Because /// the inset is determined automatically by the intrinsic height. /// You can customize insets only for the half, tip and hidden positions. /// /// - Note: /// By default, the `positionReference` is set to `.fromSafeArea`. public protocol FloatingPanelIntrinsicLayout: FloatingPanelLayout { } public extension FloatingPanelIntrinsicLayout { var initialPosition: FloatingPanelPosition { return .full } var supportedPositions: Set<FloatingPanelPosition> { return [.full] } func insetFor(position: FloatingPanelPosition) -> CGFloat? { return nil } var positionReference: FloatingPanelLayoutReference { return .fromSafeArea } } public enum FloatingPanelLayoutReference: Int { case fromSafeArea = 0 case fromSuperview = 1 } public protocol FloatingPanelLayout: class { /// Returns the initial position of a floating panel. var initialPosition: FloatingPanelPosition { get } /// Returns a set of FloatingPanelPosition objects to tell the applicable /// positions of the floating panel controller. /// /// By default, it returns full, half and tip positions. var supportedPositions: Set<FloatingPanelPosition> { get } /// Return the interaction buffer to the top from the top position. Default is 6.0. var topInteractionBuffer: CGFloat { get } /// Return the interaction buffer to the bottom from the bottom position. Default is 6.0. /// /// - Important: /// The specified buffer is ignored when `FloatingPanelController.isRemovalInteractionEnabled` is set to true. var bottomInteractionBuffer: CGFloat { get } /// Returns a CGFloat value to determine a Y coordinate of a floating panel for each position(full, half, tip and hidden). /// /// Its returning value indicates a different inset for each position. /// For full position, a top inset from a safe area in `FloatingPanelController.view`. /// For half or tip position, a bottom inset from the safe area. /// For hidden position, a bottom inset from `FloatingPanelController.view`. /// If a position isn't supported or the default value is used, return nil. func insetFor(position: FloatingPanelPosition) -> CGFloat? /// Returns X-axis and width layout constraints of the surface view of a floating panel. /// You must not include any Y-axis and height layout constraints of the surface view /// because their constraints will be configured by the floating panel controller. /// By default, the width of a surface view fits a safe area. func prepareLayout(surfaceView: UIView, in view: UIView) -> [NSLayoutConstraint] /// Returns a CGFloat value to determine the backdrop view's alpha for a position. /// /// Default is 0.3 at full position, otherwise 0.0. func backdropAlphaFor(position: FloatingPanelPosition) -> CGFloat var positionReference: FloatingPanelLayoutReference { get } } public extension FloatingPanelLayout { var topInteractionBuffer: CGFloat { return 6.0 } var bottomInteractionBuffer: CGFloat { return 6.0 } var supportedPositions: Set<FloatingPanelPosition> { return Set([.full, .half, .tip]) } func prepareLayout(surfaceView: UIView, in view: UIView) -> [NSLayoutConstraint] { return [ surfaceView.leftAnchor.constraint(equalTo: view.sideLayoutGuide.leftAnchor, constant: 0.0), surfaceView.rightAnchor.constraint(equalTo: view.sideLayoutGuide.rightAnchor, constant: 0.0), ] } func backdropAlphaFor(position: FloatingPanelPosition) -> CGFloat { return position == .full ? 0.3 : 0.0 } var positionReference: FloatingPanelLayoutReference { return .fromSafeArea } } public class FloatingPanelDefaultLayout: FloatingPanelLayout { public init() { } public var initialPosition: FloatingPanelPosition { return .half } public func insetFor(position: FloatingPanelPosition) -> CGFloat? { switch position { case .full: return 18.0 case .half: return 262.0 case .tip: return 69.0 case .hidden: return nil } } } public class FloatingPanelDefaultLandscapeLayout: FloatingPanelLayout { public init() { } public var initialPosition: FloatingPanelPosition { return .tip } public var supportedPositions: Set<FloatingPanelPosition> { return [.full, .tip] } public func insetFor(position: FloatingPanelPosition) -> CGFloat? { switch position { case .full: return 16.0 case .tip: return 69.0 default: return nil } } } struct LayoutSegment { let lower: FloatingPanelPosition? let upper: FloatingPanelPosition? } class FloatingPanelLayoutAdapter { weak var vc: FloatingPanelController! private weak var surfaceView: FloatingPanelSurfaceView! private weak var backdropView: FloatingPanelBackdropView! var layout: FloatingPanelLayout { didSet { checkLayoutConsistance() } } private var safeAreaInsets: UIEdgeInsets { return vc?.layoutInsets ?? .zero } private var initialConst: CGFloat = 0.0 private var fixedConstraints: [NSLayoutConstraint] = [] private var fullConstraints: [NSLayoutConstraint] = [] private var halfConstraints: [NSLayoutConstraint] = [] private var tipConstraints: [NSLayoutConstraint] = [] private var offConstraints: [NSLayoutConstraint] = [] private var interactiveTopConstraint: NSLayoutConstraint? private var bottomConstraint: NSLayoutConstraint? private var heightConstraint: NSLayoutConstraint? private var fullInset: CGFloat { if layout is FloatingPanelIntrinsicLayout { return intrinsicHeight } else { return layout.insetFor(position: .full) ?? 0.0 } } private var halfInset: CGFloat { return layout.insetFor(position: .half) ?? 0.0 } private var tipInset: CGFloat { return layout.insetFor(position: .tip) ?? 0.0 } private var hiddenInset: CGFloat { return layout.insetFor(position: .hidden) ?? 0.0 } var supportedPositions: Set<FloatingPanelPosition> { return layout.supportedPositions } var topMostState: FloatingPanelPosition { return supportedPositions.sorted(by: { $0.rawValue < $1.rawValue }).first ?? .hidden } var bottomMostState: FloatingPanelPosition { return supportedPositions.sorted(by: { $0.rawValue < $1.rawValue }).last ?? .hidden } var topY: CGFloat { return positionY(for: topMostState) } var bottomY: CGFloat { return positionY(for: bottomMostState) } var topMaxY: CGFloat { return topY - layout.topInteractionBuffer } var bottomMaxY: CGFloat { return bottomY + layout.bottomInteractionBuffer } var adjustedContentInsets: UIEdgeInsets { return UIEdgeInsets(top: 0.0, left: 0.0, bottom: safeAreaInsets.bottom, right: 0.0) } func positionY(for pos: FloatingPanelPosition) -> CGFloat { switch pos { case .full: if layout is FloatingPanelIntrinsicLayout { return surfaceView.superview!.bounds.height - surfaceView.bounds.height } switch layout.positionReference { case .fromSafeArea: return (safeAreaInsets.top + fullInset) case .fromSuperview: return fullInset } case .half: switch layout.positionReference { case .fromSafeArea: return surfaceView.superview!.bounds.height - (safeAreaInsets.bottom + halfInset) case .fromSuperview: return surfaceView.superview!.bounds.height - halfInset } case .tip: switch layout.positionReference { case .fromSafeArea: return surfaceView.superview!.bounds.height - (safeAreaInsets.bottom + tipInset) case .fromSuperview: return surfaceView.superview!.bounds.height - tipInset } case .hidden: return surfaceView.superview!.bounds.height - hiddenInset } } var intrinsicHeight: CGFloat = 0.0 init(surfaceView: FloatingPanelSurfaceView, backdropView: FloatingPanelBackdropView, layout: FloatingPanelLayout) { self.layout = layout self.surfaceView = surfaceView self.backdropView = backdropView } func updateIntrinsicHeight() { #if swift(>=4.2) let fittingSize = UIView.layoutFittingCompressedSize #else let fittingSize = UILayoutFittingCompressedSize #endif var intrinsicHeight = surfaceView.contentView?.systemLayoutSizeFitting(fittingSize).height ?? 0.0 var safeAreaBottom: CGFloat = 0.0 if #available(iOS 11.0, *) { safeAreaBottom = surfaceView.contentView?.safeAreaInsets.bottom ?? 0.0 if safeAreaBottom > 0 { intrinsicHeight -= safeAreaInsets.bottom } } self.intrinsicHeight = max(intrinsicHeight, 0.0) log.debug("Update intrinsic height =", intrinsicHeight, ", surface(height) =", surfaceView.frame.height, ", content(height) =", surfaceView.contentView?.frame.height ?? 0.0, ", content safe area(bottom) =", safeAreaBottom) } func prepareLayout(in vc: FloatingPanelController) { self.vc = vc NSLayoutConstraint.deactivate(fixedConstraints + fullConstraints + halfConstraints + tipConstraints + offConstraints) NSLayoutConstraint.deactivate(constraint: self.heightConstraint) self.heightConstraint = nil NSLayoutConstraint.deactivate(constraint: self.bottomConstraint) self.bottomConstraint = nil surfaceView.translatesAutoresizingMaskIntoConstraints = false backdropView.translatesAutoresizingMaskIntoConstraints = false // Fixed constraints of surface and backdrop views let surfaceConstraints = layout.prepareLayout(surfaceView: surfaceView, in: vc.view!) let backdropConstraints = [ backdropView.topAnchor.constraint(equalTo: vc.view.topAnchor, constant: 0.0), backdropView.leftAnchor.constraint(equalTo: vc.view.leftAnchor,constant: 0.0), backdropView.rightAnchor.constraint(equalTo: vc.view.rightAnchor, constant: 0.0), backdropView.bottomAnchor.constraint(equalTo: vc.view.bottomAnchor, constant: 0.0), ] fixedConstraints = surfaceConstraints + backdropConstraints if vc.contentMode == .fitToBounds { bottomConstraint = surfaceView.bottomAnchor.constraint(equalTo: vc.view.bottomAnchor, constant: 0.0) } // Flexible surface constraints for full, half, tip and off let topAnchor: NSLayoutYAxisAnchor = { if layout.positionReference == .fromSuperview { return vc.view.topAnchor } else { return vc.layoutGuide.topAnchor } }() switch layout { case is FloatingPanelIntrinsicLayout: // Set up on updateHeight() break default: fullConstraints = [ surfaceView.topAnchor.constraint(equalTo: topAnchor, constant: fullInset), ] } let bottomAnchor: NSLayoutYAxisAnchor = { if layout.positionReference == .fromSuperview { return vc.view.bottomAnchor } else { return vc.layoutGuide.bottomAnchor } }() halfConstraints = [ surfaceView.topAnchor.constraint(equalTo: bottomAnchor, constant: -halfInset), ] tipConstraints = [ surfaceView.topAnchor.constraint(equalTo: bottomAnchor, constant: -tipInset), ] offConstraints = [ surfaceView.topAnchor.constraint(equalTo:vc.view.bottomAnchor, constant: -hiddenInset), ] } func startInteraction(at state: FloatingPanelPosition, offset: CGPoint = .zero) { guard self.interactiveTopConstraint == nil else { return } NSLayoutConstraint.deactivate(fullConstraints + halfConstraints + tipConstraints + offConstraints) let interactiveTopConstraint: NSLayoutConstraint switch layout.positionReference { case .fromSafeArea: initialConst = surfaceView.frame.minY - safeAreaInsets.top + offset.y interactiveTopConstraint = surfaceView.topAnchor.constraint(equalTo: vc.layoutGuide.topAnchor, constant: initialConst) case .fromSuperview: initialConst = surfaceView.frame.minY + offset.y interactiveTopConstraint = surfaceView.topAnchor.constraint(equalTo: vc.view.topAnchor, constant: initialConst) } NSLayoutConstraint.activate([interactiveTopConstraint]) self.interactiveTopConstraint = interactiveTopConstraint } func endInteraction(at state: FloatingPanelPosition) { // Don't deactivate `interactiveTopConstraint` here because it leads to // unsatisfiable constraints if self.interactiveTopConstraint == nil { // Actiavate `interactiveTopConstraint` for `fitToBounds` mode. // It goes throught this path when the pan gesture state jumps // from .begin to .end. startInteraction(at: state) } } // The method is separated from prepareLayout(to:) for the rotation support // It must be called in FloatingPanelController.traitCollectionDidChange(_:) func updateHeight() { guard let vc = vc else { return } NSLayoutConstraint.deactivate(constraint: heightConstraint) heightConstraint = nil if layout is FloatingPanelIntrinsicLayout { updateIntrinsicHeight() } defer { if layout is FloatingPanelIntrinsicLayout { NSLayoutConstraint.deactivate(fullConstraints) fullConstraints = [ surfaceView.topAnchor.constraint(equalTo: vc.layoutGuide.bottomAnchor, constant: -fullInset), ] } } guard vc.contentMode != .fitToBounds else { return } switch layout { case is FloatingPanelIntrinsicLayout: heightConstraint = surfaceView.heightAnchor.constraint(equalToConstant: intrinsicHeight + safeAreaInsets.bottom) default: let const = -(positionY(for: topMostState)) heightConstraint = surfaceView.heightAnchor.constraint(equalTo: vc.view.heightAnchor, constant: const) } NSLayoutConstraint.activate(constraint: heightConstraint) surfaceView.bottomOverflow = vc.view.bounds.height + layout.topInteractionBuffer } func updateInteractiveTopConstraint(diff: CGFloat, allowsTopBuffer: Bool, with behavior: FloatingPanelBehavior) { defer { layoutSurfaceIfNeeded() // MUST be called to update `surfaceView.frame` } let topMostConst: CGFloat = { var ret: CGFloat = 0.0 switch layout.positionReference { case .fromSafeArea: ret = topY - safeAreaInsets.top case .fromSuperview: ret = topY } return max(ret, 0.0) // The top boundary is equal to the related topAnchor. }() let bottomMostConst: CGFloat = { var ret: CGFloat = 0.0 let _bottomY = vc.isRemovalInteractionEnabled ? positionY(for: .hidden) : bottomY switch layout.positionReference { case .fromSafeArea: ret = _bottomY - safeAreaInsets.top case .fromSuperview: ret = _bottomY } return min(ret, surfaceView.superview!.bounds.height) }() let minConst = allowsTopBuffer ? topMostConst - layout.topInteractionBuffer : topMostConst let maxConst = bottomMostConst + layout.bottomInteractionBuffer var const = initialConst + diff // Rubberbanding top buffer if behavior.allowsRubberBanding(for: .top), const < topMostConst { let buffer = topMostConst - const const = topMostConst - rubberbandEffect(for: buffer, base: vc.view.bounds.height) } // Rubberbanding bottom buffer if behavior.allowsRubberBanding(for: .bottom), const > bottomMostConst { let buffer = const - bottomMostConst const = bottomMostConst + rubberbandEffect(for: buffer, base: vc.view.bounds.height) } interactiveTopConstraint?.constant = max(minConst, min(maxConst, const)) } // According to @chpwn's tweet: https://twitter.com/chpwn/status/285540192096497664 // x = distance from the edge // c = constant value, UIScrollView uses 0.55 // d = dimension, either width or height private func rubberbandEffect(for buffer: CGFloat, base: CGFloat) -> CGFloat { return (1.0 - (1.0 / ((buffer * 0.55 / base) + 1.0))) * base } func activateFixedLayout() { // Must deactivate `interactiveTopConstraint` here NSLayoutConstraint.deactivate(constraint: self.interactiveTopConstraint) self.interactiveTopConstraint = nil NSLayoutConstraint.activate(fixedConstraints) if vc.contentMode == .fitToBounds { NSLayoutConstraint.activate(constraint: self.bottomConstraint) } } func activateInteractiveLayout(of state: FloatingPanelPosition) { defer { layoutSurfaceIfNeeded() log.debug("activateLayout -- surface.presentation = \(self.surfaceView.presentationFrame) surface.frame = \(self.surfaceView.frame)") } var state = state setBackdropAlpha(of: state) if isValid(state) == false { state = layout.initialPosition } NSLayoutConstraint.deactivate(fullConstraints + halfConstraints + tipConstraints + offConstraints) switch state { case .full: NSLayoutConstraint.activate(fullConstraints) case .half: NSLayoutConstraint.activate(halfConstraints) case .tip: NSLayoutConstraint.activate(tipConstraints) case .hidden: NSLayoutConstraint.activate(offConstraints) } } func activateLayout(of state: FloatingPanelPosition) { activateFixedLayout() activateInteractiveLayout(of: state) } func isValid(_ state: FloatingPanelPosition) -> Bool { return supportedPositions.union([.hidden]).contains(state) } private func layoutSurfaceIfNeeded() { #if !TEST guard surfaceView.window != nil else { return } #endif surfaceView.superview?.layoutIfNeeded() } private func setBackdropAlpha(of target: FloatingPanelPosition) { if target == .hidden { self.backdropView.alpha = 0.0 } else { // self.backdropView.alpha = layout.backdropAlphaFor(position: target) } } private func checkLayoutConsistance() { // Verify layout configurations assert(supportedPositions.count > 0) assert(supportedPositions.contains(layout.initialPosition), "Does not include an initial position (\(layout.initialPosition)) in supportedPositions (\(supportedPositions))") if layout is FloatingPanelIntrinsicLayout { assert(layout.insetFor(position: .full) == nil, "Return `nil` for full position on FloatingPanelIntrinsicLayout") } if halfInset > 0 { assert(halfInset > tipInset, "Invalid half and tip insets") } // The verification isn't working on orientation change(portrait -> landscape) // of a floating panel in tab bar. Because the `safeAreaInsets.bottom` is // updated in delay so that it can be 83.0(not 53.0) even after the surface // and the super view's frame is fit to landscape already. /*if fullInset > 0 { assert(middleY > topY, "Invalid insets { topY: \(topY), middleY: \(middleY) }") assert(bottomY > topY, "Invalid insets { topY: \(topY), bottomY: \(bottomY) }") }*/ } func segument(at posY: CGFloat, forward: Bool) -> LayoutSegment { /// ----------------------->Y /// --> forward <-- backward /// |-------|===o===|-------| |-------|-------|===o===| /// |-------|-------x=======| |-------|=======x-------| /// |-------|-------|===o===| |-------|===o===|-------| /// pos: o/x, seguement: = let sortedPositions = supportedPositions.sorted(by: { $0.rawValue < $1.rawValue }) let upperIndex: Int? if forward { #if swift(>=4.2) upperIndex = sortedPositions.firstIndex(where: { posY < positionY(for: $0) }) #else upperIndex = sortedPositions.index(where: { posY < positionY(for: $0) }) #endif } else { #if swift(>=4.2) upperIndex = sortedPositions.firstIndex(where: { posY <= positionY(for: $0) }) #else upperIndex = sortedPositions.index(where: { posY <= positionY(for: $0) }) #endif } switch upperIndex { case 0: return LayoutSegment(lower: nil, upper: sortedPositions.first) case let upperIndex?: return LayoutSegment(lower: sortedPositions[upperIndex - 1], upper: sortedPositions[upperIndex]) default: return LayoutSegment(lower: sortedPositions[sortedPositions.endIndex - 1], upper: nil) } } }
37.730956
145
0.629553
ab8ae7dd358c921b0c4408bf7797e6e6b79dd249
8,858
/* 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 http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import XCTest import TSCBasic import TSCUtility import PackageModel import PackageGraph import SPMTestSupport import SourceControl import Workspace final class PinsStoreTests: XCTestCase { let v1: Version = "1.0.0" func testBasics() throws { let fooPath = AbsolutePath("/foo") let barPath = AbsolutePath("/bar") let foo = PackageIdentity(path: fooPath) let bar = PackageIdentity(path: barPath) let fooRepo = RepositorySpecifier(url: fooPath.pathString) let barRepo = RepositorySpecifier(url: barPath.pathString) let revision = Revision(identifier: "81513c8fd220cf1ed1452b98060cd80d3725c5b7") let fooRef = PackageReference.remote(identity: foo, location: fooRepo.url) let barRef = PackageReference.remote(identity: bar, location: barRepo.url) let state = CheckoutState.version(v1, revision: revision) let fs = InMemoryFileSystem() let pinsFile = AbsolutePath("/pinsfile.txt") var store = try PinsStore(pinsFile: pinsFile, workingDirectory: .root, fileSystem: fs, mirrors: .init()) // Pins file should not be created right now. XCTAssert(!fs.exists(pinsFile)) XCTAssert(store.pins.map{$0}.isEmpty) store.pin(packageRef: fooRef, state: state) try store.saveState() XCTAssert(fs.exists(pinsFile)) // Load the store again from disk. let store2 = try PinsStore(pinsFile: pinsFile, workingDirectory: .root, fileSystem: fs, mirrors: .init()) // Test basics on the store. for s in [store, store2] { XCTAssert(s.pins.map{$0}.count == 1) XCTAssertEqual(s.pinsMap[bar], nil) let fooPin = s.pinsMap[foo]! XCTAssertEqual(fooPin.packageRef, fooRef) XCTAssertEqual(fooPin.state.version, v1) XCTAssertEqual(fooPin.state.revision, revision) XCTAssertEqual(fooPin.state.description, v1.description) } // We should be able to pin again. store.pin(packageRef: fooRef, state: state) store.pin( packageRef: fooRef, state: CheckoutState.version("1.0.2", revision: revision) ) store.pin(packageRef: barRef, state: state) try store.saveState() store = try PinsStore(pinsFile: pinsFile, workingDirectory: .root, fileSystem: fs, mirrors: .init()) XCTAssert(store.pins.map{$0}.count == 2) // Test branch pin. do { store.pin( packageRef: barRef, state: CheckoutState.branch(name: "develop", revision: revision) ) try store.saveState() store = try PinsStore(pinsFile: pinsFile, workingDirectory: .root, fileSystem: fs, mirrors: .init()) let barPin = store.pinsMap[bar]! XCTAssertEqual(barPin.state.branch, "develop") XCTAssertEqual(barPin.state.version, nil) XCTAssertEqual(barPin.state.revision, revision) XCTAssertEqual(barPin.state.description, "develop") } // Test revision pin. do { store.pin(packageRef: barRef, state: .revision(revision)) try store.saveState() store = try PinsStore(pinsFile: pinsFile, workingDirectory: .root, fileSystem: fs, mirrors: .init()) let barPin = store.pinsMap[bar]! XCTAssertEqual(barPin.state.branch, nil) XCTAssertEqual(barPin.state.version, nil) XCTAssertEqual(barPin.state.revision, revision) XCTAssertEqual(barPin.state.description, revision.identifier) } } func testLoadingSchema1() throws { let fs = InMemoryFileSystem() let pinsFile = AbsolutePath("/pinsfile.txt") try fs.writeFileContents(pinsFile) { $0 <<< """ { "object": { "pins": [ { "package": "Clang_C", "repositoryURL": "https://github.com/something/Clang_C.git", "state": { "branch": null, "revision": "90a9574276f0fd17f02f58979423c3fd4d73b59e", "version": "1.0.2", } }, { "package": "Commandant", "repositoryURL": "https://github.com/something/Commandant.git", "state": { "branch": null, "revision": "c281992c31c3f41c48b5036c5a38185eaec32626", "version": "0.12.0" } } ] }, "version": 1 } """ } let store = try PinsStore(pinsFile: pinsFile, workingDirectory: .root, fileSystem: fs, mirrors: .init()) XCTAssertEqual(store.pinsMap.keys.map { $0.description }.sorted(), ["clang_c", "commandant"]) } func testEmptyPins() throws { let fs = InMemoryFileSystem() let pinsFile = AbsolutePath("/pinsfile.txt") let store = try PinsStore(pinsFile: pinsFile, workingDirectory: .root, fileSystem: fs, mirrors: .init()) try store.saveState() XCTAssertFalse(fs.exists(pinsFile)) let fooPath = AbsolutePath("/foo") let foo = PackageIdentity(path: fooPath) let fooRef = PackageReference.remote(identity: foo, location: fooPath.pathString) let revision = Revision(identifier: "81513c8fd220cf1ed1452b98060cd80d3725c5b7") store.pin(packageRef: fooRef, state: .version(v1, revision: revision)) XCTAssert(!fs.exists(pinsFile)) try store.saveState() XCTAssert(fs.exists(pinsFile)) store.unpinAll() try store.saveState() XCTAssertFalse(fs.exists(pinsFile)) } func testPinsWithMirrors() throws { let fooURL = "https://github.com/corporate/foo.git" let fooIdentity = PackageIdentity(url: fooURL) let fooMirroredURL = "https://github.corporate.com/team/foo.git" let barURL = "https://github.com/corporate/baraka.git" let barIdentity = PackageIdentity(url: barURL) let barMirroredURL = "https://github.corporate.com/team/bar.git" let barMirroredIdentity = PackageIdentity(url: barMirroredURL) let bazURL = "https://github.com/cool/baz.git" let bazIdentity = PackageIdentity(url: bazURL) let mirrors = DependencyMirrors() mirrors.set(mirrorURL: fooMirroredURL, forURL: fooURL) mirrors.set(mirrorURL: barMirroredURL, forURL: barURL) let fileSystem = InMemoryFileSystem() let pinsFile = AbsolutePath("/pins.txt") let store = try PinsStore(pinsFile: pinsFile, workingDirectory: .root, fileSystem: fileSystem, mirrors: mirrors) store.pin(packageRef: .remote(identity: fooIdentity, location: fooMirroredURL), state: .version(v1, revision: .init(identifier: "foo-revision"))) store.pin(packageRef: .remote(identity: barMirroredIdentity, location: barMirroredURL), state: .version(v1, revision: .init(identifier: "bar-revision"))) store.pin(packageRef: .remote(identity: bazIdentity, location: bazURL), state: .version(v1, revision: .init(identifier: "baz-revision"))) try store.saveState() XCTAssert(fileSystem.exists(pinsFile)) // Load the store again from disk, with no mirrors let store2 = try PinsStore(pinsFile: pinsFile, workingDirectory: .root, fileSystem: fileSystem, mirrors: .init()) XCTAssert(store2.pinsMap.count == 3) XCTAssertEqual(store2.pinsMap[fooIdentity]!.packageRef.location, fooURL) XCTAssertEqual(store2.pinsMap[barIdentity]!.packageRef.location, barURL) XCTAssertEqual(store2.pinsMap[bazIdentity]!.packageRef.location, bazURL) // Load the store again from disk, with mirrors let store3 = try PinsStore(pinsFile: pinsFile, workingDirectory: .root, fileSystem: fileSystem, mirrors: mirrors) XCTAssert(store3.pinsMap.count == 3) XCTAssertEqual(store3.pinsMap[fooIdentity]!.packageRef.location, fooMirroredURL) XCTAssertEqual(store3.pinsMap[barMirroredIdentity]!.packageRef.location, barMirroredURL) XCTAssertEqual(store3.pinsMap[bazIdentity]!.packageRef.location, bazURL) } }
41.2
121
0.617182
ef245008068cc3c501cc7a14ac237839d77dc817
15,557
// Copyright 2019 The TensorFlow Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import CoreImage import TensorFlowLite import UIKit import Accelerate /// Stores results for a particular frame that was successfully run through the `Interpreter`. struct Result { let inferenceTime: Double let inferences: [Inference] } /// Stores one formatted inference. struct Inference { let confidence: Float var className: String let rect: CGRect let displayColor: UIColor } /// Information about a model file or labels file. typealias FileInfo = (name: String, extension: String) /// Information about the MobileNet SSD model. enum MobileNetSSD { static let modelInfo: FileInfo = (name: "detect", extension: "tflite") static let labelsInfo: FileInfo = (name: "labelmap", extension: "txt") } /// This class handles all data preprocessing and makes calls to run inference on a given frame /// by invoking the `Interpreter`. It then formats the inferences obtained and returns the top N /// results for a successful inference. class ModelDataHandler: NSObject { // MARK: - Internal Properties /// The current thread count used by the TensorFlow Lite Interpreter. let threadCount: Int let threadCountLimit = 10 let threshold: Float = 0.3 // MARK: Model parameters let batchSize = 1 let inputChannels = 3 let inputWidth = 480 let inputHeight = 480 // image mean and std for floating model, should be consistent with parameters used in model training let imageMean: Float = 1 let imageStd: Float = 1 // MARK: Private properties private var labels: [String] = [] /// TensorFlow Lite `Interpreter` object for performing inference on a given model. private var interpreter: Interpreter private let bgraPixel = (channels: 4, alphaComponent: 3, lastBgrComponent: 2) private let rgbPixelChannels = 3 private let colorStrideValue = 10 private let colors = [ UIColor.red, UIColor(displayP3Red: 90.0/255.0, green: 200.0/255.0, blue: 250.0/255.0, alpha: 1.0), UIColor.green, UIColor.orange, UIColor.blue, UIColor.purple, UIColor.magenta, UIColor.yellow, UIColor.cyan, UIColor.brown ] private var classificationModelDataHandler: ClassificationModelDataHandler? = ClassificationModelDataHandler(modelFileInfo: MobileNet.modelInfo, labelsFileInfo: MobileNet.labelsInfo) // MARK: - Initialization /// A failable initializer for `ModelDataHandler`. A new instance is created if the model and /// labels files are successfully loaded from the app's main bundle. Default `threadCount` is 1. init?(modelFileInfo: FileInfo, labelsFileInfo: FileInfo, threadCount: Int = 1) { let modelFilename = modelFileInfo.name // Construct the path to the model file. guard let modelPath = Bundle.main.path( forResource: modelFilename, ofType: modelFileInfo.extension ) else { print("Failed to load the model file with name: \(modelFilename).") return nil } // Specify the options for the `Interpreter`. self.threadCount = threadCount var options = Interpreter.Options() options.threadCount = threadCount do { // Create the `Interpreter`. interpreter = try Interpreter(modelPath: modelPath, options: options) // Allocate memory for the model's input `Tensor`s. try interpreter.allocateTensors() } catch let error { print("Failed to create the interpreter with error: \(error.localizedDescription)") return nil } super.init() // Load the classes listed in the labels file. loadLabels(fileInfo: labelsFileInfo) } /// This class handles all data preprocessing and makes calls to run inference on a given frame /// through the `Interpreter`. It then formats the inferences obtained and returns the top N /// results for a successful inference. func runModel(onFrame pixelBuffer: CVPixelBuffer) -> Result? { let imageWidth = CVPixelBufferGetWidth(pixelBuffer) let imageHeight = CVPixelBufferGetHeight(pixelBuffer) let sourcePixelFormat = CVPixelBufferGetPixelFormatType(pixelBuffer) assert(sourcePixelFormat == kCVPixelFormatType_32ARGB || sourcePixelFormat == kCVPixelFormatType_32BGRA || sourcePixelFormat == kCVPixelFormatType_32RGBA) let imageChannels = 4 assert(imageChannels >= inputChannels) // Crops the image to the biggest square in the center and scales it down to model dimensions. let scaledSize = CGSize(width: inputWidth, height: inputHeight) guard let scaledPixelBuffer = pixelBuffer.resized(to: scaledSize) else { return nil } let interval: TimeInterval let outputBoundingBox: Tensor let outputClasses: Tensor let outputScores: Tensor let outputCount: Tensor do { let inputTensor = try interpreter.input(at: 0) // Remove the alpha component from the image buffer to get the RGB data. guard let rgbData = rgbDataFromBuffer( scaledPixelBuffer, byteCount: batchSize * inputWidth * inputHeight * inputChannels, isModelQuantized: inputTensor.dataType == .uInt8 ) else { print("Failed to convert the image buffer to RGB data.") return nil } // Copy the RGB data to the input `Tensor`. try interpreter.copy(rgbData, toInputAt: 0) // Run inference by invoking the `Interpreter`. let startDate = Date() try interpreter.invoke() interval = Date().timeIntervalSince(startDate) * 1000 outputScores = try interpreter.output(at: 0) outputBoundingBox = try interpreter.output(at: 1) outputCount = try interpreter.output(at: 2) outputClasses = try interpreter.output(at: 3) } catch let error { print("Failed to invoke the interpreter with error: \(error.localizedDescription)") return nil } // Formats the results var resultArray = formatResults( boundingBox: [Float](unsafeData: outputBoundingBox.data) ?? [], outputClasses: [Float](unsafeData: outputClasses.data) ?? [], outputScores: [Float](unsafeData: outputScores.data) ?? [], outputCount: Int(([Float](unsafeData: outputCount.data) ?? [0])[0]), width: CGFloat(imageWidth), height: CGFloat(imageHeight) ) for i in 0..<resultArray.count { let rect = resultArray[i].rect // dump(rect) let ciImage = CIImage(cvPixelBuffer: pixelBuffer) let bbox = ciImage.cropped(to: rect) var destPixelBuffer: CVPixelBuffer? CVPixelBufferCreate(kCFAllocatorDefault, Int(rect.size.width), Int(rect.size.height), CVPixelBufferGetPixelFormatType(pixelBuffer), nil, &destPixelBuffer) CIContext().render(bbox, to: destPixelBuffer!, bounds: bbox.extent, colorSpace: CGColorSpace(name: CGColorSpace.sRGB)) var classificationResult = self.classificationModelDataHandler?.runModel(onFrame: destPixelBuffer!) resultArray[i].className = classificationResult!.inferences[0].label } // dump(classificationResult) // for bbox in resultArray: // outputClass = classify(bbox) // resultArray.outputClasses[bbox_index] = outputClass // Returns the inference time and inferences let result = Result(inferenceTime: interval, inferences: resultArray) return result } /// Filters out all the results with confidence score < threshold and returns the top N results /// sorted in descending order. func formatResults(boundingBox: [Float], outputClasses: [Float], outputScores: [Float], outputCount: Int, width: CGFloat, height: CGFloat) -> [Inference]{ var resultsArray: [Inference] = [] if (outputCount == 0) { return resultsArray } for i in 0...outputCount - 1 { let score = outputScores[i] // Filters results with confidence < threshold. guard score >= threshold else { continue } // Gets the output class names for detected classes from labels list. let outputClassIndex = Int(outputClasses[i]) let outputClass = labels[outputClassIndex + 1] var rect: CGRect = CGRect.zero // Translates the detected bounding box to CGRect. rect.origin.y = CGFloat(boundingBox[4*i]) rect.origin.x = CGFloat(boundingBox[4*i+1]) rect.size.height = CGFloat(boundingBox[4*i+2]) - rect.origin.y rect.size.width = CGFloat(boundingBox[4*i+3]) - rect.origin.x // The detected corners are for model dimensions. So we scale the rect with respect to the // actual image dimensions. let newRect = rect.applying(CGAffineTransform(scaleX: width, y: height)) // Gets the color assigned for the class let colorToAssign = colorForClass(withIndex: outputClassIndex + 1) let inference = Inference(confidence: score, className: outputClass, rect: newRect, displayColor: colorToAssign) resultsArray.append(inference) } // Sort results in descending order of confidence. resultsArray.sort { (first, second) -> Bool in return first.confidence > second.confidence } return resultsArray } /// Loads the labels from the labels file and stores them in the `labels` property. private func loadLabels(fileInfo: FileInfo) { let filename = fileInfo.name let fileExtension = fileInfo.extension guard let fileURL = Bundle.main.url(forResource: filename, withExtension: fileExtension) else { fatalError("Labels file not found in bundle. Please add a labels file with name " + "\(filename).\(fileExtension) and try again.") } do { let contents = try String(contentsOf: fileURL, encoding: .utf8) labels = contents.components(separatedBy: .newlines) } catch { fatalError("Labels file named \(filename).\(fileExtension) cannot be read. Please add a " + "valid labels file and try again.") } } /// Returns the RGB data representation of the given image buffer with the specified `byteCount`. /// /// - Parameters /// - buffer: The BGRA pixel buffer to convert to RGB data. /// - byteCount: The expected byte count for the RGB data calculated using the values that the /// model was trained on: `batchSize * imageWidth * imageHeight * componentsCount`. /// - isModelQuantized: Whether the model is quantized (i.e. fixed point values rather than /// floating point values). /// - Returns: The RGB data representation of the image buffer or `nil` if the buffer could not be /// converted. private func rgbDataFromBuffer( _ buffer: CVPixelBuffer, byteCount: Int, isModelQuantized: Bool ) -> Data? { CVPixelBufferLockBaseAddress(buffer, .readOnly) defer { CVPixelBufferUnlockBaseAddress(buffer, .readOnly) } guard let sourceData = CVPixelBufferGetBaseAddress(buffer) else { return nil } let width = CVPixelBufferGetWidth(buffer) let height = CVPixelBufferGetHeight(buffer) let sourceBytesPerRow = CVPixelBufferGetBytesPerRow(buffer) let destinationChannelCount = 3 let destinationBytesPerRow = destinationChannelCount * width var sourceBuffer = vImage_Buffer(data: sourceData, height: vImagePixelCount(height), width: vImagePixelCount(width), rowBytes: sourceBytesPerRow) guard let destinationData = malloc(height * destinationBytesPerRow) else { print("Error: out of memory") return nil } defer { free(destinationData) } var destinationBuffer = vImage_Buffer(data: destinationData, height: vImagePixelCount(height), width: vImagePixelCount(width), rowBytes: destinationBytesPerRow) if (CVPixelBufferGetPixelFormatType(buffer) == kCVPixelFormatType_32BGRA){ vImageConvert_BGRA8888toRGB888(&sourceBuffer, &destinationBuffer, UInt32(kvImageNoFlags)) } else if (CVPixelBufferGetPixelFormatType(buffer) == kCVPixelFormatType_32ARGB) { vImageConvert_ARGB8888toRGB888(&sourceBuffer, &destinationBuffer, UInt32(kvImageNoFlags)) } let byteData = Data(bytes: destinationBuffer.data, count: destinationBuffer.rowBytes * height) if isModelQuantized { return byteData } // Not quantized, convert to floats let bytes = Array<UInt8>(unsafeData: byteData)! var floats = [Float]() for i in 0..<bytes.count { floats.append((Float(bytes[i]) - imageMean) / imageStd) } return Data(copyingBufferOf: floats) } /// This assigns color for a particular class. private func colorForClass(withIndex index: Int) -> UIColor { // We have a set of colors and the depending upon a stride, it assigns variations to of the base // colors to each object based on its index. let baseColor = colors[index % colors.count] var colorToAssign = baseColor let percentage = CGFloat((colorStrideValue / 2 - index / colors.count) * colorStrideValue) if let modifiedColor = baseColor.getModified(byPercentage: percentage) { colorToAssign = modifiedColor } return colorToAssign } } // MARK: - Extensions extension Data { /// Creates a new buffer by copying the buffer pointer of the given array. /// /// - Warning: The given array's element type `T` must be trivial in that it can be copied bit /// for bit with no indirection or reference-counting operations; otherwise, reinterpreting /// data from the resulting buffer has undefined behavior. /// - Parameter array: An array with elements of type `T`. init<T>(copyingBufferOf array: [T]) { self = array.withUnsafeBufferPointer(Data.init) } } extension Array { /// Creates a new array from the bytes of the given unsafe data. /// /// - Warning: The array's `Element` type must be trivial in that it can be copied bit for bit /// with no indirection or reference-counting operations; otherwise, copying the raw bytes in /// the `unsafeData`'s buffer to a new array returns an unsafe copy. /// - Note: Returns `nil` if `unsafeData.count` is not a multiple of /// `MemoryLayout<Element>.stride`. /// - Parameter unsafeData: The data containing the bytes to turn into an array. init?(unsafeData: Data) { guard unsafeData.count % MemoryLayout<Element>.stride == 0 else { return nil } #if swift(>=5.0) self = unsafeData.withUnsafeBytes { .init($0.bindMemory(to: Element.self)) } #else self = unsafeData.withUnsafeBytes { .init(UnsafeBufferPointer<Element>( start: $0, count: unsafeData.count / MemoryLayout<Element>.stride )) } #endif // swift(>=5.0) } }
37.486747
156
0.681237
dd0851e6fe4be7401456899155cb7cbc521a0850
336
import Foundation public protocol InternalProtocolRefiningPublicProtocol_Refined {} protocol InternalProtocolRefiningPublicProtocol: InternalProtocolRefiningPublicProtocol_Refined {} public class InternalProtocolRefiningPublicProtocolRetainer { public init() { let _: InternalProtocolRefiningPublicProtocol? = nil } }
30.545455
98
0.833333
d6ba815eebe6877ecf5f90699df81ef6dd14360c
10,550
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #if canImport(Combine) && swift(>=5.0) && canImport(FirebaseStorage) import Combine import FirebaseStorage import FirebaseStorageSwift @available(swift 5.0) @available(iOS 13.0, macOS 10.15, macCatalyst 13.0, tvOS 13.0, watchOS 6.0, *) extension StorageReference { // MARK: - Uploads /// Asynchronously uploads data to the currently specified `StorageReference`. /// This is not recommended for large files, and one should instead upload a file from disk. /// /// The publisher will emit events on the **main** thread. /// /// - Parameters: /// - uploadData: The Data to upload. /// - metadata: metadata `StorageMetadata` containing additional information (MIME type, etc.) /// /// - Returns: A publisher emitting a `StorageMetadata` instance. The publisher will emit on the *main* thread. @discardableResult public func putData(_ data: Data, metadata: StorageMetadata? = nil) -> Future<StorageMetadata, Error> { var task: StorageUploadTask? return Future<StorageMetadata, Error> { promise in task = self.putData(data, metadata: metadata) { result in promise(result) } } .handleEvents(receiveCancel: { task?.cancel() }) .upstream } /// Asynchronously uploads a file to the currently specified `StorageReference`. /// /// The publisher will emit events on the **main** thread. /// /// - Parameters: /// - fileURL: A `URL` representing the system file path of the object to be uploaded. /// - metadata: `StorageMetadata` containing additional information (MIME type, etc.) about the object being uploaded. /// /// - Returns: A publisher emitting a `StorageMetadata` instance. The publisher will emit on the *main* thread. @discardableResult public func putFile(from fileURL: URL, metadata: StorageMetadata? = nil) -> Future<StorageMetadata, Error> { var task: StorageUploadTask? return Future<StorageMetadata, Error> { promise in task = self.putFile(from: fileURL, metadata: metadata) { result in promise(result) } } .handleEvents(receiveCancel: { task?.cancel() }) .upstream } // MARK: - Downloads /// Asynchronously downloads the object at the `StorageReference` to an `Data` object in memory. /// An `Data` of the provided max size will be allocated, so ensure that the device has enough free /// memory to complete the download. For downloading large files, `writeToFile` may be a better option. /// /// The publisher will emit events on the **main** thread. /// /// - Parameters: /// - size: The maximum size in bytes to download. If the download exceeds this size /// the task will be cancelled and an error will be returned. /// /// - Returns: A publisher emitting a `Data` instance. The publisher will emit on the *main* thread. @discardableResult public func getData(maxSize size: Int64) -> Future<Data, Error> { var task: StorageDownloadTask? return Future<Data, Error> { promise in task = self.getData(maxSize: size) { result in promise(result) } } .handleEvents(receiveCancel: { task?.cancel() }) .upstream } /// Asynchronously downloads the object at the current path to a specified system filepath. /// /// The publisher will emit events on the **main** thread. /// /// - Parameters: /// - fileURL: A file system URL representing the path the object should be downloaded to. /// /// - Returns: A publisher emitting a `URL` pointing to the file path of the downloaded file /// on success. The publisher will emit on the *main* thread. @discardableResult public func write(toFile fileURL: URL) -> Future<URL, Error> { var task: StorageDownloadTask? return Future<URL, Error> { promise in task = self.write(toFile: fileURL) { result in promise(result) } } .handleEvents(receiveCancel: { task?.cancel() }) .upstream } /// Asynchronously retrieves a long lived download URL with a revokable token. /// This can be used to share the file with others, but can be revoked by a developer /// in the Firebase Console if desired. /// /// The publisher will emit events on the **main** thread. /// /// - Returns: A publisher emitting a `URL` instance. The publisher will emit on the *main* thread. @discardableResult public func downloadURL() -> Future<URL, Error> { Future<URL, Error> { promise in self.downloadURL { result in promise(result) } } } // MARK: - List Support /// List all items (files) and prefixes (folders) under this `StorageReference`. /// /// This is a helper method for calling `list()` repeatedly until there are no more results. /// Consistency of the result is not guaranteed if objects are inserted or removed while this /// operation is executing. All results are buffered in memory. /// /// The publisher will emit events on the **main** thread. /// /// - Remark: /// `listAll` is only available for projects using Firebase Rules Version 2. /// /// - Returns: A publisher emitting a `StorageListResult` instance. The publisher will emit on the *main* thread. @discardableResult public func listAll() -> Future<StorageListResult, Error> { Future<StorageListResult, Error> { promise in self.listAll { result in promise(result) } } } /// List up to `maxResults` items (files) and prefixes (folders) under this `StorageReference`. /// /// Note that "/" is treated as a path delimiter. Firebase Storage does not support unsupported object /// paths that end with "/" or contain two consecutive "/"s. All invalid objects in Firebase Storage will be /// filtered. /// /// The publisher will emit events on the **main** thread. /// /// - Parameters: /// - maxResults: The maximum number of results to return in a single page. Must be greater /// than 0 and at most 1000. /// /// - Remark: /// `list(maxResults:)` is only available for projects using Firebase Rules Version 2. /// /// - Returns: A publisher emitting a `StorageListResult` instance. The publisher will emit on the *main* thread. @discardableResult public func list(maxResults: Int64) -> Future<StorageListResult, Error> { Future<StorageListResult, Error> { promise in self.list(maxResults: maxResults) { result in promise(result) } } } /// Resumes a previous call to `list(maxResults:)`, starting after a pagination token. /// Returns the next set of items (files) and prefixes (folders) under this `StorageReference. /// /// Note that "/" is treated as a path delimiter. Firebase Storage does not support unsupported object /// paths that end with "/" or contain two consecutive "/"s. All invalid objects in Firebase Storage /// will be filtered out. /// /// The publisher will emit events on the **main** thread. /// /// - Parameters: /// - maxResults: The maximum number of results to return in a single page. Must be greater /// than 0 and at most 1000. /// - pageToken: A page token from a previous call to list. /// /// - Remark: /// `list(maxResults:pageToken:)` is only available for projects using Firebase Rules Version 2. /// /// - Returns: A publisher emitting a `StorageListResult` instance. The publisher will emit on the *main* thread. @discardableResult public func list(maxResults: Int64, pageToken: String) -> Future<StorageListResult, Error> { Future<StorageListResult, Error> { promise in self.list(maxResults: maxResults, pageToken: pageToken) { result in promise(result) } } } // MARK: - Metadata Operations /// Retrieves metadata associated with an object at the current path. /// /// The publisher will emit events on the **main** thread. /// /// - Returns: A publisher emitting a `StorageMetadata` instance. The publisher will emit on the *main* thread. @discardableResult public func getMetadata() -> Future<StorageMetadata, Error> { Future<StorageMetadata, Error> { promise in self.getMetadata { result in promise(result) } } } /// Updates the metadata associated with an object at the current path. /// /// The publisher will emit events on the **main** thread. /// /// - Parameters: /// - metadata: A `StorageMetadata` object with the metadata to update. /// /// - Returns: A publisher emitting a `StorageMetadata` instance. The publisher will emit on the *main* thread. @discardableResult public func updateMetadata(_ metadata: StorageMetadata) -> Future<StorageMetadata, Error> { Future<StorageMetadata, Error> { promise in self.updateMetadata(metadata) { result in promise(result) } } } // MARK: - Delete /// Deletes the object at the current path. /// /// The publisher will emit events on the **main** thread. /// /// - Returns: A publisher that emits whether the call was successful or not. The publisher will emit on the *main* thread. @discardableResult public func delete() -> Future<Bool, Error> { Future<Bool, Error> { promise in self.delete { error in if let error = error { promise(.failure(error)) } else { promise(.success(true)) } } } } } #endif // canImport(Combine) && swift(>=5.0) && canImport(FirebaseStorage)
38.786765
127
0.639431
62c66bd89a1647f620d3011bb9834858c66ba205
469
// // BlackTheme.swift // NISwift // // Created by nixs on 2019/3/18. // Copyright © 2019年 nixs. All rights reserved. // import UIKit class BlackTheme: ThemeProtocol { var backgroundColor: UIColor{ get{ return UIColor.black } } var titleTextColor: UIColor{ get{ return UIColor.white } } var detailTextColor: UIColor { get{ return UIColor.lightGray } } }
16.172414
48
0.552239
1d9aa167075600ba431f0610b509739e0ee821f0
2,345
// // GoogleSignInService.swift // FirebaseService // // Created by sudo.park on 2022/01/02. // import UIKit import RxSwift import Domain import GoogleSignIn // MARK: - GoggleSignInService public protocol GoggleSignInService: OAuthService, OAuthServiceProviderTypeRepresentable { func handleURLOrNot(_ url: URL) -> Bool } public final class GoggleSignInServiceImple: GoggleSignInService { public init() {} public var providerType: OAuthServiceProviderType { return OAuthServiceProviderTypes.google } } extension GoggleSignInServiceImple { public func requestSignIn() -> Maybe<Domain.OAuthCredential> { guard let clientID = FirebaseApp.app()?.options.clientID else { return .error(AuthErrors.noFirebaseClientID) } return Maybe.create { [weak self] callback in guard let topViewController = self?.topViewController() else { callback(.completed) return Disposables.create() } let configure = GIDConfiguration(clientID: clientID) GIDSignIn.sharedInstance.signIn(with: configure, presenting: topViewController) { user, error in guard error == nil, let authToken = user?.authentication, let idToken = authToken.idToken else { callback(.error(AuthErrors.oauth2Fail(error))) return } let credential = GoogleAuthCredential(idToken: idToken, accessToken: authToken.accessToken) callback(.success(credential)) } return Disposables.create() } } private func topViewController() -> UIViewController? { return UIApplication.shared.windows.first?.rootViewController?.topPresentedViewController() } } extension GoggleSignInServiceImple { public func handleURLOrNot(_ url: URL) -> Bool { return GIDSignIn.sharedInstance.handle(url) } } private extension UIViewController { func topPresentedViewController() -> UIViewController { guard let presented = self.presentedViewController else { return self } return presented.topPresentedViewController() } }
27.916667
108
0.628998
e553f081ae563048ede4af0d248fefe242302223
1,347
// // AppDelegate.swift // SearchModule // // Created by hanwe on 2021/08/19. // import UIKit @main class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } }
36.405405
179
0.746102
ef339aa67bb1e6fb0c5acdd6bd009ed2dc17d6ea
2,115
// // AppDelegate.swift // ParseSaveTest // // Created by Rick Terrill on 9/1/15. // Copyright (c) 2015 Big Swing. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { startParse() 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:. } }
44.0625
285
0.745626
9cdc4056a38dfceeb324acde2a704746bc9cf068
2,795
// // PlayButtonView.swift // QTRadio // // Created by Enrica on 2017/11/1. // Copyright © 2017年 Enrica. All rights reserved. // // 主要是用来管理TabBar正中间的播放按钮 import UIKit class PlayButtonView: UIView { // MARK: - 保存私有属性 /// 父控制器 fileprivate var parentVc: UIViewController // MARK: - 懒加载属性 /// tabbar_np_normal fileprivate lazy var imageView: UIImageView = { // 创建imageView let imageView = UIImageView() // 设置normalImageView的图片 imageView.image = UIImage(named: "tabbar_np_normal") // tabbar_np_normal // 设置imageView的尺寸 imageView.sizeToFit() // 开启imageView的手势交互 imageView.isUserInteractionEnabled = true return imageView }() /// 中间的播放按钮 fileprivate lazy var playButton: UIButton = { // 创建按钮 let playButton = UIButton(image: "play_page_control_bar_play_48x48_", highlightedImage: "play_page_control_bar_play_disabled_48x48_") // 监听中间播放按钮的点击 playButton.addTarget(self, action: #selector(PlayButtonView.playButtonClick), for: .touchUpInside) return playButton }() // MARK: - 自定义构造函数 /// 根据外部传递过来的参数自定义背景view /// - 参数frame: 表示背景view的frame /// - 参数parentVc: 表示父控制器 init(frame: CGRect, parentVc: UIViewController) { // 将外部传递过来的参数保存到私有属性中 self.parentVc = parentVc super.init(frame: frame) // 统一设置UI界面 setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension PlayButtonView { // 统一设置UI界面 fileprivate func setupUI() { // 添加normalImageView addSubview(imageView) // 添加中间的播放按钮 addSubview(playButton) } /// 调整子控件的frame override func layoutSubviews() { super.layoutSubviews() playButton.center = imageView.center } } /// 监听按钮的点击 extension PlayButtonView { /// 点击中间的播放按钮,弹出控制器 @objc fileprivate func playButtonClick() { // 点击中间的播放按钮,push到下一个控制器 // 这里在实际开发过程中需要做一个判断,如果 // 有在播放的专辑,则直接播放,如果没有,则push // 取出tabBar根控制器 let tabBarVc: UITabBarController = (UIApplication.shared.keyWindow!.rootViewController as? UITabBarController)! // 取出当前选中的导航控制器 let nav: UINavigationController = (tabBarVc.selectedViewController as? UINavigationController)! let vc = UIViewController() vc.view.backgroundColor = UIColor.randomColor() // push到下一个控制器 nav.pushViewController(vc, animated: true) } }
22.909836
145
0.588551
2ff76f3fab8f2aed24f02538ba2a4907ffd6993b
1,460
//---------------------------------------------------- // // Generated by www.easywsdl.com // Version: 5.7.0.0 // // Created by Quasar Development // //--------------------------------------------------- import Foundation /** * specDomain: S19749 (C-0-T12206-A19563-S17926-S19749-cpt) */ public enum EPA_FdV_AUTHZ_FamilyMemberCousin:Int,CustomStringConvertible { case COUSN case MCOUSN case PCOUSN static func createWithXml(node:DDXMLNode) -> EPA_FdV_AUTHZ_FamilyMemberCousin? { return createWithString(value: node.stringValue!) } static func createWithString(value:String) -> EPA_FdV_AUTHZ_FamilyMemberCousin? { var i = 0 while let item = EPA_FdV_AUTHZ_FamilyMemberCousin(rawValue: i) { if String(describing: item) == value { return item } i += 1 } return nil } public var stringValue : String { return description } public var description : String { switch self { case .COUSN: return "COUSN" case .MCOUSN: return "MCOUSN" case .PCOUSN: return "PCOUSN" } } public func getValue() -> Int { return rawValue } func serialize(__parent:DDXMLNode) { __parent.stringValue = stringValue } }
20.857143
84
0.508904
16cb4263b6b7b82abfe8d5a73ce781f0dcf01ba0
771
// // MapView.swift // Landmark // // Created by Sharetrip-iOS on 31/08/2020. // Copyright © 2020 AP. All rights reserved. import SwiftUI import MapKit struct MapView: UIViewRepresentable { func makeUIView(context: Context) -> MKMapView { MKMapView(frame: .zero) } func updateUIView(_ uiView: MKMapView, context: Context) { let coordinate = CLLocationCoordinate2D( latitude: 34.011286, longitude: -116.166868) let span = MKCoordinateSpan(latitudeDelta: 2.0, longitudeDelta: 2.0) let region = MKCoordinateRegion(center: coordinate, span: span) uiView.setRegion(region, animated: true) } } struct MapView_Previews: PreviewProvider { static var previews: some View { MapView() } }
24.870968
76
0.670558
ccedfbb2686d3629345a51b0b0f113b68716b93f
2,865
// // GoogleStyle.swift // Pods // // Created by Fernando on 1/2/17. // // import Foundation public struct GoogleStyle { var featureType: FeatureType? var elementType: ElementType? var stylers: [[String:Any]]? public init(json: [String:Any]) { if let featureTypeString = json["featureType"] as? String { if let featureType = FeatureType(rawValue: featureTypeString) { self.featureType = featureType } else { print("Unsupported feature type: \(featureTypeString)") } } if let elementTypeString = json["elementType"] as? String { if let elementType = ElementType(rawValue: elementTypeString) { self.elementType = elementType } else { print("Unsupported element type: \(elementTypeString)") } } if let stylers = json["stylers"] as? [[String:Any]] { self.stylers = stylers } } public var encodedStyles: String { var style = "" if let featureType = self.featureType { style.append("s.t:") style.append(featureType.convertedValue) } else { style.append("s.t:") style.append("undefined") } if let elementType = self.elementType { if Array(style).last! != "|" && Array(style).last! != "," { style.append("|") } style.append("s.e:") style.append(elementType.convertedValue) } if let stylers = self.stylers { for styler in stylers { for (key, value) in styler { if let stylerType = StylerType(rawValue: key) { if Array(style).last! != "|" && Array(style).last! != "," { style.append("|") } if key == "color" { if let color = value as? String { if Array(color).count == 7 { style.append("\(stylerType.convertedValue):#ff\(color.replacingOccurrences(of: "#", with: ""))") } else if Array(color).count != 9 { print("Malformed color") } else { style.append("\(stylerType.convertedValue):\(value)") } } } else { style.append("\(stylerType.convertedValue):\(value)") } } else { print ("Unsupported styler type \(key)") } } } } return style } }
34.939024
132
0.44363
082e1979aedd5ca8acee2cffc437aca603b207cf
649
// // CollectionVIewCellData.swift // Memorize // // Created by Вика on 04/12/2019. // Copyright © 2019 Vika Olegova. All rights reserved. // import UIKit /// Класс данных ячейки коллекшн вью с экрана создания\редактирования слова class ImageCollectionViewCellData { var image: UIImage? /// загрузилось изображение или нет var isLoaded: Bool { return image != nil } /// хитрая(нет) замена конструктора без параметров static var loading: ImageCollectionViewCellData { return ImageCollectionViewCellData() } private init() { } init(image: UIImage) { self.image = image } }
22.37931
75
0.66718
e0840a699336a301165ce9d20b5027aba4bbf626
109
import XCTest import MoatTests var tests = [XCTestCaseEntry]() tests += MoatTests.allTests() XCTMain(tests)
15.571429
31
0.770642
b93906294572675552bdd2d5d30096bce6a276a4
4,126
// // CipherManager.swift // CryCipher // // Created by Thibault Defeyter on 23/02/2019. // import Foundation import CryptoSwift /// Cipher related Constants struct CipherConstants { static let headerLength = 8 static let saltLength = 32 static let initializationVectorLength = 16 static let hashLength = 32 static let totalLength = headerLength + saltLength + initializationVectorLength + hashLength static let currentVersion = 0 static let header = [UInt8]("CRY00001".utf8) } /// The Cipher to be written/read from the encrypted file public struct Cipher: Equatable { let header: [UInt8] = CipherConstants.header let salt: [UInt8] let initializationVector: [UInt8] let encryptedBytes: [UInt8] let hash: [UInt8] } /// Manage Ciphers Encryption/Decryption public struct CipherManager: Manager { public typealias ClearContent = [UInt8] public typealias EncryptedContent = Cipher public typealias Secret = [UInt8] private let encryptionManager: AnyManager<[UInt8], [UInt8], EncryptionSecret> private let randomGenerator: RandomGenerator private let keyCoupleGenerator: KeyCoupleGenerator private let signatureManager: AnySignatureManager<HashContent, [UInt8]> init(encryptionManager: AnyManager<[UInt8], [UInt8], EncryptionSecret>, randomGenerator: RandomGenerator, keyCoupleGenerator: KeyCoupleGenerator, signatureManager: AnySignatureManager<HashContent, [UInt8]>) { self.encryptionManager = encryptionManager self.randomGenerator = randomGenerator self.keyCoupleGenerator = keyCoupleGenerator self.signatureManager = signatureManager } public init() { self.init( encryptionManager: AnyManager(manager: EncryptionManager()), randomGenerator: RandomGeneratorImpl(), keyCoupleGenerator: KeyCoupleGeneratorImpl(), signatureManager: AnySignatureManager(manager: HashSignatureManager()) ) } public func encrypt(content: ClearContent, withSecret secret: Secret) throws -> EncryptedContent { // generate random salt and init vector for key generation let salt = try self.randomGenerator.generateRandomBytes(length: CipherConstants.saltLength) let initializationVector = try self.randomGenerator.generateRandomBytes( length: CipherConstants.initializationVectorLength ) // generate a key from secret and salt let key = try self.keyCoupleGenerator.generateKeyCouple(fromPassword: secret, andSalt: salt) // encrypt the data using AES256 (key and init vector) let encryptedBytes = try self.encryptionManager.encrypt( content: content, withSecret: EncryptionSecret(key: key.encryptionKey, initializationVector: initializationVector) ) // compute the hash of the encrypted data let hash = try self.signatureManager.sign( content: HashContent( key: key.hashKey, encryptedBytes: encryptedBytes ) ) return Cipher( salt: salt, initializationVector: initializationVector, encryptedBytes: encryptedBytes, hash: hash ) } public func decrypt(content: EncryptedContent, withSecret secret: Secret) throws -> ClearContent { // generate a key from secret and salt let key = try self.keyCoupleGenerator.generateKeyCouple(fromPassword: secret, andSalt: content.salt) // verify the hash of the encrypted data try self.signatureManager.verify( content: HashContent(key: key.hashKey, encryptedBytes: content.encryptedBytes), signature: content.hash ) // decrypt the data using AES256 (key and init vector) let decryptedBytes = try self.encryptionManager.decrypt( content: content.encryptedBytes, withSecret: EncryptionSecret(key: key.encryptionKey, initializationVector: content.initializationVector) ) return decryptedBytes } }
35.264957
116
0.690742