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
141fe0eac2c406ba5e031490f61065a5b9e2204f
4,171
// // APIMethodCall.swift // APIMethodCall // // Created by Stephen Kockentiedt on 16.09.21. // import Foundation import Vapor /// An ID used by the code generated by SwiftyBridges to identify an API method public struct APIMethodID: Codable, Hashable { var rawValue: String } extension APIMethodID: ExpressibleByStringLiteral { public init(stringLiteral value: String) { rawValue = value } } /// A protocl used by structs generated by SwiftyBridges holding the info of an API method call public protocol APIMethodCall: Content { associatedtype API: APIDefinition associatedtype ReturnType: Codable static var methodID: APIMethodID { get } /// Executes the method call on the API definition /// - Returns: A future for the return value of the API method func call(on api: API) throws -> EventLoopFuture<ReturnType> } /// This is used as a replacement for the `Void` return type in generated code to prevent compiler errors because `Void` does not conform to `Codable` public struct NoReturnValue: Codable { public init() {} public init(from decoder: Decoder) throws {} public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(0) } } /// This type wraps types conforming to `APIMethodCall` so that calling code can decode API call requests and apply the API call iteself without knowing the return type at compile time public struct AnyAPIMethod<API: APIDefinition> { /// A function type that takes an instance of an API definition, calls an API method with the parameters decoded from the request and encodes the return value as a `Response` typealias MethodCall = (API) throws -> EventLoopFuture<Response> /// The ID used to identify this specific API method let methodID: APIMethodID /// A closure that decodes the method parameters from the request and returns a preconfigured `MethodCall` private let decodeCallAction: (Request) -> EventLoopFuture<MethodCall> /// Creates an instance with a specific type conforming to `APIMethodCall /// - Parameters: /// - method: The request that was received for the API method call public init<MethodCallType: APIMethodCall>(method: MethodCallType.Type) where MethodCallType.API == API { methodID = method.methodID decodeCallAction = { (request: Request) -> EventLoopFuture<MethodCall> in return MethodCallType.decodeRequest(request).map { (call: MethodCallType) -> MethodCall in func callAPIMethodAndEncodeReturnValue(api: API) throws -> EventLoopFuture<Response> { try call.call(on: api).flatMap { $0.encodeResponse(for: request) } } return callAPIMethodAndEncodeReturnValue(api:) } } } /// Decodes the parameters from the given request and returns a preconfigured method call /// - Parameter request: A request encoding an API method call /// - Returns: A closure that takes an instance of an API definition, calls the API method represented by this instance with the parameters decoded from `request` and encodes the return value as a `Response` func decodeCall(from request: Request) -> EventLoopFuture<MethodCall> { decodeCallAction(request) } } private extension Encodable { /// Encodes `Encodable` as a `Response`. /// /// - Parameter request: The request for this response /// - Returns: A future for the encoded response func encodeResponse(for request: Request) -> EventLoopFuture<Response> { EncodingHelper(self).encodeResponse(for: request) } } /// Allows `Encodable` values to be encoded as a `Response` private struct EncodingHelper<Wrapped: Encodable>: Content { var wrappedValue: Wrapped init(_ wrappedValue: Wrapped) { self.wrappedValue = wrappedValue } init(from decoder: Decoder) throws { fatalError("EncodingHelper does not support decoding.") } func encode(to encoder: Encoder) throws { try wrappedValue.encode(to: encoder) } }
40.105769
211
0.700312
01a81b2aed94582f4c5d7125cf88b35c65e6c487
275
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing struct Q<T where I=e{let a{enum b { var e let a=e let:T.E=b
22.916667
87
0.730909
ef10796dc4f12458f127ec1caaca9a8820766d62
2,412
// // EyeView.swift // EyesUI // // Created by Timofey Surkov on 21.02.2022. // Copyright © 2022 com.timofeysurkov. All rights reserved. // import UIKit import EyesKit final class EyeView: UIView { // MARK: - Subviews private let eyeballView: UIView = { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = Colors.foregroundMainLight return view }() // MARK: - Initializers override init(frame: CGRect) { super.init(frame: .zero) setupLayout() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Internal Instance Methods override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) guard traitCollection.userInterfaceStyle != previousTraitCollection?.userInterfaceStyle else { return } self.layer.borderColor = Colors.foregroundMain.cgColor } func setEyeballTransform(transformInfo: TransformInfo) { eyeballView.transform = CGAffineTransform( translationX: transformInfo.x * bounds.width / 2, y: transformInfo.y * bounds.height / 2 ).concatenating( CGAffineTransform(rotationAngle: transformInfo.rotationAngle) ).concatenating( CGAffineTransform(scaleX: transformInfo.scale, y: transformInfo.scale) ) } // MARK: - Private Instance Methods private func setupLayout () { self.translatesAutoresizingMaskIntoConstraints = false self.clipsToBounds = true self.layer.masksToBounds = true self.layer.cornerRadius = 16 self.layer.cornerCurve = .continuous self.layer.borderWidth = 1 self.layer.borderColor = Colors.foregroundMain.cgColor self.backgroundColor = Colors.backgroundMainLight addSubview(eyeballView) NSLayoutConstraint.activate([ eyeballView.centerXAnchor.constraint(equalTo: self.centerXAnchor), eyeballView.centerYAnchor.constraint(equalTo: self.centerYAnchor), eyeballView.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: GoldenRatio.inversedCGFloatValue), eyeballView.heightAnchor.constraint(equalTo: eyeballView.widthAnchor) ]) } }
30.923077
120
0.682836
79d574ad3691df9beda62b84bd3638f9494e5000
753
// // Common.swift // RxSwiftIn4HoursPractice // // Created by Dannian Park on 2021/06/25. // import UIKit let LARGE_IMAGE_URL = "https://picsum.photos/1024/768/?random" let LARGER_IMAGE_URL = "https://picsum.photos/1280/720/?random" let LARGEST_IMAGE_URL = "https://picsum.photos/2560/1440/?random" func syncLoadImage(from imageUrl: String) -> UIImage? { guard let url = URL(string: imageUrl) else { return nil } guard let data = try? Data(contentsOf: url) else { return nil } let image = UIImage(data: data) return image } func asyncLoadImage(from imageUrl: String, completed: @escaping (UIImage?) -> Void) { DispatchQueue.global().async { let image = syncLoadImage(from: imageUrl) completed(image) } }
26.892857
85
0.690571
621686feb0a23eedb2980dbdf3c0c5beef75dcad
810
// // Copyright 2020 Swiftkube Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation /// `ListableResource` conformance for the type-erased `AnyKubernetesAPIResource`. extension AnyKubernetesAPIResource: ListableResource { public typealias List = AnyKubernetesAPIResourceList }
35.217391
82
0.77037
ccdd7fe287fef5495817866c7e6e38d3e1db8ec5
723
// // DiscoverInteractor.swift // TheMovieDBDomain // // Created by Mohammed Gamal on 10/19/20. // import Foundation public protocol DiscoverInteractorInterface { func discoverMovies(handler: @escaping (DiscoverResultEntity) -> (Void)) } public class DiscoverInteractor: DiscoverInteractorInterface { let discoverDomainRepo: DiscoverDomainRepoInterface public init (discoverDomainRepo: DiscoverDomainRepoInterface) { self.discoverDomainRepo = discoverDomainRepo } public func discoverMovies(handler: @escaping (DiscoverResultEntity) -> (Void)) { discoverDomainRepo.discoverMovies { (discoverDomainModel) in handler(discoverDomainModel) } } }
25.821429
85
0.724758
487b6f5d027b38d6508c9004135a556acee1b483
6,867
/* * GUUnitsType.swift * GUUnits * * Created by Callum McColl on 29/07/2020. * Copyright © 2020 Callum McColl. 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. All advertising materials mentioning features or use of this * software must display the following acknowledgement: * * This product includes software developed by Callum McColl. * * 4. Neither the name of the author nor the names of contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. * * ----------------------------------------------------------------------- * This program is free software; you can redistribute it and/or * modify it under the above terms or under the terms of the GNU * General Public License as published by the Free Software Foundation; * either version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see http://www.gnu.org/licenses/ * or write to the Free Software Foundation, Inc., 51 Franklin Street, * Fifth Floor, Boston, MA 02110-1301, USA. * */ public protocol GUUnitsType { associatedtype RawValue var rawValue: RawValue { get } init(rawValue: RawValue) } extension GUUnitsType where Self: CVarArg, Self.RawValue: CVarArg { public var _cVarArgEncoding: [Int] { self.rawValue._cVarArgEncoding } } extension GUUnitsType where Self: Equatable, Self.RawValue: Equatable { public static func == (lhs: Self, rhs: Self) -> Bool { return lhs.rawValue == rhs.rawValue } } extension GUUnitsType where Self: CustomReflectable, Self.RawValue: CustomReflectable { public var customMirror: Mirror { return self.rawValue.customMirror } } extension GUUnitsType where Self: Decodable, Self.RawValue: Decodable { public init(from decoder: Decoder) throws { self.init(rawValue: try RawValue(from: decoder)) } } extension GUUnitsType where Self: Encodable, Self.RawValue: Encodable { public func encode(to encoder: Encoder) throws { return try self.rawValue.encode(to: encoder) } } extension GUUnitsType where Self: Hashable, Self.RawValue: Hashable { public func hash(into hasher: inout Hasher) { self.rawValue.hash(into: &hasher) } } extension GUUnitsType where Self: BinaryInteger, Self.RawValue: BinaryInteger { public init?(exactly source: Self) { guard let value = RawValue(exactly: source.rawValue) else { return nil } self.init(rawValue: value) } public init?<T>(exactly source: T) where T: BinaryFloatingPoint, T: GUUnitsType { fatalError("You cannot convert \(T.self) to \(Self.self).") } public init<T>(_ source: T) where T: BinaryFloatingPoint, T: GUUnitsType { fatalError("You cannot convert \(T.self) to \(Self.self).") } public init(_ source: Self) { self.init(rawValue: RawValue(source.rawValue)) } public init<T>(_: T) where T: BinaryInteger, T: GUUnitsType { fatalError("You cannot convert \(T.self) to \(Self.self).") } public init(truncatingIfNeeded source: Self) { self.init(rawValue: RawValue(truncatingIfNeeded: source.rawValue)) } public init<T>(truncatingIfNeeded source: T) where T: BinaryInteger, T: GUUnitsType { fatalError("You cannot convert \(T.self) to \(Self.self).") } public init(clamping source: Self) { self.init(rawValue: RawValue(clamping: source.rawValue)) } public init<T>(clamping source: T) where T: BinaryInteger, T: GUUnitsType { fatalError("You cannot convert \(T.self) to \(Self.self).") } } extension GUUnitsType where Self: BinaryFloatingPoint, Self.RawValue: BinaryFloatingPoint { public init(_ source: Self) { self.init(rawValue: RawValue(source.rawValue)) } public init<T>(_ source: T) where T: BinaryFloatingPoint, T: GUUnitsType { fatalError("You cannot convert \(T.self) to \(Self.self).") } public init?(exactly source: Self) { guard let value = RawValue(exactly: source.rawValue) else { return nil } self.init(rawValue: value) } public init?<T>(exactly source: T) where T: BinaryFloatingPoint, T: GUUnitsType { fatalError("You cannot convert \(T.self) to \(Self.self).") } } extension GUUnitsType where Self: BinaryFloatingPoint, Self.RawValue: BinaryFloatingPoint, Self.RawSignificand : FixedWidthInteger { public init(_ value: Self) { self.init(rawValue: RawValue(value.rawValue)) } public init<Source>(_ value: Source) where Source: BinaryInteger, Source: GUUnitsType { fatalError("You cannot convert \(Source.self) to \(Self.self).") } public init?(exactly value: Self) { guard let value = RawValue(exactly: value.rawValue) else { return nil } self.init(rawValue: value) } public init?<Source>(exactly value: Source) where Source: BinaryInteger, Source: GUUnitsType { fatalError("You cannot convert \(Source.self) to \(Self.self).") } }
33.497561
132
0.679045
fca3252c8bb7c281cbc031aaa13dc5abaf6817ef
2,070
// // AppExtension.swift // SwiftExtension // // Created by 王洋 on 2019/1/24. // Copyright © 2019 wannayoung. All rights reserved. // import UIKit // MARK: - App public struct App { // 应用名称 public static var displayName: String? { return Bundle.main.infoDictionary?[kCFBundleNameKey as String] as? String } // BundleID public static var bundleID: String? { return Bundle.main.bundleIdentifier } // 版本号 public static var version: String? { return Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String } // Build版本号 public static var buildNumber: String? { return Bundle.main.object(forInfoDictionaryKey: kCFBundleVersionKey as String) as? String } } // MARK: - Properties public extension App { // 小红点数量 public static var badgeNumber: Int { get { return UIApplication.shared.applicationIconBadgeNumber } set { UIApplication.shared.applicationIconBadgeNumber = newValue } } // 是否调试模式 public static var isDebug: Bool { #if DEBUG return true #else return false #endif } // 是否TestFlight public static var isTestFlight: Bool { return Bundle.main.appStoreReceiptURL?.path.contains("sandboxReceipt") == true } // 是否注册通知 public static var isNotificationsRegistered: Bool { return UIApplication.shared.isRegisteredForRemoteNotifications } } // MARK: - Methods public extension App { // 检测到用户截屏 public static func didTakeScreenShot(_ action: @escaping (_ notification: Notification) -> Void) { _ = NotificationCenter.default.addObserver(forName: UIApplication.userDidTakeScreenshotNotification, object: nil, queue: OperationQueue.main) { notification in action(notification) } } }
24.939759
108
0.594686
6adb95e5efb9a4761f77470bd6ec4b999026dc8e
2,472
#!/usr/bin/env xcrun --sdk macosx swift import Foundation enum Flavour: String { case flavour1 = "Flavour1" case flavour2 = "Flavour2" case flavour3 = "Flavour3" case none func path() -> String { var flavourFolderName = "" switch self { case .flavour1: flavourFolderName = "Flavour1" case .flavour2: flavourFolderName = "Flavour2" case .flavour3: flavourFolderName = "Flavour3" default: flavourFolderName = "" } return FileManager.default.currentDirectoryPath.appending("/BuildConfiguration/Configurations/\(flavourFolderName)") } } func fatalError(_ errorMessage: String) { print("ERROR - \(errorMessage)") exit(0) } func warning(_ warningMessage: String) { print("WARNING - \(warningMessage)") } func parseParameters() -> Flavour { var arguments = CommandLine.arguments guard arguments.count > 1 else { fatalError("Pass atleast one flavour name") return .none } guard arguments.count == 2 else { fatalError("Single flavour can be build at a time: Flavours:\(arguments)") return .none } let flavourName = arguments[1] if let flavour = Flavour(rawValue: flavourName) { return flavour } else { fatalError("Pass a valid flavour name") return .none } } func getPodXCConfigFiles() -> [URL] { var paths = [URL]() let fileManager = FileManager.default let rootPath = fileManager.currentDirectoryPath.appending("/Pods/Target Support Files/Pods-Application") do { let files = try fileManager.contentsOfDirectory(atPath: rootPath) for file in files where file.hasSuffix(".xcconfig") { paths.append(URL(fileURLWithPath: rootPath.appending(file))) } } catch { fatalError(error.localizedDescription) } return paths } let flavour = parseParameters() let defaultPath = FileManager.default.currentDirectoryPath.appending("/BuildConfiguration/Flavour") let podXCConfigFiles = getPodXCConfigFiles() print("Flavour path: \(flavour.path()) defaultpath: \(defaultPath) xcconfig paths \(podXCConfigFiles)") do { try FileManager.default.removeItem(atPath: defaultPath) try FileManager.default.copyItem(atPath: flavour.path(), toPath: defaultPath) } catch let error { fatalError(error.localizedDescription) } print("done")
27.775281
124
0.654531
670fd1bd3e06ed8c2d3b2337d8bbb8aaf86206d8
1,654
import Foundation /// Math class Solution { //unsigned -> 8 bit: 0 to 255 // unsigned -> 32 bit: 0 to 2,147,483,648 // 2's complement -> given N-bit + 2's complement = 2^N => get 2's complement by // reversing given N-bit and addinng 1 to it func reverseBitsWrongAnswer(_ n: Int) -> Int { let binary = String(n, radix: 2) // check how its done & implement your own var bits = Array.init(repeating: 0, count: 32) var result = 0 print(binary) for i in (0..<binary.count).reversed() { //diagnostic can be improved, analyze, report and fix //let test = Int(String(binary[binary.index(binary.startIndex, offsetBy: i)])) //let test1 = Int((binary[binary.index(binary.startIndex, offsetBy: i)])) //bits[i] = Int(String(binary[binary.index(binary.startIndex, offsetBy: i)])) ?? 0 bits[i] = binary[binary.index(binary.startIndex, offsetBy: i)].wholeNumberValue ?? 0 } bits.reverse() for i in 0..<bits.count { result = result + Int(Double(bits[i])*pow(Double(2), Double(i))) } return result } func reverseBits(_ n: Int) -> Int { var ret = 0, power = 31, number = n //reverses bits of a number and sums them while number != 0 { //get LSB and shift it by power times ret = ret + (n & 1) << power number = number >> 1 power = power - 1 } return ret } } //Example: 00000010100101000001111010011100 func testReverseBits() { print(Solution.init().reverseBits(43261596)) } testReverseBits()
38.465116
96
0.577993
5be44e7b2a1a4c4a0e6c8827ef221971acb62f95
1,279
// // ClassTableViewCell.swift // AnywhereFitness // // Created by Lambda_School_Loaner_204 on 1/8/20. // Copyright © 2020 Lambda_School_Loaner_219. All rights reserved. // import UIKit class ClassTableViewCell: UITableViewCell { // MARK: - IBOutlets @IBOutlet private weak var titleLabel: UILabel! @IBOutlet private weak var instructorLabel: UILabel! @IBOutlet private weak var dateLabel: UILabel! @IBOutlet private weak var locationLabel: UILabel! var fitnessClass: FitnessClassRepresentation? { didSet { updateViews() } } private func updateViews() { guard let fitnessClass = fitnessClass else { return } titleLabel.text = fitnessClass.name // have to somehow get the instructor name here! //instructorLabel.text = fitnessClass. dateLabel.text = fitnessClass.startTime locationLabel.text = fitnessClass.location } private func dateFormatter(_ isoDateString: String) -> String { let isoDateFormatter = ISO8601DateFormatter() let date = isoDateFormatter.date(from: isoDateString) let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MMM d, h:mm a" return dateFormatter.string(from: date!) } }
27.804348
67
0.682565
e5ca7535ae144dbfa2b6932a1034092318c0d39e
11,718
// // GameScene.swift // FlappyBird // // Created by Nate Murray on 6/2/14. // Copyright (c) 2014 Fullstack.io. All rights reserved. // import SpriteKit class GameScene: SKScene, SKPhysicsContactDelegate{ let verticalPipeGap = 150.0 var bird:SKSpriteNode! var skyColor:SKColor! var pipeTextureUp:SKTexture! var pipeTextureDown:SKTexture! var movePipesAndRemove:SKAction! var moving:SKNode! var pipes:SKNode! var canRestart = Bool() var scoreLabelNode:SKLabelNode! var score = NSInteger() let birdCategory: UInt32 = 1 << 0 let worldCategory: UInt32 = 1 << 1 let pipeCategory: UInt32 = 1 << 2 let scoreCategory: UInt32 = 1 << 3 override func didMoveToView(view: SKView) { canRestart = false // setup physics self.physicsWorld.gravity = CGVector( dx: 0.0, dy: -5.0 ) self.physicsWorld.contactDelegate = self // setup background color // skyColor = SKColor(red: 81.0/255.0, green: 192.0/255.0, blue: 201.0/255.0, alpha: 1.0) skyColor = SKColor(red: 201.0/255.0, green: 102.0/255.0, blue: 81.0/255.0, alpha: 1.0) self.backgroundColor = skyColor moving = SKNode() self.addChild(moving) pipes = SKNode() moving.addChild(pipes) // ground let groundTexture = SKTexture(imageNamed: "land") groundTexture.filteringMode = .Nearest // shorter form for SKTextureFilteringMode.Nearest let moveGroundSprite = SKAction.moveByX(-groundTexture.size().width * 2.0, y: 0, duration: NSTimeInterval(0.02 * groundTexture.size().width * 2.0)) let resetGroundSprite = SKAction.moveByX(groundTexture.size().width * 2.0, y: 0, duration: 0.0) let moveGroundSpritesForever = SKAction.repeatActionForever(SKAction.sequence([moveGroundSprite,resetGroundSprite])) for var i:CGFloat = 0; i < 2.0 + self.frame.size.width / ( groundTexture.size().width * 2.0 ); ++i { let sprite = SKSpriteNode(texture: groundTexture) sprite.setScale(2.0) sprite.position = CGPoint(x: i * sprite.size.width, y: sprite.size.height / 2.0) sprite.runAction(moveGroundSpritesForever) moving.addChild(sprite) } // skyline let skyTexture = SKTexture(imageNamed: "sky") skyTexture.filteringMode = .Nearest let moveSkySprite = SKAction.moveByX(-skyTexture.size().width * 2.0, y: 0, duration: NSTimeInterval(0.1 * skyTexture.size().width * 2.0)) let resetSkySprite = SKAction.moveByX(skyTexture.size().width * 2.0, y: 0, duration: 0.0) let moveSkySpritesForever = SKAction.repeatActionForever(SKAction.sequence([moveSkySprite,resetSkySprite])) for var i:CGFloat = 0; i < 2.0 + self.frame.size.width / ( skyTexture.size().width * 2.0 ); ++i { let sprite = SKSpriteNode(texture: skyTexture) sprite.setScale(2.0) sprite.zPosition = -20 sprite.position = CGPoint(x: i * sprite.size.width, y: sprite.size.height / 2.0 + groundTexture.size().height * 2.0) sprite.runAction(moveSkySpritesForever) moving.addChild(sprite) } // create the pipes textures pipeTextureUp = SKTexture(imageNamed: "PipeUp") pipeTextureUp.filteringMode = .Nearest pipeTextureDown = SKTexture(imageNamed: "PipeDown") pipeTextureDown.filteringMode = .Nearest // create the pipes movement actions let distanceToMove = CGFloat(self.frame.size.width + 2.0 * pipeTextureUp.size().width) let movePipes = SKAction.moveByX(-distanceToMove, y:0.0, duration:NSTimeInterval(0.01 * distanceToMove)) let removePipes = SKAction.removeFromParent() movePipesAndRemove = SKAction.sequence([movePipes, removePipes]) // spawn the pipes let spawn = SKAction.runBlock({() in self.spawnPipes()}) let delay = SKAction.waitForDuration(NSTimeInterval(2.0)) let spawnThenDelay = SKAction.sequence([spawn, delay]) let spawnThenDelayForever = SKAction.repeatActionForever(spawnThenDelay) self.runAction(spawnThenDelayForever) // setup our bird let birdTexture1 = SKTexture(imageNamed: "bird-01") birdTexture1.filteringMode = .Nearest let birdTexture2 = SKTexture(imageNamed: "bird-02") birdTexture2.filteringMode = .Nearest let anim = SKAction.animateWithTextures([birdTexture1, birdTexture2], timePerFrame: 0.2) let flap = SKAction.repeatActionForever(anim) bird = SKSpriteNode(texture: birdTexture1) bird.setScale(2.0) bird.position = CGPoint(x: self.frame.size.width * 0.35, y:self.frame.size.height * 0.6) bird.runAction(flap) // CQ flying physics bird.physicsBody = SKPhysicsBody(circleOfRadius: bird.size.height / 2.0) bird.physicsBody?.dynamic = true bird.physicsBody?.allowsRotation = false bird.physicsBody?.categoryBitMask = birdCategory bird.physicsBody?.collisionBitMask = worldCategory | pipeCategory bird.physicsBody?.contactTestBitMask = worldCategory | pipeCategory self.addChild(bird) // create the ground var ground = SKNode() ground.position = CGPoint(x: 0, y: groundTexture.size().height) ground.physicsBody = SKPhysicsBody(rectangleOfSize: CGSize(width: self.frame.size.width, height: groundTexture.size().height * 2.0)) ground.physicsBody?.dynamic = false ground.physicsBody?.categoryBitMask = worldCategory self.addChild(ground) // Initialize label and create a label which holds the score score = 0 scoreLabelNode = SKLabelNode(fontNamed:"MarkerFelt-Wide") scoreLabelNode.position = CGPoint( x: self.frame.midX, y: 3 * self.frame.size.height / 4 ) scoreLabelNode.zPosition = 100 scoreLabelNode.text = String(score) self.addChild(scoreLabelNode) } func spawnPipes() { let pipePair = SKNode() pipePair.position = CGPoint( x: self.frame.size.width + pipeTextureUp.size().width * 2, y: 0 ) pipePair.zPosition = -10 let height = UInt32( self.frame.size.height / 4) let y = Double(arc4random_uniform(height) + height); let pipeDown = SKSpriteNode(texture: pipeTextureDown) pipeDown.setScale(2.0) pipeDown.position = CGPoint(x: 0.0, y: y + Double(pipeDown.size.height) + verticalPipeGap) pipeDown.physicsBody = SKPhysicsBody(rectangleOfSize: pipeDown.size) pipeDown.physicsBody?.dynamic = false pipeDown.physicsBody?.categoryBitMask = pipeCategory pipeDown.physicsBody?.contactTestBitMask = birdCategory pipePair.addChild(pipeDown) let pipeUp = SKSpriteNode(texture: pipeTextureUp) pipeUp.setScale(2.0) pipeUp.position = CGPoint(x: 0.0, y: y) pipeUp.physicsBody = SKPhysicsBody(rectangleOfSize: pipeUp.size) pipeUp.physicsBody?.dynamic = false pipeUp.physicsBody?.categoryBitMask = pipeCategory pipeUp.physicsBody?.contactTestBitMask = birdCategory pipePair.addChild(pipeUp) var contactNode = SKNode() contactNode.position = CGPoint( x: pipeDown.size.width + bird.size.width / 2, y: self.frame.midY ) contactNode.physicsBody = SKPhysicsBody(rectangleOfSize: CGSize( width: pipeUp.size.width, height: self.frame.size.height )) contactNode.physicsBody?.dynamic = false contactNode.physicsBody?.categoryBitMask = scoreCategory contactNode.physicsBody?.contactTestBitMask = birdCategory pipePair.addChild(contactNode) pipePair.runAction(movePipesAndRemove) pipes.addChild(pipePair) } func resetScene (){ // Move bird to original position and reset velocity bird.position = CGPoint(x: self.frame.size.width / 2.5, y: self.frame.midY) bird.physicsBody?.velocity = CGVector( dx: 0, dy: 0 ) bird.physicsBody?.collisionBitMask = worldCategory | pipeCategory bird.speed = 1.0 bird.zRotation = 0.0 // Remove all existing pipes pipes.removeAllChildren() // Reset _canRestart canRestart = false // Reset score score = 0 scoreLabelNode.text = String(score) // Restart animation moving.speed = 1 } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { /* Called when a touch begins */ if moving.speed > 0 { for touch: AnyObject in touches { let location = touch.locationInNode(self) bird.physicsBody?.velocity = CGVector(dx: 0, dy: 0) bird.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 47)) // THE ABOVE LINE WAS 30, THIS SEEMS TO BE THE SPEED WHICH THE HEAD RISES } } else if canRestart { self.resetScene() } } // TODO: Move to utilities somewhere. There's no reason this should be a member function func clamp(min: CGFloat, max: CGFloat, value: CGFloat) -> CGFloat { if( value > max ) { return max } else if( value < min ) { return min } else { return value } } override func update(currentTime: CFTimeInterval) { /* Called before each frame is rendered */ bird.zRotation = self.clamp( -1, max: 0.5, value: bird.physicsBody!.velocity.dy * ( bird.physicsBody!.velocity.dy < 0 ? 0.003 : 0.001 ) ) } func didBeginContact(contact: SKPhysicsContact) { if moving.speed > 0 { if ( contact.bodyA.categoryBitMask & scoreCategory ) == scoreCategory || ( contact.bodyB.categoryBitMask & scoreCategory ) == scoreCategory { // Bird has contact with score entity score++ scoreLabelNode.text = String(score) // Add a little visual feedback for the score increment scoreLabelNode.runAction(SKAction.sequence([SKAction.scaleTo(1.5, duration:NSTimeInterval(0.1)), SKAction.scaleTo(1.0, duration:NSTimeInterval(0.1))])) } else { //!@£$ LOOKS LIKE THE SPEED ALONG THE Y AXIS, ALSO BREAKS THE GAME FAILING WHEN TOUCHING PIPE !@£$ moving.speed = 0 bird.physicsBody?.collisionBitMask = worldCategory bird.runAction( SKAction.rotateByAngle(CGFloat(M_PI) * CGFloat(bird.position.y) * 0.01, duration:0), completion:{self.bird.speed = 0 }) // Flash background if contact is detected self.removeActionForKey("flash") self.runAction(SKAction.sequence([SKAction.repeatAction(SKAction.sequence([SKAction.runBlock({ self.backgroundColor = SKColor(red: 1, green: 0, blue: 0, alpha: 1.0) }),SKAction.waitForDuration(NSTimeInterval(0.05)), SKAction.runBlock({ self.backgroundColor = self.skyColor }), SKAction.waitForDuration(NSTimeInterval(0.05))]), count:4), SKAction.runBlock({ self.canRestart = true })]), withKey: "flash") } } } }
43.4
167
0.616658
de9d79d856f05aba6c434c6e318452ed922867bf
916
import XCTest import Quick import Nimble var beforeSuiteWasExecuted = false class FunctionalTests_BeforeSuite_BeforeSuiteSpec: QuickSpec { override func spec() { beforeSuite { beforeSuiteWasExecuted = true } } } class FunctionalTests_BeforeSuite_Spec: QuickSpec { override func spec() { it("is executed after beforeSuite") { expect(beforeSuiteWasExecuted).to(beTruthy()) } } } class BeforeSuiteTests: XCTestCase { func testBeforeSuiteIsExecutedBeforeAnyExamples() { // Execute the spec with an assertion before the one with a beforeSuite let specs = NSArray(objects: FunctionalTests_BeforeSuite_Spec.classForCoder(), FunctionalTests_BeforeSuite_BeforeSuiteSpec.classForCoder()) let result = qck_runSpecs(specs as! [AnyObject]) XCTAssert(result.hasSucceeded) } }
27.757576
97
0.681223
ab4f98f85ba630db4fffe29468fcadaf47bd1059
843
// // ASVPredicateRule.swift // Gonzo // // Created by AMIT on 1/31/22. // import Foundation public class ASVRegxRule: ASVRule { private var regx: String? private var errorMsg: String? public init(_ regx: String?, _ errorMsg: String? = nil) { self.regx = regx self.errorMsg = errorMsg } public func validate(_ value: Any?, _ fieldName: String?, _ defaultErrorMsg: String?) -> ASVError? { if let value = value as? String, let regx = regx, isValid(value, regx) { return nil } return ASVError(errorMsg: errorMsg ?? defaultErrorMsg ?? "\(fieldName ?? "") is not correct") } func isValid(_ value: String, _ regx: String) -> Bool { let check = NSPredicate(format: "SELF MATCHES %@", regx) return check.evaluate(with: value) } }
27.193548
104
0.604982
e90bd87c9ba046de7b9140054804224dc6762f80
286
/// A type that provide a stub public protocol StubProvider { /// Provide a stub for type /// /// - Parameter type: The type you want to stub /// - Returns: Return a stub or return nil if you can't instantiate a value. func stub<T>(of type: T.Type) throws -> T? }
28.6
80
0.632867
f960c235031230b563e1b507d78666f2f711137a
9,891
// // FormViewController.swift // bus // // Created by HeartNest on 12/11/14. // Copyright (c) 2014 asscubo. All rights reserved. // import UIKit class FormViewController: SlashViewController, UITextFieldDelegate { @IBOutlet weak var spinner: UIActivityIndicatorView! @IBOutlet weak var numStop: UITextField! @IBOutlet weak var numBus: UITextField! @IBOutlet var feedPan: UITextView! @IBOutlet weak var searchButton: UIButton! @IBOutlet weak var addrLabel: UILabel! var addr:NSDictionary! var amIActive = false override func viewDidLoad() { super.viewDidLoad() //components configurations self.numStop.delegate = self; self.numBus.delegate = self; makeTextFieldBorder(self.numStop) makeTextFieldBorder(self.numBus) self.searchButton.layer.borderWidth = 1.5 self.searchButton.layer.borderColor = (UIColor( red: 163/255, green: 162/255, blue:159/255, alpha: 1.0 )).CGColor; self.searchButton.layer.cornerRadius = 19; self.searchButton.clipsToBounds = true; self.spinner.hidden = true //gesture recognizers let tapRecognizer = UITapGestureRecognizer(target: self, action: "handleSingleTap:") tapRecognizer.numberOfTapsRequired = 1 self.view.addGestureRecognizer(tapRecognizer) //radio center NSNotificationCenter.defaultCenter().addObserver(self, selector: "loadLastSearch", name: NSUserDefaultsDidChangeNotification, object: nil) loadAddresses(); loadLastSearch(); } func loadAddresses(){ let path = NSBundle.mainBundle().pathForResource("data", ofType: "json") let jsonData = NSData(contentsOfFile:path!) let datastring = String(data: jsonData!, encoding: NSUTF8StringEncoding) self.addr = convertStringToDictionary(datastring!) } func loadLastSearch(){ if(NSUserDefaults().objectForKey(LASTSKEY) != nil && !amIActive){ let lastsearch = NSUserDefaults().objectForKey(LASTSKEY) as! String; let splitted = lastsearch.componentsSeparatedByString(",") if(splitted.count == 2){ self.numStop.text = splitted[0]; self.numBus.text = splitted[1]; loadAddrByStopNum(splitted[0]) }else if(splitted.count == 3){ self.numStop.text = splitted[0]; self.numBus.text = splitted[1]; self.addrLabel.text = splitted[2]; } self.feedPan.attributedText = NSMutableAttributedString(string:"", attributes:nil) } } func loadAddrByStopNum(t:String){ if(self.addr["k\(t)"] != nil){ let denomination: String = self.addr["k\(t)"]! as! String self.addrLabel.text = denomination; }else{ self.addrLabel.text = ""; } } func checkBusByStopInLog(t:String) -> String { for raw:String in self.tableData{ let sliced = raw.componentsSeparatedByString(",") if(sliced[0] == t){ return sliced[1]; } } return ""; } //editing @IBAction func inserting(sender: UITextField) { let t = sender.text; loadAddrByStopNum(t!) let buscode = checkBusByStopInLog(t!) if(buscode != ""){ self.numBus.text = buscode; } } //query button @IBAction func query(sender: UIButton) { amIActive = true; self.numStop.resignFirstResponder() self.numBus.resignFirstResponder() performQuery() amIActive = false; } //show result func performQuery(){ let ns = self.numStop.text! as String; if(ns.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) != ""){ self.feedPan.attributedText = NSMutableAttributedString(string:"", attributes:nil) self.spinner.hidden = false self.spinner.startAnimating(); let nb = self.numBus.text! as String; if(self.addr["k\(ns)"] != nil){ let al = self.addr["k\(ns)"]! as! String updateSearchLog("\(ns),\(nb),\(al)") }else{ updateSearchLog("\(ns),\(nb)") } // let url: NSURL = NSURL(string: "https://solweb.tper.it/tperit/webservices/hellobus.asmx/QueryHellobus?fermata=\(ns)&linea=\(nb)&oraHHMM=")! let url: NSURL = NSURL(string: "https://hellobuswsweb.tper.it/web-services/hello-bus.asmx/QueryHellobus?fermata=\(ns)&linea=\(nb)&oraHHMM=null")! let request1: NSURLRequest = NSURLRequest(URL: url) let queue:NSOperationQueue = NSOperationQueue() NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in // let err: NSError if(data != nil){ let xmlArrival = NSString(data: data!, encoding: NSUTF8StringEncoding) let xmlNSArrival: String = xmlArrival! as String var notagArrival = xmlNSArrival.stringByReplacingOccurrencesOfString("</string>", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil) // notagArrival = notagArrival.stringByReplacingOccurrencesOfString(", ", withString: "\n", options: NSStringCompareOptions.LiteralSearch, range: nil) notagArrival = notagArrival.stringByReplacingOccurrencesOfString("/ ", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil) let splittedcombi = notagArrival.componentsSeparatedByString("TperHellobus: ") var resStr:String; if(splittedcombi.count == 2){ //successfull let splitted = splittedcombi[1].componentsSeparatedByString(",") //parentesi problem let part1 = splitted[0].componentsSeparatedByString("(") if(splitted.count == 2){ let part2 = splitted[1].componentsSeparatedByString("(") resStr = part1[0].stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())+"\n"+part2[0].stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()); }else{ resStr = part1[0]; } }else{ //help let splittedcombi2 = notagArrival.componentsSeparatedByString("HellobusHelp: ") if(splittedcombi2.count == 2){ resStr = splittedcombi2[1]; }else{ resStr = splittedcombi[0]; } } dispatch_async (dispatch_get_main_queue (), { let attrs = [NSFontAttributeName : UIFont.systemFontOfSize(24.0)] let gString = NSMutableAttributedString(string:resStr, attributes:attrs) self.feedPan.attributedText = gString self.spinner.hidden = true self.spinner.stopAnimating(); }); }else{ dispatch_async (dispatch_get_main_queue (), { let attrs = [NSFontAttributeName : UIFont.systemFontOfSize(24.0)] let fmcntmsg = NSLocalizedString("FORM_CNNERR",comment:"A connection problem occured ..") let gString = NSMutableAttributedString(string:fmcntmsg, attributes:attrs) self.feedPan.attributedText = gString self.spinner.hidden = true self.spinner.stopAnimating(); }); } }) } } //default single tap outside func handleSingleTap(recognizer: UITapGestureRecognizer) { self.view.endEditing(true) } // called when 'return' key pressed. return NO to ignore. func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true; } func makeTextFieldBorder(textField:UITextField){ let border = CALayer() let width = CGFloat(1.0) //border.borderColor = UIColor.grayColor().CGColor border.borderColor = (UIColor( red: 170/255, green: 170/255, blue:172/255, alpha: 1.0 )).CGColor; border.frame = CGRect(x: 0, y: textField.frame.size.height - width, width: textField.frame.size.width, height: textField.frame.size.height) border.borderWidth = width textField.layer.addSublayer(border) textField.layer.masksToBounds = true } func convertStringToDictionary(text: String) -> [String:AnyObject]? { if let data = text.dataUsingEncoding(NSUTF8StringEncoding) { do { return try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject] } catch let error as NSError { print(error) } } return nil } }
38.636719
206
0.55323
fbceced8ad6de081d241a7295e0ad994517877f3
912
// // ErrorAlertSupporting.swift // OpenWeatherIos // // Created by Marin Ipati on 15/09/2021. // import UIKit public protocol ErrorAlertSupporting { func showAlert( in viewController: UIViewController, title: String?, message: String?, dismissTitle: String?, dismissHandler: (() -> Void)? ) } extension ErrorAlertSupporting { public func showAlert( in viewController: UIViewController, title: String?, message: String?, dismissTitle: String?, dismissHandler: (() -> Void)? = nil ) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) let dismissAction = UIAlertAction(title: dismissTitle, style: .cancel) { _ in dismissHandler?() } alert.addAction(dismissAction) viewController.present(alert, animated: true) } }
22.243902
93
0.622807
c167f221e9b47f84decf837645821e62b328b584
1,076
// // DispatchQueue+Extension.swift // ViPass // // Created by Ngo Lien on 4/25/18. // Copyright © 2018 Ngo Lien. All rights reserved. // import Foundation import UIKit /* Usages: DispatchQueue.background(delay: 3.0, background: { // do something in background }, completion: { // when background job finishes, wait 3 seconds and do something in main thread }) DispatchQueue.background(background: { // do something in background }, completion:{ // when background job finished, do something in main thread }) DispatchQueue.background(delay: 3.0, completion:{ // do something in main thread after 3 seconds }) */ extension DispatchQueue { static func background(delay: Double = 0.0, background: (()->Void)? = nil, completion: (() -> Void)? = nil) { DispatchQueue.global(qos: .background).async { background?() if let completion = completion { DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: { completion() }) } } } }
25.023256
113
0.625465
edfe57442b7ee27ca5c0dffb94f046e63cb3df25
1,048
// // ViewFluxer.swift // FluxerKit-Demo // // Created by Yuto Akiba on 2019/03/19. // Copyright © 2019 Yuto Akiba. All rights reserved. // import FluxerKit import RxSwift final class ViewFluxer: Fluxer { enum Action { case increase case decrease } enum Dispatcher { case increaseValue case decreaseValue } struct Store { let value = BehaviorSubject<Int>(value: 0) } let store: Store init() { self.store = Store() } func dispatch(action: Action) throws -> Observable<Dispatcher> { switch action { case .increase: return .just(.increaseValue) case .decrease: return .just(.decreaseValue) } } func updateStore(dispatcher: ViewFluxer.Dispatcher) throws { let value = try store.value.value() switch dispatcher { case .increaseValue: store.value.onNext(value + 1) case .decreaseValue: store.value.onNext(value - 1) } } }
20.153846
68
0.580153
d9809526c6814104626ed61a8837aa8fe3b955cb
3,813
// // SyncCarbObject.swift // TidepoolServiceKit // // Created by Darin Krauss on 4/1/20. // Copyright © 2020 LoopKit Authors. All rights reserved. // import CryptoKit import LoopKit import TidepoolKit extension SyncCarbObject { var datum: TDatum? { guard let origin = datumOrigin else { return nil } return TFoodDatum(time: datumTime, name: datumName, nutrition: datumNutrition).adornWith(origin: origin) } private var datumTime: Date { startDate } private var datumName: String? { foodType } private var datumNutrition: TFoodDatum.Nutrition { return TFoodDatum.Nutrition(carbohydrate: datumCarbohydrate, estimatedAbsorptionDuration: absorptionTime) } private var datumCarbohydrate: TFoodDatum.Nutrition.Carbohydrate { return TFoodDatum.Nutrition.Carbohydrate(net: grams) } private var datumOrigin: TOrigin? { guard let resolvedSyncIdentifier = resolvedSyncIdentifier else { return nil } if let provenanceIdentifier = provenanceIdentifier, !provenanceIdentifier.isEmpty, provenanceIdentifier != Bundle.main.bundleIdentifier { return TOrigin(id: resolvedSyncIdentifier, name: provenanceIdentifier, type: .application) } return TOrigin(id: resolvedSyncIdentifier) } } extension SyncCarbObject { var selector: TDatum.Selector? { guard let resolvedSyncIdentifier = resolvedSyncIdentifier else { return nil } return TDatum.Selector(origin: TDatum.Selector.Origin(id: resolvedSyncIdentifier)) } } fileprivate extension SyncCarbObject { var resolvedSyncIdentifier: String? { var resolvedString: String? // The Tidepool backend requires a unique identifier for each datum that does not change from creation // through updates to deletion. Since carb objects do not inherently have such a unique identifier, // we can generate one based upon the HealthKit provenance identifier (the unique source identifier of // the carb, namely the bundle identifier) plus the HealthKit sync identifier. // // However, while all carbs created within Loop are guaranteed to have a HealthKit sync identifier, this // is not true for carbs created outside of Loop. In this case, we fall back to using the HealthKit UUID. // This works because any HealthKit objects without a sync identifier CANNOT be updated, by definition, // (only created and deleted) and the UUID is constant for this use case. if let provenanceIdentifier = provenanceIdentifier { if let syncIdentifier = syncIdentifier { resolvedString = "provenanceIdentifier:\(provenanceIdentifier):syncIdentifier:\(syncIdentifier)" } else if let uuid = uuid { resolvedString = "provenanceIdentifier:\(provenanceIdentifier):uuid:\(uuid)" } } else { // DEPRECATED: Backwards compatibility (DIY) // For previously existing carbs created outside of Loop we do not have a provenance identifier and // we cannot rely on the sync identifier (since it is scoped by the provenance identifier). Therefore, // just fallback to use the UUID. if let uuid = uuid { resolvedString = "uuid:\(uuid)" } } // Finally, assuming we have a valid string, MD5 hash the string to yield a nice identifier return resolvedString?.md5hash } } fileprivate extension String { var md5hash: String? { guard let data = data(using: .utf8) else { return nil } let hash = Insecure.MD5.hash(data: data) return hash.map { String(format: "%02hhx", $0) }.joined() } }
39.309278
145
0.67401
228d49f2ebc0c9cfd1a67cb5caff7d09a3ef126e
2,066
/** * Copyright 2015 IBM Corp. 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 Foundation import ObjectMapper /** **SentimentResponse** Returned by the AlchemyLanguage service. */ public struct SentimentResponse: AlchemyLanguageGenericModel, Mappable { // MARK: AlchemyGenericModel public var totalTransactions: Int? // MARK: AlchemyLanguageGenericModel public var language: String? public var url: String? // MARK: DocSentiment /** response when normal sentimented call is used */ public var docSentiment: Sentiment? // Normal /** response when targeted sentimented call is used */ public var sentimentResults: [DocumentSentiment]? // Targeted /** (undocumented) */ public var usage: String? /** warnings about incorrect usage or failures in detection */ public var warningMessage: String? public init?(_ map: Map) {} public mutating func mapping(map: Map) { // alchemyGenericModel totalTransactions <- (map["totalTransactions"], Transformation.stringToInt) // alchemyLanguageGenericModel language <- map["language"] url <- map["url"] // sentiment - alchemyLanguage sometimes returns as "docSentiment," sometimes as "sentiment" docSentiment <- map["docSentiment"] sentimentResults <- map["results"] usage <- map["usage"] warningMessage <- map["warningMessage"] } }
29.098592
100
0.664569
6951a9a436e0ae008a757a2cfef65b3f34da6249
2,170
// // AppDelegate.swift // FormField // // Created by WANG Jie on 10/24/2016. // Copyright (c) 2016 WANG Jie. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. 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:. } }
46.170213
285
0.752995
62e936855bb26cbca74e6e22b27b86b00d373275
925
// // Array+MWExtension.swift // WorkPlatformIOS // // Created by mwk_pro on 2019/2/27. // Copyright © 2019 mwk_pro. All rights reserved. // import Foundation public extension Array { func mw_JSONString() -> String { if (!JSONSerialization.isValidJSONObject(self)) { mw_print_i("无法解析出JSONString") return "" } let data : NSData! = try! JSONSerialization.data(withJSONObject: self, options: []) as NSData? let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue) return JSONString! as String } func mw_JSONData() -> Data? { if (!JSONSerialization.isValidJSONObject(self)) { mw_print_i("无法解析出JSONData") return nil } let data : NSData! = try! JSONSerialization.data(withJSONObject: self, options: []) as NSData? return data as Data } }
28.030303
102
0.614054
01ae013d114cfad4c29c5df857bfaf5f667c6790
1,072
// // EPCalendarCell1.swift // EPCalendar // // Created by Prabaharan Elangovan on 09/11/15. // Copyright © 2015 Prabaharan Elangovan. All rights reserved. // import UIKit class EPCalendarCell1: UICollectionViewCell { var currentDate: Date! var isCellSelectable: Bool? @IBOutlet weak var lblDay: UILabel! override func awakeFromNib() { super.awakeFromNib() } func selectedForLabelColor(_ color: UIColor) { self.lblDay.layer.cornerRadius = self.lblDay.frame.size.width/2 self.lblDay.layer.backgroundColor = color.cgColor self.lblDay.textColor = UIColor.white } func deSelectedForLabelColor(_ color: UIColor) { self.lblDay.layer.backgroundColor = UIColor.clear.cgColor self.lblDay.textColor = color } func setTodayCellColor(_ backgroundColor: UIColor) { self.lblDay.layer.cornerRadius = self.lblDay.frame.size.width/2 self.lblDay.layer.backgroundColor = backgroundColor.cgColor self.lblDay.textColor = UIColor.white } }
26.8
71
0.681903
1a4836416918074dde4e0e5cf9036c7eaa8371f6
1,423
// // ViewController.swift // MixInterface // // Created by Alessio Roberto on 18/11/2020. // import SwiftUI import UIKit class ViewController: UIViewController { private lazy var viewModel: ViewModel = ViewModel() private lazy var specialView = makerSpecialView() override func viewDidLoad() { super.viewDidLoad() // Add our SwiftUI view controller as a child: addSwiftUI(customView: specialView) // Apply a series of Auto Layout constraints to its view: NSLayoutConstraint.activate([ specialView.view.topAnchor.constraint(equalTo: view.topAnchor), specialView.view.leadingAnchor.constraint(equalTo: view.leadingAnchor), specialView.view.widthAnchor.constraint(equalTo: view.widthAnchor), specialView.view.bottomAnchor.constraint(equalTo: view.bottomAnchor) ]) } private func makerSpecialView() -> UIHostingController<FormView> { let formView = FormView(viewModel: viewModel, keyboardHandler: KeyboardFollower()) let formVC = UIHostingController(rootView: formView) formVC.view.translatesAutoresizingMaskIntoConstraints = false return formVC } } extension UIViewController { func addSwiftUI<T>(customView: UIHostingController<T>) { addChild(customView) view.addSubview(customView.view) customView.didMove(toParent: self) } }
29.645833
90
0.697822
e80418a001d33a38c9f29c85377587e3827db0b5
986
// // TestFixtures.swift // // // Created by Mathew Gacy on 7/23/21. // import Foundation @testable import MGNetworking struct User: Codable, Equatable { let id: Int var name: String var username: String static var defaultUser: User { User(id: 1, name: "Leanne Graham", username: "Bret") } } enum TestParameter: Parameter { case name(String) case username(String) public var name: String { switch self { case .name: return "name" case .username: return "username" } } public var value: String? { switch self { case .name(let value): return value case .username(let value): return value } } } let userJSON = """ {"id":1,"name":"Leanne Graham","username":"Bret"} """ extension String { static var usersPath = "/users" static var userURL = "https://jsonplaceholder.typicode.com/users/1" static var jsonPlaceholder = "jsonplaceholder.typicode.com" }
20.122449
71
0.618661
5b1332ec1c848a8061c32324984abefccc2bed3e
1,595
// // ComputePlugin.swift // VidFramework // // Created by David Gavilan on 2018/02/19. // Copyright © 2018 David Gavilan. All rights reserved. // import Metal import MetalKit class ComputePlugin: GraphicPlugin { fileprivate var computePrimitives: [ComputePrimitive] = [] func queue(_ prim: ComputePrimitive) { let alreadyQueued = computePrimitives.contains { $0 === prim } if !alreadyQueued { computePrimitives.append(prim) } } func dequeue(_ prim: ComputePrimitive) { let index = computePrimitives.firstIndex { $0 === prim } if let i = index { computePrimitives.remove(at: i) } } override func draw(drawable: CAMetalDrawable, commandBuffer: MTLCommandBuffer, camera: Camera) { if computePrimitives.isEmpty { return } let renderPassDescriptor = Renderer.shared.createRenderPassWithColorAttachmentTexture(drawable.texture, clear: false) guard let encoder = commandBuffer.makeRenderCommandEncoder(descriptor: renderPassDescriptor) else { return } encoder.pushDebugGroup("ComputePrimitives") for prim in computePrimitives { prim.compute(encoder: encoder) } encoder.popDebugGroup() encoder.endEncoding() } override func updateBuffers(_ syncBufferIndex: Int, camera _: Camera) { for prim in computePrimitives { prim.processResult(syncBufferIndex) if prim.isDone { dequeue(prim) } } } }
30.09434
125
0.630721
01a51b3ad299d9521469205f9a6e1d3e4e3e9414
1,104
// // HttpServerBridger.swift // APNAssistant // // Created by WataruSuzuki on 2019/09/29. // Copyright © 2019 WataruSuzuki. All rights reserved. // import UIKit import Swifter class HttpServerBridger: NSObject //, HttpServerIODelegate { private let portNumber = 8081 private let server = HttpServer() var url: URL { get { return URL(string: "http://localhost:\(portNumber)/index.html")! } } func startCocoaHTTPServer() { let path = UtilFileManager.getProfilesAppGroupPath() print(path) server["/:path"] = shareFilesFromDirectory( path, defaults: [ "index.html", "configrationProfile.html", "set-to-device.mobileconfig"] ) //server.delegate = self do { try server.start(in_port_t(portNumber)) } catch { //(・A・)!! // fatalError("Swifter could not start!!") } } // MARK: HttpServerIODelegate /* func socketConnectionReceived(_ socket: Socket) { } */ }
23
80
0.563406
7631fbb66413217577317c7061ac502e99cd8a5b
2,150
// // AppDelegate.swift // Autotune // // Created by Erik Van Lankvelt on 12/28/15. // Copyright © 2015 Hippololamus. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and 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:. } }
45.744681
285
0.754419
2ffa444d45cbf09a516f02db036e6c1a8a170c3a
8,080
// // OpenTimesCardView.swift // bm-persona // // Created by Shawn Huang on 7/4/20. // Copyright © 2020 RJ Pimentel. All rights reserved. // import UIKit fileprivate let kViewMargin: CGFloat = 16 /// Displays the open times for the current day when collapsed and for all days when opened. class OpenTimesCardView: CollapsibleCardView { private var item: HasOpenTimes! public init(item: HasOpenTimes, animationView: UIView, toggleAction: ((Bool) -> Void)? = nil, toggleCompletionAction: ((Bool) -> Void)? = nil) { super.init() self.item = item super.setContents(collapsedView: collapsedView(), openedView: openedView(), animationView: animationView, toggleAction: toggleAction, toggleCompletionAction: toggleCompletionAction, leftIcon: clockIcon) } required init?(coder: NSCoder) { super.init(coder: coder) } private func collapsedView() -> UIView { let defaultView = UIView() defaultView.translatesAutoresizingMaskIntoConstraints = false guard let weeklyHours = item.weeklyHours, weeklyHours.hoursForWeekday(DayOfWeek.weekday(Date())).count > 0 else { return defaultView } var leftView: UIView? var rightView: UIView? if let isOpen = item.isOpen { leftView = isOpen ? TagView.open : TagView.closed } // collapsed view shows the next open interval for the current day or a "closed" label if let nextOpenInterval = item.nextOpenInterval() { rightView = timeSpanLabel(interval: nextOpenInterval, shouldBoldIfCurrent: false) } else { rightView = closedLabel() } return leftRightView(leftView: leftView, rightView: rightView, centered: true) ?? defaultView } private func openedView() -> UIStackView { guard item.weeklyHours != nil else { return UIStackView() } // stack of all the days displayed when opened let view = UIStackView() view.translatesAutoresizingMaskIntoConstraints = false view.axis = .vertical view.alignment = .fill view.distribution = .equalSpacing view.spacing = 5 for day in DayOfWeek.allCases { let dayLabel = UILabel() dayLabel.translatesAutoresizingMaskIntoConstraints = false // if this is the current day, bold the day name label if DayOfWeek.weekday(Date()) == day { dayLabel.font = Font.bold(10) } else { dayLabel.font = Font.light(10) } dayLabel.text = day.stringRepresentation() if let dayView = leftRightView(leftView: dayLabel, rightView: hourSpanLabelStack(weekday: day)) { view.addArrangedSubview(dayView) } } return view } /// Creates a vertical stack with all hour intervals for one day private func hourSpanLabelStack(weekday: DayOfWeek) -> UIStackView? { guard let weeklyHours = item.weeklyHours else { return nil } let intervals = weeklyHours.hoursForWeekday(weekday) // if no data is available for the day, shows as empty guard intervals.count > 0 else { return nil } // stack for all the intervals in one day let view = UIStackView() view.translatesAutoresizingMaskIntoConstraints = false view.axis = .vertical view.alignment = .trailing view.distribution = .equalSpacing view.spacing = 5 for interval in intervals { // prevents adding 0 second intervals (that mean closed all day) if interval.duration > 0 { view.addArrangedSubview(timeSpanLabel(interval: interval)) } } // if there are intervals, but none of them are > 0 seconds, closed all day if view.arrangedSubviews.count == 0 { view.addArrangedSubview(closedLabel(bold: DayOfWeek.weekday(Date()) == weekday)) } return view } /** Creates a label displaying the given time interval. - parameter shouldBoldIfCurrent: whether the interval should be bold if the current time falls within its bounds (set to false for the collapsedView) - returns: label displaying the given interval */ private func timeSpanLabel(interval: DateInterval, shouldBoldIfCurrent: Bool = true) -> UILabel { let formatter = DateIntervalFormatter() formatter.dateStyle = .none formatter.timeStyle = .short let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false /* Remove the date, and only include hour and minute in string display. Otherwise, string is too long when interval spans two days (e.g. 9pm-12:30am) */ if let start = interval.start.timeOnly(), let end = interval.end.timeOnly() { label.text = formatter.string(from: start, to: end) } // bold label if the current time is in the interval and it's in the openedView if shouldBoldIfCurrent, interval.contains(Date()) { label.font = Font.bold(10) } else { label.font = Font.light(10) } return label } /** Creates a label to show that the item is closed - parameter bold: whether to bold the label */ private func closedLabel(bold: Bool = false) -> UILabel { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.text = "Closed" if bold { label.font = Font.bold(10) } else { label.font = Font.light(10) } return label } /** Creates a left aligned and right aligned view that are paired together - parameter centered: whether the views are vertically centered (top aligned if false) */ private func leftRightView(leftView: UIView?, rightView: UIView?, centered: Bool = false) -> UIView? { guard leftView != nil || rightView != nil else { return nil } let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false // left bound to constrain the right view to is either the far left (if no left view), or the left view var leftBound = view if let leftView = leftView { view.addSubview(leftView) leftView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true view.topAnchor.constraint(lessThanOrEqualTo: leftView.topAnchor).isActive = true view.bottomAnchor.constraint(greaterThanOrEqualTo: leftView.bottomAnchor).isActive = true if centered { leftView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true } else { leftView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true } leftBound = leftView } if let rightView = rightView { view.addSubview(rightView) rightView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true rightView.leftAnchor.constraint(greaterThanOrEqualTo: leftBound.rightAnchor, constant: kViewMargin).isActive = true view.topAnchor.constraint(lessThanOrEqualTo: rightView.topAnchor).isActive = true view.bottomAnchor.constraint(greaterThanOrEqualTo: rightView.bottomAnchor).isActive = true if centered { rightView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true } else { rightView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true } } return view } private let clockIcon: UIImageView = { let img = UIImageView() img.contentMode = .scaleAspectFit img.image = UIImage(named: "Clock") img.translatesAutoresizingMaskIntoConstraints = false img.clipsToBounds = true return img }() }
41.435897
210
0.632426
87529a8484f51c0e8a19f9d16310681811608920
4,524
// // Movie.swift // Popcorn Night // // Created by Michael Isaakidis on 17/09/2018. // Copyright © 2018 Michael Isaakidis. All rights reserved. // import Foundation struct Genre: Codable { let genreId: Int let name: String? enum CodingKeys: String, CodingKey { case genreId = "id" case name = "name" } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) name = try container.decode(String.self, forKey: .name) genreId = try container.decode(Int.self, forKey: .genreId) } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(name, forKey: .name) try container.encode(genreId, forKey: .genreId) } } struct Movie: Codable { let posterPath: String? let backdropPath: String? let overview: String let releaseDate: String let movieId: Int let title: String let popularity: Float let voteAverage: Float let originalLanguage: String? let voteCount: Int let homepage: String? let revenue: Int? let runtime: Int? var genres: [Genre]? let genreIds: [Int]? enum CodingKeys: String, CodingKey { case posterPath = "poster_path" case overview = "overview" case releaseDate = "release_date" case movieId = "id" case title = "title" case popularity = "popularity" case voteAverage = "vote_average" case backdropPath = "backdrop_path" case originalLanguage = "original_language" case voteCount = "vote_count" case homepage = "homepage" case revenue = "revenue" case runtime = "runtime" case genres = "genres" case genreIds = "genre_ids" } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) posterPath = try container.decode(String.self, forKey: .posterPath) backdropPath = try? container.decode(String.self, forKey: .backdropPath) overview = try container.decode(String.self, forKey: .overview) releaseDate = try container.decode(String.self, forKey: .releaseDate) movieId = try container.decode(Int.self, forKey: .movieId) title = try container.decode(String.self, forKey: .title) popularity = try container.decode(Float.self, forKey: .popularity) voteAverage = try container.decode(Float.self, forKey: .voteAverage) voteCount = try container.decode(Int.self, forKey: .voteCount) revenue = try? container.decode(Int.self, forKey: .revenue) runtime = try? container.decode(Int.self, forKey: .runtime) originalLanguage = try? container.decode(String.self, forKey: .originalLanguage) homepage = try? container.decode(String.self, forKey: .homepage) genreIds = try? container.decode([Int].self, forKey: .genreIds) genres = try? container.decode([Genre].self, forKey: .genres) } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(posterPath, forKey: .posterPath) try container.encode(backdropPath, forKey: .backdropPath) try container.encode(overview, forKey: .overview) try container.encode(releaseDate, forKey: .releaseDate) try container.encode(movieId, forKey: .movieId) try container.encode(title, forKey: .title) try container.encode(popularity, forKey: .popularity) try container.encode(voteAverage, forKey: .voteAverage) try container.encode(voteCount, forKey: .voteCount) try container.encode(revenue, forKey: .revenue) try container.encode(runtime, forKey: .runtime) try container.encode(originalLanguage, forKey: .originalLanguage) try container.encode(homepage, forKey: .homepage) try container.encode(genreIds, forKey: .genreIds) try container.encode(genres, forKey: .genres) } func genresString() -> String? { if let genres = genres { return genres.map { (genre) -> String in genre.name! }.joined(separator: " | ") } return nil } func releaseYear() -> String { if let year = releaseDate.split(separator: "-").first { return String(year) } return releaseDate } }
36.780488
88
0.643678
8ffcfb8f076a261a5093ddb88de7ca0d71db064e
4,856
// // InterceptApiViewController.swift // Noober // // Created by Abhishek Agarwal on 28/03/22. // Copyright © 2022 Noober. All rights reserved. // import UIKit protocol InterceptApiViewControllerDelegate: AnyObject { func didTappedSubmit(response: String?) } class InterceptApiViewController: UIViewController { weak var delegate: InterceptApiViewControllerDelegate? private let urlTxtLabel = NoobLabel(text: "URL", textColor: .blue, font: UIFont.preferredFont(forTextStyle: .headline)) private let urlLabel = NoobLabel(text: "URL", textColor: .black, font: UIFont.preferredFont(forTextStyle: .subheadline)) private let url: String private var responseBody: String = "" private lazy var bodyField: UITextView = { let view = UITextView() view.translatesAutoresizingMaskIntoConstraints = false view.font = UIFont.preferredFont(forTextStyle: .caption1) view.textColor = .black view.keyboardType = .default view.isEditable = true view.textAlignment = .left view.delegate = self return view }() private lazy var scrollView: UIScrollView = { let view = UIScrollView() view.isScrollEnabled = true view.translatesAutoresizingMaskIntoConstraints = false return view }() private lazy var submitButton: UIButton = { let view = UIButton() view.translatesAutoresizingMaskIntoConstraints = false view.layer.borderColor = UIColor.black.cgColor view.layer.borderWidth = 2 view.layer.cornerRadius = 12 view.titleLabel?.font = UIFont.preferredFont(forTextStyle: .caption1) view.setTitleColor(.black, for: .normal) view.titleLabel?.adjustsFontSizeToFitWidth = true view.setTitle("Submit", for: .normal) view.addTarget(self, action: #selector(didTappedSubmit), for: .touchUpInside) return view }() init(url: String?, delegate: InterceptApiViewControllerDelegate, responseBody: String) { self.url = url ?? "" self.delegate = delegate self.responseBody = responseBody super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white setupViews() } private func setupViews() { view.addSubview(scrollView) scrollView.addSubview(urlTxtLabel) scrollView.addSubview(urlLabel) scrollView.addSubview(bodyField) scrollView.addSubview(submitButton) bodyField.becomeFirstResponder() urlLabel.text = url bodyField.text = responseBody NSLayoutConstraint.activate([ scrollView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), scrollView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor), scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor), scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor), urlTxtLabel.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor, constant: 10), urlTxtLabel.topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 20), urlLabel.leadingAnchor.constraint(equalTo: urlTxtLabel.leadingAnchor), urlLabel.topAnchor.constraint(equalTo: urlTxtLabel.bottomAnchor, constant: 4), urlLabel.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -20), urlLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10), bodyField.leadingAnchor.constraint(equalTo: urlTxtLabel.leadingAnchor), bodyField.topAnchor.constraint(equalTo: urlLabel.bottomAnchor, constant: 10), bodyField.widthAnchor.constraint(equalTo: urlLabel.widthAnchor), bodyField.heightAnchor.constraint(greaterThanOrEqualToConstant: 200), submitButton.leadingAnchor.constraint(equalTo: urlTxtLabel.leadingAnchor), submitButton.topAnchor.constraint(equalTo: bodyField.bottomAnchor, constant: 10), submitButton.widthAnchor.constraint(equalTo: urlLabel.widthAnchor), submitButton.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor, constant: -20) ]) } @objc private func didTappedSubmit() { delegate?.didTappedSubmit(response: bodyField.text) dismiss(animated: true) } } extension InterceptApiViewController: UITextViewDelegate { func textViewDidChange(_ textView: UITextView) { if (textView.text?.isEmpty) ?? true { submitButton.setTitle("Cancel", for: .normal) } else { submitButton.setTitle("Submit", for: .normal) } } }
37.9375
124
0.688015
7292be77d8988630b7698aa6a15cd9eba73f4789
2,925
// // HitsList.swift // // // Created by Vladislav Fitc on 29/03/2021. // import Foundation import SwiftUI /// A view presenting the list of search hits @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 7.0, *) public struct HitsList<Row: View, Item: Codable, NoResults: View>: View { @ObservedObject public var hitsObservable: HitsObservableController<Item> /// Closure constructing a hit row view public var row: (Item?, Int) -> Row /// Closure constructing a no results view public var noResults: (() -> NoResults)? public init(_ hitsObservable: HitsObservableController<Item>, @ViewBuilder row: @escaping (Item?, Int) -> Row, @ViewBuilder noResults: @escaping () -> NoResults) { self.hitsObservable = hitsObservable self.row = row self.noResults = noResults } public var body: some View { if let noResults = noResults?(), hitsObservable.hits.isEmpty { noResults } else { if #available(iOS 14.0, OSX 11.0, tvOS 14.0, *) { ScrollView(showsIndicators: false) { LazyVStack { ForEach(0..<hitsObservable.hits.count, id: \.self) { index in row(atIndex: index) } } }.id(hitsObservable.scrollID) } else { List(0..<hitsObservable.hits.count, id: \.self) { index in row(atIndex: index) }.id(hitsObservable.scrollID) } } } private func row(atIndex index: Int) -> some View { row(hitsObservable.hits[index], index).onAppear { hitsObservable.notifyAppearanceOfHit(atIndex: index) } } } @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 7.0, *) public extension HitsList where NoResults == Never { init(_ hitsObservable: HitsObservableController<Item>, @ViewBuilder row: @escaping (Item?, Int) -> Row) { self.hitsObservable = hitsObservable self.row = row self.noResults = nil } } #if os(iOS) @available(iOS 13.0, tvOS 13.0, watchOS 7.0, *) struct HitsView_Previews: PreviewProvider { static var previews: some View { let hitsController: HitsObservableController<String> = .init() NavigationView { HitsList(hitsController) { string, _ in VStack { HStack { Text(string ?? "---") .frame(maxWidth: .infinity, minHeight: 30, maxHeight: .infinity, alignment: .leading) .padding(.horizontal, 16) } Divider() } } noResults: { Text("No results") } .padding(.top, 20) .onAppear { hitsController.hits = ["One", "Two", "Three"] }.navigationBarTitle("Hits") } NavigationView { HitsList(hitsController) { string, _ in VStack { HStack { Text(string ?? "---") } Divider() } } noResults: { Text("No results") }.navigationBarTitle("Hits") } } } #endif
26.590909
99
0.597949
4b8649fd09a58d97734177e4aef73cf398e9f90b
13,387
// // UIView+Extension.swift // FFAutoLayout // // Created by 刘凡 on 15/6/27. // Copyright © 2015年 joyios. All rights reserved. // import UIKit /// 对齐类型枚举,设置控件相对于父视图的位置 /// /// - TopLeft: 左上 /// - TopRight: 右上 /// - TopCenter: 中上 /// - BottomLeft: 左下 /// - BottomRight: 右下 /// - BottomCenter: 中下 /// - CenterLeft: 左中 /// - CenterRight: 右中 /// - CenterCenter: 中中 public enum ff_AlignType { case TopLeft case TopRight case TopCenter case BottomLeft case BottomRight case BottomCenter case CenterLeft case CenterRight case CenterCenter private func layoutAttributes(isInner: Bool, isVertical: Bool) -> ff_LayoutAttributes { let attributes = ff_LayoutAttributes() switch self { case .TopLeft: attributes.horizontals(.Left, to: .Left).verticals(.Top, to: .Top) if isInner { return attributes } else if isVertical { return attributes.verticals(.Bottom, to: .Top) } else { return attributes.horizontals(.Right, to: .Left) } case .TopRight: attributes.horizontals(.Right, to: .Right).verticals(.Top, to: .Top) if isInner { return attributes } else if isVertical { return attributes.verticals(.Bottom, to: .Top) } else { return attributes.horizontals(.Left, to: .Right) } case .TopCenter: // 仅内部 & 垂直参照需要 attributes.horizontals(.CenterX, to: .CenterX).verticals(.Top, to: .Top) return isInner ? attributes : attributes.verticals(.Bottom, to: .Top) case .BottomLeft: attributes.horizontals(.Left, to: .Left).verticals(.Bottom, to: .Bottom) if isInner { return attributes } else if isVertical { return attributes.verticals(.Top, to: .Bottom) } else { return attributes.horizontals(.Right, to: .Left) } case .BottomRight: attributes.horizontals(.Right, to: .Right).verticals(.Bottom, to: .Bottom) if isInner { return attributes } else if isVertical { return attributes.verticals(.Top, to: .Bottom) } else { return attributes.horizontals(.Left, to: .Right) } case .BottomCenter: // 仅内部 & 垂直参照需要 attributes.horizontals(.CenterX, to: .CenterX).verticals(.Bottom, to: .Bottom) return isInner ? attributes : attributes.verticals(.Top, to: .Bottom) case .CenterLeft: // 仅内部 & 水平参照需要 attributes.horizontals(.Left, to: .Left).verticals(.CenterY, to: .CenterY) return isInner ? attributes : attributes.horizontals(.Right, to: .Left) case .CenterRight: // 仅内部 & 水平参照需要 attributes.horizontals(.Right, to: .Right).verticals(.CenterY, to: .CenterY) return isInner ? attributes : attributes.horizontals(.Left, to: .Right) case .CenterCenter: // 仅内部参照需要 return ff_LayoutAttributes(horizontal: .CenterX, referHorizontal: .CenterX, vertical: .CenterY, referVertical: .CenterY) } } } extension UIView { /// 填充子视图 /// /// - parameter referView: 参考视图 /// - parameter insets: 间距 public func ff_Fill(referView: UIView, insets: UIEdgeInsets = UIEdgeInsetsZero) -> [NSLayoutConstraint] { translatesAutoresizingMaskIntoConstraints = false var cons = [NSLayoutConstraint]() cons += NSLayoutConstraint.constraintsWithVisualFormat("H:|-\(insets.left)-[subView]-\(insets.right)-|", options: NSLayoutFormatOptions.AlignAllBaseline, metrics: nil, views: ["subView" : self]) cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-\(insets.top)-[subView]-\(insets.bottom)-|", options: NSLayoutFormatOptions.AlignAllBaseline, metrics: nil, views: ["subView" : self]) superview?.addConstraints(cons) return cons } /// 参照参考视图内部对齐 /// /// - parameter type: 对齐方式 /// - Parameter referView: 参考视图 /// - Parameter size: 视图大小,如果是 nil 则不设置大小 /// - Parameter offset: 偏移量,默认是 CGPoint(x: 0, y: 0) /// /// - returns: 约束数组 public func ff_AlignInner(type: ff_AlignType, referView: UIView, size: CGSize?, offset: CGPoint = CGPointZero) -> [NSLayoutConstraint] { return ff_AlignLayout(referView, attributes: type.layoutAttributes(true, isVertical: true), size: size, offset: offset) } /// 参照参考视图垂直对齐 /// /// - parameter type: 对齐方式 /// - parameter referView: 参考视图 /// - parameter size: 视图大小,如果是 nil 则不设置大小 /// - parameter offset: 偏移量,默认是 CGPoint(x: 0, y: 0) /// /// - returns: 约束数组 public func ff_AlignVertical(type: ff_AlignType, referView: UIView, size: CGSize?, offset: CGPoint = CGPointZero) -> [NSLayoutConstraint] { return ff_AlignLayout(referView, attributes: type.layoutAttributes(false, isVertical: true), size: size, offset: offset) } /// 参照参考视图水平对齐 /// /// - parameter type: 对齐方式 /// - parameter referView: 参考视图 /// - parameter size: 视图大小,如果是 nil 则不设置大小 /// - parameter offset: 偏移量,默认是 CGPoint(x: 0, y: 0) /// /// - returns: 约束数组 public func ff_AlignHorizontal(type: ff_AlignType, referView: UIView, size: CGSize?, offset: CGPoint = CGPointZero) -> [NSLayoutConstraint] { return ff_AlignLayout(referView, attributes: type.layoutAttributes(false, isVertical: false), size: size, offset: offset) } /// 在当前视图内部水平平铺控件 /// /// - parameter views: 子视图数组 /// - parameter insets: 间距 /// /// - returns: 约束数组 public func ff_HorizontalTile(views: [UIView], insets: UIEdgeInsets) -> [NSLayoutConstraint] { assert(!views.isEmpty, "views should not be empty") var cons = [NSLayoutConstraint]() let firstView = views[0] firstView.ff_AlignInner(ff_AlignType.TopLeft, referView: self, size: nil, offset: CGPoint(x: insets.left, y: insets.top)) cons.append(NSLayoutConstraint(item: firstView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: -insets.bottom)) // 添加后续视图的约束 var preView = firstView for i in 1..<views.count { let subView = views[i] cons += subView.ff_sizeConstraints(firstView) subView.ff_AlignHorizontal(ff_AlignType.TopRight, referView: preView, size: nil, offset: CGPoint(x: insets.right, y: 0)) preView = subView } let lastView = views.last! cons.append(NSLayoutConstraint(item: lastView, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Right, multiplier: 1.0, constant: -insets.right)) addConstraints(cons) return cons } /// 在当前视图内部垂直平铺控件 /// /// - parameter views: 子视图数组 /// - parameter insets: 间距 /// /// - returns: 约束数组 public func ff_VerticalTile(views: [UIView], insets: UIEdgeInsets) -> [NSLayoutConstraint] { assert(!views.isEmpty, "views should not be empty") var cons = [NSLayoutConstraint]() let firstView = views[0] firstView.ff_AlignInner(ff_AlignType.TopLeft, referView: self, size: nil, offset: CGPoint(x: insets.left, y: insets.top)) cons.append(NSLayoutConstraint(item: firstView, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Right, multiplier: 1.0, constant: -insets.right)) // 添加后续视图的约束 var preView = firstView for i in 1..<views.count { let subView = views[i] cons += subView.ff_sizeConstraints(firstView) subView.ff_AlignVertical(ff_AlignType.BottomLeft, referView: preView, size: nil, offset: CGPoint(x: 0, y: insets.bottom)) preView = subView } let lastView = views.last! cons.append(NSLayoutConstraint(item: lastView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: -insets.bottom)) addConstraints(cons) return cons } /// 从约束数组中查找指定 attribute 的约束 /// /// - parameter constraintsList: 约束数组 /// - parameter attribute: 约束属性 /// /// - returns: attribute 对应的约束 public func ff_Constraint(constraintsList: [NSLayoutConstraint], attribute: NSLayoutAttribute) -> NSLayoutConstraint? { for constraint in constraintsList { if constraint.firstItem as! NSObject == self && constraint.firstAttribute == attribute { return constraint } } return nil } // MARK: - 私有函数 /// 参照参考视图对齐布局 /// /// - parameter referView: 参考视图 /// - parameter attributes: 参照属性 /// - parameter size: 视图大小,如果是 nil 则不设置大小 /// - parameter offset: 偏移量,默认是 CGPoint(x: 0, y: 0) /// /// - returns: 约束数组 private func ff_AlignLayout(referView: UIView, attributes: ff_LayoutAttributes, size: CGSize?, offset: CGPoint) -> [NSLayoutConstraint] { translatesAutoresizingMaskIntoConstraints = false var cons = [NSLayoutConstraint]() cons += ff_positionConstraints(referView, attributes: attributes, offset: offset) if size != nil { cons += ff_sizeConstraints(size!) } superview?.addConstraints(cons) return cons } /// 尺寸约束数组 /// /// - parameter size: 视图大小 /// /// - returns: 约束数组 private func ff_sizeConstraints(size: CGSize) -> [NSLayoutConstraint] { var cons = [NSLayoutConstraint]() cons.append(NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: size.width)) cons.append(NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: size.height)) return cons } /// 尺寸约束数组 /// /// - parameter referView: 参考视图,与参考视图大小一致 /// /// - returns: 约束数组 private func ff_sizeConstraints(referView: UIView) -> [NSLayoutConstraint] { var cons = [NSLayoutConstraint]() cons.append(NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: referView, attribute: NSLayoutAttribute.Width, multiplier: 1.0, constant: 0)) cons.append(NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: referView, attribute: NSLayoutAttribute.Height, multiplier: 1.0, constant: 0)) return cons } /// 位置约束数组 /// /// - parameter referView: 参考视图 /// - parameter attributes: 参照属性 /// - parameter offset: 偏移量 /// /// - returns: 约束数组 private func ff_positionConstraints(referView: UIView, attributes: ff_LayoutAttributes, offset: CGPoint) -> [NSLayoutConstraint] { var cons = [NSLayoutConstraint]() cons.append(NSLayoutConstraint(item: self, attribute: attributes.horizontal, relatedBy: NSLayoutRelation.Equal, toItem: referView, attribute: attributes.referHorizontal, multiplier: 1.0, constant: offset.x)) cons.append(NSLayoutConstraint(item: self, attribute: attributes.vertical, relatedBy: NSLayoutRelation.Equal, toItem: referView, attribute: attributes.referVertical, multiplier: 1.0, constant: offset.y)) return cons } } /// 布局属性 private final class ff_LayoutAttributes { var horizontal: NSLayoutAttribute var referHorizontal: NSLayoutAttribute var vertical: NSLayoutAttribute var referVertical: NSLayoutAttribute init() { horizontal = NSLayoutAttribute.Left referHorizontal = NSLayoutAttribute.Left vertical = NSLayoutAttribute.Top referVertical = NSLayoutAttribute.Top } init(horizontal: NSLayoutAttribute, referHorizontal: NSLayoutAttribute, vertical: NSLayoutAttribute, referVertical: NSLayoutAttribute) { self.horizontal = horizontal self.referHorizontal = referHorizontal self.vertical = vertical self.referVertical = referVertical } private func horizontals(from: NSLayoutAttribute, to: NSLayoutAttribute) -> Self { horizontal = from referHorizontal = to return self } private func verticals(from: NSLayoutAttribute, to: NSLayoutAttribute) -> Self { vertical = from referVertical = to return self } }
38.915698
222
0.617166
e015a5694a666d5d164a3f0f3a2cf4a305184674
1,908
/// /// MIT License /// /// Copyright (c) 2020 Sascha Müllner /// /// 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. /// /// Created by Sascha Müllner on 24.11.20. import Foundation import SwiftUI import GameKit class MatchMakingViewModel: ObservableObject { @Published public var showModal = false @Published public var showAlert = false @Published public var alertTitle: String = "" @Published public var alertMessage: String = "" @Published public var currentState: String = "Loading GameKit..." public init() { } public func load() { self.showMatchMakerModal() } public func showAlert(title: String, message: String) { self.showAlert = true self.alertTitle = title self.alertMessage = message } public func showMatchMakerModal() { self.showModal = true } }
34.071429
82
0.710168
296f937c7e0a2068643e49f7f43c574f1af7c1af
505
// // ViewController.swift // ForMeal // // Created by song_dzhong on 16/10/27. // Copyright © 2016年 songdezhong. 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. } }
19.423077
80
0.671287
87c5380a8c85e7354d95e26582399bfff76b13ec
2,332
// // AgreementPromotionView.swift // martkurly // // Created by Doyoung Song on 8/21/20. // Copyright © 2020 Team3x3. All rights reserved. // import UIKit class AgreementPromotionView: UIView { // MARK: - Properties let label = UILabel().then { let string = StringManager().agreementPromotion[0] let color = ColorManager.General.mainPurple.rawValue let font = UIFont.systemFont(ofSize: 14, weight: .regular) let attributes: [NSAttributedString.Key: Any] = [ NSAttributedString.Key.foregroundColor: color, NSAttributedString.Key.font: font ] let attributedString = NSMutableAttributedString(string: string, attributes: attributes) let string2 = StringManager().agreementPromotion[1] let color2 = ColorManager.General.chevronGray.rawValue let font2 = UIFont.systemFont(ofSize: 13.5, weight: .light) let attributes2: [NSAttributedString.Key: Any] = [ .foregroundColor: color2, .font: font2 ] let attributedString2 = NSMutableAttributedString(string: string2, attributes: attributes2) attributedString.append(attributedString2) let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineSpacing = 4 let attributes3 = [NSAttributedString.Key.paragraphStyle: paragraphStyle] attributedString.addAttributes(attributes3, range: NSRange(location: 0, length: attributedString.length)) $0.attributedText = attributedString $0.numberOfLines = 0 } // MARK: - Lifecycle override init(frame: CGRect) { super.init(frame: frame) configureUI() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - UI private func configureUI() { setPropertyAttributes() setConstraints() } private func setPropertyAttributes() { self.layer.borderColor = ColorManager.General.backGray.rawValue.cgColor self.layer.borderWidth = 1 self.layer.cornerRadius = 4 } private func setConstraints() { self.addSubview(label) label.snp.makeConstraints { $0.leading.trailing.equalToSuperview().inset(10) $0.centerY.equalToSuperview() } } }
31.945205
113
0.657376
4630c7c25db8fb359486c58d32c53bb4acc4e030
627
// 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 // RUN: not %target-swift-frontend %s -typecheck func g<d { class A { func c) -> Self { typealias h: (m: AnyObject, a(t: B, e(")!.dynamicType) } i: A { assert([self.e> String { } enum b in c { } } protocol a { } class A : A { } class B<d) -> { var d = { func b: d { var b, g> S
22.392857
79
0.674641
76f944cdd281c3f68b1a5366698e5f269315641b
570
// // StoryboardHelper.swift // PriconneDB // // Created by Kazutoshi Baba on 2019/05/02. // Copyright © 2019 Kazutoshi Baba. All rights reserved. // import UIKit enum Storyboard: String { case main = "Main" } protocol StoryboardHelper {} extension StoryboardHelper where Self: UIViewController { static func instantiate(storyboard: Storyboard) -> Self { let storyboard = UIStoryboard.storyboard(storyboard) return storyboard.instantiateViewController(ofType: Self.self) } } extension UIViewController: StoryboardHelper {}
21.111111
70
0.717544
db42523622057a95a25df24924662824ff5f66c8
10,024
// // PaymentSheetTestPlayground.swift // PaymentSheet Example // // Created by Yuki Tokuhiro on 9/14/20. // Copyright © 2020 stripe-ios. All rights reserved. // import Stripe import UIKit class PaymentSheetTestPlayground: UIViewController { // Configuration @IBOutlet weak var customerModeSelector: UISegmentedControl! @IBOutlet weak var applePaySelector: UISegmentedControl! @IBOutlet weak var billingModeSelector: UISegmentedControl! @IBOutlet weak var currencySelector: UISegmentedControl! @IBOutlet weak var modeSelector: UISegmentedControl! @IBOutlet weak var loadButton: UIButton! // Inline @IBOutlet weak var selectPaymentMethodImage: UIImageView! @IBOutlet weak var selectPaymentMethodButton: UIButton! @IBOutlet weak var checkoutInlineButton: UIButton! // Complete @IBOutlet weak var checkoutButton: UIButton! // Other var newCustomerID: String? // Stores the new customer returned from the backend for reuse enum CustomerMode { case guest case new case returning } enum Currency: String, CaseIterable { case usd case eur } enum IntentMode: String { case payment case setup } var customerMode: CustomerMode { switch customerModeSelector.selectedSegmentIndex { case 0: return .guest case 1: return .new default: return .returning } } var applePayConfiguration: PaymentSheet.ApplePayConfiguration? { if applePaySelector.selectedSegmentIndex == 0 { return PaymentSheet.ApplePayConfiguration( merchantId: "com.foo.example", merchantCountryCode: "US") } else { return nil } } var customerConfiguration: PaymentSheet.CustomerConfiguration? { if let customerID = customerID, let ephemeralKey = ephemeralKey, customerMode != .guest { return PaymentSheet.CustomerConfiguration( id: customerID, ephemeralKeySecret: ephemeralKey) } return nil } /// Currency specified in the UI toggle var currency: Currency { let index = currencySelector.selectedSegmentIndex guard index >= 0 && index < Currency.allCases.count else { return .usd } return Currency.allCases[index] } var intentMode: IntentMode { switch modeSelector.selectedSegmentIndex { case 1: return .setup default: return .payment } } var configuration: PaymentSheet.Configuration { var configuration = PaymentSheet.Configuration() configuration.merchantDisplayName = "Example, Inc." configuration.returnURL = "payments-example://stripe-redirect" configuration.applePay = applePayConfiguration configuration.customer = customerConfiguration configuration.returnURL = "payments-example://stripe-redirect" return configuration } var clientSecret: String? var ephemeralKey: String? var customerID: String? var manualFlow: PaymentSheet.FlowController? func makeAlertController() -> UIAlertController { let alertController = UIAlertController( title: "Complete", message: "Completed", preferredStyle: .alert) let OKAction = UIAlertAction(title: "OK", style: .default) { (action) in alertController.dismiss(animated: true, completion: nil) } alertController.addAction(OKAction) return alertController } override func viewDidLoad() { super.viewDidLoad() checkoutButton.addTarget(self, action: #selector(didTapCheckoutButton), for: .touchUpInside) checkoutButton.isEnabled = false loadButton.addTarget(self, action: #selector(load), for: .touchUpInside) selectPaymentMethodButton.isEnabled = false selectPaymentMethodButton.addTarget( self, action: #selector(didTapSelectPaymentMethodButton), for: .touchUpInside) checkoutInlineButton.addTarget( self, action: #selector(didTapCheckoutInlineButton), for: .touchUpInside) checkoutInlineButton.isEnabled = false } @objc func didTapCheckoutInlineButton() { checkoutInlineButton.isEnabled = false manualFlow?.confirm(from: self) { result in let alertController = self.makeAlertController() switch result { case .canceled: alertController.message = "canceled" self.checkoutInlineButton.isEnabled = true case .failed(let error): alertController.message = "\(error)" self.present(alertController, animated: true) self.checkoutInlineButton.isEnabled = true case .completed: alertController.message = "success!" self.present(alertController, animated: true) } } } @objc func didTapCheckoutButton() { let mc: PaymentSheet switch intentMode { case .payment: mc = PaymentSheet(paymentIntentClientSecret: clientSecret!, configuration: configuration) case .setup: mc = PaymentSheet(setupIntentClientSecret: clientSecret!, configuration: configuration) } mc.present(from: self) { result in let alertController = self.makeAlertController() switch result { case .canceled: print("Canceled! \(String(describing: mc.mostRecentError))") case .failed(let error): alertController.message = error.localizedDescription print(error) self.present(alertController, animated: true) case .completed: alertController.message = "Success!" self.present(alertController, animated: true) self.checkoutButton.isEnabled = false } } } @objc func didTapSelectPaymentMethodButton() { manualFlow?.presentPaymentOptions(from: self) { self.updatePaymentMethodSelection() } } func updatePaymentMethodSelection() { // Update the payment method selection button if let paymentOption = manualFlow?.paymentOption { self.selectPaymentMethodButton.setTitle(paymentOption.label, for: .normal) self.selectPaymentMethodButton.setTitleColor(.label, for: .normal) self.selectPaymentMethodImage.image = paymentOption.image self.checkoutInlineButton.isEnabled = true } else { self.selectPaymentMethodButton.setTitle("Select", for: .normal) self.selectPaymentMethodButton.setTitleColor(.systemBlue, for: .normal) self.selectPaymentMethodImage.image = nil self.checkoutInlineButton.isEnabled = false } } } // MARK: - Backend extension PaymentSheetTestPlayground { @objc func load() { checkoutButton.isEnabled = false checkoutInlineButton.isEnabled = false selectPaymentMethodButton.isEnabled = false manualFlow = nil let session = URLSession.shared let url = URL(string: "https://stripe-mobile-payment-sheet-test-playground-v3.glitch.me/checkout")! let customer: String = { switch customerMode { case .guest: return "guest" case .new: return newCustomerID ?? "new" case .returning: return "returning" } }() let json = try! JSONEncoder().encode([ "customer": customer, "currency": currency.rawValue, "mode": intentMode.rawValue, ]) var urlRequest = URLRequest(url: url) urlRequest.httpMethod = "POST" urlRequest.httpBody = json urlRequest.setValue("application/json", forHTTPHeaderField: "Content-type") let task = session.dataTask(with: urlRequest) { data, response, error in guard error == nil, let data = data, let json = try? JSONDecoder().decode([String: String].self, from: data) else { print(error as Any) return } self.clientSecret = json["intentClientSecret"] self.ephemeralKey = json["customerEphemeralKeySecret"] self.customerID = json["customerId"] StripeAPI.defaultPublishableKey = json["publishableKey"] let completion: (Result<PaymentSheet.FlowController, Error>) -> Void = { result in switch result { case .failure(let error): print(error as Any) case .success(let manualFlow): self.manualFlow = manualFlow self.selectPaymentMethodButton.isEnabled = true self.updatePaymentMethodSelection() } } DispatchQueue.main.async { if self.customerMode == .new && self.newCustomerID == nil { self.newCustomerID = self.customerID } self.checkoutButton.isEnabled = true switch self.intentMode { case .payment: PaymentSheet.FlowController.create( paymentIntentClientSecret: self.clientSecret!, configuration: self.configuration, completion: completion ) case .setup: PaymentSheet.FlowController.create( setupIntentClientSecret: self.clientSecret!, configuration: self.configuration, completion: completion ) } } } task.resume() } }
35.295775
107
0.605148
5bf1dd19701b6a3a8263900fa4d67b3771cae8aa
1,271
// // SegueNavigationRow.swift // Provenance // // Created by Joseph Mattiello on 12/25/18. // Copyright © 2018 Provenance Emu. All rights reserved. // import Foundation final class SegueNavigationRow: NavigationRow<SystemSettingsCell> { weak var viewController: UIViewController? required init(text: String, detailText: DetailText = .none, viewController: UIViewController, segue: String, customization: ((UITableViewCell, Row & RowStyle) -> Void)? = nil) { self.viewController = viewController #if os(tvOS) super.init(text: text, detailText: detailText, icon: nil, customization: customization) { [weak viewController] _ in guard let viewController = viewController else { return } viewController.performSegue(withIdentifier: segue, sender: nil) } #else super.init(text: text, detailText: detailText, icon: nil, customization: customization, accessoryButtonAction: { [weak viewController] _ in guard let viewController = viewController else { return } viewController.performSegue(withIdentifier: segue, sender: nil) }) #endif } }
34.351351
151
0.63336
87fd1b06bcc06c50fd0eebbe8ff47edfd05490fc
405
// // Swiftlib.swift // IDP_Framework // // Created by Kuldipsinh Gadhavi on 17/10/19. // Copyright © 2019 Kuldipsinh Gadhavi. All rights reserved. // import Foundation public final class IDP_Framework { let name = "SwiftyLib" public func add(a: Int, b: Int) -> Int { return a + b } public func sub(a: Int, b: Int) -> Int { return a - b } }
15.576923
61
0.57284
5d02b751c7e257b8f0cc4b3541db100af6415bcf
18,253
import Foundation extension EncodableRecord where Self: Encodable { public func encode(to container: inout PersistenceContainer) { let encoder = RecordEncoder<Self>(persistenceContainer: container) try! encode(to: encoder) container = encoder.persistenceContainer } } // MARK: - RecordEncoder /// The encoder that encodes a record into GRDB's PersistenceContainer private class RecordEncoder<Record: EncodableRecord>: Encoder { var codingPath: [CodingKey] { [] } var userInfo: [CodingUserInfoKey: Any] { Record.databaseEncodingUserInfo } private var _persistenceContainer: PersistenceContainer var persistenceContainer: PersistenceContainer { _persistenceContainer } init(persistenceContainer: PersistenceContainer) { _persistenceContainer = persistenceContainer } func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> { let container = KeyedContainer<Key>(recordEncoder: self) return KeyedEncodingContainer(container) } func unkeyedContainer() -> UnkeyedEncodingContainer { fatalError("unkeyed encoding is not supported") } func singleValueContainer() -> SingleValueEncodingContainer { // @itaiferber on https://forums.swift.org/t/how-to-encode-objects-of-unknown-type/12253/11 // // > Encoding a value into a single-value container is equivalent to // > encoding the value directly into the encoder, with the primary // > difference being the above: encoding into the encoder writes the // > contents of a type into the encoder, while encoding to a // > single-value container gives the encoder a chance to intercept the // > type as a whole. // // Wait for somebody hitting this fatal error so that we can write a // meaningful regression test. fatalError("single value encoding is not supported") } private struct KeyedContainer<Key: CodingKey>: KeyedEncodingContainerProtocol { var recordEncoder: RecordEncoder var userInfo: [CodingUserInfoKey: Any] { Record.databaseEncodingUserInfo } var codingPath: [CodingKey] { [] } // swiftlint:disable comma func encode(_ value: Bool, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encode(_ value: Int, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encode(_ value: Int8, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encode(_ value: Int16, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encode(_ value: Int32, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encode(_ value: Int64, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encode(_ value: UInt, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encode(_ value: UInt8, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encode(_ value: UInt16, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encode(_ value: UInt32, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encode(_ value: UInt64, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encode(_ value: Float, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encode(_ value: Double, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encode(_ value: String, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } // swiftlint:enable comma func encode<T>(_ value: T, forKey key: Key) throws where T: Encodable { try recordEncoder.encode(value, forKey: key) } func encodeNil(forKey key: Key) throws { recordEncoder.persist(nil, forKey: key) } // swiftlint:disable comma func encodeIfPresent(_ value: Bool?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encodeIfPresent(_ value: Int?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encodeIfPresent(_ value: Int8?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encodeIfPresent(_ value: Int16?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encodeIfPresent(_ value: Int32?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encodeIfPresent(_ value: Int64?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encodeIfPresent(_ value: UInt?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encodeIfPresent(_ value: UInt8?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encodeIfPresent(_ value: UInt16?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encodeIfPresent(_ value: UInt32?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encodeIfPresent(_ value: UInt64?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encodeIfPresent(_ value: Float?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encodeIfPresent(_ value: Double?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encodeIfPresent(_ value: String?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } // swiftlint:disable comma func encodeIfPresent<T>(_ value: T?, forKey key: Key) throws where T: Encodable { if let value = value { try recordEncoder.encode(value, forKey: key) } else { recordEncoder.persist(nil, forKey: key) } } func nestedContainer<NestedKey>( keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey> { fatalError("Not implemented") } func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer { fatalError("Not implemented") } func superEncoder() -> Encoder { fatalError("Not implemented") } func superEncoder(forKey key: Key) -> Encoder { fatalError("Not implemented") } } /// Helper methods @inline(__always) fileprivate func persist(_ value: DatabaseValueConvertible?, forKey key: CodingKey) { _persistenceContainer[key.stringValue] = value } @inline(__always) fileprivate func encode<T>(_ value: T, forKey key: CodingKey) throws where T: Encodable { if let date = value as? Date { persist(Record.databaseDateEncodingStrategy.encode(date), forKey: key) } else if let uuid = value as? UUID { persist(Record.databaseUUIDEncodingStrategy.encode(uuid), forKey: key) } else if let value = value as? DatabaseValueConvertible { // Prefer DatabaseValueConvertible encoding over Decodable. persist(value.databaseValue, forKey: key) } else { do { // This encoding will fail for types that encode into keyed // or unkeyed containers, because we're encoding a single // value here (string, int, double, data, null). If such an // error happens, we'll switch to JSON encoding. let encoder = ColumnEncoder(recordEncoder: self, key: key) try value.encode(to: encoder) if encoder.requiresJSON { // Here we handle empty arrays and dictionaries. throw JSONRequiredError() } } catch is JSONRequiredError { // Encode to JSON let jsonData = try Record.databaseJSONEncoder(for: key.stringValue).encode(value) // Store JSON String in the database for easier debugging and // database inspection. Thanks to SQLite weak typing, we won't // have any trouble decoding this string into data when we // eventually perform JSON decoding. // TODO: possible optimization: avoid this conversion to string, // and store raw data bytes as an SQLite string let jsonString = String(data: jsonData, encoding: .utf8)! persist(jsonString, forKey: key) } } } } // MARK: - ColumnEncoder /// The encoder that encodes into a database column private class ColumnEncoder<Record: EncodableRecord>: Encoder { var recordEncoder: RecordEncoder<Record> var key: CodingKey var codingPath: [CodingKey] { [key] } var userInfo: [CodingUserInfoKey: Any] { Record.databaseEncodingUserInfo } var requiresJSON = false init(recordEncoder: RecordEncoder<Record>, key: CodingKey) { self.recordEncoder = recordEncoder self.key = key } func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> where Key: CodingKey { // Keyed values require JSON encoding: we need to throw // JSONRequiredError. Since we can't throw right from here, let's // delegate the job to a dedicated container. requiresJSON = true let container = JSONRequiredEncoder<Record>.KeyedContainer<Key>(codingPath: codingPath) return KeyedEncodingContainer(container) } func unkeyedContainer() -> UnkeyedEncodingContainer { // Keyed values require JSON encoding: we need to throw // JSONRequiredError. Since we can't throw right from here, let's // delegate the job to a dedicated container. requiresJSON = true return JSONRequiredEncoder<Record>(codingPath: codingPath) } func singleValueContainer() -> SingleValueEncodingContainer { self } } extension ColumnEncoder: SingleValueEncodingContainer { func encodeNil() throws { recordEncoder.persist(nil, forKey: key) } func encode(_ value: Bool ) throws { recordEncoder.persist(value, forKey: key) } func encode(_ value: Int ) throws { recordEncoder.persist(value, forKey: key) } func encode(_ value: Int8 ) throws { recordEncoder.persist(value, forKey: key) } func encode(_ value: Int16 ) throws { recordEncoder.persist(value, forKey: key) } func encode(_ value: Int32 ) throws { recordEncoder.persist(value, forKey: key) } func encode(_ value: Int64 ) throws { recordEncoder.persist(value, forKey: key) } func encode(_ value: UInt ) throws { recordEncoder.persist(value, forKey: key) } func encode(_ value: UInt8 ) throws { recordEncoder.persist(value, forKey: key) } func encode(_ value: UInt16) throws { recordEncoder.persist(value, forKey: key) } func encode(_ value: UInt32) throws { recordEncoder.persist(value, forKey: key) } func encode(_ value: UInt64) throws { recordEncoder.persist(value, forKey: key) } func encode(_ value: Float ) throws { recordEncoder.persist(value, forKey: key) } func encode(_ value: Double) throws { recordEncoder.persist(value, forKey: key) } func encode(_ value: String) throws { recordEncoder.persist(value, forKey: key) } func encode<T>(_ value: T) throws where T: Encodable { try recordEncoder.encode(value, forKey: key) } } // MARK: - JSONRequiredEncoder /// The error that triggers JSON encoding private struct JSONRequiredError: Error { } /// The encoder that always ends up with a JSONRequiredError private struct JSONRequiredEncoder<Record: EncodableRecord>: Encoder { var codingPath: [CodingKey] var userInfo: [CodingUserInfoKey: Any] { Record.databaseEncodingUserInfo } func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> where Key: CodingKey { let container = KeyedContainer<Key>(codingPath: codingPath) return KeyedEncodingContainer(container) } func unkeyedContainer() -> UnkeyedEncodingContainer { self } func singleValueContainer() -> SingleValueEncodingContainer { self } struct KeyedContainer<KeyType: CodingKey>: KeyedEncodingContainerProtocol { var codingPath: [CodingKey] var userInfo: [CodingUserInfoKey: Any] { Record.databaseEncodingUserInfo } func encodeNil(forKey key: KeyType) throws { throw JSONRequiredError() } func encode(_ value: Bool, forKey key: KeyType) throws { throw JSONRequiredError() } func encode(_ value: Int, forKey key: KeyType) throws { throw JSONRequiredError() } func encode(_ value: Int8, forKey key: KeyType) throws { throw JSONRequiredError() } func encode(_ value: Int16, forKey key: KeyType) throws { throw JSONRequiredError() } func encode(_ value: Int32, forKey key: KeyType) throws { throw JSONRequiredError() } func encode(_ value: Int64, forKey key: KeyType) throws { throw JSONRequiredError() } func encode(_ value: UInt, forKey key: KeyType) throws { throw JSONRequiredError() } func encode(_ value: UInt8, forKey key: KeyType) throws { throw JSONRequiredError() } func encode(_ value: UInt16, forKey key: KeyType) throws { throw JSONRequiredError() } func encode(_ value: UInt32, forKey key: KeyType) throws { throw JSONRequiredError() } func encode(_ value: UInt64, forKey key: KeyType) throws { throw JSONRequiredError() } func encode(_ value: Float, forKey key: KeyType) throws { throw JSONRequiredError() } func encode(_ value: Double, forKey key: KeyType) throws { throw JSONRequiredError() } func encode(_ value: String, forKey key: KeyType) throws { throw JSONRequiredError() } func encode<T>(_ value: T, forKey key: KeyType) throws where T: Encodable { throw JSONRequiredError() } func nestedContainer<NestedKey>( keyedBy keyType: NestedKey.Type, forKey key: KeyType) -> KeyedEncodingContainer<NestedKey> where NestedKey: CodingKey { let container = KeyedContainer<NestedKey>(codingPath: codingPath + [key]) return KeyedEncodingContainer(container) } func nestedUnkeyedContainer(forKey key: KeyType) -> UnkeyedEncodingContainer { JSONRequiredEncoder(codingPath: codingPath) } func superEncoder() -> Encoder { JSONRequiredEncoder(codingPath: codingPath) } func superEncoder(forKey key: KeyType) -> Encoder { JSONRequiredEncoder(codingPath: codingPath) } } } extension JSONRequiredEncoder: SingleValueEncodingContainer { func encodeNil() throws { throw JSONRequiredError() } func encode(_ value: Bool ) throws { throw JSONRequiredError() } func encode(_ value: Int ) throws { throw JSONRequiredError() } func encode(_ value: Int8 ) throws { throw JSONRequiredError() } func encode(_ value: Int16 ) throws { throw JSONRequiredError() } func encode(_ value: Int32 ) throws { throw JSONRequiredError() } func encode(_ value: Int64 ) throws { throw JSONRequiredError() } func encode(_ value: UInt ) throws { throw JSONRequiredError() } func encode(_ value: UInt8 ) throws { throw JSONRequiredError() } func encode(_ value: UInt16) throws { throw JSONRequiredError() } func encode(_ value: UInt32) throws { throw JSONRequiredError() } func encode(_ value: UInt64) throws { throw JSONRequiredError() } func encode(_ value: Float ) throws { throw JSONRequiredError() } func encode(_ value: Double) throws { throw JSONRequiredError() } func encode(_ value: String) throws { throw JSONRequiredError() } func encode<T>(_ value: T) throws where T: Encodable { throw JSONRequiredError() } } extension JSONRequiredEncoder: UnkeyedEncodingContainer { var count: Int { 0 } mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer<NestedKey> where NestedKey: CodingKey { let container = KeyedContainer<NestedKey>(codingPath: codingPath) return KeyedEncodingContainer(container) } mutating func nestedUnkeyedContainer() -> UnkeyedEncodingContainer { self } mutating func superEncoder() -> Encoder { self } } @available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) private var iso8601Formatter: ISO8601DateFormatter = { let formatter = ISO8601DateFormatter() formatter.formatOptions = .withInternetDateTime return formatter }() extension DatabaseDateEncodingStrategy { @inline(__always) fileprivate func encode(_ date: Date) -> DatabaseValueConvertible? { switch self { case .deferredToDate: return date.databaseValue case .timeIntervalSinceReferenceDate: return date.timeIntervalSinceReferenceDate case .timeIntervalSince1970: return date.timeIntervalSince1970 case .millisecondsSince1970: return Int64(floor(1000.0 * date.timeIntervalSince1970)) case .secondsSince1970: return Int64(floor(date.timeIntervalSince1970)) case .iso8601: if #available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) { return iso8601Formatter.string(from: date) } else { fatalError("ISO8601DateFormatter is unavailable on this platform.") } case .formatted(let formatter): return formatter.string(from: date) case .custom(let format): return format(date) } } } extension DatabaseUUIDEncodingStrategy { @inline(__always) fileprivate func encode(_ uuid: UUID) -> DatabaseValueConvertible? { switch self { case .deferredToUUID: return uuid.databaseValue case .string: return uuid.uuidString } } }
49.466125
116
0.663836
acef3941da8589b170453e5f97ff2dd5e4e855a6
675
// // CalculatorButton.swift // HelloWorld // // Created by 冯旭超 on 2020/3/19. // Copyright © 2020 冯旭超. All rights reserved. // import SwiftUI struct CalculatorButton: View { let fontSize: CGFloat = 38 let title: String let size: CGSize let backgroundColorName: String let action: () -> Void var body: some View { Button(action: action) { Text(title) .font(.system(size: fontSize)) .foregroundColor(.white) .frame(width: size.width, height: size.width) .background(Color(backgroundColorName)) .cornerRadius(size.width / 2) } } }
23.275862
61
0.571852
1aa0d050ac954455e2734f2e4c88ee115c189903
6,495
/* * Copyright (c) 2015 Razeware LLC * * 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 let fileSystemRootURL = NSURL.fileURLWithPath("/", isDirectory: true) class ViewController: NSViewController { @IBOutlet weak var tableView:NSTableView! @IBOutlet weak var statusLabel:NSTextField! let sizeFormatter = NSByteCountFormatter() var directory:Directory? var directoryItems:[Metadata]? var sortOrder = Directory.FileOrder.Name var sortAscending = true var dateFormatter:NSDateFormatter { let formatter = NSDateFormatter() formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" return formatter } override func viewDidLoad() { super.viewDidLoad() tableView.setDelegate(self) tableView.setDataSource(self) tableView.target = self tableView.doubleAction = #selector(tableViewDoubleClick(_:)) // 1 let descriptorName = NSSortDescriptor(key: Directory.FileOrder.Name.rawValue, ascending: true) let descriptorDate = NSSortDescriptor(key: Directory.FileOrder.Date.rawValue, ascending: true) let descriptorSize = NSSortDescriptor(key: Directory.FileOrder.Size.rawValue, ascending: true) // 2 tableView.tableColumns[1].sortDescriptorPrototype = descriptorName; tableView.tableColumns[2].sortDescriptorPrototype = descriptorDate; tableView.tableColumns[3].sortDescriptorPrototype = descriptorSize; statusLabel.stringValue = "" } var rootURL: NSURL? { return representedObject as? NSURL } override var representedObject: AnyObject? { didSet { if let url = representedObject as? NSURL { directory = Directory(folderURL:url) reloadFileList() } } } @IBAction func revealSelectedButtonClick(sender:AnyObject){ let row = tableView.rowForView(sender as! NSView) if let item = directoryItems?[row] { NSWorkspace.sharedWorkspace().selectFile(item.url.path, inFileViewerRootedAtPath: "") } } func tableViewDoubleClick(sender:AnyObject){ guard tableView.selectedRow >= 0, let item = directoryItems?[tableView.selectedRow] else { return } // ignore current directory item click guard tableView.selectedRow != 1 else { return } print("tableViewDoubleClick: \(item.url)") if item.isFolder { self.representedObject = item.url }else { NSWorkspace.sharedWorkspace().openURL(item.url) } } func reloadDirectoryItems(){ directoryItems = directory?.contentsOrderedBy(sortOrder, ascending: sortAscending) guard let currentURL = self.rootURL else { return } if let firstItem = Metadata.create(fileURL: currentURL, withName: ".") { directoryItems?.insert(firstItem, atIndex: 0) } guard let parentURL = currentURL.URLByDeletingLastPathComponent else { return } guard fileSystemRootURL != currentURL else { return } if let firstItem = Metadata.create(fileURL: parentURL, withName: "..") { directoryItems?.insert(firstItem, atIndex: 0) } } func reloadFileList(){ reloadDirectoryItems() tableView.reloadData() updateStatus() } func updateStatus(){ guard let rootURL = self.rootURL else { return } guard let rootPath = rootURL.path else { return } let text:String let itemsSelected = tableView.selectedRowIndexes.count if directoryItems == nil { text = "" }else if itemsSelected == 0 { text = "\(directoryItems!.count) items in \(rootPath)" }else if itemsSelected == 1 { text = directoryItems?[tableView.selectedRow].url.path ?? "ERROR" } else { text = "\(itemsSelected) of \(directoryItems!.count) selected" } statusLabel.stringValue = text self.view.window?.title = "File Viewer " + rootPath } } extension ViewController : NSTableViewDataSource { func numberOfRowsInTableView(tableView: NSTableView) -> Int { return directoryItems?.count ?? 0 } func tableView(tableView: NSTableView, sortDescriptorsDidChange oldDescriptors: [NSSortDescriptor]) { guard let sortDescriptor = tableView.sortDescriptors.first else { return } if let order = Directory.FileOrder(rawValue: sortDescriptor.key!) { sortOrder = order sortAscending = sortDescriptor.ascending } reloadFileList() } } extension ViewController: NSTableViewDelegate { func tableViewSelectionDidChange(notification: NSNotification) { updateStatus() } func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? { var image:NSImage? var text = "" var cellIdentifier = "" guard let item = directoryItems?[row] else { return nil } if tableColumn == tableView.tableColumns[0] { cellIdentifier = "ActionCell" }else if tableColumn == tableView.tableColumns[1] { image = item.icon text = item.name cellIdentifier = "NameCell" }else if tableColumn == tableView.tableColumns[2] { text = self.dateFormatter.stringFromDate(item.date) cellIdentifier = "DateCell" }else if tableColumn == tableView.tableColumns[3] { text = item.isFolder ? "--" : sizeFormatter.stringFromByteCount(item.size) cellIdentifier = "SizeCell" } if let cell = tableView.makeViewWithIdentifier(cellIdentifier, owner: nil) as? NSTableCellView { cell.textField?.stringValue = text cell.imageView?.image = image return cell } return nil } }
31.838235
111
0.708083
5d7a708659cf31a456fbb960d34fd7086dca4809
1,014
// RUN: %target-run-simple-swift( -Xfrontend -disable-availability-checking -parse-as-library) | %FileCheck %s // REQUIRES: executable_test // REQUIRES: concurrency // rdar://76038845 // REQUIRES: concurrency_runtime // UNSUPPORTED: back_deployment_runtime class X { init() { print("X: init") } deinit { print("X: deinit") } } struct Boom: Error {} @available(SwiftStdlib 5.1, *) func test_detach() async { let x = X() let h = detach { print("inside: \(x)") } await h.get() // CHECK: X: init // CHECK: inside: main.X // CHECK: X: deinit } @available(SwiftStdlib 5.1, *) func test_detach_throw() async { let x = X() let h = detach { print("inside: \(x)") throw Boom() } do { try await h.get() } catch { print("error: \(error)") } // CHECK: X: init // CHECK: inside: main.X // CHECK: error: Boom() } @available(SwiftStdlib 5.1, *) @main struct Main { static func main() async { await test_detach() await test_detach_throw() } }
17.482759
110
0.609467
618a11acc7330355a5e5aa71fbd95814f1f0cd53
333
// // Brand.swift // ModelSynchro // // Created by Jonathan Samudio on 01/04/18. // Copyright © 2018 Prolific Interactive. All rights reserved. // /* Auto-Generated using ModelSynchro */ struct Brand: Codable { let id: Int let name: String enum CodingKeys: String, CodingKey { case id = "id" case name = "name" } }
15.857143
63
0.663664
5de7cd5f5b24774315553d81f9b4eece98eaf8a7
1,326
// // SampleTreeDataSource.swift // ImageDocker // // Created by Kelvin Wong on 2020/2/1. // Copyright © 2020 nonamecat. All rights reserved. // import Foundation class SampleDataSource1: StaticTreeDataSource { override init() { super.init() var tree_data:[TreeCollection] = [] for i in 1...3 { let tree = TreeCollection("root_\(i)") tree.addChild("leaf_1") tree.addChild("leaf_2") tree.addChild("leaf_3") tree.getChild("leaf_1")!.addChild("grand_1") tree.getChild("leaf_1")!.addChild("grand_2") tree.getChild("leaf_1")!.addChild("grand_3") tree.getChild("leaf_3")!.addChild("grand_a") tree.getChild("leaf_3")!.addChild("grand_b") tree.getChild("leaf_3")!.addChild("grand_c") tree.getChild("leaf_3")!.addChild("grand_d_very_long_long_long_long_text_to_see_next_line") tree_data.append(tree) } for data in tree_data { flattable_all.append(data) // print("flatted: \(data.path)") flattable_all.append(contentsOf: data.getUnlimitedDepthChildren()) } // print("total \(flattable_all.count) node") self.filter(keyword: "") self.convertFlatToTree() } }
31.571429
103
0.589744
509181861e1820766ee97d6c3575e99e61bdde07
1,219
import XCTest import Combine @testable import PublishedKVO final class PublishedKVOTests: XCTestCase { func testPublishedKVO() { var step = 0 // step 0 = start, step 1 = first publisher value, ... let exp = expectation(description: "testPublishedKVO") class Example { @PublishedKVO(\.completedUnitCount) var progress = Progress(totalUnitCount: 5) } let ex = Example() XCTAssertEqual(ex.progress.completedUnitCount, 0) let c1 = ex.$progress.sink { object in switch step { case 0: XCTAssertEqual(object.completedUnitCount, 0) step += 1 case 1: XCTAssertEqual(object.completedUnitCount, 1) step += 1 case 2: XCTAssertEqual(object.completedUnitCount, 2) step += 1 case 3: XCTAssertEqual(object.completedUnitCount, 2) step += 1 case 4: XCTAssertEqual(object.completedUnitCount, 2) exp.fulfill() default: XCTFail("unexpected case") } } ex.progress.completedUnitCount += 1 ex.progress.completedUnitCount += 1 ex.$progress.emit() ex.$progress.send(ex.progress) waitForExpectations(timeout: 1) c1.cancel() } static var allTests = [ ("testPublishedKVO", testPublishedKVO), ] }
22.574074
69
0.672683
0353b7a38bf897b1d70ccc4202765be274eb97a0
1,145
// // FacetOrdering.swift // // // Created by Vladislav Fitc on 15/06/2021. // import Foundation /// Facets and facets values ordering rules container public struct FacetOrdering { /// The ordering of facets. public let facets: FacetsOrder /// The ordering of facet values, within an individual list. public let values: [Attribute: FacetValuesOrder] /** - parameters: - facets: The ordering of facets. - values: The ordering of facet values, within an individual list. */ public init(facets: FacetsOrder = .init(), values: [Attribute: FacetValuesOrder] = [:]) { self.facets = facets self.values = values } } extension FacetOrdering: Codable { enum CodingKeys: String, CodingKey { case facets case values } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.facets = try container.decodeIfPresent(forKey: .facets) ?? FacetsOrder() let rawValues = try container.decodeIfPresent([String: FacetValuesOrder].self, forKey: .values) ?? [:] self.values = rawValues.mapKeys(Attribute.init) } }
24.361702
106
0.686463
090ac3921378328033e726466b13ee2b16e5dea5
705
// // SymmetricCipher.swift // Envelope // // Created by George Lim on 2019-08-02. // Copyright © 2019 George Lim. All rights reserved. // import Foundation public protocol SymmetricCipher { var sharedSecret: CFData { get } func encrypt(_ plaintext: Data) throws -> Data func decrypt(_ ciphertext: Data) throws -> Data func encrypt(_ plaintext: String) throws -> Data func decrypt(_ ciphertext: Data) throws -> String? } public extension SymmetricCipher { func encrypt(_ plaintext: String) throws -> Data { return try encrypt(Data(plaintext.utf8)) } func decrypt(_ ciphertext: Data) throws -> String? { return try String(data: decrypt(ciphertext), encoding: .utf8) } }
23.5
65
0.703546
0eff97e56f83e0e2ef2155d169209ded56ff3e54
2,905
// // RedirectionCoordinator.swift // XCoordinator // // Created by Paul Kraft on 08.12.18. // Copyright © 2018 QuickBird Studios. All rights reserved. // import Foundation open class RedirectionCoordinator<RouteType: Route, TransitionType: TransitionProtocol>: Coordinator { // MARK: - Stored properties private let superTransitionPerformer: AnyTransitionPerformer<TransitionType> private let viewControllerBox = ReferenceBox<UIViewController>() private let _prepareTransition: ((RouteType) -> TransitionType)? // MARK: - Computed properties public var rootViewController: TransitionType.RootViewController { return superTransitionPerformer.rootViewController } open var viewController: UIViewController! { return viewControllerBox.get() } // MARK: - Init public init(viewController: UIViewController, superTransitionPerformer: AnyTransitionPerformer<TransitionType>, prepareTransition: ((RouteType) -> TransitionType)?) { viewControllerBox.set(viewController) self.superTransitionPerformer = superTransitionPerformer _prepareTransition = prepareTransition } public convenience init<T: TransitionPerformer>(viewController: UIViewController, superTransitionPerformer: T, prepareTransition: ((RouteType) -> TransitionType)?) where T.TransitionType == TransitionType { self.init( viewController: viewController, superTransitionPerformer: AnyTransitionPerformer(superTransitionPerformer), prepareTransition: prepareTransition ) } // MARK: - Methods open func presented(from presentable: Presentable?) { viewController?.presented(from: presentable) viewControllerBox.releaseStrongReference() } open func prepareTransition(for route: RouteType) -> TransitionType { guard let prepareTransition = _prepareTransition else { fatalError("Please override \(#function) or provide a prepareTransition-closure in the initializer.") } return prepareTransition(route) } public func performTransition(_ transition: TransitionType, with options: TransitionOptions, completion: PresentationHandler?) { superTransitionPerformer.performTransition(transition, with: options, completion: completion) } } // MARK: - Deprecated extension RedirectionCoordinator { @available(*, deprecated, renamed: "init(viewController:superTransitionPerfomer:prepareTransition:)") public convenience init<C: Coordinator>(viewController: UIViewController, superCoordinator: C, prepareTransition: ((RouteType) -> TransitionType)?) where C.TransitionType == TransitionType { self.init( viewController: viewController, superTransitionPerformer: AnyTransitionPerformer(superCoordinator), prepareTransition: prepareTransition ) } }
38.223684
210
0.733907
ff08c2d78a13aa881817ccffeddc5f3580d0f47a
4,154
// // AloyInterceptorProtocol.swift // AloyNetworking // // Copyright © 2022 Nunzio Giulio Caggegi All rights reserved. // import Combine import Foundation // MARK: - RequestAdapter public protocol RequestAdapter { /// Inspects and adapts the specified `URLRequest` in some manner and return the request. /// - Parameter urlRequest: The final request to adapt /// - Returns: The final URLRequest to send func adapt(_ urlRequest: URLRequest) -> URLRequest } // MARK: - RetryAdapter public protocol RetryAdapter { @available(iOS 15.0.0, *) func retry(_ request: URLRequest, for session: URLSession, dueTo error: Error?) async throws -> RetryResult // MARK: - iOS > 15 Protocols /// This func must be used to execute code before retry a failed request in `async-await` version. After the code, you must return a RetryResult /// /// This is an example of Future usage /// /// do { /// let _ = try await webService.sendRequest(request: request) /// return .retry /// } catch { /// return .doNotRetry /// } /// /// - Parameter request: The request failes /// - Parameter session: The session that generated the failed request /// - Parameter error: The error generated by the request failed /// - Returns: The `RetryResult` to determinate if the system must retry the failed request. @available(iOS 13.0, *) func retry(_ request: URLRequest, for session: URLSession, dueTo error: Error?) -> AnyPublisher<RetryResult, Error> // MARK: - iOS > 13 Protocols /// This func must be used to execute code before retry a failed request in Combine version. After the code, you must return a Future with RetryResult /// /// This is an example of Future usage /// /// return Future { promise in /// webService.sendRequest(request: request) /// .sink { completion in /// promise(.success(.doNotRetry)) /// } receiveValue: { results in /// promise(.success(.retry)) /// } /// }.eraseToAnyPublisher() /// /// - Parameter request: The request failes /// - Parameter session: The session that generated the failed request /// - Parameter error: The error generated by the request failed /// - Returns: AnyPublisher with `RetryResult` to determinate if the system must retry the failed request. func retry(_ request: URLRequest, for session: URLSession, dueTo error: Error?, completion: @escaping (RetryResult) -> Void) // MARK: - iOS < 13 Protocols /// This func must be used to execute code before retry a failed request. After the code, you must launch a closure with a RetryResult enum /// /// This is an example: /// /// webService.sendRequest(request: request) { completionResult in /// switch completionResult { /// case .success(_): /// completion(.retry) /// case .failure(_): /// completion(.doNotRetry) /// } /// } /// /// - Parameter request: The request failes /// - Parameter session: The session that generated the failed request /// - Parameter error: The error generated by the request failed /// - Parameter completion: Completion closure to be executed when a retry decision has been determined. } // MARK: - AloyInterceptorProtocol public protocol AloyInterceptorProtocol: RequestAdapter, RetryAdapter {} public extension AloyInterceptorProtocol { func adapt(_ urlRequest: URLRequest) -> URLRequest { return urlRequest } @available(iOS 13.0, *) func retry(_: URLRequest, for _: URLSession, dueTo _: Error?) -> AnyPublisher<RetryResult, Error> { return Future { promise in promise(.success(.doNotRetry)) }.eraseToAnyPublisher() } func retry(_: URLRequest, for _: URLSession, dueTo _: Error?, completion: @escaping (RetryResult) -> Void) { completion(.doNotRetry) } } // MARK: - RetryResult /// Outcome of determination whether retry is necessary. public enum RetryResult { /// Retry should be attempted immediately. case retry /// Do not retry. case doNotRetry }
34.616667
152
0.662013
692784bbd8b597a89c113a83d27cd73a45ec2ed5
4,083
import Foundation /** A wrapper for the `UserDefaults` class for navigation-specific settings. Properties are prefixed before they are stored in `UserDefaults.standard`. To specify criteria when calculating routes, use the `NavigationRouteOptions` class. To customize the user experience during a particular turn-by-turn navigation session, use the `NavigationOptions` class when initializing a `NavigationViewController`. */ public class NavigationSettings { public enum StoredProperty: CaseIterable { case voiceVolume, voiceMuted, distanceUnit public var key: String { switch self { case .voiceVolume: return "voiceVolume" case .voiceMuted: return "voiceMuted" case .distanceUnit: return "distanceUnit" } } } /** The volume that the voice controller will use. This volume is relative to the system’s volume where 1.0 is same volume as the system. */ public dynamic var voiceVolume: Float = 1.0 { didSet { notifyChanged(property: .voiceVolume, value: voiceVolume) } } /** Specifies whether to mute the voice controller or not. */ public dynamic var voiceMuted : Bool = false { didSet { notifyChanged(property: .voiceMuted, value: voiceMuted) } } /** Specifies the preferred distance measurement unit. - note: Anything but `kilometer` and `mile` will fall back to the default measurement for the current locale. Meters and feets will be used when the presented distances are small enough. See `DistanceFormatter` for more information. */ public dynamic var distanceUnit : LengthFormatter.Unit = Locale.current.usesMetric ? .kilometer : .mile { didSet { notifyChanged(property: .distanceUnit, value: distanceUnit.rawValue) } } var usesMetric: Bool { get { switch distanceUnit { case .kilometer: return true case .mile: return false default: return Locale.current.usesMetric } } } /** The shared navigation settings object that affects the entire application. */ public static let shared = NavigationSettings() /// Returns a reflection of this class excluding the `properties` variable. lazy var properties: [Mirror.Child] = { let properties = Mirror(reflecting: self).children return properties.filter({ (child) -> Bool in if let label = child.label { return label != "properties.storage" && label != "$__lazy_storage_$_properties" } return false }) }() private func notifyChanged(property: StoredProperty, value: Any) { UserDefaults.standard.set(value, forKey: property.key.prefixed) NotificationCenter.default.post(name: .navigationSettingsDidChange, object: nil, userInfo: [property.key: value]) } private func setupFromDefaults() { for property in StoredProperty.allCases { guard let val = UserDefaults.standard.object(forKey: property.key.prefixed) else { continue } switch property { case .voiceVolume: if let volume = val as? Float { voiceVolume = volume } case .voiceMuted: if let muted = val as? Bool { voiceMuted = muted } case .distanceUnit: if let value = val as? Int, let unit = LengthFormatter.Unit(rawValue: value) { distanceUnit = unit } } } } init() { setupFromDefaults() } } extension String { fileprivate var prefixed: String { return "MB" + self } }
32.664
253
0.579476
69259cb131bcc35e20a4bc7ad6a91fe2794f8f59
756
import XCTest import UselessValidatorPod class Tests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } }
26.068966
111
0.60582
382647d8ad7562449c2d0d62c827b9f2457a73db
6,779
// // Blessing.swift // Blessing // // Created by k on 02/11/2016. // Copyright © 2016 egg. All rights reserved. // import Foundation public enum Server: CustomStringConvertible { case dnspod case qcloud(id: Int, key: String) // id, key case aliyun(account: String) public var description: String { switch self { case .qcloud: return "QCloud" case .dnspod: return "DNSPod" case .aliyun: return "AliYun" } } } public enum Result<T> { case success(T) case failure(Error) public var value: T? { switch self { case .success(let value): return value case .failure: return nil } } public var error: Error? { switch self { case .success: return nil case .failure(let error): return error } } } extension Result { public func map<U>(_ transform: (T) -> U) -> Result<U> { switch self { case .success(let value): return .success(transform(value)) case .failure(let error): return .failure(error) } } public func flatMap<U>(_ transform: (T) -> Result<U>) -> Result<U> { switch self { case .success(let value): return transform(value) case .failure(let error): return .failure(error) } } } protocol RecordType { associatedtype T var ips: [T] { get } var ttl: Int { get } var timestamp: TimeInterval { get } var isExpired: Bool { get } } extension RecordType { var isExpired: Bool { return Date().timeIntervalSince1970 > (timestamp + Double(ttl)) } } public struct Record: RecordType { public typealias T = String public var ips: [T] public var ttl: Int public var timestamp: TimeInterval } public class Blessing { public static let shared = Blessing() private init() { manager = NetworkReachabilityManager() bindListener() } public var debug: Bool = false private let cache: Cache<Record> = Cache() private let manager: NetworkReachabilityManager? private var host: String = "" private var server: Server = .dnspod /// Async query public func query(_ host: String, on server: Server = .dnspod, queue: DispatchQueue = .main, handler: ((Result<Record>) -> Void)? = nil) { self.host = host self.server = server let isDebug = debug // cache if let record = cache.get(for: host) { if isDebug { print("**Blessing**: Async query `\(host)` on \(server), record from cache.") } handler?(.success(record)) return } switch server { case .dnspod: URLSessionRequestSender.shared.send(DnspodRequest(domain: host), queue: queue) { [weak self] (result: Result<Dnspod>) in let record = result.map { $0.toRecord() } handler?(record) if let value = record.value { self?.cache.set(value, for: host) } if isDebug { print("**Blessing**: Async query `\(host)` on \(server), record from server.") print("**Blessing**: \(record.value)") } } case let .qcloud(id, key): URLSessionRequestSender.shared.send(QcloudRequest(domain: host, id: id, key: key), queue: queue) { [weak self] (result: Result<Qcloud>) in let record = result.map { $0.toRecord() } handler?(record) if let value = record.value { self?.cache.set(value, for: host) } if isDebug { print("**Blessing**: Async query `\(host)` on \(server), record from server.") print("**Blessing**: \(record.value)") } } case .aliyun(let account): URLSessionRequestSender.shared.send(AliyunRequest(domain: host, account: account), queue: queue) { [weak self] (result: Result<Aliyun>) in let record = result.map { $0.toRecord() } handler?(record) if let value = record.value { self?.cache.set(value, for: host) } if isDebug { print("**Blessing**: Async query `\(host)` on \(server), record from server.") print("**Blessing**: \(record.value)") } } } } /// Sync query public func query(_ host: String, on server: Server = .dnspod) -> Result<Record> { self.host = host self.server = server // cache if let record = cache.get(for: host) { if debug { print("**Blessing**: Sync query `\(host)` on \(server), record from cache.") } return .success(record) } let record: Result<Record> switch server { case .dnspod: let result = URLSessionRequestSender.shared.send(DnspodRequest(domain: host)) record = result.map { $0.toRecord() } case let .qcloud(id, key): let result = URLSessionRequestSender.shared.send(QcloudRequest(domain: host, id: id, key: key)) record = result.map { $0.toRecord() } case .aliyun(let account): let result = URLSessionRequestSender.shared.send(AliyunRequest(domain: host, account: account)) record = result.map { $0.toRecord() } } if let value = record.value { self.cache.set(value, for: host) print("**Blessing**: Sync query `\(host)` on \(server), record from server.") print("**Blessing**: \(value)") } return record } private func bindListener() { manager?.listener = { [weak self] status in guard let sSelf = self else { return } switch status { case .notReachable: if sSelf.debug { print("**Blessing**: Network not reachable.") } return case .unknown: if sSelf.debug { print("**Blessing**: Unknown network.") } case .reachable(let type): if sSelf.debug { print("**Blessing**: Connected with \(type).") } } sSelf.cache.clean() if !sSelf.host.isEmpty { sSelf.query(sSelf.host, on: sSelf.server, handler: nil) } } manager?.startListening() } }
28.724576
150
0.517038
0e4198de47143f0e1fd38231f59ab89482a9370a
3,837
// // RepositoryListActionCreatorTests.swift // SwiftUI-FluxTests // // Created by Yusuke Kita on 6/15/19. // Copyright © 2019 Yusuke Kita. All rights reserved. // import Foundation import Combine import XCTest @testable import SwiftUI_Flux final class RepositoryListActionCreatorTests: XCTestCase { private let dispatcher: RepositoryListDispatcher = .shared func test_updateRepositoriesWhenOnAppear() { let apiService = MockAPIService() apiService.stub(for: SearchRepositoryRequest.self) { _ in Result.Publisher( SearchRepositoryResponse( items: [.init(id: 1, fullName: "foo", owner: .init(id: 2, login: "bar", avatarUrl: URL(string: "baz")!))] ) ) .eraseToAnyPublisher() } let actionCreator = makeActionCreator(apiService: apiService) var repositories: [Repository] = [] dispatcher.register { (action) in switch action { case .updateRepositories(let value): repositories.append(contentsOf: value) default: break } } actionCreator.onAppear() XCTAssertTrue(!repositories.isEmpty) } func test_serviceErrorWhenOnAppear() { let apiService = MockAPIService() apiService.stub(for: SearchRepositoryRequest.self) { _ in Result.Publisher( APIServiceError.responseError ).eraseToAnyPublisher() } let actionCreator = makeActionCreator(apiService: apiService) let expectation = self.expectation(description: "error") var errorShown = false dispatcher.register { (action) in switch action { case .showError: errorShown = true XCTAssertTrue(errorShown) expectation.fulfill() default: break } } actionCreator.onAppear() wait(for: [expectation], timeout: 3.0) } func test_logListViewWhenOnAppear() { let trackerService = MockTrackerService() let actionCreator = makeActionCreator(trackerService: trackerService) actionCreator.onAppear() XCTAssertTrue(trackerService.loggedTypes.contains(.listView)) } func test_showIconEnabledWhenOnAppear() { let experimentService = MockExperimentService() experimentService.stubs[.showIcon] = true let actionCreator = makeActionCreator(experimentService: experimentService) var iconShown = false dispatcher.register { (action) in switch action { case .showIcon: iconShown = true default: break } } actionCreator.onAppear() XCTAssertTrue(iconShown) } func test_showIconDisabledWhenOnAppear() { let experimentService = MockExperimentService() experimentService.stubs[.showIcon] = false let actionCreator = makeActionCreator(experimentService: experimentService) var iconShown = false dispatcher.register { (action) in switch action { case .showError: iconShown = true default: break } } actionCreator.onAppear() XCTAssertFalse(iconShown) } private func makeActionCreator( apiService: APIServiceType = MockAPIService(), trackerService: TrackerType = MockTrackerService(), experimentService: ExperimentServiceType = MockExperimentService() ) -> RepositoryListActionCreator { return .init( dispatcher: dispatcher, apiService: apiService, trackerService: trackerService, experimentService: experimentService ) } }
32.794872
125
0.614543
bb4ce31da61dd76150603e407df53362e7346bda
16,084
// // CalculatorCtrlr.swift // hnup // // Created by CP3 on 16/5/12. // Copyright © 2016年 DataYP. All rights reserved. // import UIKit struct CalStack<Element> { fileprivate var elements = [Element]() mutating func push(_ element: Element) { elements.append(element) #if DEBUG print("--- push \((element as! CalOperation).character) ---") printArray() #endif } @discardableResult mutating func pop() -> Element? { let element = elements.popLast() #if DEBUG if let a = element { print("--- pop \((a as! CalOperation).character) ---") } else { print("--- pop nil ---") } printArray() #endif return element } var topItem: Element? { return elements.last } var count: Int { return elements.count } mutating func removeAll() { elements.removeAll() } var secondItem: Element? { if elements.count >= 2 { return elements[elements.count - 2] } return nil } #if DEBUG func printArray() { print("stack: \n(") for op in elements { print(" ", (op as! CalOperation).character, ",") } print(")\n") } #endif } public final class Calculator: UIViewController { fileprivate let expressionLabel = UILabel().fontSize(24).textColor(UIColor(rgbHexValue: 0x999999)).alignRight() fileprivate let resultLabel = UILabel().fontSize(48).textColor(UIColor(rgbHexValue: 0x333333)).alignRight() fileprivate let formatter = NumberFormatter() // 记录用户输入的操作 fileprivate var stack = CalStack<CalOperation>() // 备份执行的操作,主要用于用户输入"+/-"之后,变换成"×/÷" fileprivate var backupStack = CalStack<CalOperation>() // 记录用户输入的数字和小数点 fileprivate var userInput = "" // 用户输入的数值或者计算出来的结果 fileprivate var accumulator: Double = 0.0 // 记录表达式 fileprivate var expression = "" { didSet { expressionLabel.text = expression } } // 记录前一个不会变化的表达式 fileprivate var preExpression = "" // 记录用户输入的数值表达式,这个值是不断变化和修正的 fileprivate var inputExpression = "" { didSet { expression = preExpression + inputExpression } } // 标记是否输入了等号 fileprivate var isPreEquality = true // 标记是否输入了运算符 fileprivate var isPreOperator = false /// 计算完成回调,将计算结果返回 public var completion: ((Double) -> Void)? public init() { super.init(nibName: nil, bundle: nil) initFormatter() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initFormatter() } private func initFormatter() { formatter.numberStyle = .decimal formatter.alwaysShowsDecimalSeparator = false formatter.maximumFractionDigits = 8 formatter.exponentSymbol = "e" formatter.positiveInfinitySymbol = "错误" formatter.negativeInfinitySymbol = "错误" } public override func viewDidLoad() { super.viewDidLoad() self.title = "计算器" setupView() } } private extension Calculator { func setupView() { view.backgroundColor = UIColor.white let resultBoardView = { () -> UIView in let resultView = UIView() resultView.backgroundColor = UIColor.white expressionLabel.lineBreakMode = .byTruncatingHead resultLabel.text = "0" resultLabel.adjustsFontSizeToFitWidth = true resultLabel.baselineAdjustment = .alignCenters let space1 = UIView(), space2 = UIView(), space3 = UIView() resultView.addSubview(space1) resultView.addSubview(space2) resultView.addSubview(space3) resultView.addSubview(expressionLabel) resultView.addSubview(resultLabel) [space1, space2, space3, expressionLabel, resultLabel].forEach { view in view.translatesAutoresizingMaskIntoConstraints = false } resultView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[space1][expressionLabel(==29)][space2(==space1)][resultLabel][space3(==space1)]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["space1": space1, "space2": space2, "space3": space3, "expressionLabel": expressionLabel, "resultLabel": resultLabel])) resultView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[space1]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["space1": space1])) resultView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[space2]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["space2": space2])) resultView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[space3]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["space3": space3])) resultView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-15-[expressionLabel]-15-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["expressionLabel": expressionLabel])) resultView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-15-[resultLabel]-15-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["resultLabel": resultLabel])) return resultView }() let inputBoardView = CalInputView() resultBoardView.backgroundColor = UIColor.white view.addSubview(resultBoardView) view.addSubview(inputBoardView) resultBoardView.translatesAutoresizingMaskIntoConstraints = false inputBoardView.translatesAutoresizingMaskIntoConstraints = false view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[topGuide][resultBoardView][inputBoardView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["topGuide": topLayoutGuide, "resultBoardView": resultBoardView, "inputBoardView": inputBoardView])) view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[resultBoardView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["resultBoardView": resultBoardView])) view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[inputBoardView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["inputBoardView": inputBoardView])) view.addConstraint(NSLayoutConstraint(item: resultBoardView, attribute: .height, relatedBy: .equal, toItem: inputBoardView, attribute: .height, multiplier: 0.35, constant: 0)) inputBoardView.userOperation = { [unowned self] operation in self.handleOperation(operation) } } } private extension Calculator { func handleOperation(_ operation: CalOperation) { // 用户点击"="或者"清空(C)"操作之后,清空表达式, if isPreEquality { preExpression = "" inputExpression = "" expression = "" } // 用户输入的不是操作符(+、-、×、÷),清空备份栈内容 if !operation.isOperator { backupStack.removeAll() } // 处理对应的各种操作 switch operation { case .digit(let digit): handleDigit(digit) case .decimalPoint: handleDot() case .addition, .subtraction: handleLowOperation(operation) case .multiplication, .division: handleHighOperation(operation) case .equality: handleEquality() case .clear: handleClearOperator() case .completion: handleComplication() default: break } // 记录上一次的操作是不是等于操作,清空(C)相当于一个结果为0的等于操作 switch operation { case .equality, .clear: isPreEquality = true default: isPreEquality = false } // 记录上一次的操作是不是操作符,如果是操作符,记录此时的表达式 if operation.isOperator { isPreOperator = true preExpression = expression } else { isPreOperator = false } } // 处理输入数字 func handleDigit(_ digit: Int) { // 一次最多输入9个数字,不包括小数点 let hasDot = userInputHasDot() if userInput.characters.count >= (hasDot ? 10 : 9) { return } // 记录用户输入的操作数 userInput += String(digit) accumulator = Double(userInput) ?? 0.0 // 清除前导0 if !hasDot && accumulator == 0 { userInput = "" } // 展示输入数,没有小数点时,格式化;有小数点时,直接添加 if !hasDot { updateResultText(isCalculation: false) } else { resultLabel.text = (resultLabel.text ?? "") + String(digit) inputExpression = resultLabel.text ?? "" } } // 处理输入小数点 func handleDot() { // 已经存在小数点,或者已经输入了9个数字 if userInputHasDot() || userInput.characters.count >= 9 { return } // "."变换成"0." if userInput.isEmpty { userInput = "0." resultLabel.text = "0." } else { userInput += "." resultLabel.text = (resultLabel.text ?? "") + "." } accumulator = Double(userInput) ?? 0.0 inputExpression = resultLabel.text ?? "" } // 处理+、-运算 func handleLowOperation(_ operation: CalOperation) { // 前一个是运算符,出栈 if isPreOperator { //弹出前一个运算符 stack.pop() // 表达式删除前一个运算符 expression.remove(at: expression.characters.index(before: expression.endIndex)) } else { // 将用户输入的操作数入栈 stack.push(.operand(accumulator)) updateResultText(isCalculation: false) } // 1+2+ || 1+2*3+ // 执行之前的运算,1+2+ -> 3+ || 1+2*3+ -> 1+6+ if stack.count >= 3 { if let operand2 = stack.pop(), let operators = stack.pop(), let operand1 = stack.pop() { // 备份操作历史 backupStack.push(operand2) backupStack.push(operators) backupStack.push(operand1) computeAndPushResult(operand1: operand1, operators: operators, operand2: operand2) } } // 1+2*3+ -> 1+6+ -> 7+ // 执行之前的运算 if stack.count >= 3 { if let operand2 = stack.pop(), let operators = stack.pop(), let operand1 = stack.pop() { // 备份操作历史,operand2是上一次的运算结果,所以不需要备份 backupStack.push(operators) backupStack.push(operand1) computeAndPushResult(operand1: operand1, operators: operators, operand2: operand2) } } // 将操作符入栈 pushOperator(operation) } // 处理×、÷运算 func handleHighOperation(_ operation: CalOperation) { // 前一个是运算符,出栈 // userInput.isEmpty有两种情况,一种是前一个是运算符,二是相等操作 // 所以用!isEquality排除不是相等操作的情况 if isPreOperator /*userInput.isEmpty && !isEquality*/ { // 由低运算符变成高运算符,并且之前进行了数学运算,恢复以前的操作,由操作结果恢复成运算表达式 if let topOperator = stack.topItem, topOperator.isLowPriorityOperator && backupStack.count > 0 { // 弹出前一个运算符 stack.pop() //弹出运算结果 stack.pop() // 恢复之前的操作表达式 while let element = backupStack.pop() { stack.push(element) } // 恢复之前的运算中间值 if let topOperation = stack.topItem { if case CalOperation.operand(let value) = topOperation { accumulator = value updateResultText(isCalculation: true) } } } else { // 弹出前一个运算符 stack.pop() } // 表达式删除前一个运算符 expression.remove(at: expression.characters.index(before: expression.endIndex)) } else { // 将用户输入的操作数入栈 stack.push(.operand(accumulator)) updateResultText(isCalculation: false) } // 1+2*3* -> 1+6* if stack.count >= 3 { if let previousOperator = stack.secondItem { switch previousOperator { case .multiplication, .division: popToCompute() default: break } } } // 将操作符入栈 pushOperator(operation) } // 处理"="运算 func handleEquality() { // 前一个是运算符,出栈 if isPreOperator { // 弹出前一个运算符 stack.pop() // 表达式删除前一个运算符 expression.remove(at: expression.characters.index(before: expression.endIndex)) } else { // 将用户输入的操作数入栈 stack.push(.operand(accumulator)) updateResultText(isCalculation: false) } expression += "=" // 1+2= || 1*2= || 1+2*3= if stack.count >= 3 { popToCompute() } // 1+2*3= -> 1+6= if stack.count >= 3 { popToCompute() } // 清空userInput和栈 userInput = "" stack.removeAll() } // 处理清空(C)操作 func handleClearOperator() { resultLabel.text = "0" userInput = "" stack.removeAll() accumulator = 0.0 preExpression = "" inputExpression = "" expression = "" } // 处理完成操作 func handleComplication() { handleEquality() completion?(accumulator) navigationController?.popViewController(animated: true) } //MARK: - Help Methods // 将运算符入栈,清空userInput func pushOperator(_ operation: CalOperation) { stack.push(operation) expression += operation.character userInput = "" } /// 出栈,然后进行数值运算,最后把结果入栈 func popToCompute() { if let operand2 = stack.pop(), let operators = stack.pop(), let operand1 = stack.pop() { computeAndPushResult(operand1: operand1, operators: operators, operand2: operand2) } } // 数学运算然后入栈和显示结果 func computeAndPushResult(operand1: CalOperation, operators: CalOperation, operand2: CalOperation) { if let result = compute(operand1: operand1, operators: operators, operand2: operand2) { stack.push(.operand(result)) accumulator = result updateResultText(isCalculation: true) } } /// 进行加减乘除数学运算 func compute(operand1: CalOperation, operators: CalOperation, operand2: CalOperation) -> Double? { var result: Double? = nil if case CalOperation.operand(let value1) = operand1, case CalOperation.operand(let value2) = operand2 { switch operators { case .addition: result = value1 + value2 case .subtraction: result = value1 - value2 case .multiplication: result = value1 * value2 case .division: result = value1 / value2 default: break } } return result } // 更新resultLabel的内容 func updateResultText(isCalculation: Bool) { if accumulator >= 1000000000 { formatter.numberStyle = .scientific } else { formatter.numberStyle = .decimal } let string = formatter.string(from: NSNumber(value: accumulator)) ?? "0" resultLabel.text = string if !isCalculation { inputExpression = string } } // 判断是否有小数点 func userInputHasDot() -> Bool { return userInput.contains(".") } }
32.691057
361
0.564225
acbeaab8023a5621e74b16d9bce1d52986fbaa35
2,112
// // ScreenBoardViewController.swift // SmartGreenhouseSystem // // Created by Murat Can on 21.11.2020. // import UIKit import paper_onboarding class ScreenBoardViewController: UIViewController { @IBOutlet weak var tutorialButton: UIButton! @IBOutlet weak var onboardingView: PaperOnboarding! let itemArray = [ OnboardingItemInfo(informationImage: UIImage(named: "monitor")!, title: "Monitoring", description: "You can see your current variables on Green Smarthouse System.", pageIcon: UIImage(named: "circle")!, color: .systemGreen, titleColor: .black, descriptionColor: .white, titleFont: UIFont(name: "AvenirNext-Bold", size: 23)!, descriptionFont: UIFont(name: "AvenirNext-Medium", size: 14)!), OnboardingItemInfo(informationImage: UIImage(named: "controlling")!, title: "Controlling", description: "You can remote control your Green Smarthouse System.", pageIcon: UIImage(named: "circle")!, color: .systemPink, titleColor: .black, descriptionColor: .white, titleFont: UIFont(name: "AvenirNext-Bold", size: 23)!, descriptionFont: UIFont(name: "AvenirNext-Medium", size: 14)!), OnboardingItemInfo(informationImage: UIImage(named: "fruits")!, title: "Information", description: "You can read general information about Fruits and Vegetables.", pageIcon: UIImage(named: "circle")!, color: .systemBlue, titleColor: .black, descriptionColor: .white, titleFont: UIFont(name: "AvenirNext-Bold", size: 23)!, descriptionFont: UIFont(name: "AvenirNext-Medium", size: 14)!) ] override func viewDidLoad() { super.viewDidLoad() onboardingView.dataSource = self tutorialButton.titleLabel?.textAlignment = .center tutorialButton.backgroundColor = .lightText } @IBAction func tutorialButtonClicked(_ sender: Any) { } } extension ScreenBoardViewController: PaperOnboardingDataSource { func onboardingItemsCount() -> Int { itemArray.count } func onboardingItem(at index: Int) -> OnboardingItemInfo { itemArray[index] } }
39.111111
395
0.701231
56820a5ea2f672aa191225a46f65304fe6843f06
2,592
// Copyright 2021-22 Jean Bovet // // 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 SwiftUI struct TurnoutShapeView: View { let layout: Layout let category: Turnout.Category let requestedState: Turnout.State let actualState: Turnout.State let shapeContext = ShapeContext() let viewSize = CGSize(width: 64, height: 34) var turnout: Turnout { let t = Turnout() t.category = category t.requestedState = requestedState t.actualState = actualState t.center = .init(x: viewSize.width/2, y: viewSize.height/2) return t } var shape: TurnoutShape { let shape = TurnoutShape(layout: layout, turnout: turnout, shapeContext: shapeContext) return shape } var body: some View { Canvas { context, size in context.withCGContext { context in shape.draw(ctx: context) } }.frame(width: viewSize.width, height: viewSize.height) } } struct TurnoutShapeView_Previews: PreviewProvider { static let layout = LayoutLoop1().newLayout() static var previews: some View { VStack(alignment: .leading) { ForEach(Turnout.Category.allCases, id:\.self) { category in HStack { ForEach(Turnout.states(for: category)) { state in TurnoutShapeView(layout: layout, category: category, requestedState: state, actualState: Turnout.defaultState(for: category)) } } } } } }
39.272727
160
0.670525
729a84870f320ca6b7527443c44620e9206958bd
1,909
// // ArticlesViewController.swift // iYoga // // Created by Kaustubh on 22/06/20. // Copyright © 2020 Kaustubh. All rights reserved. // import UIKit class ArticlesViewController: UIViewController { @IBOutlet var titleLabel: UILabel! @IBOutlet var subLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func loadView() { view = UIView() //view.backgroundColor = UIColor(red:0.93, green:0.93, blue:0.93, alpha:1.0) view.backgroundColor = .white self.configureViews() } // MARK: - View Configuration // MARK: This method will configure View Controller Component(s) func configureViews() { self.loggerMin("") titleLabel = UILabel() titleLabel.text = Constants.labelTexts.iYArticlesTitle titleLabel.font = UIFont.init(name: "Ubuntu-Bold", size: 26.0) titleLabel.textColor = .firstColorOption titleLabel.textAlignment = .center self.view.addSubview(titleLabel) titleLabel.translatesAutoresizingMaskIntoConstraints = false titleLabel.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true titleLabel.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true subLabel = UILabel() subLabel.text = Constants.labelTexts.iYPageNotImplemented subLabel.font = UIFont.init(name: "Ubuntu", size: 20.0) subLabel.textColor = .secondColorOption subLabel.textAlignment = .center self.view.addSubview(subLabel) subLabel.translatesAutoresizingMaskIntoConstraints = false subLabel.centerXAnchor.constraint(equalTo: titleLabel.centerXAnchor).isActive = true subLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 10).isActive = true } }
36.018868
101
0.686747
d5227059ed4e0ae611a1b8c25dc38d7ecab92173
3,669
// // CLUIImage+Extention.swift // TestDemo // // Created by fuyongYU on 2018/5/28. // Copyright © 2018年 YeMaoZi. All rights reserved. // import UIKit extension UIImage { var opaque: Bool { get { let alphaInfo = cgImage?.alphaInfo let opaque = alphaInfo == .noneSkipLast || alphaInfo == .noneSkipFirst || alphaInfo == .none return opaque } } func resizeWidth(to width: CGFloat) -> UIImage? { let height = size.height * width / size.width return resize(to: CGSize(width: width, height: height)) } func resizeHeight(to height: CGFloat) -> UIImage? { let width = size.width * height / size.height return resize(to: CGSize(width: width, height: height)) } func resize(to maxWidthOrHeight: CGFloat) -> UIImage? { if maxWidthOrHeight < size.width && maxWidthOrHeight < size.height { return self } else if size.width > size.height { return resizeWidth(to: maxWidthOrHeight) } else if size.width < size.height { return resizeHeight(to: maxWidthOrHeight) } else { return resize(to: CGSize(width: maxWidthOrHeight, height: maxWidthOrHeight)) } } func resize(to size: CGSize) -> UIImage? { UIGraphicsBeginImageContextWithOptions(size, opaque, scale) draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height)) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } func cropping(in rect: CGRect) -> UIImage? { UIGraphicsBeginImageContextWithOptions(rect.size, opaque, scale) draw(in: CGRect(x: -rect.origin.x, y: -rect.origin.y, width: size.width, height: size.height)) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } func jpegData(with compressionQuality: CGFloat) -> Data? { return UIImageJPEGRepresentation(self, compressionQuality) } func pngData() -> Data? { return UIImagePNGRepresentation(self) } func image(withTintColor color: UIColor) -> UIImage? { UIGraphicsBeginImageContextWithOptions(size, opaque, scale) guard let context = UIGraphicsGetCurrentContext() else { return nil } let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) context.translateBy(x: 0, y: size.height) context.scaleBy(x: 1.0, y: -1.0) context.setBlendMode(.normal) context.clip(to: rect, mask: cgImage!) context.setFillColor(color.cgColor) context.fill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } func image(withBlendColor color: UIColor) -> UIImage? { guard let coloredImage = self.image(withTintColor: color) else { return nil } let filter = CIFilter(name: "CIColorBlendMode") filter?.setValue(ciImage, forKey: kCIInputBackgroundImageKey) filter?.setValue(CIImage(cgImage: coloredImage.cgImage!), forKey: kCIInputImageKey) guard let outputImage = filter?.outputImage else { return nil } let context = CIContext(options: nil) guard let cgImage = context.createCGImage(outputImage, from: outputImage.extent) else { return nil } let image = UIImage(cgImage: cgImage, scale: scale, orientation: imageOrientation) return image } }
33.972222
102
0.623058
90c0ea1bad1caa585697c431c44c3961719797c1
261
class Alive: Command { init() { super.init(syntax: ["alive"], args: 1, exec: { msg, _, room in room.postMessage(":\(msg.id!) Finding for some socks to wear") }) self.description = "to check the status of the bot" } }
29
74
0.551724
331fdc25873e658cbf17ce0500ccbfdc1453e98c
900
// // FilterCell.swift // LetsEat // // Created by iOS 15 Programming on 14/12/2021. // import UIKit class FilterCell: UICollectionViewCell { @IBOutlet var nameLabel: UILabel! @IBOutlet var thumbnailImageView: UIImageView! override func awakeFromNib() { super.awakeFromNib() thumbnailImageView.layer.cornerRadius = 9 thumbnailImageView.layer.masksToBounds = true } } extension FilterCell: ImageFiltering { func set(filterItem: FilterItem, imageForThumbnail: UIImage) { nameLabel.text = filterItem.name if let filter = filterItem.filter { if filter != "None" { let filteredImage = apply(filter: filter, originalImage: imageForThumbnail) thumbnailImageView.image = filteredImage } else { thumbnailImageView.image = imageForThumbnail } } } }
28.125
91
0.644444
71f6f3a673d651f2c97d19b2aebd155b31ecfed3
2,455
// // User.swift // MyTwitter // // Created by Barbara Ristau on 1/22/17. // Copyright © 2017 FeiLabs. All rights reserved. // import UIKit class User: NSObject { var name: String? var screenname: String? var profileUrl: URL? var tagline: String? var followersCount: Int? var followingCount: Int? var profileBannerUrl: URL? var location: String? var favoriteCount: Int? var tweetCount: Int? var dictionary: NSDictionary? init(dictionary: NSDictionary) { self.dictionary = dictionary name = dictionary["name"] as? String screenname = dictionary["screen_name"] as? String favoriteCount = dictionary["favourites_count"] as? Int tweetCount = dictionary["statuses_count"] as? Int if let profileUrlString = dictionary["profile_image_url_https"] as? String { profileUrl = URL(string: profileUrlString) } if let profileBannerUrlString = dictionary["profile_banner_url"] as? String{ profileBannerUrl = URL(string: profileBannerUrlString) } location = dictionary["location"] as? String tagline = dictionary["description"] as? String followersCount = dictionary["followers_count"] as? Int followingCount = dictionary["friends_count"] as? Int } // Setting up Persisitence for Current User static let userDidLogoutNotification = "UserDidLogout" static var _currentUser: User? class var currentUser: User? { get { if _currentUser == nil{ let defaults = UserDefaults.standard let userData = defaults.object(forKey: "currentUserData") as? Data if let userData = userData{ print("I found data cached") if let dictionary = try? JSONSerialization.jsonObject(with: userData, options: .allowFragments){ print("I deserialized the data") _currentUser = User(dictionary: dictionary as! NSDictionary) } } } return _currentUser } set(user) { _currentUser = user let defaults = UserDefaults.standard if let user = user { let data = try! JSONSerialization.data(withJSONObject: user.dictionary!, options: []) defaults.set(data, forKey: "currentUserData") } else { defaults.set(nil, forKey: "currentUserData") } defaults.synchronize() } } }
24.79798
108
0.630957
9ced576ba9d3cbd1db14e23b06f178d08aa97f5b
1,351
// // AppDelegate.swift // SwiftCodeCollection // // Created by 张鸿运 on 2020/12/5. // 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.513514
179
0.746854
46955ec58f27738727a16dbb9163fee02a3af037
2,825
// // ViewController.swift // ToyToastDemo // // Created by Tachibana Kaoru on 4/19/15. // Copyright (c) 2015 Toyship.org. 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. } @IBAction func showDarkGrayToast(_ sender: Any) { let mytoast : ToyToastViewController = ToyToastViewController( title:"Lorem ipsum", message:"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", style:ColorStyle.DarkGray) self.present(mytoast, animated: true, completion: nil) } @IBAction func showLightGrayToast(_ sender: Any) { let mytoast : ToyToastViewController = ToyToastViewController( title:"Lorem ipsum", message:"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", style:ColorStyle.LightGray) self.present(mytoast, animated: true, completion: nil) } @IBAction func showWhiteToast(_ sender: Any) { let mytoast : ToyToastViewController = ToyToastViewController( title:"Lorem ipsum", message:"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", style:ColorStyle.White) self.present(mytoast, animated: true, completion: nil) } @IBAction func showToastLonger(_ sender: Any) { let mytoast : ToyToastViewController = ToyToastViewController( title:"Lorem ipsum", message:"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", style:ColorStyle.DarkGray) mytoast.showtime = 5.0 self.present(mytoast, animated: true, completion: nil) } @IBAction func showToastWithoutTitle(_ sender: Any) { let mytoast : ToyToastViewController = ToyToastViewController( title:"", message:"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", style:ColorStyle.White) self.present(mytoast, animated: true, completion: nil) } }
31.388889
147
0.625487
d5a25ffd912c7580d02f1b3d241450694d45b3d0
1,144
// // ExerciseViewModel.swift // UIPath_ios // // Created by liqc on 2018/11/12. // Copyright © 2018年 liqc. All rights reserved. // import Foundation import Alamofire import SwiftyJSON class ExerciseViewModel { var exercises = [ExerciseData]() func getExercises(chapterId: Int?, onSuccess: @escaping () -> Void, onFail: @escaping (String) -> Void) { guard let chapterId = chapterId else {return onFail("Invalid chapter.")} guard var api = URLComponents(string: exerciseAPI) else {return onFail("Invalid api.")} api.queryItems = [ URLQueryItem(name: "chapter_id", value: "\(chapterId)") ] Alamofire.request(api, method: .get).responseJSON { response in if let error = response.error { return onFail(error.localizedDescription) } guard let data = response.data else { return onFail("have no response data.") } let json = JSON(data) self.exercises = json.arrayValue.map{ExerciseData($0)} return onSuccess() } } }
30.105263
109
0.588287
22353ed90005879570591ca629a928632fcba998
6,292
// // FacebookAuth.swift // FBSDKCoreKit // // Created by Darwin Morocho on 11/10/20. // import Flutter import FBSDKCoreKit import FBSDKLoginKit import Foundation class FacebookAuth: NSObject { let loginManager : LoginManager = LoginManager() var pendingResult: FlutterResult? = nil private var mainWindow: UIWindow? { if let applicationWindow = UIApplication.shared.delegate?.window ?? nil { return applicationWindow } if #available(iOS 13.0, *) { if let scene = UIApplication.shared.connectedScenes.first(where: { $0.session.role == .windowApplication }), let sceneDelegate = scene.delegate as? UIWindowSceneDelegate, let window = sceneDelegate.window as? UIWindow { return window } } return nil } /* handle the platform channel */ public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { let args = call.arguments as? [String: Any] switch call.method { case "login": let permissions = args?["permissions"] as! [String] self.login(permissions: permissions, flutterResult: result) case "getAccessToken": if let token = AccessToken.current, !token.isExpired { let accessToken = getAccessToken(accessToken: token) result(accessToken) }else{ result(nil) } case "getUserData": let fields = args?["fields"] as! String getUserData(fields: fields, flutterResult: result) case "logOut": loginManager.logOut() result(nil) case "updateAutoLogAppEventsEnabled": let enabled = args?["enabled"] as! Bool self.updateAutoLogAppEventsEnabled(enabled: enabled, flutterResult: result) case "isAutoLogAppEventsEnabled": let enabled:Bool = Settings.shared.isAutoLogAppEventsEnabled result(enabled) default: result(FlutterMethodNotImplemented) } } /* use the facebook sdk to request a login with some permissions */ private func login(permissions: [String], flutterResult: @escaping FlutterResult){ let isOK = setPendingResult(methodName: "login", flutterResult: flutterResult) if(!isOK){ return } let viewController: UIViewController = (mainWindow?.rootViewController)! loginManager.logIn(permissions: permissions, tracking: .limited, from: viewController, handler: { (result,error)->Void in if error != nil{ self.finishWithError(errorCode: "FAILED", message: error!.localizedDescription) }else if result!.isCancelled{ self.finishWithError(errorCode: "CANCELLED", message: "User has cancelled login with facebook") }else{ self.finishWithResult(data:self.getAccessToken(accessToken: result!.token! )) } }) } /** retrive the user data from facebook, this could be fail if you are trying to get data without the user autorization permission */ private func getUserData(fields: String, flutterResult: @escaping FlutterResult) { let graphRequest : GraphRequest = GraphRequest(graphPath: "me", parameters: ["fields":fields]) graphRequest.start { (connection, result, error) -> Void in if (error != nil) { self.sendErrorToClient(result: flutterResult, errorCode: "FAILED", message: error!.localizedDescription) } else { let resultDic = result as! NSDictionary flutterResult(resultDic) // sned the response to the client } } } /** Enable or disable the AutoLogAppEvents */ private func updateAutoLogAppEventsEnabled(enabled: Bool,flutterResult: @escaping FlutterResult){ Settings.shared.isAutoLogAppEventsEnabled = enabled flutterResult(nil) } // define a login task private func setPendingResult(methodName: String, flutterResult: @escaping FlutterResult) -> Bool { if(pendingResult != nil){// if we have a previous login task sendErrorToClient(result: pendingResult!, errorCode: "OPERATION_IN_PROGRESS", message: "The method \(methodName) called while another Facebook login operation was in progress.") return false } pendingResult = flutterResult; return true } // send the success response to the client private func finishWithResult(data: Any?){ if (pendingResult != nil) { pendingResult!(data) pendingResult = nil } } // handle the login errors private func finishWithError(errorCode:String, message: String){ if (pendingResult != nil) { sendErrorToClient(result: pendingResult!, errorCode: errorCode, message: message) pendingResult = nil } } // sends a error response to the client private func sendErrorToClient(result:FlutterResult,errorCode:String, message: String){ result(FlutterError(code: errorCode, message: message, details: nil)) } /** get the access token data as a Dictionary */ private func getAccessToken(accessToken: AccessToken) -> [String : Any] { let data = [ "token": accessToken.tokenString, "userId": accessToken.userID, "expires": Int64((accessToken.expirationDate.timeIntervalSince1970*1000).rounded()), "lastRefresh":Int64((accessToken.refreshDate.timeIntervalSince1970*1000).rounded()), "applicationId":accessToken.appID, "isExpired":accessToken.isExpired, "grantedPermissions":accessToken.permissions.map {item in item.name}, "declinedPermissions":accessToken.declinedPermissions.map {item in item.name}, ] as [String : Any] return data; } }
35.348315
189
0.605372
d55d238e05440ffb10e375f344135b102e506130
5,858
// // DateFormatters.swift // SwiftDate // // Created by Daniele Margutti on 06/06/2018. // Copyright © 2018 SwiftDate. All rights reserved. // import Foundation public protocol DateToStringTrasformable { static func format(_ date: DateRepresentable, options: Any?) -> String } public protocol StringToDateTransformable { static func parse(_ string: String, region: Region, options: Any?) -> DateInRegion? } // MARK: - Formatters /// Format to represent a date to string /// /// - iso: standard iso format. The ISO8601 formatted date, time and millisec "yyyy-MM-dd'T'HH:mm:ssZZZZZ" /// - extended: Extended format. "eee dd-MMM-yyyy GG HH:mm:ss.SSS zzz" /// - rss: The RSS formatted date "EEE, d MMM yyyy HH:mm:ss ZZZ" i.e. "Fri, 09 Sep 2011 15:26:08 +0200" /// - altRSS: The Alternative RSS formatted date "d MMM yyyy HH:mm:ss ZZZ" i.e. "09 Sep 2011 15:26:08 +0200" /// - dotNet: The dotNet formatted date "/Date(%d%d)/" i.e. "/Date(1268123281843)/" /// - httpHeader: The http header formatted date "EEE, dd MM yyyy HH:mm:ss ZZZ" i.e. "Tue, 15 Nov 1994 12:45:26 GMT" /// - custom: custom string format /// - standard: A generic standard format date i.e. "EEE MMM dd HH:mm:ss Z yyyy" /// - date: Date only format (short = "2/27/17", medium = "Feb 27, 2017", long = "February 27, 2017", full = "Monday, February 27, 2017" /// - time: Time only format (short = "2:22 PM", medium = "2:22:06 PM", long = "2:22:06 PM EST", full = "2:22:06 PM Eastern Standard Time" /// - dateTime: Date/Time format (short = "2/27/17, 2:22 PM", medium = "Feb 27, 2017, 2:22:06 PM", long = "February 27, 2017 at 2:22:06 PM EST", full = "Monday, February 27, 2017 at 2:22:06 PM Eastern Standard Time" public enum DateToStringStyles { case iso(_: ISOFormatter.Options) case extended case rss case altRSS case dotNet case httpHeader case sql case date(_: DateFormatter.Style) case time(_: DateFormatter.Style) case dateTime(_: DateFormatter.Style) case custom(_: String) case standard case relative(style: RelativeFormatter.Style?) public func toString(_ date: DateRepresentable) -> String { switch self { case .iso(let opts): return ISOFormatter.format(date, options: opts) case .extended: return date.formatterForRegion(format: DateFormats.extended).string(from: date.date) case .rss: return date.formatterForRegion(format: DateFormats.rss).string(from: date.date) case .altRSS: return date.formatterForRegion(format: DateFormats.altRSS).string(from: date.date) case .sql: return date.formatterForRegion(format: DateFormats.sql).string(from: date.date) case .dotNet: return DOTNETFormatter.format(date, options: nil) case .httpHeader: return date.formatterForRegion(format: DateFormats.httpHeader).string(from: date.date) case .custom(let format): return date.formatterForRegion(format: format).string(from: date.date) case .standard: return date.formatterForRegion(format: DateFormats.standard).string(from: date.date) case .date(let style): return date.formatterForRegion(format: nil, configuration: { $0.dateStyle = style $0.timeStyle = .none }).string(from: date.date) case .time(let style): return date.formatterForRegion(format: nil, configuration: { $0.dateStyle = .none $0.timeStyle = style }).string(from: date.date) case .dateTime(let style): return date.formatterForRegion(format: nil, configuration: { $0.dateStyle = style $0.timeStyle = style }).string(from: date.date) case .relative(let style): return RelativeFormatter.format(date, options: style) } } } // MARK: - Parsers /// String to date transform /// /// - iso: standard automatic iso parser (evaluate the date components automatically) /// - extended: Extended format. "eee dd-MMM-yyyy GG HH:mm:ss.SSS zzz" /// - rss: The RSS formatted date "EEE, d MMM yyyy HH:mm:ss ZZZ" i.e. "Fri, 09 Sep 2011 15:26:08 +0200" /// - altRSS: The Alternative RSS formatted date "d MMM yyyy HH:mm:ss ZZZ" i.e. "09 Sep 2011 15:26:08 +0200" /// - dotNet: The dotNet formatted date "/Date(%d%d)/" i.e. "/Date(1268123281843)/" /// - httpHeader: The http header formatted date "EEE, dd MM yyyy HH:mm:ss ZZZ" i.e. "Tue, 15 Nov 1994 12:45:26 GMT" /// - strict: custom string format with lenient options active /// - custom: custom string format /// - standard: A generic standard format date i.e. "EEE MMM dd HH:mm:ss Z yyyy" public enum StringToDateStyles { case iso(_: ISOParser.Options) case extended case rss case altRSS case dotNet case sql case httpHeader case strict(_: String) case custom(_: String) case standard public func toDate(_ string: String, region: Region) -> DateInRegion? { switch self { case .iso(let options): return ISOParser.parse(string, region: region, options: options) case .custom(let format): return DateInRegion(string, format: format, region: region) case .extended: return DateInRegion(string, format: DateFormats.extended, region: region) case .sql: return DateInRegion(string, format: DateFormats.sql, region: region) case .rss: return DateInRegion(string, format: DateFormats.rss, region: Region.ISO)?.convertTo(locale: region.locale) case .altRSS: return DateInRegion(string, format: DateFormats.altRSS, region: Region.ISO)?.convertTo(locale: region.locale) case .dotNet: return DOTNETParser.parse(string, region: region, options: nil) case .httpHeader: return DateInRegion(string, format: DateFormats.httpHeader, region: region) case .standard: return DateInRegion(string, format: DateFormats.standard, region: region) case .strict(let format): let formatter = DateFormatter.sharedFormatter(forRegion: region, format: format) formatter.isLenient = true guard let absDate = formatter.date(from: string) else { return nil } return DateInRegion(absDate, region: region) } } }
46.492063
215
0.712188
1cd1e5b02067e49da64db314e2fc7ff3b3421809
301
// // Copyright © 2022 Alexander Romanov // ViewOffsetKey.swift // import SwiftUI struct ViewOffsetKey: PreferenceKey { typealias Value = CGFloat static var defaultValue = CGFloat.zero static func reduce(value: inout Value, nextValue: () -> Value) { value += nextValue() } }
20.066667
68
0.677741
edada81af10465314cb38fdfe673e377e135d77a
5,382
// // UIAnimatedButton.swift // ARShow // // Created by Serg Rudenko on 3/23/18. // Copyright © 2018 Owly Labs. All rights reserved. // import UIKit open class UIAnimatedView: UIView { private var tapBeganProcess:Bool = false private var wasTapCancel:Bool = false private var wasTapEnd:Bool = false private var wasLongPress:Bool = false private var scaleX:CGFloat = 0.97 private var scaleY:CGFloat = 0.97 private var selected_alpha:CGFloat = 1.0 var timer: Timer? var didSelectHandler:(_ object: UIAnimatedView)->Void = {_ in } var didLongTapHandler:(_ object: UIAnimatedView)->Void = {_ in } @objc open func setupHandler(scale_x:CGFloat, scale_y:CGFloat, alpha:CGFloat, didSelectCollection:@escaping(_ object: UIAnimatedView) ->()) { didSelectHandler = didSelectCollection self.selected_alpha = alpha self.scaleX = scale_x self.scaleY = scale_y } open func setupHandler(didSelectCollection:@escaping(_ object: UIAnimatedView) ->()) { didSelectHandler = didSelectCollection } open func setupLongPressHandler(didLongTap:@escaping(_ object: UIAnimatedView) ->()) { didLongTapHandler = didLongTap } override public func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { if let touch = touches.first { self.runTimer() _ = touch.location(in: self) // do something with your currentPoint self.tapBeganProcess = true UIView.animate(withDuration: 0.1, animations: { self.transform = CGAffineTransform.init(scaleX: self.scaleX, y: self.scaleY) self.alpha = self.selected_alpha }) { (done) in if (self.wasTapEnd == true || self.wasTapCancel == true){ UIView.animate(withDuration: 0.05, animations: { self.transform = CGAffineTransform.init(scaleX: 1.0, y: 1.0) self.alpha = 1.0 }) { (done) in if (self.wasTapEnd == true){ self.userTap() }else{ self.stopTimer() } self.tapBeganProcess = false self.wasTapCancel = false self.wasTapEnd = false } }else{ self.tapBeganProcess = false self.wasTapCancel = false self.wasTapEnd = false } } } } /* override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { if let touch = touches.first { _ = touch.location(in: self) self.needAnimateAfterTap = true } }*/ override public func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { if let touch = touches.first{ self.wasTapEnd = true if (self.tapBeganProcess == true){ return }else{ self.wasTapEnd = false } //let currentPoint = touch.location(in: self) // do something with your currentPoint UIView.animate(withDuration: 0.1, animations: { self.transform = CGAffineTransform.init(scaleX: 1.0, y: 1.0) }) { (done) in let location = touch.location(in: self) if location.x >= 0 && location.y>=0 { self.userTap() self.alpha = 1.0 } } } } override public func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { if touches.first != nil { //let currentPoint = touch.location(in: self) // do something with your currentPoint self.wasTapCancel = true self.stopTimer() if (self.tapBeganProcess == true){ return }else{ self.wasTapCancel = false } UIView.animate(withDuration: 0.1, animations: { self.transform = CGAffineTransform.init(scaleX: 1.0, y: 1.0) }) { (done) in self.alpha = 1.0 } } } func userTap(){ if (self.wasLongPress == true) { self.stopTimer() }else{ self.stopTimer() self.didSelectHandler(self) } } func runTimer(){ self.wasLongPress = false self.stopTimer() timer = Timer.scheduledTimer(timeInterval: 1.1, target: self, selector: #selector(userLongTap), userInfo: nil, repeats: false) } func stopTimer(){ if (timer != nil){ timer!.invalidate() timer = nil } } @objc func userLongTap(){ self.wasLongPress = true self.didLongTapHandler(self) let fakeTouch:Set<NSObject> = [UITouch()] let event = UIEvent() self.touchesCancelled(fakeTouch as! Set<UITouch>, with: event) } }
30.40678
139
0.511706
5b097c6b4e6d54f5614728fe85573c152a8721b4
2,178
// // AppDelegate.swift // MyAwesomeLibrary // // Created by imranjutt on 07/01/2017. // Copyright (c) 2017 imranjutt. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and 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:. } }
46.340426
285
0.75528
ffaa04d6abe8ab57c7682295150b1e29d85b613d
773
// // FollowingViewModel.swift // appoetry1 // // Created by Kristaps Brēmers on 21.03.19. // Copyright © 2019. g. Chili. All rights reserved. // import UIKit final class FollowingViewModel { var onCreatePostTap: (() -> Void)? var onCellTap: ((String) -> Void)? var followingArray: [String] = [] var idx: String var databaseService: DatabaseService? init(idx: String, databaseService: DatabaseService) { self.databaseService = databaseService self.idx = idx } func fetchFollowings(with completionHandler: @escaping (Bool) -> Void) { databaseService?.getFollowings(idx: idx, with: { (loaded) in if loaded { completionHandler(true) } }) } }
23.424242
76
0.606727
ace42bb61d31838e4df26a4257b9de6d3e601e56
1,404
// // BrazeListener.swift // edX // // Created by Saeed Bashir on 5/20/21. // Copyright © 2021 edX. All rights reserved. // import Foundation @objc class BrazeListener: NSObject, OEXPushListener { typealias Environment = OEXSessionProvider & OEXRouterProvider & OEXConfigProvider var environment: Environment @objc init(environment: Environment){ self.environment = environment } func didReceiveLocalNotification(userInfo: [AnyHashable : Any] = [:]) { //Implementation for local Notification } func didReceiveRemoteNotification(userInfo: [AnyHashable : Any] = [:]) { guard let dictionary = userInfo as? [String: Any], isBrazeNotification(userinfo: userInfo) else { return } if Appboy.sharedInstance() == nil { SEGAppboyIntegrationFactory.instance().saveRemoteNotification(userInfo) } Analytics.shared().receivedRemoteNotification(userInfo) let link = PushLink(dictionary: dictionary) DeepLinkManager.sharedInstance.processNotification(with: link, environment: environment) } private func isBrazeNotification(userinfo: [AnyHashable : Any]) -> Bool { //A push notification sent from the braze has a key ab in it like ab = {c = "c_value";}; guard let _ = userinfo["ab"] as? [String : Any], userinfo.count > 0 else { return false } return true } }
33.428571
114
0.680199
d7429f4e4e9d2ae49d45376e9e4400141adf9fb6
2,560
// Copyright (c) 2020-2021 InSeven Limited // // 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 Combine #if os(iOS) import UIKit #endif public class ThumbnailManager { let targetQueue: DispatchQueue let imageCache: ImageCache let downloadManager: DownloadManager public init(imageCache: ImageCache, downloadManager: DownloadManager) { self.targetQueue = DispatchQueue(label: "targetQueue", attributes: .concurrent) self.imageCache = imageCache self.downloadManager = downloadManager } func cachedImage(for item: Item) -> Future<Image, Error> { return Future { (promise) in self.imageCache.get(identifier: item.identifier) { (result) in promise(result) } } } public func thumbnail(for item: Item, scale: CGFloat) -> AnyPublisher<Image, Error> { return cachedImage(for: item) .catch { _ in Utilities.meta(for: item.url).flatMap { $0.resize(height: 200 * scale) } } .catch { _ in self.downloadManager.thumbnail(for: item.url).flatMap { $0.resize(height: 200 * scale) } } .map({ (image) -> Image in self.imageCache.set(identifier: item.identifier, image: image) { (result) in if case .failure(let error) = result { print("Failed to cache image with error \(error)") } } return image }) .eraseToAnyPublisher() } }
40
116
0.670313
4611d5f31735e67c022570eacc946907fe581bd9
544
// // BibRow.swift // Polaris // // Created by Andrew Despres on 3/14/19. // Copyright © 2019 Downey City Library. All rights reserved. // import Foundation public struct BibRow: Codable { let alternate: Bool let elementID: Int let label: String let occurence: Int let value: String fileprivate enum CodingKeys: String, CodingKey { case alternate = "Alternate" case elementID = "ElementID" case label = "Label" case occurence = "Occurence" case value = "Value" } }
20.923077
62
0.630515
e6a66039e7531468db36ac21d102f0ce28393b42
403
// // Copyright © 2019 An Tran. All rights reserved. // import Core import DataModels import SuperArcCoreComponent import SuperArcCoreUI import SuperArcCore import XCoordinator public protocol AuthorsInterfaceProtocol: OnDemandInterface { func showAuthor(authorMetaData: AuthorMetaData, dependency: AuthorsDependency, anyAuthorsRouter: AnyComponentRouter<AuthorsComponentRoute>) -> Presentable }
26.866667
158
0.831266
6147921e9ae746e9e1896078fba5adfcd59e308c
769
// // V1SubstrateMessage.swift // // // Created by Julia Samol on 10.01.22. // import Foundation import BeaconCore public struct V1SubstrateMessage: BlockchainV1Message { public var id: String { "" } public var type: String { "" } public var version: String { "" } public init(from beaconMessage: BeaconMessage<Substrate>, senderID: String) throws { throw Beacon.Error.messageVersionNotSupported(version: "1", blockchainIdentifier: Substrate.identifier) } public func toBeaconMessage(with origin: Beacon.Origin, completion: @escaping (Result<BeaconMessage<Substrate>, Error>) -> ()) { completion(.failure(Beacon.Error.messageVersionNotSupported(version: "1", blockchainIdentifier: Substrate.identifier))) } }
32.041667
132
0.710013
1611bd59dda06e00853cd6c49a986c47367e9218
1,869
import Foundation /** The edge_ngram tokenizer first breaks text down into words whenever it encounters one of a list of specified characters, then it emits N-grams of each word where the start of the N-gram is anchored to the beginning of the word. Edge N-Grams are useful for search-as-you-type queries. [More information](https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-edgengram-tokenizer.html) */ public struct EdgeNGramTokenizer: Tokenizer { /// :nodoc: public static var typeKey = TokenizerType.edgengram public enum CharacterClass: String, Codable { case letter case digit case whitespace case punctuation case symbol } /// Holds the string that Elasticsearch uses to identify the tokenizer type public let type = typeKey.rawValue public let name: String public let minGram: Int? public let maxGram: Int? public let tokenChars: [CharacterClass]? enum CodingKeys: String, CodingKey { case type case minGram = "min_gram" case maxGram = "max_gram" case tokenChars = "token_chars" } public init(name: String, minGram: Int, maxGram: Int, tokenChars: [CharacterClass]? = nil) { self.name = name self.minGram = minGram self.maxGram = maxGram self.tokenChars = tokenChars } /// :nodoc: public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.name = (decoder.codingPath.last?.stringValue)! self.minGram = try container.decodeIfPresent(Int.self, forKey: .minGram) self.maxGram = try container.decodeIfPresent(Int.self, forKey: .maxGram) self.tokenChars = try container.decodeIfPresent([CharacterClass].self, forKey: .tokenChars) } }
34.611111
228
0.676833
0a96861c4c49283e086580388ca12146ae9b8024
674
// // Days.swift // Stylist // // Created by Ashli Rankin on 4/3/19. // Copyright © 2019 Ashli Rankin. All rights reserved. // import Foundation struct Days{ let dayId:String let userId:String let avalibleHours:[String] init(dayId:String,userId:String,avalibleHours:[String]){ self.avalibleHours = avalibleHours self.dayId = dayId self.userId = userId } init(dict:[String:Any]){ self.avalibleHours = dict[DaysCollectionKeys.avalibliehours] as? [String] ?? [String]() self.dayId = dict[DaysCollectionKeys.daysId] as? String ?? "dayId not found" self.userId = dict[DaysCollectionKeys.userId] as? String ?? "no user id found" } }
24.962963
91
0.692878
1432916c0c5b5ec421011da5a2c899a143c2e98b
1,395
// // UnitListDialogViewModel.swift // SmartMacOSUILibrary // // Created by Michael Rommel on 16.08.21. // import SwiftUI import SmartAILibrary class UnitListDialogViewModel: ObservableObject { @Environment(\.gameEnvironment) var gameEnvironment: GameEnvironment weak var delegate: GameViewModelDelegate? @Published var unitViewModels: [UnitViewModel] = [] init() { } func update(for player: AbstractPlayer) { guard let gameModel = self.gameEnvironment.game.value else { fatalError("cant get game") } var tempUnitViewModels: [UnitViewModel] = [] let units = gameModel.units(of: player) for unitRef in units { guard let unit = unitRef else { continue } let unitViewModel = UnitViewModel(unit: unit) unitViewModel.delegate = self tempUnitViewModels.append(unitViewModel) } self.unitViewModels = tempUnitViewModels } func closeDialog() { self.delegate?.closeDialog() } } extension UnitListDialogViewModel: UnitViewModelDelegate { func clicked(on unit: AbstractUnit?, at index: Int) { self.delegate?.closeDialog() self.delegate?.select(unit: unit) } func clicked(on unitType: UnitType, at index: Int) { fatalError("should not happen") } }
20.820896
68
0.634409
46323a04614ff8bc49951f101bd435f2941581e1
5,955
import Foundation import Intents @available(iOSApplicationExtension 14.0, *) class DashboardWidgetConfigurationIntentHandler: NSObject, DashboardWidgetConfigurationIntentHandling { private let printerManager: PrinterManager init(printerManager: PrinterManager) { self.printerManager = printerManager } // MARK: Printer Parameter handling func resolvePrinter1(for intent: DashboardWidgetConfigurationIntent, with completion: @escaping (WidgetPrinterResolutionResult) -> Void) { resolvePrinter(for: intent.printer1, with: completion) } func resolvePrinter2(for intent: DashboardWidgetConfigurationIntent, with completion: @escaping (WidgetPrinterResolutionResult) -> Void) { resolvePrinter(for: intent.printer2, with: completion) } func resolvePrinter3(for intent: DashboardWidgetConfigurationIntent, with completion: @escaping (WidgetPrinterResolutionResult) -> Void) { resolvePrinter(for: intent.printer3, with: completion) } func resolvePrinter4(for intent: DashboardWidgetConfigurationIntent, with completion: @escaping (WidgetPrinterResolutionResult) -> Void) { resolvePrinter(for: intent.printer4, with: completion) } // MARK: Possible values func providePrinter1OptionsCollection(for intent: DashboardWidgetConfigurationIntent, with completion: @escaping (INObjectCollection<WidgetPrinter>?, Error?) -> Void) { providePrinterOptionsCollection(for: intent, with: completion) } func providePrinter2OptionsCollection(for intent: DashboardWidgetConfigurationIntent, with completion: @escaping (INObjectCollection<WidgetPrinter>?, Error?) -> Void) { providePrinterOptionsCollection(for: intent, with: completion) } func providePrinter3OptionsCollection(for intent: DashboardWidgetConfigurationIntent, with completion: @escaping (INObjectCollection<WidgetPrinter>?, Error?) -> Void) { providePrinterOptionsCollection(for: intent, with: completion) } func providePrinter4OptionsCollection(for intent: DashboardWidgetConfigurationIntent, with completion: @escaping (INObjectCollection<WidgetPrinter>?, Error?) -> Void) { providePrinterOptionsCollection(for: intent, with: completion) } // MARK: Default values func defaultPrinter1(for intent: DashboardWidgetConfigurationIntent) -> WidgetPrinter? { // If intent has proper values then use it if let widgetPrinter = intent.printer1, let _ = widgetPrinter.url { return widgetPrinter } // If not return a new widget printer based on the default printer return defaultPrinter(index: 0) } func defaultPrinter2(for intent: DashboardWidgetConfigurationIntent) -> WidgetPrinter? { // If intent has proper values then use it if let widgetPrinter = intent.printer2, let _ = widgetPrinter.url { return widgetPrinter } // If not return a new widget printer based on the default printer return defaultPrinter(index: 1) } func defaultPrinter3(for intent: DashboardWidgetConfigurationIntent) -> WidgetPrinter? { // If intent has proper values then use it if let widgetPrinter = intent.printer3, let _ = widgetPrinter.url { return widgetPrinter } // If not return a new widget printer based on the default printer return defaultPrinter(index: 2) } func defaultPrinter4(for intent: DashboardWidgetConfigurationIntent) -> WidgetPrinter? { // If intent has proper values then use it if let widgetPrinter = intent.printer4, let _ = widgetPrinter.url { return widgetPrinter } // If not return a new widget printer based on the default printer return defaultPrinter(index: 3) } // MARK: - Private functions fileprivate func createWidgetPrinter(printer: Printer) -> WidgetPrinter { let widgetPrinter = WidgetPrinter(identifier: printer.name, display: printer.name) widgetPrinter.name = printer.name widgetPrinter.url = printer.objectID.uriRepresentation().absoluteString widgetPrinter.hostname = printer.hostname widgetPrinter.apiKey = printer.apiKey widgetPrinter.username = printer.username widgetPrinter.password = printer.password widgetPrinter.preemptiveAuth = printer.preemptiveAuthentication() ? 1 : 0 return widgetPrinter } fileprivate func resolvePrinter(for printer: WidgetPrinter?, with completion: @escaping (WidgetPrinterResolutionResult) -> Void) { if let printerURL = printer?.url, let url = URL(string: printerURL), let selectedPrinter = printerManager.getPrinterByObjectURL(url: url) { let widgetPrinter = createWidgetPrinter(printer: selectedPrinter) completion(WidgetPrinterResolutionResult.success(with: widgetPrinter)) } else { // This case should not happen completion(WidgetPrinterResolutionResult.needsValue()) } } fileprivate func providePrinterOptionsCollection(for intent: DashboardWidgetConfigurationIntent, with completion: @escaping (INObjectCollection<WidgetPrinter>?, Error?) -> Void) { let widgetPrinters: [WidgetPrinter] = printerManager.getPrinters().map { printer in return createWidgetPrinter(printer: printer) } // Create a collection with the array of characters. let collection = INObjectCollection(items: widgetPrinters) // Call the completion handler, passing the collection. completion(collection, nil) } fileprivate func defaultPrinter(index: Int) -> WidgetPrinter? { let printers = printerManager.getPrinters() if printers.count > index { return createWidgetPrinter(printer: printers[index]) } return nil } }
45.458015
183
0.708984
4be81cc81a2587847f5a8ded7a95b2ef633140ba
1,009
// // NewPlayerView.swift // MovieHub // // Created by Ronnie Arvanites on 10/10/20. // import Foundation import SwiftUI import AVKit struct VideoPlayer: UIViewRepresentable { typealias UIViewType = UIView var player: AVPlayer func makeUIView(context: UIViewRepresentableContext<VideoPlayer>) -> UIView { let controller = AVPlayerViewController() // controller.player = AVPlayer(url: url) controller.player = self.player //Enables audio try! AVAudioSession.sharedInstance().setCategory(.playback) context.coordinator.controller = controller return controller.view } func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<VideoPlayer>) { } func makeCoordinator() -> VideoPlayer.Coordinator { Coordinator() } class Coordinator: NSObject { var controller: AVPlayerViewController? deinit { print("deinit coordinator") } } }
22.931818
91
0.657086
8aed4a13daea60b87548ce3d8fb1c8601feb977f
30,517
// // DUXBetaBarPanelWidget.swift // DJIUXSDKWidgets // // MIT License // // Copyright © 2018-2020 DJI // // 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 fileprivate let defaultInterWidgetSpace = CGFloat(12.0) /****************************************************************************** * Some rules of the layout here: * Widgets are added into the bar moving from left to right. So if a new widget is added (not inserted) all * widgets will shift left (towards leading edge). * For vertical bars, the leftBar is hanging at the top, and the rightBar is at the bottom of the vertical area. * Bar panels do not have title bars or close bars. * Bar panels to support margins on all edges. ******************************************************************************/ /** * The LayoutInfoTuple contains the widget, the widget visibility, the height and width constraints on the widget * to allow dynamic adjustments. * If isVisible is false, the height and width NSLayoutConstraint will be nil. This lets us * track and deactivate constraints before updating them in UpdateUI, so we don't get constraint build up and conflicts. * * - Parameters: * - widget: The widget this tuple is about * - isVisible: Is the widget currently visible * - heightConstraint: The current active constraint on the heightAnchor for this widget. Optional * - widthConstraint: The current active constraint on the widthAnchor for this widget. Optional */ typealias LayoutInfoTuple = (widget: DUXBetaBaseWidget, isVisible: Bool, heightConstraint: NSLayoutConstraint?, widthConstraint: NSLayoutConstraint?) /** * DUXBetaBarPanelWidget implements the Bar Panel which descends from DUXBetaPanelWidget. The bar panel is a single strip of widgets * either horizontal or vertical which has a left/right side, or a top/bottom side (but still using the left/right nomenclature.) * Widgets can be added or removed or even made invisible while the widget is on screen and the visible widgets will adjust * positions in the visible bar. * * Margins can be added either one at a time by setting the individual margins or all at once by calling the * setBarMargins method. */ @objcMembers open class DUXBetaBarPanelWidget : DUXBetaPanelWidget { /// The topMargin for insetting the panel contents public var topMargin: CGFloat = 0.0 { didSet { updatetMarginConstraints(top: true) } } /// The bottomMargin for insetting the panel contents public var bottomMargin: CGFloat = 0.0 { didSet { updatetMarginConstraints(bottom: true) } } /// The leftMargin for insetting the panel contents public var leftMargin: CGFloat = 0.0 { didSet { updatetMarginConstraints(left: true) } } /// The rightMargin for insetting the panel contents public var rightMargin: CGFloat = 0.0 { didSet { updatetMarginConstraints(right: true) } } /// The standard widgetSizeHint indicating the minimum size for this widget and preferred aspect ratio public override var widgetSizeHint : DUXBetaWidgetSizeHint { get { return DUXBetaWidgetSizeHint(preferredAspectRatio: (panelSize.width / panelSize.height), minimumWidth: panelSize.width, minimumHeight: panelSize.height)} set {} } // Instance variables visible inside the module let rightBar = UIStackView(frame:CGRect(x: 0, y: 0, width: 20, height: 20)) let leftBar = UIStackView(frame:CGRect(x: 0, y: 0, width: 20, height: 20)) // Private instance variables enum BarIndex: Int { case leftBarIndex = 0 case rightBarIndex = 1 } fileprivate var orientation : DUXBetaPanelVariant fileprivate var panelSize = CGSize(width: 10, height: 10) fileprivate var interWidgetSpace: CGFloat = defaultInterWidgetSpace fileprivate let marginsLayoutGuide = UILayoutGuide() fileprivate var topGuideConstraint : NSLayoutConstraint? fileprivate var leftGuideConstraint : NSLayoutConstraint? fileprivate var bottomGuideConstraint : NSLayoutConstraint? fileprivate var rightGuideConstraint : NSLayoutConstraint? // This is an array of arrays. Indexing is leftBarIndex and rightBarIndex. Each array inside contains // tuples of all the widgets in the bar, a visibility shortcut (possibly not needed), and height and width constraints. fileprivate var allWidgetVisibilities : [[LayoutInfoTuple]] = [ [LayoutInfoTuple](), [LayoutInfoTuple]() ] fileprivate var panelSizeInitalLayoutDone = false fileprivate var suspendUpdates = false // We only have one modifiable constraint for horizontal or vertical. Se we can be flexible on // what these variables hold. fileprivate var rightBarConstraint: NSLayoutConstraint? fileprivate var leftBarConstraint: NSLayoutConstraint? // MARK: - Public Instance Methods /** * The default init method for the class. Sets the orientation to horiztonal. */ override public init() { self.orientation = .horizontal super.init() } /** * The default init method for the class when loading from a Storyboard or Xib. Sets the orientation to horiztonal. */ required public init?(coder: NSCoder) { self.orientation = .horizontal super.init(coder: coder) } /** * The init method for creating an instance of a bar panel with a given orientation. * * - Parameter variant: The variant specifying horizontal or vertical orientation. */ init(variant: DUXBetaPanelVariant) { self.orientation = variant super.init() } deinit { // Clean up the KVO on the installed widgets for widgetVisArray in self.allWidgetVisibilities { for aWidgetTuple in widgetVisArray { if let widgetView = aWidgetTuple.widget.view { widgetView.removeObserver(self, forKeyPath: "hidden") } } } } /** * Override of the standard viewdDidLoad. Sets the parent view for autolayout and if the widget has already been * configured, calls setupUI. */ override public func viewDidLoad() { super.viewDidLoad() self.view.translatesAutoresizingMaskIntoConstraints = false if self.isConfigured { self.setupUI() } } //MARK: - Configuration /** * Override of configure method. Takes the configuration object and extracts the specific part needed for this * widget (orientation) and calls the parent configuration for the remainder of the processing. * If the configuration has been conmpleted, calls setupUI. * * - Returns: This object instance for call chaining. */ override public func configure(_ configuration:DUXBetaPanelWidgetConfiguration) -> DUXBetaPanelWidget { self.orientation = configuration.widgetVariant let _ = super.configure(configuration) if self.isConfigured { self.setupUI() } return self } //MARK: - Margin maintainance /** * Method setupBarMargins takes the four margins (top, left, bottom, right) as a UIEdgeInserts and applies them to the bar panel. * * - Parameter marginInsets: The UIEdgeInsets structure defining the margins for top, left, bottom, and right. */ public func setBarMargins(marginInsets: UIEdgeInsets) { topMargin = marginInsets.top leftMargin = marginInsets.left bottomMargin = marginInsets.bottom rightMargin = marginInsets.right } //MARK: - Bar content control /** * The method widgetCount returns the number of widgets in the right/bottom bar side only. * * - Returns: Int/NSInteger number of widgets in the right or bottom side of the widget. */ public override func widgetCount() -> Int { return self.rightWidgetCount() } /** * The method rightWidgetCount returns the number of widgets in the right/bottom bar side. * * - Returns: Interer/NSInteger number of widgets in the right or bottom side of the widget. */ public func rightWidgetCount() -> Int { return self.allWidgetVisibilities[BarIndex.rightBarIndex.rawValue].count } /** * The method leftWidgetCount returns the number of widgets in the left/top bar side. * * - Returns: Int/NSInteger number of widgets in the left or top side of the widget. */ public func leftWidgetCount() -> Int { return self.allWidgetVisibilities[BarIndex.leftBarIndex.rawValue].count } /** * The addWidgetArray method defaults to adding widgets to the right/bottom bar. * * - Parameter displayWidgets: unnamed array of widgets subclassed from from DXBaseWidget. */ public override func addWidgetArray(_ displayWidgets: [DUXBetaBaseWidget]) { self.addRightWidgetArray(displayWidgets) } /** * The addRightWidgetArray method adds the widgets from the passed array to the right/bottom bar. * * - Parameter displayWidgets: unnamed array of widgets subclassed from from DXBaseWidget. */ public func addRightWidgetArray(_ displayWidgets: [DUXBetaBaseWidget]) { self.suspendUpdates = true for aWidget in displayWidgets { // Build our tracking tuple for each widget so we can associate constraint. let isVisible = !(aWidget.view?.isHidden ?? true) // The true means isHidden since there is no view let workTuple : LayoutInfoTuple = (aWidget, isVisible, nil, nil) allWidgetVisibilities[BarIndex.rightBarIndex.rawValue].append(workTuple) // Add an abserver to the hidden property so we can handle automatic adjustment when a widget disappears or reappears aWidget.view?.addObserver(self, forKeyPath: "hidden", options: .new, context: nil) // And always have all widgets in the bar, even if invisible. self.rightBar.addArrangedSubview(aWidget.view) aWidget.view.layoutIfNeeded() } self.suspendUpdates = false self.updateUI() } /** * The addLeftWidgetArray method adds the widgets from the passed array to the left/top bar. * * - Parameter displayWidgets: unnamed array of widgets subclassed from from DXBaseWidget. */ public func addLeftWidgetArray(_ displayWidgets: [DUXBetaBaseWidget]) { for aWidget in displayWidgets { // Build our tracking tuple for each widget so we can associate constraint. let isVisible = !(aWidget.view?.isHidden ?? true) // The true means isHidden since there is no view let workTuple : LayoutInfoTuple = (aWidget, isVisible, nil, nil) allWidgetVisibilities[BarIndex.leftBarIndex.rawValue].append(workTuple) // Add an observer to the hidden property so we can handle automatic adjustment when a widget disappears or reappears aWidget.view?.addObserver(self, forKeyPath: "hidden", options: .new, context: nil) // And always have all widgets in the bar, even if invisible. self.leftBar.addArrangedSubview(aWidget.view) aWidget.view.layoutIfNeeded() } self.updateUI() } /** * The insertRightWidget method inserts the given widget into the right/bottom bar at the given index. * Indexing is from leading to trailing side. * * - Parameters: * - widget: The widget subclassed from from DXBaseWidget to insert. * - atIndex: The index at which to insert the widget in the bar array. */ public func insertRightWidget(_ widget: DUXBetaBaseWidget, atIndex: Int) { let isVisible = !(widget.view?.isHidden ?? true) // The true means isHidden since there is no view let workTuple : LayoutInfoTuple = (widget, isVisible, nil, nil) allWidgetVisibilities[BarIndex.rightBarIndex.rawValue].insert(workTuple, at: atIndex) // Add an observer to the hidden property so we can handle automatic adjustment when a widget disappears or reappears widget.view?.addObserver(self, forKeyPath: "hidden", options: .new, context: nil) self.rightBar.insertArrangedSubview(widget.view, at: atIndex) widget.view.layoutIfNeeded() self.updateUI() } /** * The insertLeftWidget method inserts the given widget into the left/top bar at the given index. * Indexing is from top to bottom. * * - Parameters: * - widget: The widget subclassed from from DXBaseWidget to insert. * - atIndex: The index at which to insert the widget in the bar array. */ public func insertLeftWidget(_ widget: DUXBetaBaseWidget, atIndex: Int) { let isVisible = !(widget.view?.isHidden ?? true) // The true means isHidden since there is no view let workTuple : LayoutInfoTuple = (widget, isVisible, nil, nil) allWidgetVisibilities[BarIndex.leftBarIndex.rawValue].insert(workTuple, at: atIndex) // Add an observer to the hidden property so we can handle automatic adjustment when a widget disappears or reappears widget.view?.addObserver(self, forKeyPath: "hidden", options: .new, context: nil) self.leftBar.insertArrangedSubview(widget.view, at: atIndex) widget.view.layoutIfNeeded() self.updateUI() } /** * The insert method inserts the given widget into the right/bottom bar at the given index. * Indexing is from leading to trailing side. * * - Parameters: * - widget: The widget subclassed from from DXBaseWidget to insert. * - atIndex: The index at which to insert the widget in the bar array. */ public override func insert(widget: DUXBetaBaseWidget, atIndex: Int) { self.insertRightWidget(widget, atIndex: atIndex) } /** * The removeRightWidget method removes the widget at the given index from the right/bottom bar. * Indexing is from leading to trailing side. * * - Parameters: * - atIndex: The index at which to remove the widget in the bar array. */ public func removeRightWidget(atIndex: Int) { let workTuple = allWidgetVisibilities[BarIndex.rightBarIndex.rawValue][atIndex] self.rightBar.removeArrangedSubview(workTuple.widget.view) workTuple.widget.view.removeFromSuperview() allWidgetVisibilities[BarIndex.rightBarIndex.rawValue].remove(at: atIndex) self.updateUI() } /** * The removeLeftWidget method removes the widget at the given index from the left/top bar. * Indexing is from top to bottom. * * - Parameters: * - atIndex: The index at which to remove the widget in the bar array. */ public func removeLeftWidget(atIndex: Int) { let workTuple = allWidgetVisibilities[BarIndex.leftBarIndex.rawValue][atIndex] self.leftBar.removeArrangedSubview(workTuple.widget.view) workTuple.widget.view.removeFromSuperview() allWidgetVisibilities[BarIndex.leftBarIndex.rawValue].remove(at: atIndex) self.updateUI() } /* The left vs right vs all methods below are split up strictly to prevent calling * updateUI twice if we wrote removeAllWidgets as a composition of the other * two remove widgets calls. */ /** * The method removeLeftWidgets removes all the widgets from the left/top bar. */ public func removeLeftWidgets() { let leftSubviews = self.leftBar.arrangedSubviews for theView in leftSubviews { self.leftBar.removeArrangedSubview(theView) theView.removeFromSuperview() } allWidgetVisibilities[BarIndex.leftBarIndex.rawValue].removeAll() self.updateUI() } /** * The method removeRightWidgets removes all the widgets from the right/bottom bar. */ public func removeRightWidgets() { let rightSubviews = self.rightBar.arrangedSubviews for theView in rightSubviews { self.rightBar.removeArrangedSubview(theView) theView.removeFromSuperview() } allWidgetVisibilities[BarIndex.rightBarIndex.rawValue].removeAll() self.updateUI() } /** * The method removeAllWidgets removes all the widgets from the both internal bars. */ public override func removeAllWidgets() { let leftSubviews = self.leftBar.arrangedSubviews for theView in leftSubviews { self.leftBar.removeArrangedSubview(theView) theView.removeFromSuperview() } allWidgetVisibilities[BarIndex.leftBarIndex.rawValue].removeAll() let rightSubviews = self.rightBar.arrangedSubviews for theView in rightSubviews { self.rightBar.removeArrangedSubview(theView) theView.removeFromSuperview() } allWidgetVisibilities[BarIndex.rightBarIndex.rawValue].removeAll() self.updateUI() } //MARK: - KVO /** The observeValue method is used to implement KVO to trigger UI updates. */ override public func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { self.updateUI() } //MARK: - UI Setup and Update func setupUI() { leftBar.translatesAutoresizingMaskIntoConstraints = false leftBar.backgroundColor = .duxbeta_black() leftBar.alignment = .center leftBar.distribution = .equalSpacing rightBar.translatesAutoresizingMaskIntoConstraints = false rightBar.backgroundColor = .duxbeta_black() rightBar.alignment = .center rightBar.distribution = .equalSpacing if orientation == .horizontal { rightBar.axis = .horizontal leftBar.axis = .horizontal } else { rightBar.axis = .vertical leftBar.axis = .vertical } self.view.addSubview(leftBar) self.view.addSubview(rightBar) // Set up the UIGuides for setting the margins self.view.addLayoutGuide(marginsLayoutGuide) updatetMarginConstraints(top: true, left: true, bottom: true, right: true) if orientation == .horizontal { // This setup is for horizontal only leftBar.topAnchor.constraint(equalTo: marginsLayoutGuide.topAnchor, constant: 0.0).isActive = true leftBar.leftAnchor.constraint(equalTo: marginsLayoutGuide.leftAnchor, constant: 0.0).isActive = true leftBar.heightAnchor.constraint(equalTo: marginsLayoutGuide.heightAnchor).isActive = true // Set up the right bar to be the full size of the view currently. When a left bar is added, both // with be constrained with a spacing constraint between them so they can't overlap. // The width anchor is dynamically calculated and proportional to the final height. It is set later // in this method. rightBar.topAnchor.constraint(equalTo: marginsLayoutGuide.topAnchor, constant: 0.0).isActive = true rightBar.rightAnchor.constraint(equalTo: marginsLayoutGuide.rightAnchor, constant: 0.0).isActive = true rightBar.heightAnchor.constraint(equalTo: marginsLayoutGuide.heightAnchor).isActive = true } else { // This is the case of orientation == .vertical. The right bar is placed at the visual top, and the left bar // is placed at the visual bottom leftBar.topAnchor.constraint(equalTo: marginsLayoutGuide.topAnchor, constant: 0.0).isActive = true leftBar.leftAnchor.constraint(equalTo: marginsLayoutGuide.leftAnchor, constant: 0.0).isActive = true leftBar.widthAnchor.constraint(equalTo: marginsLayoutGuide.widthAnchor).isActive = true // Set up the right bar to be the full size of the view currently. When a left bar is added, both // with be constrained with a spacing constraint between them so they can't overlap. // The width anchor is dynamically calculated and proportional to the final height. It is set later // in this method. rightBar.bottomAnchor.constraint(equalTo: marginsLayoutGuide.bottomAnchor, constant: 0.0).isActive = true rightBar.leftAnchor.constraint(equalTo: marginsLayoutGuide.leftAnchor, constant: 0.0).isActive = true rightBar.widthAnchor.constraint(equalTo: marginsLayoutGuide.widthAnchor).isActive = true } } /** * Override of the updateUI method for the BarPanel. It adjusts the sizes of the internal UIStackViews based on * the sizes of the items in the stack views and the margins in the widget. */ public override func updateUI() { if suspendUpdates { // Updates may be suspended duing an add Widgets operation until all widgets are added. return } // The visibility is used to compute our UIStackView size based on the shown widgets // This maintains the list of visibility so we can compute the correct size func findWidgetsMaxMin(_ widgetVisibility: inout [LayoutInfoTuple]) -> (width: CGFloat, height: CGFloat) { var maxWidth : CGFloat = 1.0 var maxHeight : CGFloat = 1.0 for (index, widgetInfo) in widgetVisibility.enumerated() { var updatedWidgetInfo = widgetInfo let currentIsHidden = updatedWidgetInfo.widget.view?.isHidden ?? true updatedWidgetInfo.isVisible = !currentIsHidden widgetVisibility[index] = updatedWidgetInfo let aWidget = widgetInfo.widget if updatedWidgetInfo.isVisible { let sizeHint = aWidget.widgetSizeHint if maxWidth < sizeHint.minimumWidth { maxWidth = sizeHint.minimumWidth } if maxHeight < sizeHint.minimumHeight { maxHeight = sizeHint.minimumHeight } } } return (maxWidth, maxHeight) } for barIdentider in [BarIndex.rightBarIndex, BarIndex.leftBarIndex] { _ = findWidgetsMaxMin(&self.allWidgetVisibilities[barIdentider.rawValue]) var itemCount: CGFloat = 1 // Force a layout here unfortunately. If we don't do this, on first updateUI the widgets aren't // correctly sized. (This may not be working fully yet.) var workBar = self.rightBar switch barIdentider { case .rightBarIndex: self.rightBar.layoutIfNeeded() case .leftBarIndex: self.leftBar.layoutIfNeeded(); workBar = self.leftBar } var barPanelSize = CGSize.zero (barPanelSize, itemCount) = findBarDimensions(workBar, orientation: self.orientation) if (itemCount == 0) { // Adjust itemCount to prevent negative interGap space computation if there are // 0 or 1 itmes. itemCount = 1 } // Making the constraint false removes it from the constraints list. var workConstraint: NSLayoutConstraint? switch barIdentider { case .rightBarIndex: rightBarConstraint?.isActive = false case .leftBarIndex: leftBarConstraint?.isActive = false; workBar = self.leftBar } workConstraint = spacingConstraint(forOrientation: orientation, andWorkBar: workBar, withSize: barPanelSize, andConstant: ((itemCount-1) * interWidgetSpace)) workConstraint?.isActive = true switch barIdentider { case .rightBarIndex: self.rightBarConstraint = workConstraint case .leftBarIndex: self.leftBarConstraint = workConstraint } } rightBar.layoutIfNeeded() leftBar.layoutIfNeeded() self.view.layoutIfNeeded() } /** * The spacingConstraint method creates the width and height ratio constraint * for the bar panel. * * - Parameters: * - orientation: The orientation of the widget. * - workBar: The stackview for which the constraint is created. * - size: The actual size of the panel. * - constant: The constant that needs to be factored in. * - Returns: An NSLayoutConstraint for the widthAnchor or heightAnchor with * the computed ratio and given constant. */ public func spacingConstraint(forOrientation orientation: DUXBetaPanelVariant, andWorkBar workBar: UIView, withSize size: CGSize, andConstant constant: CGFloat) -> NSLayoutConstraint { if orientation == .horizontal { return workBar.widthAnchor.constraint(equalTo: workBar.heightAnchor, multiplier: size.width/size.height, constant: constant) } else { // Orientation is .vertical. Checks in other places guarantee this return workBar.heightAnchor.constraint(equalTo: workBar.widthAnchor, multiplier: size.height/size.width, constant: constant) } } //MARK: - internal methods func findBarDimensions(_ bar: UIStackView, orientation: DUXBetaPanelVariant) -> (CGSize, CGFloat) { var outSize: CGSize = CGSize(width: 0.0, height: 0.0) var totalHeight: CGFloat = 0.0 var totalWidth: CGFloat = 0.0 var maxWidth: CGFloat = 0.0 var maxHeight: CGFloat = 0.0 var visibleItems: CGFloat = 0.0 for aView in bar.arrangedSubviews { if !aView.isHidden { let viewSize = aView.bounds.size if maxWidth < viewSize.width { maxWidth = viewSize.width } if maxHeight < viewSize.height { maxHeight = viewSize.height } totalWidth += viewSize.width totalHeight += viewSize.height visibleItems += 1 } } if (orientation == .horizontal) { outSize.height = maxHeight == 0 ? 1.0 : maxHeight // Never return a height of 0 or we get a divide by 0 error for the aspect ration calculation outSize.width = totalWidth //+ ((visibleItems-1) * interWidgetSpace) } else { outSize.height = totalHeight //+ ((visibleItems-1) * interWidgetSpace) outSize.width = maxWidth == 0 ? 1.0 : maxWidth // Never return a width of 0 or we get a divide by 0 error for the aspect ration calculation } return (outSize, visibleItems) } func updatetMarginConstraints(top: Bool = false, left: Bool = false, bottom: Bool = false, right: Bool = false) { if top { // Set the top margin if let oldConstraint = topGuideConstraint { oldConstraint.isActive = false } if let owningView = marginsLayoutGuide.owningView { topGuideConstraint = marginsLayoutGuide.topAnchor.constraint(equalTo:owningView.topAnchor, constant:topMargin) topGuideConstraint?.isActive = true; } } if left { // Set the left margin if let oldConstraint = leftGuideConstraint { oldConstraint.isActive = false } if let owningView = marginsLayoutGuide.owningView { leftGuideConstraint = marginsLayoutGuide.leftAnchor.constraint(equalTo:owningView.leftAnchor, constant:leftMargin) leftGuideConstraint?.isActive = true; } } if bottom { // Set the bottom margin if let oldConstraint = bottomGuideConstraint { oldConstraint.isActive = false } if let owningView = marginsLayoutGuide.owningView { bottomGuideConstraint = marginsLayoutGuide.bottomAnchor.constraint(equalTo:owningView.bottomAnchor, constant:-bottomMargin) bottomGuideConstraint?.isActive = true; } } if right { // Set the right margin if let oldConstraint = rightGuideConstraint { oldConstraint.isActive = false } if let owningView = marginsLayoutGuide.owningView { rightGuideConstraint = marginsLayoutGuide.rightAnchor.constraint(equalTo:owningView.rightAnchor, constant:-rightMargin) rightGuideConstraint?.isActive = true; } } } // Debugging method to be inserted as needed to test that no heights have gone to 0 func find0Height(_ view:UIView) { view.constraints.forEach { (constraint) in if constraint.firstAttribute == .height { if (constraint.constant == 0) || (constraint.multiplier == 0.0) { print("Bad things") } } } } }
44.812041
167
0.652423
28a38a248dc0e6b0716c16624560d2c567b3c41b
4,646
// // HotelEditViewController.swift // TravelPlanner // // Created by Ellen Shapiro (Work) on 9/10/18. // Copyright © 2018 Designated Nerd Software. All rights reserved. // import UIKit public class HotelEditViewController: UIViewController { public weak var coordinator: PlanEditCoordinator? public var hotel: Hotel! { didSet { self.configure(for: self.hotel) } } @IBOutlet var nameTextField: UITextField! @IBOutlet var addressTextField: UITextField! @IBOutlet var cityTextField: UITextField! @IBOutlet var stateProvinceTextField: UITextField! @IBOutlet var countryTextField: UITextField! @IBOutlet var arrivalDatePicker: DateTimePickerContainer! @IBOutlet var departureDatePicker: DateTimePickerContainer! var textFields: [UITextField] { return [ self.nameTextField, self.addressTextField, self.cityTextField, self.stateProvinceTextField, self.countryTextField, self.arrivalDatePicker.view.dateTextField, self.arrivalDatePicker.view.timeTextField, self.departureDatePicker.view.dateTextField, self.departureDatePicker.view.timeTextField, ] } public var mode: PlanViewMode = .edit { didSet { self.configureForMode(self.mode) } } public override func viewDidLoad() { super.viewDidLoad() self.configure(for: self.hotel) self.configureForMode(self.mode) } private func configure(for hotel: Hotel) { guard self.nameTextField != nil else { // Hasn't been set up yet return } self.nameTextField.text = hotel.name self.addressTextField.text = hotel.streetAddress self.cityTextField.text = hotel.city self.stateProvinceTextField.text = hotel.stateOrProvince self.countryTextField.text = hotel.country self.arrivalDatePicker.view.date = hotel.startDate ?? Date() self.departureDatePicker.view.date = hotel.endDate ?? Date() } private func configureForMode(_ mode: PlanViewMode) { guard self.nameTextField != nil else { // Hasn't been set up yet return } switch mode { case .edit: self.textFields.forEach { textField in textField.isUserInteractionEnabled = true textField.borderStyle = .roundedRect } case .view: self.textFields.forEach { textField in textField.isUserInteractionEnabled = false textField.borderStyle = .none } } } func validate() -> Bool { guard self.nameTextField.dns_hasText, self.addressTextField.dns_hasText, self.cityTextField.dns_hasText, self.stateProvinceTextField.dns_hasText, self.countryTextField.dns_hasText, self.datesAreValid else { return false } return true } var datesAreValid: Bool { let arrival = self.arrivalDatePicker.view.date let departure = self.departureDatePicker.view.date return arrival.dns_isBefore(departure) } } extension HotelEditViewController: StoryboardHosted { public static var storyboard: Storyboard { return SharedStoryboard.hotel } } extension HotelEditViewController: PlanEditing { var contentHeight: CGFloat { return self.departureDatePicker.frame.maxY } func savePressed() { guard self.validate() else { return } self.hotel.name = self.nameTextField.text self.hotel.streetAddress = self.addressTextField.text self.hotel.city = self.cityTextField.text self.hotel.stateOrProvince = self.stateProvinceTextField.text self.hotel.country = self.countryTextField.text self.hotel.startDate = self.arrivalDatePicker.view.date self.hotel.endDate = self.departureDatePicker.view.date do { try self.hotel.managedObjectContext?.dns_saveIfHasChanges() self.mode = .view } catch { debugPrint("Error saving MOC: \(error)") } } var plan: Plan { get { return self.hotel } set { guard let hotel = newValue as? Hotel else { fatalError("THIS IS NOT A Hotel") } self.hotel = hotel } } }
29.405063
71
0.606543
d7554f1f710e5ded510f9b63e9e8a5882f69bda5
795
import SwiftUI #if swift(>=5.4) @resultBuilder public enum ShapeBuilder { public static func buildBlock<S: Shape>(_ builder: S) -> some Shape { builder } } #else @_functionBuilder public enum ShapeBuilder { public static func buildBlock<S: Shape>(_ builder: S) -> some Shape { builder } } #endif public extension ShapeBuilder { static func buildOptional<S: Shape>(_ component: S?) -> EitherShape<S, EmptyShape> { component.flatMap(EitherShape.first) ?? EitherShape.second(EmptyShape()) } static func buildEither<First: Shape, Second: Shape>(first component: First) -> EitherShape<First, Second> { .first(component) } static func buildEither<First: Shape, Second: Shape>(second component: Second) -> EitherShape<First, Second> { .second(component) } }
24.84375
112
0.708176
2fbdc37c1ed7551acc1d6dcd43564afb6dbf6f6a
673
// // File.swift // // // Created by David House on 6/30/19. // //- DocumentLocation // * Kind: object //* Properties: //+ url: String //+ concreteTypeName: String import Foundation public struct DocumentLocation: XCResultObject { public let url: String public let concreteTypeName: String public init?(_ json: [String : AnyObject]) { do { url = try xcRequired(element: "url", from: json) concreteTypeName = try xcRequired(element: "concreteTypeName", from: json) } catch { print("Error parsing DocumentLocation: \(error.localizedDescription)") return nil } } }
22.433333
86
0.604755
cc7388bb5eaa8daa9389ef42d3f172e62ed8e9cd
612
// // UserAPIClient.swift // PeopleAndAppleStockPrices // // Created by Stephanie Ramirez on 12/13/18. // Copyright © 2018 Pursuit. All rights reserved. // import UIKit final class ImageClient { static func getImage(StringURL: String) -> UIImage? { guard let myImageURL = URL.init(string: StringURL) else {return nil} do { let data = try Data.init(contentsOf: myImageURL) // processing image guard let image = UIImage.init(data: data) else {return nil} return image } catch { print(error) return nil } } }
25.5
80
0.609477
f80534f0036173df64edaf73199c8504a888166a
4,440
// // BackupService.swift // Authenticator // // Copyright (c) 2015-2019 Authenticator authors // // 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 OneTimePassword import Security import CommonCrypto import CryptoSwift import Base32 // TODO: document protocol BackupService { func `import`(backup: Data, password: String) throws -> [Token] func export(tokens: [Token], password: String) throws -> Data } class BackupServiceImpl: BackupService { func `import`(backup: Data, password: String) throws -> [Token] { // Decryption: Extract parameters from backup data. let iterationsBytes = backup.subdata(in: 0..<4) var iterationsBigEndian: Int32 = 0 _ = withUnsafeMutableBytes(of: &iterationsBigEndian) { iterationsBytes.copyBytes(to: $0) } let iterations = Int32(bigEndian: iterationsBigEndian) let salt = backup.subdata(in: 4..<16) let iv = backup.subdata(in: 16..<28) let payload = backup.subdata(in: 28..<backup.count) // Decryption: Derive AES key from `password`. let key = try PKCS5.PBKDF2(password: password.bytes, salt: salt.bytes, iterations: Int(iterations), keyLength: 32, variant: .sha1).calculate() // Decryption: Perform AES decryption. let aes = try AES(key: key, blockMode: GCM(iv: iv.bytes, mode: .combined), padding: .noPadding) let plaintext = try aes.decrypt(payload.bytes) // TODO: Report parse failures to the user instead of silently ignoring. return (String(data: Data(plaintext), encoding: .utf8)? .split(separator: "\n") ?? []) .compactMap { uri in URL(string: String(uri)).flatMap { Token(url: $0) } } } func export(tokens: [Token], password: String) throws -> Data { // Create plaintext message // https://github.com/Authenticator-Extension/Authenticator/wiki/Standard-OTP-Backup-Format let plaintext = try tokens .map { token in var uri = try token.toURI() let secret = MF_Base32Codec.base32String(from: token.generator.secret) let secretQueryItem = URLQueryItem(name: "secret", value: secret) if uri.queryItems != nil { uri.queryItems!.append(secretQueryItem) } else { uri.queryItems = [secretQueryItem] } return uri.string! } .joined(separator: "\n") // Encryption: Derive an AES key from `password` using PBKDF2. // TODO: 140000...160000 let iterations = Int32.random(in: 1400...1600) let salt = (0..<12).map { _ in UInt8.random(in: 0...UInt8.max) } let key = try PKCS5.PBKDF2(password: password.bytes, salt: salt, iterations: Int(iterations), keyLength: 32, variant: .sha1).calculate() // Encryption: Perform AES GCM NoPadding encryption. let iv = AES.randomIV(12) let gcm = GCM(iv: iv, mode: .combined) let aes = try AES(key: key, blockMode: gcm, padding: .noPadding) let encrypted = try aes.encrypt(plaintext.bytes) // Encryption: Concatenate iterations, salt, iv, and payload. let iterationBytes = withUnsafeBytes(of: iterations.bigEndian, Data.init) let backupData = iterationBytes + salt + iv + Data(encrypted) return backupData } }
44.4
150
0.661712
7add782e905a06def2c32e86f0fb30d025f98f26
895
// // SettingsTableVC.swift // MediaSwitch // // Created by Sean Williams on 07/05/2020. // Copyright © 2020 Sean Williams. All rights reserved. // import UIKit class SettingsTableVC: UITableViewController { var selectedOption = "" // MARK: - Table view data source override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch indexPath.row { case 0: selectedOption = "terms" case 1: selectedOption = "privacy" case 2: selectedOption = "legal" case 3: selectedOption = "contact" default: break } let vc = storyboard?.instantiateViewController(identifier: "SettingsDetailVC") as! SettingsDetailVC vc.selectedSettingsOption = selectedOption show(vc, sender: self) } }
22.375
107
0.601117
dd653fe324ba1040dfaccf5a04bdec9822d2667c
220
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing if true { let start = [Void{ ([Void{ class case c,
22
87
0.740909
e8473a51ff4340d0b55c3befc8fd6181e76266a6
2,525
// // SBTLMapMock.swift // SBTLMapTest // // Created by Henry on 2019/06/21. // import XCTest @testable import SBTL struct SBTLMapMock { private(set) var rprng = ReproducibleRPNG(1024*1024) private(set) var sys = [Int:SBTLMockValue]() private(set) var impl = SBTLMap<Int,SBTLMockValue>() private var insertedKeys = [Int]() init() { } mutating func runRandom(_ n: Int) { for _ in 0..<n { stepRandom() } } mutating func stepRandom() { switch rprng.nextWithRotation() % 3 { case 0: insertRandom() case 1: updateRandom() case 2: removeRandom() default: fatalError() } } mutating func insert(_ k: Int, _ v: Int) { sys[k] = SBTLMockValue(value: v) impl[k] = SBTLMockValue(value: v) XCTAssertEqual(impl[k]?.value, v) insertedKeys.append(k) } mutating func insertRandom() { let k = rprng.nextWithRotation() let v = rprng.nextWithRotation() insert(k, v) } mutating func updateRandom() { guard insertedKeys.count > 0 else { return } let i = rprng.nextWithRotation(in: 0..<insertedKeys.count) let k = insertedKeys[i] let v = rprng.nextWithRotation() sys[k] = SBTLMockValue(value: v) impl[k] = SBTLMockValue(value: v) insertedKeys.remove(at: i) XCTAssertEqual(impl[k]?.value, v) } mutating func removeRandom() { guard insertedKeys.count > 0 else { return } let i = rprng.nextWithRotation(in: 0..<insertedKeys.count) let k = insertedKeys[i] sys[k] = nil impl[k] = nil XCTAssertEqual(impl[k]?.value, nil) insertedKeys.remove(at: i) } mutating func validate() { XCTAssertEqual(sys.count, impl.count) for (k,v) in sys { let a = impl[k] as SBTLMockValue? XCTAssertEqual(a, v) } for (k,v) in impl { let a = sys[k] XCTAssertEqual(a, v) } } } extension SBTLMapMock { var sysSortedKVs: [(Int,Int)] { return sys.map({ k,v in (k,v.value) }).sorted(by: { a,b in a.0 < b.0 }) } var implSortedKVs: [(Int,Int)] { return impl.map({ k,v in (k,v.value) }).sorted(by: { a,b in a.0 < b.0 }) } } //struct SBTLMockKey: Equatable, Comparable { // var value = 0 //} struct SBTLMockValue: SBTLValueProtocol, Equatable { var value = 0 var sum: Int { return value } }
27.747253
80
0.562376
67ab56a6c1bf18541648f8d5a808663c3f5c44be
37,817
/// /// Generated by Swift GYB. /// public struct One<S>: ScreenBuilder where S: Screen { public typealias Content = S.Content public typealias Context = S.Context public let _0: S public func index(of keyPath: PartialKeyPath<Self>) -> Int { 0 } public func keyPath(at index: Int) -> PartialKeyPath<Self> { \._0 } public func makeContent<From>(_ context: Context, router: Router<From>) -> Content where From: Screen, From.PathFrom == Self { let (c1, _) = _0.makeContent(context, router: router.next(path: \._0, isActive: true)) return c1 } public func updateContent(_ content: S.Content, with context: S.Context) { _0.updateContent(content, with: context) } } extension ContentBuilder { public static func buildBlock<C0>(_ c0: C0) -> One<C0> { One(_0: c0) } } public protocol TwoScreenBuilder: ScreenBuilder where PathFrom == (T0, T1) { associatedtype T0: Screen associatedtype T1: Screen } extension TwoScreenBuilder { public func index(of keyPath: PartialKeyPath<PathFrom>) -> Int { switch keyPath { case \PathFrom.0: return 0 case \PathFrom.1: return 1 default: return 0 } } public func keyPath(at index: Int) -> PartialKeyPath<PathFrom> { switch index { case 0: return \.0 case 1: return \.1 default: return \.0 } } } public protocol ThreeScreenBuilder: ScreenBuilder where PathFrom == (T0, T1, T2) { associatedtype T0: Screen associatedtype T1: Screen associatedtype T2: Screen } extension ThreeScreenBuilder { public func index(of keyPath: PartialKeyPath<PathFrom>) -> Int { switch keyPath { case \PathFrom.0: return 0 case \PathFrom.1: return 1 case \PathFrom.2: return 2 default: return 0 } } public func keyPath(at index: Int) -> PartialKeyPath<PathFrom> { switch index { case 0: return \.0 case 1: return \.1 case 2: return \.2 default: return \.0 } } } public protocol FourScreenBuilder: ScreenBuilder where PathFrom == (T0, T1, T2, T3) { associatedtype T0: Screen associatedtype T1: Screen associatedtype T2: Screen associatedtype T3: Screen } extension FourScreenBuilder { public func index(of keyPath: PartialKeyPath<PathFrom>) -> Int { switch keyPath { case \PathFrom.0: return 0 case \PathFrom.1: return 1 case \PathFrom.2: return 2 case \PathFrom.3: return 3 default: return 0 } } public func keyPath(at index: Int) -> PartialKeyPath<PathFrom> { switch index { case 0: return \.0 case 1: return \.1 case 2: return \.2 case 3: return \.3 default: return \.0 } } } public protocol FiveScreenBuilder: ScreenBuilder where PathFrom == (T0, T1, T2, T3, T4) { associatedtype T0: Screen associatedtype T1: Screen associatedtype T2: Screen associatedtype T3: Screen associatedtype T4: Screen } extension FiveScreenBuilder { public func index(of keyPath: PartialKeyPath<PathFrom>) -> Int { switch keyPath { case \PathFrom.0: return 0 case \PathFrom.1: return 1 case \PathFrom.2: return 2 case \PathFrom.3: return 3 case \PathFrom.4: return 4 default: return 0 } } public func keyPath(at index: Int) -> PartialKeyPath<PathFrom> { switch index { case 0: return \.0 case 1: return \.1 case 2: return \.2 case 3: return \.3 case 4: return \.4 default: return \.0 } } } public protocol SixScreenBuilder: ScreenBuilder where PathFrom == (T0, T1, T2, T3, T4, T5) { associatedtype T0: Screen associatedtype T1: Screen associatedtype T2: Screen associatedtype T3: Screen associatedtype T4: Screen associatedtype T5: Screen } extension SixScreenBuilder { public func index(of keyPath: PartialKeyPath<PathFrom>) -> Int { switch keyPath { case \PathFrom.0: return 0 case \PathFrom.1: return 1 case \PathFrom.2: return 2 case \PathFrom.3: return 3 case \PathFrom.4: return 4 case \PathFrom.5: return 5 default: return 0 } } public func keyPath(at index: Int) -> PartialKeyPath<PathFrom> { switch index { case 0: return \.0 case 1: return \.1 case 2: return \.2 case 3: return \.3 case 4: return \.4 case 5: return \.5 default: return \.0 } } } public protocol SevenScreenBuilder: ScreenBuilder where PathFrom == (T0, T1, T2, T3, T4, T5, T6) { associatedtype T0: Screen associatedtype T1: Screen associatedtype T2: Screen associatedtype T3: Screen associatedtype T4: Screen associatedtype T5: Screen associatedtype T6: Screen } extension SevenScreenBuilder { public func index(of keyPath: PartialKeyPath<PathFrom>) -> Int { switch keyPath { case \PathFrom.0: return 0 case \PathFrom.1: return 1 case \PathFrom.2: return 2 case \PathFrom.3: return 3 case \PathFrom.4: return 4 case \PathFrom.5: return 5 case \PathFrom.6: return 6 default: return 0 } } public func keyPath(at index: Int) -> PartialKeyPath<PathFrom> { switch index { case 0: return \.0 case 1: return \.1 case 2: return \.2 case 3: return \.3 case 4: return \.4 case 5: return \.5 case 6: return \.6 default: return \.0 } } } public protocol EightScreenBuilder: ScreenBuilder where PathFrom == (T0, T1, T2, T3, T4, T5, T6, T7) { associatedtype T0: Screen associatedtype T1: Screen associatedtype T2: Screen associatedtype T3: Screen associatedtype T4: Screen associatedtype T5: Screen associatedtype T6: Screen associatedtype T7: Screen } extension EightScreenBuilder { public func index(of keyPath: PartialKeyPath<PathFrom>) -> Int { switch keyPath { case \PathFrom.0: return 0 case \PathFrom.1: return 1 case \PathFrom.2: return 2 case \PathFrom.3: return 3 case \PathFrom.4: return 4 case \PathFrom.5: return 5 case \PathFrom.6: return 6 case \PathFrom.7: return 7 default: return 0 } } public func keyPath(at index: Int) -> PartialKeyPath<PathFrom> { switch index { case 0: return \.0 case 1: return \.1 case 2: return \.2 case 3: return \.3 case 4: return \.4 case 5: return \.5 case 6: return \.6 case 7: return \.7 default: return \.0 } } } public protocol NineScreenBuilder: ScreenBuilder where PathFrom == (T0, T1, T2, T3, T4, T5, T6, T7, T8) { associatedtype T0: Screen associatedtype T1: Screen associatedtype T2: Screen associatedtype T3: Screen associatedtype T4: Screen associatedtype T5: Screen associatedtype T6: Screen associatedtype T7: Screen associatedtype T8: Screen } extension NineScreenBuilder { public func index(of keyPath: PartialKeyPath<PathFrom>) -> Int { switch keyPath { case \PathFrom.0: return 0 case \PathFrom.1: return 1 case \PathFrom.2: return 2 case \PathFrom.3: return 3 case \PathFrom.4: return 4 case \PathFrom.5: return 5 case \PathFrom.6: return 6 case \PathFrom.7: return 7 case \PathFrom.8: return 8 default: return 0 } } public func keyPath(at index: Int) -> PartialKeyPath<PathFrom> { switch index { case 0: return \.0 case 1: return \.1 case 2: return \.2 case 3: return \.3 case 4: return \.4 case 5: return \.5 case 6: return \.6 case 7: return \.7 case 8: return \.8 default: return \.0 } } } #if os(macOS) || os(iOS) || os(tvOS) public struct OneController<S>: ScreenBuilder where S: Screen, S.Content: Controller { public typealias Content = [Controller] public typealias Context = S.Context let _0: S public func index(of keyPath: PartialKeyPath<Self>) -> Int { 0 } public func keyPath(at index: Int) -> PartialKeyPath<Self> { \._0 } public func makeContent<From>(_ context: S.Context, router: Router<From>) -> [Controller] where From : ContentScreen, Self.PathFrom == From.PathFrom { [makeContent(at: \._0, isActive: true, context: context, router: router)] } public func updateContent(_ content: [Controller], with context: S.Context) { _0.updateContent(content[0] as! S.Content, with: context) } } public struct TwoController<T0, T1>: TwoScreenBuilder, _ScreenBuilder where T0: Screen, T1: Screen, T0.Content: Controller, T1.Content: Controller { public typealias PathFrom = (T0, T1) public typealias Context = (T0.Context, T1.Context) public typealias Content = [Controller] let _0: (T0, T1) public func makeContent<From>(_ context: Context, router: Router<From>) -> Content where PathFrom == From.PathFrom, From : ContentScreen { let c0 = makeContent(at: \.0, isActive: true, context: context.0, router: router) let c1 = makeContent(at: \.1, isActive: false, context: context.1, router: router) return [c0, c1] } public func updateContent(_ content: [Controller], with context: Context) { _0.0.updateContent(content[0] as! T0.Content, with: context.0) _0.1.updateContent(content[1] as! T1.Content, with: context.1) } } public struct ThreeController<T0, T1, T2>: ThreeScreenBuilder, _ScreenBuilder where T0: Screen, T1: Screen, T2: Screen, T0.Content: Controller, T1.Content: Controller, T2.Content: Controller { public typealias PathFrom = (T0, T1, T2) public typealias Context = (T0.Context, T1.Context, T2.Context) public typealias Content = [Controller] let _0: (T0, T1, T2) public func makeContent<From>(_ context: Context, router: Router<From>) -> Content where PathFrom == From.PathFrom, From : ContentScreen { let c0 = makeContent(at: \.0, isActive: true, context: context.0, router: router) let c1 = makeContent(at: \.1, isActive: false, context: context.1, router: router) let c2 = makeContent(at: \.2, isActive: false, context: context.2, router: router) return [c0, c1, c2] } public func updateContent(_ content: [Controller], with context: Context) { _0.0.updateContent(content[0] as! T0.Content, with: context.0) _0.1.updateContent(content[1] as! T1.Content, with: context.1) _0.2.updateContent(content[2] as! T2.Content, with: context.2) } } public struct FourController<T0, T1, T2, T3>: FourScreenBuilder, _ScreenBuilder where T0: Screen, T1: Screen, T2: Screen, T3: Screen, T0.Content: Controller, T1.Content: Controller, T2.Content: Controller, T3.Content: Controller { public typealias PathFrom = (T0, T1, T2, T3) public typealias Context = (T0.Context, T1.Context, T2.Context, T3.Context) public typealias Content = [Controller] let _0: (T0, T1, T2, T3) public func makeContent<From>(_ context: Context, router: Router<From>) -> Content where PathFrom == From.PathFrom, From : ContentScreen { let c0 = makeContent(at: \.0, isActive: true, context: context.0, router: router) let c1 = makeContent(at: \.1, isActive: false, context: context.1, router: router) let c2 = makeContent(at: \.2, isActive: false, context: context.2, router: router) let c3 = makeContent(at: \.3, isActive: false, context: context.3, router: router) return [c0, c1, c2, c3] } public func updateContent(_ content: [Controller], with context: Context) { _0.0.updateContent(content[0] as! T0.Content, with: context.0) _0.1.updateContent(content[1] as! T1.Content, with: context.1) _0.2.updateContent(content[2] as! T2.Content, with: context.2) _0.3.updateContent(content[3] as! T3.Content, with: context.3) } } public struct FiveController<T0, T1, T2, T3, T4>: FiveScreenBuilder, _ScreenBuilder where T0: Screen, T1: Screen, T2: Screen, T3: Screen, T4: Screen, T0.Content: Controller, T1.Content: Controller, T2.Content: Controller, T3.Content: Controller, T4.Content: Controller { public typealias PathFrom = (T0, T1, T2, T3, T4) public typealias Context = (T0.Context, T1.Context, T2.Context, T3.Context, T4.Context) public typealias Content = [Controller] let _0: (T0, T1, T2, T3, T4) public func makeContent<From>(_ context: Context, router: Router<From>) -> Content where PathFrom == From.PathFrom, From : ContentScreen { let c0 = makeContent(at: \.0, isActive: true, context: context.0, router: router) let c1 = makeContent(at: \.1, isActive: false, context: context.1, router: router) let c2 = makeContent(at: \.2, isActive: false, context: context.2, router: router) let c3 = makeContent(at: \.3, isActive: false, context: context.3, router: router) let c4 = makeContent(at: \.4, isActive: false, context: context.4, router: router) return [c0, c1, c2, c3, c4] } public func updateContent(_ content: [Controller], with context: Context) { _0.0.updateContent(content[0] as! T0.Content, with: context.0) _0.1.updateContent(content[1] as! T1.Content, with: context.1) _0.2.updateContent(content[2] as! T2.Content, with: context.2) _0.3.updateContent(content[3] as! T3.Content, with: context.3) _0.4.updateContent(content[4] as! T4.Content, with: context.4) } } public struct SixController<T0, T1, T2, T3, T4, T5>: SixScreenBuilder, _ScreenBuilder where T0: Screen, T1: Screen, T2: Screen, T3: Screen, T4: Screen, T5: Screen, T0.Content: Controller, T1.Content: Controller, T2.Content: Controller, T3.Content: Controller, T4.Content: Controller, T5.Content: Controller { public typealias PathFrom = (T0, T1, T2, T3, T4, T5) public typealias Context = (T0.Context, T1.Context, T2.Context, T3.Context, T4.Context, T5.Context) public typealias Content = [Controller] let _0: (T0, T1, T2, T3, T4, T5) public func makeContent<From>(_ context: Context, router: Router<From>) -> Content where PathFrom == From.PathFrom, From : ContentScreen { let c0 = makeContent(at: \.0, isActive: true, context: context.0, router: router) let c1 = makeContent(at: \.1, isActive: false, context: context.1, router: router) let c2 = makeContent(at: \.2, isActive: false, context: context.2, router: router) let c3 = makeContent(at: \.3, isActive: false, context: context.3, router: router) let c4 = makeContent(at: \.4, isActive: false, context: context.4, router: router) let c5 = makeContent(at: \.5, isActive: false, context: context.5, router: router) return [c0, c1, c2, c3, c4, c5] } public func updateContent(_ content: [Controller], with context: Context) { _0.0.updateContent(content[0] as! T0.Content, with: context.0) _0.1.updateContent(content[1] as! T1.Content, with: context.1) _0.2.updateContent(content[2] as! T2.Content, with: context.2) _0.3.updateContent(content[3] as! T3.Content, with: context.3) _0.4.updateContent(content[4] as! T4.Content, with: context.4) _0.5.updateContent(content[5] as! T5.Content, with: context.5) } } public struct SevenController<T0, T1, T2, T3, T4, T5, T6>: SevenScreenBuilder, _ScreenBuilder where T0: Screen, T1: Screen, T2: Screen, T3: Screen, T4: Screen, T5: Screen, T6: Screen, T0.Content: Controller, T1.Content: Controller, T2.Content: Controller, T3.Content: Controller, T4.Content: Controller, T5.Content: Controller, T6.Content: Controller { public typealias PathFrom = (T0, T1, T2, T3, T4, T5, T6) public typealias Context = (T0.Context, T1.Context, T2.Context, T3.Context, T4.Context, T5.Context, T6.Context) public typealias Content = [Controller] let _0: (T0, T1, T2, T3, T4, T5, T6) public func makeContent<From>(_ context: Context, router: Router<From>) -> Content where PathFrom == From.PathFrom, From : ContentScreen { let c0 = makeContent(at: \.0, isActive: true, context: context.0, router: router) let c1 = makeContent(at: \.1, isActive: false, context: context.1, router: router) let c2 = makeContent(at: \.2, isActive: false, context: context.2, router: router) let c3 = makeContent(at: \.3, isActive: false, context: context.3, router: router) let c4 = makeContent(at: \.4, isActive: false, context: context.4, router: router) let c5 = makeContent(at: \.5, isActive: false, context: context.5, router: router) let c6 = makeContent(at: \.6, isActive: false, context: context.6, router: router) return [c0, c1, c2, c3, c4, c5, c6] } public func updateContent(_ content: [Controller], with context: Context) { _0.0.updateContent(content[0] as! T0.Content, with: context.0) _0.1.updateContent(content[1] as! T1.Content, with: context.1) _0.2.updateContent(content[2] as! T2.Content, with: context.2) _0.3.updateContent(content[3] as! T3.Content, with: context.3) _0.4.updateContent(content[4] as! T4.Content, with: context.4) _0.5.updateContent(content[5] as! T5.Content, with: context.5) _0.6.updateContent(content[6] as! T6.Content, with: context.6) } } public struct EightController<T0, T1, T2, T3, T4, T5, T6, T7>: EightScreenBuilder, _ScreenBuilder where T0: Screen, T1: Screen, T2: Screen, T3: Screen, T4: Screen, T5: Screen, T6: Screen, T7: Screen, T0.Content: Controller, T1.Content: Controller, T2.Content: Controller, T3.Content: Controller, T4.Content: Controller, T5.Content: Controller, T6.Content: Controller, T7.Content: Controller { public typealias PathFrom = (T0, T1, T2, T3, T4, T5, T6, T7) public typealias Context = (T0.Context, T1.Context, T2.Context, T3.Context, T4.Context, T5.Context, T6.Context, T7.Context) public typealias Content = [Controller] let _0: (T0, T1, T2, T3, T4, T5, T6, T7) public func makeContent<From>(_ context: Context, router: Router<From>) -> Content where PathFrom == From.PathFrom, From : ContentScreen { let c0 = makeContent(at: \.0, isActive: true, context: context.0, router: router) let c1 = makeContent(at: \.1, isActive: false, context: context.1, router: router) let c2 = makeContent(at: \.2, isActive: false, context: context.2, router: router) let c3 = makeContent(at: \.3, isActive: false, context: context.3, router: router) let c4 = makeContent(at: \.4, isActive: false, context: context.4, router: router) let c5 = makeContent(at: \.5, isActive: false, context: context.5, router: router) let c6 = makeContent(at: \.6, isActive: false, context: context.6, router: router) let c7 = makeContent(at: \.7, isActive: false, context: context.7, router: router) return [c0, c1, c2, c3, c4, c5, c6, c7] } public func updateContent(_ content: [Controller], with context: Context) { _0.0.updateContent(content[0] as! T0.Content, with: context.0) _0.1.updateContent(content[1] as! T1.Content, with: context.1) _0.2.updateContent(content[2] as! T2.Content, with: context.2) _0.3.updateContent(content[3] as! T3.Content, with: context.3) _0.4.updateContent(content[4] as! T4.Content, with: context.4) _0.5.updateContent(content[5] as! T5.Content, with: context.5) _0.6.updateContent(content[6] as! T6.Content, with: context.6) _0.7.updateContent(content[7] as! T7.Content, with: context.7) } } public struct NineController<T0, T1, T2, T3, T4, T5, T6, T7, T8>: NineScreenBuilder, _ScreenBuilder where T0: Screen, T1: Screen, T2: Screen, T3: Screen, T4: Screen, T5: Screen, T6: Screen, T7: Screen, T8: Screen, T0.Content: Controller, T1.Content: Controller, T2.Content: Controller, T3.Content: Controller, T4.Content: Controller, T5.Content: Controller, T6.Content: Controller, T7.Content: Controller, T8.Content: Controller { public typealias PathFrom = (T0, T1, T2, T3, T4, T5, T6, T7, T8) public typealias Context = (T0.Context, T1.Context, T2.Context, T3.Context, T4.Context, T5.Context, T6.Context, T7.Context, T8.Context) public typealias Content = [Controller] let _0: (T0, T1, T2, T3, T4, T5, T6, T7, T8) public func makeContent<From>(_ context: Context, router: Router<From>) -> Content where PathFrom == From.PathFrom, From : ContentScreen { let c0 = makeContent(at: \.0, isActive: true, context: context.0, router: router) let c1 = makeContent(at: \.1, isActive: false, context: context.1, router: router) let c2 = makeContent(at: \.2, isActive: false, context: context.2, router: router) let c3 = makeContent(at: \.3, isActive: false, context: context.3, router: router) let c4 = makeContent(at: \.4, isActive: false, context: context.4, router: router) let c5 = makeContent(at: \.5, isActive: false, context: context.5, router: router) let c6 = makeContent(at: \.6, isActive: false, context: context.6, router: router) let c7 = makeContent(at: \.7, isActive: false, context: context.7, router: router) let c8 = makeContent(at: \.8, isActive: false, context: context.8, router: router) return [c0, c1, c2, c3, c4, c5, c6, c7, c8] } public func updateContent(_ content: [Controller], with context: Context) { _0.0.updateContent(content[0] as! T0.Content, with: context.0) _0.1.updateContent(content[1] as! T1.Content, with: context.1) _0.2.updateContent(content[2] as! T2.Content, with: context.2) _0.3.updateContent(content[3] as! T3.Content, with: context.3) _0.4.updateContent(content[4] as! T4.Content, with: context.4) _0.5.updateContent(content[5] as! T5.Content, with: context.5) _0.6.updateContent(content[6] as! T6.Content, with: context.6) _0.7.updateContent(content[7] as! T7.Content, with: context.7) _0.8.updateContent(content[8] as! T8.Content, with: context.8) } } extension ContentBuilder { public static func buildBlock<C0>(_ c0: C0) -> OneController<C0> { OneController(_0: c0) } public static func buildBlock<T0, T1>( _ c0: T0, _ c1: T1 ) -> TwoController<T0, T1> { TwoController(_0: (c0, c1)) } public static func buildBlock<T0, T1, T2>( _ c0: T0, _ c1: T1, _ c2: T2 ) -> ThreeController<T0, T1, T2> { ThreeController(_0: (c0, c1, c2)) } public static func buildBlock<T0, T1, T2, T3>( _ c0: T0, _ c1: T1, _ c2: T2, _ c3: T3 ) -> FourController<T0, T1, T2, T3> { FourController(_0: (c0, c1, c2, c3)) } public static func buildBlock<T0, T1, T2, T3, T4>( _ c0: T0, _ c1: T1, _ c2: T2, _ c3: T3, _ c4: T4 ) -> FiveController<T0, T1, T2, T3, T4> { FiveController(_0: (c0, c1, c2, c3, c4)) } public static func buildBlock<T0, T1, T2, T3, T4, T5>( _ c0: T0, _ c1: T1, _ c2: T2, _ c3: T3, _ c4: T4, _ c5: T5 ) -> SixController<T0, T1, T2, T3, T4, T5> { SixController(_0: (c0, c1, c2, c3, c4, c5)) } public static func buildBlock<T0, T1, T2, T3, T4, T5, T6>( _ c0: T0, _ c1: T1, _ c2: T2, _ c3: T3, _ c4: T4, _ c5: T5, _ c6: T6 ) -> SevenController<T0, T1, T2, T3, T4, T5, T6> { SevenController(_0: (c0, c1, c2, c3, c4, c5, c6)) } public static func buildBlock<T0, T1, T2, T3, T4, T5, T6, T7>( _ c0: T0, _ c1: T1, _ c2: T2, _ c3: T3, _ c4: T4, _ c5: T5, _ c6: T6, _ c7: T7 ) -> EightController<T0, T1, T2, T3, T4, T5, T6, T7> { EightController(_0: (c0, c1, c2, c3, c4, c5, c6, c7)) } public static func buildBlock<T0, T1, T2, T3, T4, T5, T6, T7, T8>( _ c0: T0, _ c1: T1, _ c2: T2, _ c3: T3, _ c4: T4, _ c5: T5, _ c6: T6, _ c7: T7, _ c8: T8 ) -> NineController<T0, T1, T2, T3, T4, T5, T6, T7, T8> { NineController(_0: (c0, c1, c2, c3, c4, c5, c6, c7, c8)) } } #endif #if canImport(SwiftUI) && canImport(Combine) import SwiftUI @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) public struct TwoView<T0, T1>: TwoScreenBuilder, _ScreenBuilder where T0: Screen, T1: Screen, T0.Content: View, T1.Content: View { public typealias PathFrom = (T0, T1) public typealias Context = (T0.Context, T1.Context) public typealias Content = (AnyView, AnyView) let _0: (T0, T1) public func makeContent<From>(_ context: Context, router: Router<From>) -> Content where From: ContentScreen, PathFrom == From.PathFrom { let (c0, _) = _0.0.makeContent(context.0, router: router.next(path: \.0, isActive: true)) let (c1, _) = _0.1.makeContent(context.1, router: router.next(path: \.1, isActive: false)) return (AnyView(c0.tag(0)), AnyView(c1.tag(1))) } } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) public struct ThreeView<T0, T1, T2>: ThreeScreenBuilder, _ScreenBuilder where T0: Screen, T1: Screen, T2: Screen, T0.Content: View, T1.Content: View, T2.Content: View { public typealias PathFrom = (T0, T1, T2) public typealias Context = (T0.Context, T1.Context, T2.Context) public typealias Content = (AnyView, AnyView, AnyView) let _0: (T0, T1, T2) public func makeContent<From>(_ context: Context, router: Router<From>) -> Content where From: ContentScreen, PathFrom == From.PathFrom { let (c0, _) = _0.0.makeContent(context.0, router: router.next(path: \.0, isActive: true)) let (c1, _) = _0.1.makeContent(context.1, router: router.next(path: \.1, isActive: false)) let (c2, _) = _0.2.makeContent(context.2, router: router.next(path: \.2, isActive: false)) return (AnyView(c0.tag(0)), AnyView(c1.tag(1)), AnyView(c2.tag(2))) } } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) public struct FourView<T0, T1, T2, T3>: FourScreenBuilder, _ScreenBuilder where T0: Screen, T1: Screen, T2: Screen, T3: Screen, T0.Content: View, T1.Content: View, T2.Content: View, T3.Content: View { public typealias PathFrom = (T0, T1, T2, T3) public typealias Context = (T0.Context, T1.Context, T2.Context, T3.Context) public typealias Content = (AnyView, AnyView, AnyView, AnyView) let _0: (T0, T1, T2, T3) public func makeContent<From>(_ context: Context, router: Router<From>) -> Content where From: ContentScreen, PathFrom == From.PathFrom { let (c0, _) = _0.0.makeContent(context.0, router: router.next(path: \.0, isActive: true)) let (c1, _) = _0.1.makeContent(context.1, router: router.next(path: \.1, isActive: false)) let (c2, _) = _0.2.makeContent(context.2, router: router.next(path: \.2, isActive: false)) let (c3, _) = _0.3.makeContent(context.3, router: router.next(path: \.3, isActive: false)) return (AnyView(c0.tag(0)), AnyView(c1.tag(1)), AnyView(c2.tag(2)), AnyView(c3.tag(3))) } } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) public struct FiveView<T0, T1, T2, T3, T4>: FiveScreenBuilder, _ScreenBuilder where T0: Screen, T1: Screen, T2: Screen, T3: Screen, T4: Screen, T0.Content: View, T1.Content: View, T2.Content: View, T3.Content: View, T4.Content: View { public typealias PathFrom = (T0, T1, T2, T3, T4) public typealias Context = (T0.Context, T1.Context, T2.Context, T3.Context, T4.Context) public typealias Content = (AnyView, AnyView, AnyView, AnyView, AnyView) let _0: (T0, T1, T2, T3, T4) public func makeContent<From>(_ context: Context, router: Router<From>) -> Content where From: ContentScreen, PathFrom == From.PathFrom { let (c0, _) = _0.0.makeContent(context.0, router: router.next(path: \.0, isActive: true)) let (c1, _) = _0.1.makeContent(context.1, router: router.next(path: \.1, isActive: false)) let (c2, _) = _0.2.makeContent(context.2, router: router.next(path: \.2, isActive: false)) let (c3, _) = _0.3.makeContent(context.3, router: router.next(path: \.3, isActive: false)) let (c4, _) = _0.4.makeContent(context.4, router: router.next(path: \.4, isActive: false)) return (AnyView(c0.tag(0)), AnyView(c1.tag(1)), AnyView(c2.tag(2)), AnyView(c3.tag(3)), AnyView(c4.tag(4))) } } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) public struct SixView<T0, T1, T2, T3, T4, T5>: SixScreenBuilder, _ScreenBuilder where T0: Screen, T1: Screen, T2: Screen, T3: Screen, T4: Screen, T5: Screen, T0.Content: View, T1.Content: View, T2.Content: View, T3.Content: View, T4.Content: View, T5.Content: View { public typealias PathFrom = (T0, T1, T2, T3, T4, T5) public typealias Context = (T0.Context, T1.Context, T2.Context, T3.Context, T4.Context, T5.Context) public typealias Content = (AnyView, AnyView, AnyView, AnyView, AnyView, AnyView) let _0: (T0, T1, T2, T3, T4, T5) public func makeContent<From>(_ context: Context, router: Router<From>) -> Content where From: ContentScreen, PathFrom == From.PathFrom { let (c0, _) = _0.0.makeContent(context.0, router: router.next(path: \.0, isActive: true)) let (c1, _) = _0.1.makeContent(context.1, router: router.next(path: \.1, isActive: false)) let (c2, _) = _0.2.makeContent(context.2, router: router.next(path: \.2, isActive: false)) let (c3, _) = _0.3.makeContent(context.3, router: router.next(path: \.3, isActive: false)) let (c4, _) = _0.4.makeContent(context.4, router: router.next(path: \.4, isActive: false)) let (c5, _) = _0.5.makeContent(context.5, router: router.next(path: \.5, isActive: false)) return (AnyView(c0.tag(0)), AnyView(c1.tag(1)), AnyView(c2.tag(2)), AnyView(c3.tag(3)), AnyView(c4.tag(4)), AnyView(c5.tag(5))) } } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) public struct SevenView<T0, T1, T2, T3, T4, T5, T6>: SevenScreenBuilder, _ScreenBuilder where T0: Screen, T1: Screen, T2: Screen, T3: Screen, T4: Screen, T5: Screen, T6: Screen, T0.Content: View, T1.Content: View, T2.Content: View, T3.Content: View, T4.Content: View, T5.Content: View, T6.Content: View { public typealias PathFrom = (T0, T1, T2, T3, T4, T5, T6) public typealias Context = (T0.Context, T1.Context, T2.Context, T3.Context, T4.Context, T5.Context, T6.Context) public typealias Content = (AnyView, AnyView, AnyView, AnyView, AnyView, AnyView, AnyView) let _0: (T0, T1, T2, T3, T4, T5, T6) public func makeContent<From>(_ context: Context, router: Router<From>) -> Content where From: ContentScreen, PathFrom == From.PathFrom { let (c0, _) = _0.0.makeContent(context.0, router: router.next(path: \.0, isActive: true)) let (c1, _) = _0.1.makeContent(context.1, router: router.next(path: \.1, isActive: false)) let (c2, _) = _0.2.makeContent(context.2, router: router.next(path: \.2, isActive: false)) let (c3, _) = _0.3.makeContent(context.3, router: router.next(path: \.3, isActive: false)) let (c4, _) = _0.4.makeContent(context.4, router: router.next(path: \.4, isActive: false)) let (c5, _) = _0.5.makeContent(context.5, router: router.next(path: \.5, isActive: false)) let (c6, _) = _0.6.makeContent(context.6, router: router.next(path: \.6, isActive: false)) return (AnyView(c0.tag(0)), AnyView(c1.tag(1)), AnyView(c2.tag(2)), AnyView(c3.tag(3)), AnyView(c4.tag(4)), AnyView(c5.tag(5)), AnyView(c6.tag(6))) } } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) public struct EightView<T0, T1, T2, T3, T4, T5, T6, T7>: EightScreenBuilder, _ScreenBuilder where T0: Screen, T1: Screen, T2: Screen, T3: Screen, T4: Screen, T5: Screen, T6: Screen, T7: Screen, T0.Content: View, T1.Content: View, T2.Content: View, T3.Content: View, T4.Content: View, T5.Content: View, T6.Content: View, T7.Content: View { public typealias PathFrom = (T0, T1, T2, T3, T4, T5, T6, T7) public typealias Context = (T0.Context, T1.Context, T2.Context, T3.Context, T4.Context, T5.Context, T6.Context, T7.Context) public typealias Content = (AnyView, AnyView, AnyView, AnyView, AnyView, AnyView, AnyView, AnyView) let _0: (T0, T1, T2, T3, T4, T5, T6, T7) public func makeContent<From>(_ context: Context, router: Router<From>) -> Content where From: ContentScreen, PathFrom == From.PathFrom { let (c0, _) = _0.0.makeContent(context.0, router: router.next(path: \.0, isActive: true)) let (c1, _) = _0.1.makeContent(context.1, router: router.next(path: \.1, isActive: false)) let (c2, _) = _0.2.makeContent(context.2, router: router.next(path: \.2, isActive: false)) let (c3, _) = _0.3.makeContent(context.3, router: router.next(path: \.3, isActive: false)) let (c4, _) = _0.4.makeContent(context.4, router: router.next(path: \.4, isActive: false)) let (c5, _) = _0.5.makeContent(context.5, router: router.next(path: \.5, isActive: false)) let (c6, _) = _0.6.makeContent(context.6, router: router.next(path: \.6, isActive: false)) let (c7, _) = _0.7.makeContent(context.7, router: router.next(path: \.7, isActive: false)) return (AnyView(c0.tag(0)), AnyView(c1.tag(1)), AnyView(c2.tag(2)), AnyView(c3.tag(3)), AnyView(c4.tag(4)), AnyView(c5.tag(5)), AnyView(c6.tag(6)), AnyView(c7.tag(7))) } } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) public struct NineView<T0, T1, T2, T3, T4, T5, T6, T7, T8>: NineScreenBuilder, _ScreenBuilder where T0: Screen, T1: Screen, T2: Screen, T3: Screen, T4: Screen, T5: Screen, T6: Screen, T7: Screen, T8: Screen, T0.Content: View, T1.Content: View, T2.Content: View, T3.Content: View, T4.Content: View, T5.Content: View, T6.Content: View, T7.Content: View, T8.Content: View { public typealias PathFrom = (T0, T1, T2, T3, T4, T5, T6, T7, T8) public typealias Context = (T0.Context, T1.Context, T2.Context, T3.Context, T4.Context, T5.Context, T6.Context, T7.Context, T8.Context) public typealias Content = (AnyView, AnyView, AnyView, AnyView, AnyView, AnyView, AnyView, AnyView, AnyView) let _0: (T0, T1, T2, T3, T4, T5, T6, T7, T8) public func makeContent<From>(_ context: Context, router: Router<From>) -> Content where From: ContentScreen, PathFrom == From.PathFrom { let (c0, _) = _0.0.makeContent(context.0, router: router.next(path: \.0, isActive: true)) let (c1, _) = _0.1.makeContent(context.1, router: router.next(path: \.1, isActive: false)) let (c2, _) = _0.2.makeContent(context.2, router: router.next(path: \.2, isActive: false)) let (c3, _) = _0.3.makeContent(context.3, router: router.next(path: \.3, isActive: false)) let (c4, _) = _0.4.makeContent(context.4, router: router.next(path: \.4, isActive: false)) let (c5, _) = _0.5.makeContent(context.5, router: router.next(path: \.5, isActive: false)) let (c6, _) = _0.6.makeContent(context.6, router: router.next(path: \.6, isActive: false)) let (c7, _) = _0.7.makeContent(context.7, router: router.next(path: \.7, isActive: false)) let (c8, _) = _0.8.makeContent(context.8, router: router.next(path: \.8, isActive: false)) return (AnyView(c0.tag(0)), AnyView(c1.tag(1)), AnyView(c2.tag(2)), AnyView(c3.tag(3)), AnyView(c4.tag(4)), AnyView(c5.tag(5)), AnyView(c6.tag(6)), AnyView(c7.tag(7)), AnyView(c8.tag(8))) } } extension ContentBuilder { @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) public static func buildBlock<T0, T1>( _ c0: T0, _ c1: T1 ) -> TwoView<T0, T1> { TwoView(_0: (c0, c1)) } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) public static func buildBlock<T0, T1, T2>( _ c0: T0, _ c1: T1, _ c2: T2 ) -> ThreeView<T0, T1, T2> { ThreeView(_0: (c0, c1, c2)) } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) public static func buildBlock<T0, T1, T2, T3>( _ c0: T0, _ c1: T1, _ c2: T2, _ c3: T3 ) -> FourView<T0, T1, T2, T3> { FourView(_0: (c0, c1, c2, c3)) } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) public static func buildBlock<T0, T1, T2, T3, T4>( _ c0: T0, _ c1: T1, _ c2: T2, _ c3: T3, _ c4: T4 ) -> FiveView<T0, T1, T2, T3, T4> { FiveView(_0: (c0, c1, c2, c3, c4)) } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) public static func buildBlock<T0, T1, T2, T3, T4, T5>( _ c0: T0, _ c1: T1, _ c2: T2, _ c3: T3, _ c4: T4, _ c5: T5 ) -> SixView<T0, T1, T2, T3, T4, T5> { SixView(_0: (c0, c1, c2, c3, c4, c5)) } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) public static func buildBlock<T0, T1, T2, T3, T4, T5, T6>( _ c0: T0, _ c1: T1, _ c2: T2, _ c3: T3, _ c4: T4, _ c5: T5, _ c6: T6 ) -> SevenView<T0, T1, T2, T3, T4, T5, T6> { SevenView(_0: (c0, c1, c2, c3, c4, c5, c6)) } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) public static func buildBlock<T0, T1, T2, T3, T4, T5, T6, T7>( _ c0: T0, _ c1: T1, _ c2: T2, _ c3: T3, _ c4: T4, _ c5: T5, _ c6: T6, _ c7: T7 ) -> EightView<T0, T1, T2, T3, T4, T5, T6, T7> { EightView(_0: (c0, c1, c2, c3, c4, c5, c6, c7)) } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) public static func buildBlock<T0, T1, T2, T3, T4, T5, T6, T7, T8>( _ c0: T0, _ c1: T1, _ c2: T2, _ c3: T3, _ c4: T4, _ c5: T5, _ c6: T6, _ c7: T7, _ c8: T8 ) -> NineView<T0, T1, T2, T3, T4, T5, T6, T7, T8> { NineView(_0: (c0, c1, c2, c3, c4, c5, c6, c7, c8)) } } #endif
49.693824
214
0.639395
bfa076f62e6a848b6d897642d2b82991034d3862
162
import XCTest #if !canImport(ObjectiveC) public func allTests() -> [XCTestCaseEntry] { return [ testCase(Kinoswin_APITests.allTests), ] } #endif
16.2
45
0.679012
ab0db3f85be67950f3d851cfd51d17224c74e05a
1,527
// // BusinessCell.swift // Yelp // // Created by Carina Boo on 10/20/16. // Copyright © 2016 Timothy Lee. All rights reserved. // import UIKit import AFNetworking class BusinessCell: UITableViewCell { @IBOutlet weak var thumbImageView: UIImageView! @IBOutlet weak var ratingImageView: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var reviewCountLabel: UILabel! @IBOutlet weak var addressLabel: UILabel! @IBOutlet weak var categoriesLabel: UILabel! @IBOutlet weak var distanceLabel: UILabel! var business: Business! { didSet { nameLabel.text = business.name reviewCountLabel.text = "\(business.reviewCount ?? 0) Reviews" addressLabel.text = business.address categoriesLabel.text = business.categories distanceLabel.text = business.distance if let imageURL = business.imageURL { thumbImageView.setImageWith(imageURL) } if let ratingImageURL = business.ratingImageURL { ratingImageView.setImageWith(ratingImageURL) } } } override func awakeFromNib() { super.awakeFromNib() // Initialization code thumbImageView.layer.cornerRadius = 3 thumbImageView.clipsToBounds = true } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
29.365385
74
0.64964
20e026f3f9ac6c30418591608afd9deddab58d4f
778
import UIKit public class ViewController: XNGCollectionViewController { private let kNumberOfCells = 20 public override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return kNumberOfCells } public override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) if let cell = cell as? CollectionViewCell { let color = UIColor(hue: CGFloat(indexPath.item) / CGFloat(kNumberOfCells), saturation: 0.5, brightness: 1.0, alpha: 1.0) cell.color = color } return cell } }
35.363636
137
0.715938
56f49e14c048986295f5ace6f766d1ef7754dbd0
2,219
import UIKit import Backendless class ObjectsWithRelationsViewController: UITableViewController { var tableName = "" var objectIds = [String]() var related = "" var relatedTableName = "" var propertyType = "" private let FIND_RELATED = "Find with related" private let SHOW_PROPERTIES = "ShowRelatedProperties" private let utils = Utils.shared override func viewDidLoad() { super.viewDidLoad() } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return objectIds.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "ObjectIdCell", for: indexPath) cell.textLabel?.text = objectIds[indexPath.row] return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { performSegue(withIdentifier: SHOW_PROPERTIES, sender: indexPath) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let propertiesVC = segue.destination as? PropertiesViewController, let indexPath = sender as? IndexPath { propertiesVC.operation = FIND_RELATED propertiesVC.related = related propertiesVC.objectId = objectIds[indexPath.row] propertiesVC.tableName = relatedTableName Backendless.shared.data.describe(tableName: relatedTableName, responseHandler: { properties in var fields = [String : String]() for property in properties { if property.getTypeName() != "RELATION" && property.getTypeName() != "RELATION_LIST" { fields[property.name] = property.getTypeName() } } propertiesVC.fields = fields propertiesVC.tableView.reloadData() }, errorHandler: { [weak self] fault in if self != nil { self?.utils.showErrorAler(target: self!, fault: fault) } }) } } }
36.377049
109
0.621
67605af981282e4d22efd100c44481e16136a31c
3,530
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// @_exported import Foundation // Clang module import CoreFoundation import CoreGraphics //===----------------------------------------------------------------------===// // NSObject //===----------------------------------------------------------------------===// // These conformances should be located in the `ObjectiveC` module, but they can't // be placed there because string bridging is not available there. extension NSObject : CustomStringConvertible {} extension NSObject : CustomDebugStringConvertible {} public let NSNotFound: Int = .max //===----------------------------------------------------------------------===// // NSLocalizedString //===----------------------------------------------------------------------===// /// Returns a localized string, using the main bundle if one is not specified. public func NSLocalizedString(_ key: String, tableName: String? = nil, bundle: Bundle = Bundle.main, value: String = "", comment: String) -> String { return bundle.localizedString(forKey: key, value:value, table:tableName) } //===----------------------------------------------------------------------===// // NSLog //===----------------------------------------------------------------------===// public func NSLog(_ format: String, _ args: CVarArg...) { withVaList(args) { NSLogv(format, $0) } } //===----------------------------------------------------------------------===// // AnyHashable //===----------------------------------------------------------------------===// extension AnyHashable : _ObjectiveCBridgeable { public func _bridgeToObjectiveC() -> NSObject { // This is unprincipled, but pretty much any object we'll encounter in // Swift is NSObject-conforming enough to have -hash and -isEqual:. return unsafeBitCast(base as AnyObject, to: NSObject.self) } public static func _forceBridgeFromObjectiveC( _ x: NSObject, result: inout AnyHashable? ) { result = AnyHashable(x) } public static func _conditionallyBridgeFromObjectiveC( _ x: NSObject, result: inout AnyHashable? ) -> Bool { self._forceBridgeFromObjectiveC(x, result: &result) return result != nil } public static func _unconditionallyBridgeFromObjectiveC( _ source: NSObject? ) -> AnyHashable { // `nil` has historically been used as a stand-in for an empty // string; map it to an empty string. if _slowPath(source == nil) { return AnyHashable(String()) } return AnyHashable(source!) } } //===----------------------------------------------------------------------===// // CVarArg for bridged types //===----------------------------------------------------------------------===// extension CVarArg where Self: _ObjectiveCBridgeable { /// Default implementation for bridgeable types. public var _cVarArgEncoding: [Int] { let object = self._bridgeToObjectiveC() _autorelease(object) return _encodeBitsAsWords(object) } }
36.020408
82
0.510198
e886c2403d03ac96c16fe639ea4e236bc3fefb21
2,165
// // PostDiscoveryViewDataSource.swift // Photostream // // Created by Mounir Ybanez on 20/12/2016. // Copyright © 2016 Mounir Ybanez. All rights reserved. // import UIKit extension PostDiscoveryViewController { override func numberOfSections(in collectionView: UICollectionView) -> Int { switch sceneType { case .grid: return 1 case .list: return presenter.postCount } } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { switch sceneType { case .grid: return presenter.postCount case .list: return 1 } } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { switch sceneType { case .grid: let cell = PostGridCollectionCell.dequeue(from: collectionView, for: indexPath)! let item = presenter.post(at: indexPath.row) as? PostGridCollectionCellItem cell.configure(with: item) return cell case .list: let cell = PostListCollectionCell.dequeue(from: collectionView, for: indexPath)! let item = presenter.post(at: indexPath.section) as? PostListCollectionCellItem cell.configure(with: item) cell.delegate = self return cell } } override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { switch kind { case UICollectionElementKindSectionHeader where sceneType == .list: let header = PostListCollectionHeader.dequeue(from: collectionView, for: indexPath)! let item = presenter.post(at: indexPath.section) as? PostListCollectionHeaderItem header.configure(with: item) header.delegate = self return header default: return UICollectionReusableView() } } }
33.307692
171
0.627714