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
796b07a37a2cc4b71aee301aa6d69c7edf179025
2,353
// // AccountSubscribeTests.swift // ECHONetworkTests // // Created by Vladimir Sharaev on 11.11.2019. // Copyright © 2019 PixelPlex. All rights reserved. // import XCTest @testable import EchoFramework class AccountSubscribeTests: XCTestCase, SubscribeAccountDelegate { var accountUpdatesCount = 0 var echo: ECHO! override func tearDown() { super.tearDown() echo = nil } func didUpdateAccount(userAccount: UserAccount) { accountUpdatesCount += 1 } func testSubscribeAcount() { //arrange echo = ECHO(settings: Settings(build: { $0.apiOptions = [.database, .networkBroadcast, .accountHistory] $0.network = ECHONetwork(url: Constants.nodeUrl, prefix: .echo, echorandPrefix: .echo) $0.debug = true })) let exp = expectation(description: "testSubscribeAcount") //act echo.start { (result) in switch result { case .success(_): self.echo.subscribeToAccount(nameOrId: Constants.defaultName, delegate: self) self.echo.sendTransferOperation(fromNameOrId: Constants.defaultName, wif: Constants.defaultWIF, toNameOrId: Constants.defaultToName, amount: 1, asset: Constants.defaultAsset, assetForFee: nil, sendCompletion: { (result) in switch result { case .success(_): break case .failure(let error): XCTFail("testSubscribeAcount \(error)") } }) { (_) in DispatchQueue.main.asyncAfter(deadline: .now() + 2, execute: { exp.fulfill() }) } case .failure(let error): XCTFail("testSubscribeAcount \(error)") } } //assert waitForExpectations(timeout: Constants.timeout) { error in XCTAssertTrue(self.accountUpdatesCount > 0) } } }
32.680556
98
0.490863
640aa7b8d1154f8340cb08be2ae2d8a3043e9c6e
1,700
// // LocalizedStringManager.swift // LoungeMeSDK // // Created by Doğu Emre DEMİRÇİVİ on 22.07.2019. // Copyright © 2019 TAV Airports. All rights reserved. // import Foundation internal final class LocalizedStringManager { // MARK: - Static Fields private static let AVAILABLE_LANGUAGE_CODES = ["tr", "en"] private static let FALLBACK_LANGUAGE_CODE = "en" private static let STRING_MAP = [ "tr": [ "close": "KAPAT", "languageCode": "tr", "secureHomeUrl": "https://lounge.me/tr/secure-home" ], "en": [ "close": "CLOSE", "languageCode": "en", "secureHomeUrl": "https://lounge.me/en/secure-home" ] ] // MARK: - Public Static Methods public static func getValue(forKey key: String) -> String { guard var preferredLocalization = Locale.preferredLanguages[0].components(separatedBy: "-").first else { fatalError("failed to get preferred localization") } // Check if language code is fine to use, otherwise pick fallback code if !AVAILABLE_LANGUAGE_CODES.contains(preferredLocalization) { preferredLocalization = FALLBACK_LANGUAGE_CODE } guard let stringMap = STRING_MAP[preferredLocalization] else { fatalError("failed to get corresponding language map, preferredLocalization: \(preferredLocalization)") } guard let value = stringMap[key] else { fatalError("failed to get value from language map, key: \(key), preferredLocalization: \(preferredLocalization)") } return value } }
32.075472
125
0.611765
5d08d299d560484b8ff32dd7626109fb8bd8169b
1,408
// // BeamCollectionViewCell.swift // beam // // Created by Robin Speijer on 28-09-15. // Copyright © 2015 Awkward. All rights reserved. // import UIKit class BeamCollectionViewCell: UICollectionViewCell, DynamicDisplayModeView { override func didMoveToWindow() { super.didMoveToWindow() if window != nil { selectedBackgroundView = UIView(frame: bounds) selectedBackgroundView?.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight] registerForDisplayModeChangeNotifications() } else { selectedBackgroundView = nil unregisterForDisplayModeChangeNotifications() } } deinit { unregisterForDisplayModeChangeNotifications() } @objc func displayModeDidChangeNotification(_ notification: Notification) { displayModeDidChangeAnimated(true) } func displayModeDidChange() { switch displayMode { case .default: backgroundColor = UIColor.white selectedBackgroundView?.backgroundColor = UIColor.beamGreyExtraExtraLight() case .dark: backgroundColor = UIColor.beamDarkContentBackgroundColor() selectedBackgroundView?.backgroundColor = UIColor.beamGreyDark() } contentView.backgroundColor = backgroundColor } }
29.333333
124
0.665483
c16108717cfb08a153a7e9fec0fda60faee89e9f
2,749
// // XXHud.swift // Mall360 // // Created by x on 2019/3/8. // Copyright © 2019 x. All rights reserved. // import Foundation //import MBProgressHUD import ZKProgressHUD class XXHud:NSObject { class func showIndeterminate(hostView:UIView, animation:Bool) { ZKProgressHUD.setMaskStyle(.visible) ZKProgressHUD.setMaskBackgroundColor(UIColor.white) ZKProgressHUD.setAutoDismissDelay(10) ZKProgressHUD.show() return //暂时屏蔽,会导致崩溃 // return // let hud = MBProgressHUD.init(view: hostView) // hud.mode = .indeterminate // hostView.addSubview(hud) // hud.show(animated: animation) } // class func showIndeterminate(hostView:UIView, title:String,message:String, animation:Bool) { // let hud = MBProgressHUD.init(view: hostView) // hud.mode = .indeterminate // hud.label.text = title // hud.detailsLabel.text = message // hostView.addSubview(hud) // hud.show(animated: animation) // } // class func showIndeterminate(hostView:UIView, afterDelay:TimeInterval, animation:Bool) { // let hud = MBProgressHUD.init(view: hostView) // hud.mode = .indeterminate // hostView.addSubview(hud) // hud.show(animated: animation) // hud.hide(animated: animation, afterDelay: afterDelay) // } class func showIndeterminate(hostView:UIView, message:String, animation:Bool) { ZKProgressHUD.setMaskStyle(.hide) ZKProgressHUD.setAutoDismissDelay(1) if message.count > 0 { ZKProgressHUD.showMessage(message) } // let hud = MBProgressHUD.init(view: hostView) // hud.mode = .text // hud.detailsLabel.text = message // hud.detailsLabel.font = hud.label.font // hostView.addSubview(hud) // hud.show(animated: animation) // var duration = 1.0 * Double(message.count) / 15 // duration = duration < 1.0 ? 1.0:duration // duration = duration > 3.0 ? 3.0:duration // hud.hide(animated: animation, afterDelay: duration) } // class func showIndeterminate(hostView:UIView, message:String, afterDelay:TimeInterval, animation:Bool) { // ZKProgressHUD.showMessage(message) // return // let hud = MBProgressHUD.init(view: hostView) // hud.mode = .text // hud.detailsLabel.text = message // hud.detailsLabel.font = hud.label.font // hostView.addSubview(hud) // hud.show(animated: animation) // hud.hide(animated: animation, afterDelay: afterDelay) // } class func hideAllHud() { ZKProgressHUD.dismiss() // MBProgressHUD.hideAllHUDs(for: hostView, animated: animation) } }
34.3625
110
0.633685
72f827bc562b96012408d9ce713969cd361b7140
3,688
// // ChapterDivisionElement.swift // Tehilim2.0 // // Created by israel.berezin on 01/07/2020. // // To parse the JSON, add this file to your project and do: // // let chapterDivision = try ChapterDivision(json) import Foundation // MARK: - ChapterDivisionElement class ChapterDivisionElement: NSObject, Codable, NSCoding { func encode(with coder: NSCoder) { coder.encode(self.start, forKey: "start") coder.encode(self.end, forKey: "end") } required init?(coder: NSCoder) { self.start = coder.decodeObject(forKey: "start") as! String self.end = coder.decodeObject(forKey: "end") as! String } var start, end: String var startAt: Int{ Int(start) ?? 0 } var endIn: Int{ Int(end) ?? 0 } enum CodingKeys: String, CodingKey { case start = "Start" case end = "End" } init(start: String, end: String) { self.start = start self.end = end } } // MARK: ChapterDivisionElement convenience initializers and mutators extension ChapterDivisionElement { convenience init(data: Data) throws { let me = try newJSONDecoder().decode(ChapterDivisionElement.self, from: data) self.init(start: me.start, end: me.end) } convenience init(_ json: String, using encoding: String.Encoding = .utf8) throws { guard let data = json.data(using: encoding) else { throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil) } try self.init(data: data) } convenience init(fromURL url: URL) throws { try self.init(data: try Data(contentsOf: url)) } func with( start: String? = nil, end: String? = nil ) -> ChapterDivisionElement { return ChapterDivisionElement( start: start ?? self.start, end: end ?? self.end ) } func jsonData() throws -> Data { return try newJSONEncoder().encode(self) } func jsonString(encoding: String.Encoding = .utf8) throws -> String? { return String(data: try self.jsonData(), encoding: encoding) } } typealias ChapterDivision = [ChapterDivisionElement] extension Array where Element == ChapterDivision.Element { init(data: Data) throws { self = try newJSONDecoder().decode(ChapterDivision.self, from: data) } init(_ json: String, using encoding: String.Encoding = .utf8) throws { guard let data = json.data(using: encoding) else { throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil) } try self.init(data: data) } init(fromURL url: URL) throws { try self.init(data: try Data(contentsOf: url)) } func jsonData() throws -> Data { return try newJSONEncoder().encode(self) } func jsonString(encoding: String.Encoding = .utf8) throws -> String? { return String(data: try self.jsonData(), encoding: encoding) } } // MARK: - Helper functions for creating encoders and decoders func newJSONDecoder() -> JSONDecoder { let decoder = JSONDecoder() if #available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) { decoder.dateDecodingStrategy = .iso8601 } return decoder } func newJSONEncoder() -> JSONEncoder { let encoder = JSONEncoder() if #available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) { encoder.dateEncodingStrategy = .iso8601 } return encoder } // //extension ChapterDivisionElement: CustomStringConvertible { // override var description: String { // return "start = \(String(describing: start)), end = \(String(describing: end))" // } //}
26.342857
89
0.623644
1d9c62fd8abff7e1de4834cfcf8db4dd1f3e125b
1,467
// // Patchable.swift // Restivus // // Created by Ryan Baldwin on 2017-08-21. // Copyright © 2017 bunnyhug.me. All rights governed under the Apache 2 License Agreement // import Foundation /// Designates the conforming type as a PATCH HTTP Request. public protocol Patchable: Restable {} extension Patchable { /// Creates a PATCH request for the current instance /// /// - Returns: The URLRequest /// - Throws: An HTTPMethodError when the attempt to make the URLRequest failed. public func request() throws -> URLRequest { return try HTTPMethod.patch.makeURLRequest(for: self) } } extension Patchable where Self: PreEncoded { /// Creates a PATCH request for the current PreEncoded instance, /// and uses the `data` value as the body for the request. /// /// - Returns: The URLRequest /// - Throws: An HTTPMethodError when the attempt to make the URLRequest failed. public func request() throws -> URLRequest { return try HTTPMethod.patch.makeURLRequest(for: self) } } extension Patchable where Self: Encodable { /// Creates a PATCH request for the current Encodable instance, /// and encodes itself into the HTTP body of the request. /// /// - Returns: The URLRequest /// - Throws: An HTTPMethodError when the attempt to make the URLRequest failed. public func request() throws -> URLRequest { return try HTTPMethod.patch.makeURLRequest(for: self) } }
31.891304
90
0.690525
feb9b0cdf3ec715a756ef2870febbd215451fdd6
2,670
// // // Project Name: Thecircle // Workspace: Loophole // MacOS Version: 11.2 // // File Name: AnimatedTapGestureModifier.swift // Creation: 4/9/21 7:51 PM // // Company: Thecircle LLC // Contact: [email protected] // Website: https://thecircle.xyz // Author: Dragos-Costin Mandu // // Copyright © 2021 Thecircle LLC. All rights reserved. // // import SwiftUI public struct AnimatedTapGestureModifier: ViewModifier { /// The minimum scale of a View when tapped. public static var minScale: CGFloat = 0.97 /// The maximum scale of a View when is not tapped. public static var maxScale: CGFloat = 1 public static var animationDelay: Double = 0 public static var animationSpeed: Double = 1.2 public static var tapCount: Int = 1 private var animation: Animation { Animation .spring() .delay(AnimatedTapGestureModifier.animationDelay) .speed(AnimatedTapGestureModifier.animationSpeed) } /// Keeps track of the current content scale. @State private var scale: CGFloat = AnimatedTapGestureModifier.maxScale private let isActive: Bool private let onTapAction: () -> Void /// Adds a tap gesture with an animation on the content View. /// - Parameter onTapAction: Action called when the content tap animation ended. init(isActive: Bool, onTapAction: @escaping () -> Void) { self.isActive = isActive self.onTapAction = onTapAction } public func body(content: Content) -> some View { Group { if isActive { content .scaleEffect(scale) .onTapGesture(count: AnimatedTapGestureModifier.tapCount) { withAnimation(animation) { scale = AnimatedTapGestureModifier.minScale } } .onChange(of: scale) { _ in if scale == AnimatedTapGestureModifier.minScale { withAnimation(animation) { scale = AnimatedTapGestureModifier.maxScale } } else if scale == AnimatedTapGestureModifier.maxScale { onTapAction() } } } else { content } } } }
27.8125
84
0.515356
bb32ec389dd424321127837056ec3cfe5ec0d71e
1,700
// // CreditCardTableViewCell.swift // ManGO // // Created by Priba on 10/24/19. // Copyright © 2019 Priba. All rights reserved. // import UIKit import MaterialComponents class CreditCardTableViewCell: UITableViewCell { @IBOutlet weak var backView: UIView! @IBOutlet weak var shadowView: ShadowMaterialView! @IBOutlet weak var brandLogo: UIImageView! @IBOutlet weak var deleteBtn: UIButton! @IBOutlet weak var lastFourDigitsLbl: UILabel! @IBOutlet weak var exparationLbl: UILabel! @IBOutlet weak var fullNameLbl: UILabel! override func awakeFromNib() { super.awakeFromNib() self.selectionStyle = .none backView.layer.cornerRadius = 12 shadowView.layer.cornerRadius = 12 } func populate(card: CardModel){ lastFourDigitsLbl.text = card.last4 exparationLbl.text = card.expiration fullNameLbl.text = card.fullName if card.isDefault { shadowView.setShadowColor(.mangoGreen, for: .normal) backView.layer.borderWidth = 1.5 backView.layer.borderColor = UIColor.mangoGreen.cgColor }else{ shadowView.setShadowColor(.lightGray, for: .normal) backView.layer.borderColor = UIColor.white.cgColor } switch card.brand { case "MASTERCARD": brandLogo.image = UIImage(named: "mastercard") case "AMERICANEXPRESS": brandLogo.image = UIImage(named: "americanExpressCard") case "VISA": brandLogo.image = UIImage(named: "visaCard") default: brandLogo.image = UIImage(named: "card") } } }
28.333333
67
0.632353
e9b40f446e61a67a93c940e72778d14123a414fc
11,696
import BigInt import VioletCore // cSpell:ignore setobject // In CPython: // Objects -> setobject.c // https://docs.python.org/3.7/c-api/set.html // sourcery: pytype = frozenset, isDefault, hasGC, isBaseType // sourcery: subclassInstancesHave__dict__ public struct PyFrozenSet: PyObjectMixin, AbstractSet { // sourcery: pytypedoc internal static let doc = """ frozenset() -> empty frozenset object frozenset(iterable) -> frozenset object Build an immutable unordered collection of unique elements. """ internal typealias Element = OrderedSet.Element // sourcery: storedProperty internal var elements: OrderedSet { self.elementsPtr.pointee } public let ptr: RawPtr public init(ptr: RawPtr) { self.ptr = ptr } internal func initialize(_ py: Py, type: PyType, elements: OrderedSet) { self.initializeBase(py, type: type) self.elementsPtr.initialize(to: elements) } // Nothing to do here. internal func beforeDeinitialize(_ py: Py) {} internal static func createDebugInfo(ptr: RawPtr) -> PyObject.DebugMirror { let zelf = PyFrozenSet(ptr: ptr) var result = PyObject.DebugMirror(object: zelf) result.append(name: "count", value: zelf.count, includeInDescription: true) result.append(name: "elements", value: zelf.elements) return result } // MARK: - AbstractSet internal static func newObject(_ py: Py, elements: OrderedSet) -> PyFrozenSet { return py.newFrozenSet(elements: elements) } // MARK: - Equatable, comparable // sourcery: pymethod = __eq__ internal static func __eq__(_ py: Py, zelf: PyObject, other: PyObject) -> CompareResult { return Self.abstract__eq__(py, zelf: zelf, other: other) } // sourcery: pymethod = __ne__ internal static func __ne__(_ py: Py, zelf: PyObject, other: PyObject) -> CompareResult { return Self.abstract__ne__(py, zelf: zelf, other: other) } // sourcery: pymethod = __lt__ internal static func __lt__(_ py: Py, zelf: PyObject, other: PyObject) -> CompareResult { return Self.abstract__lt__(py, zelf: zelf, other: other) } // sourcery: pymethod = __le__ internal static func __le__(_ py: Py, zelf: PyObject, other: PyObject) -> CompareResult { return Self.abstract__le__(py, zelf: zelf, other: other) } // sourcery: pymethod = __gt__ internal static func __gt__(_ py: Py, zelf: PyObject, other: PyObject) -> CompareResult { return Self.abstract__gt__(py, zelf: zelf, other: other) } // sourcery: pymethod = __ge__ internal static func __ge__(_ py: Py, zelf: PyObject, other: PyObject) -> CompareResult { return Self.abstract__ge__(py, zelf: zelf, other: other) } // MARK: - Hashable // sourcery: pymethod = __hash__ internal static func __hash__(_ py: Py, zelf _zelf: PyObject) -> HashResult { guard let zelf = Self.downcast(py, _zelf) else { return .invalidSelfArgument(_zelf, Self.pythonTypeName) } // This is hash function from 'tuple', which means that 'frozenset' // and 'tuple' with the same elements (in the same order) will have // the same hash. var x: PyHash = 0x34_5678 var multiplier = Hasher.multiplier for element in zelf.elements { let y = element.hash x = (x ^ y) * multiplier multiplier += 82_520 + PyHash(2 * zelf.elements.count) } let result = x + 97_531 return .value(result) } // MARK: - String // sourcery: pymethod = __repr__ internal static func __repr__(_ py: Py, zelf _zelf: PyObject) -> PyResult { guard let zelf = Self.downcast(py, _zelf) else { return Self.invalidZelfArgument(py, _zelf, "__repr__") } if zelf.elements.isEmpty { return PyResult(py, interned: "frozenset()") } if zelf.hasReprLock { return PyResult(py, interned: "frozenset(...)") } return zelf.withReprLock { switch Self.abstractJoinElementsForRepr(py, zelf: zelf) { case let .value(elements): let result = "frozenset({" + elements + "})" return PyResult(py, result) case let .error(e): return .error(e) } } } // MARK: - Attributes // sourcery: pymethod = __getattribute__ internal static func __getattribute__(_ py: Py, zelf _zelf: PyObject, name: PyObject) -> PyResult { guard let zelf = Self.downcast(py, _zelf) else { return Self.invalidZelfArgument(py, _zelf, "__getattribute__") } return AttributeHelper.getAttribute(py, object: zelf.asObject, name: name) } // MARK: - Class // sourcery: pyproperty = __class__ internal static func __class__(_ py: Py, zelf: PyObject) -> PyType { return zelf.type } // MARK: - Length // sourcery: pymethod = __len__ internal static func __len__(_ py: Py, zelf _zelf: PyObject) -> PyResult { guard let zelf = Self.downcast(py, _zelf) else { return Self.invalidZelfArgument(py, _zelf, "__len__") } let result = zelf.count return PyResult(py, result) } // MARK: - Contains // sourcery: pymethod = __contains__ internal static func __contains__(_ py: Py, zelf: PyObject, object: PyObject) -> PyResult { return Self.abstract__contains__(py, zelf: zelf, object: object) } // MARK: - And, or, xor // sourcery: pymethod = __and__ internal static func __and__(_ py: Py, zelf: PyObject, other: PyObject) -> PyResult { return Self.abstract__and__(py, zelf: zelf, other: other) } // sourcery: pymethod = __rand__ internal static func __rand__(_ py: Py, zelf: PyObject, other: PyObject) -> PyResult { return Self.abstract__rand__(py, zelf: zelf, other: other) } // sourcery: pymethod = __or__ internal static func __or__(_ py: Py, zelf: PyObject, other: PyObject) -> PyResult { return Self.abstract__or__(py, zelf: zelf, other: other) } // sourcery: pymethod = __ror__ internal static func __ror__(_ py: Py, zelf: PyObject, other: PyObject) -> PyResult { return Self.abstract__ror__(py, zelf: zelf, other: other) } // sourcery: pymethod = __xor__ internal static func __xor__(_ py: Py, zelf: PyObject, other: PyObject) -> PyResult { return Self.abstract__xor__(py, zelf: zelf, other: other) } // sourcery: pymethod = __rxor__ internal static func __rxor__(_ py: Py, zelf: PyObject, other: PyObject) -> PyResult { return Self.abstract__rxor__(py, zelf: zelf, other: other) } // MARK: - Sub // sourcery: pymethod = __sub__ internal static func __sub__(_ py: Py, zelf: PyObject, other: PyObject) -> PyResult { return Self.abstract__sub__(py, zelf: zelf, other: other) } // sourcery: pymethod = __rsub__ internal static func __rsub__(_ py: Py, zelf: PyObject, other: PyObject) -> PyResult { return Self.abstract__rsub__(py, zelf: zelf, other: other) } // MARK: - Is subset, superset, disjoint internal static let isSubsetDoc = """ Report whether another set contains this set. """ // sourcery: pymethod = issubset, doc = isSubsetDoc internal static func issubset(_ py: Py, zelf: PyObject, other: PyObject) -> PyResult { return self.abstractIsSubset(py, zelf: zelf, other: other) } internal static let isSupersetDoc = """ Report whether this set contains another set. """ // sourcery: pymethod = issuperset, doc = isSupersetDoc internal static func issuperset(_ py: Py, zelf: PyObject, other: PyObject) -> PyResult { return self.abstractIsSuperset(py, zelf: zelf, other: other) } internal static let isDisjointDoc = """ Return True if two sets have a null intersection. """ // sourcery: pymethod = isdisjoint, doc = isDisjointDoc internal static func isdisjoint(_ py: Py, zelf: PyObject, other: PyObject) -> PyResult { return self.abstractIsDisjoint(py, zelf: zelf, other: other) } // MARK: - Intersection, union, difference internal static let intersectionDoc = """ Return the intersection of two sets as a new set. (i.e. all elements that are in both sets.) """ // sourcery: pymethod = intersection, doc = intersectionDoc internal static func intersection(_ py: Py, zelf: PyObject, other: PyObject) -> PyResult { return self.abstractIntersection(py, zelf: zelf, other: other) } internal static let unionDoc = """ Return the union of sets as a new set. (i.e. all elements that are in either set.) """ // sourcery: pymethod = union, doc = unionDoc internal static func union(_ py: Py, zelf: PyObject, other: PyObject) -> PyResult { return self.abstractUnion(py, zelf: zelf, other: other) } internal static let differenceDoc = """ Return the difference of two or more sets as a new set. (i.e. all elements that are in this set but not the others.) """ // sourcery: pymethod = difference, doc = differenceDoc internal static func difference(_ py: Py, zelf: PyObject, other: PyObject) -> PyResult { return self.abstractDifference(py, zelf: zelf, other: other) } internal static let symmetricDifferenceDoc = """ Return the symmetric difference of two sets as a new set. (i.e. all elements that are in exactly one of the sets. """ // sourcery: pymethod = symmetric_difference, doc = symmetricDifferenceDoc internal static func symmetric_difference(_ py: Py, zelf: PyObject, other: PyObject) -> PyResult { return self.abstractSymmetricDifference(py, zelf: zelf, other: other) } // MARK: - Copy internal static let copyDoc = "Return a shallow copy of a set." // sourcery: pymethod = copy, doc = copyDoc internal static func copy(_ py: Py, zelf _zelf: PyObject) -> PyResult { guard let zelf = Self.downcast(py, _zelf) else { return Self.invalidZelfArgument(py, _zelf, "copy") } let result = py.newFrozenSet(elements: zelf.elements) return PyResult(result) } // MARK: - Iter // sourcery: pymethod = __iter__ internal static func __iter__(_ py: Py, zelf _zelf: PyObject) -> PyResult { guard let zelf = Self.downcast(py, _zelf) else { return Self.invalidZelfArgument(py, _zelf, "__iter__") } let result = py.newIterator(set: zelf) return PyResult(result) } // MARK: - Python new // sourcery: pystaticmethod = __new__ internal static func __new__(_ py: Py, type: PyType, args: [PyObject], kwargs: PyDict?) -> PyResult { let isBuiltin = type === py.types.frozenset if isBuiltin { if let e = ArgumentParser.noKwargsOrError(py, fnName: Self.pythonTypeName, kwargs: kwargs) { return .error(e.asBaseException) } } // Guarantee 0 or 1 args if let e = ArgumentParser.guaranteeArgsCountOrError(py, fnName: Self.pythonTypeName, args: args, min: 0, max: 1) { return .error(e.asBaseException) } let elements: OrderedSet if let iterable = args.first { switch Self.getElements(py, iterable: iterable) { case let .value(e): elements = e case let .error(e): return .error(e) } } else { elements = OrderedSet() } let result: PyFrozenSet = isBuiltin ? py.newFrozenSet(elements: elements) : py.memory.newFrozenSet(type: type, elements: elements) return PyResult(result) } }
31.956284
93
0.645007
381415353724e0bf6b2457e0f324dc748ab57d03
126
import Foundation enum eProjectContentType: Int, Codable { case Market = 1 case Political = 2 case Social = 3 }
15.75
40
0.674603
e4628e968b24c9d483ecd0aa7128ba0b49a0eda0
11,448
// // Copyright 2018-2020 Amazon.com, // Inc. or its affiliates. All Rights Reserved. // // SPDX-License-Identifier: Apache-2.0 // import XCTest @testable import Amplify @testable import AmplifyTestCommon @testable import AWSPluginsCore /* type ModelMultipleOwner @model @auth(rules: [ # Defaults to use the "owner" field. { allow: owner }, { allow: owner, ownerField: "editors", operations: [update, read] } ]) { id: ID! content: String editors: [String] } */ public struct ModelMultipleOwner: Model { public let id: String public var content: String public var editors: [String]? public init(id: String = UUID().uuidString, content: String, editors: [String]? = []) { self.id = id self.content = content self.editors = editors } public enum CodingKeys: String, ModelKey { case id case content case editors } public static let keys = CodingKeys.self public static let schema = defineSchema { model in let modelMultipleOwner = ModelMultipleOwner.keys model.authRules = [ rule(allow: .owner), rule(allow: .owner, ownerField: "editors", operations: [.update, .read]) ] model.fields( .id(), .field(modelMultipleOwner.content, is: .required, ofType: .string), .field(modelMultipleOwner.editors, is: .optional, ofType: .embeddedCollection(of: String.self)) ) } } class ModelMultipleOwnerAuthRuleTests: XCTestCase { override func setUp() { ModelRegistry.register(modelType: ModelMultipleOwner.self) } override func tearDown() { ModelRegistry.reset() } // Ensure that the `owner` field is added to the model fields func testModelMultipleOwner_CreateMutation() { var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelType: ModelMultipleOwner.self, operationType: .mutation) documentBuilder.add(decorator: DirectiveNameDecorator(type: .create)) documentBuilder.add(decorator: AuthRuleDecorator(.mutation)) let document = documentBuilder.build() let expectedQueryDocument = """ mutation CreateModelMultipleOwner { createModelMultipleOwner { id content editors __typename owner } } """ XCTAssertEqual(document.name, "createModelMultipleOwner") XCTAssertEqual(document.stringValue, expectedQueryDocument) XCTAssertTrue(document.variables.isEmpty) } // Ensure that the `owner` field is added to the model fields func testModelMultipleOwner_DeleteMutation() { var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelType: ModelMultipleOwner.self, operationType: .mutation) documentBuilder.add(decorator: DirectiveNameDecorator(type: .delete)) documentBuilder.add(decorator: AuthRuleDecorator(.mutation)) let document = documentBuilder.build() let expectedQueryDocument = """ mutation DeleteModelMultipleOwner { deleteModelMultipleOwner { id content editors __typename owner } } """ XCTAssertEqual(document.name, "deleteModelMultipleOwner") XCTAssertEqual(document.stringValue, expectedQueryDocument) XCTAssertTrue(document.variables.isEmpty) } // Ensure that the `owner` field is added to the model fields func testModelMultipleOwner_UpdateMutation() { var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelType: ModelMultipleOwner.self, operationType: .mutation) documentBuilder.add(decorator: DirectiveNameDecorator(type: .update)) documentBuilder.add(decorator: AuthRuleDecorator(.mutation)) let document = documentBuilder.build() let expectedQueryDocument = """ mutation UpdateModelMultipleOwner { updateModelMultipleOwner { id content editors __typename owner } } """ XCTAssertEqual(document.name, "updateModelMultipleOwner") XCTAssertEqual(document.stringValue, expectedQueryDocument) XCTAssertTrue(document.variables.isEmpty) } // Ensure that the `owner` field is added to the model fields func testModelMultipleOwner_GetQuery() { var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelType: ModelMultipleOwner.self, operationType: .query) documentBuilder.add(decorator: DirectiveNameDecorator(type: .get)) documentBuilder.add(decorator: AuthRuleDecorator(.query)) let document = documentBuilder.build() let expectedQueryDocument = """ query GetModelMultipleOwner { getModelMultipleOwner { id content editors __typename owner } } """ XCTAssertEqual(document.name, "getModelMultipleOwner") XCTAssertEqual(document.stringValue, expectedQueryDocument) XCTAssertTrue(document.variables.isEmpty) } // A List query is a paginated selection set, make sure the `owner` field is added to the model fields func testModelMultipleOwner_ListQuery() { var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelType: ModelMultipleOwner.self, operationType: .query) documentBuilder.add(decorator: DirectiveNameDecorator(type: .list)) documentBuilder.add(decorator: PaginationDecorator()) documentBuilder.add(decorator: AuthRuleDecorator(.query)) let document = documentBuilder.build() let expectedQueryDocument = """ query ListModelMultipleOwners($limit: Int) { listModelMultipleOwners(limit: $limit) { items { id content editors __typename owner } nextToken } } """ XCTAssertEqual(document.name, "listModelMultipleOwners") XCTAssertEqual(document.stringValue, expectedQueryDocument) } func testModelMultipleOwner_SyncQuery() { var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelType: ModelMultipleOwner.self, operationType: .query) documentBuilder.add(decorator: DirectiveNameDecorator(type: .sync)) documentBuilder.add(decorator: PaginationDecorator()) documentBuilder.add(decorator: ConflictResolutionDecorator()) documentBuilder.add(decorator: AuthRuleDecorator(.query)) let document = documentBuilder.build() let expectedQueryDocument = """ query SyncModelMultipleOwners($limit: Int) { syncModelMultipleOwners(limit: $limit) { items { id content editors __typename _version _deleted _lastChangedAt owner } nextToken startedAt } } """ XCTAssertEqual(document.name, "syncModelMultipleOwners") XCTAssertEqual(document.stringValue, expectedQueryDocument) } // Only the 'owner' inherently has `.create` operation, requiring the subscription operation to contain the input func testModelMultipleOwner_OnCreateSubscription() { var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelType: ModelMultipleOwner.self, operationType: .subscription) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onCreate, "111"))) let document = documentBuilder.build() let expectedQueryDocument = """ subscription OnCreateModelMultipleOwner($owner: String!) { onCreateModelMultipleOwner(owner: $owner) { id content editors __typename owner } } """ XCTAssertEqual(document.name, "onCreateModelMultipleOwner") XCTAssertEqual(document.stringValue, expectedQueryDocument) guard let variables = document.variables else { XCTFail("The document doesn't contain variables") return } XCTAssertEqual(variables["owner"] as? String, "111") } // Each owner with `.update` operation requires the ownerField on the corresponding subscription operation func testModelMultipleOwner_OnUpdateSubscription() { var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelType: ModelMultipleOwner.self, operationType: .subscription) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onUpdate)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onUpdate, "111"))) let document = documentBuilder.build() let expectedQueryDocument = """ subscription OnUpdateModelMultipleOwner($editors: String!, $owner: String!) { onUpdateModelMultipleOwner(editors: $editors, owner: $owner) { id content editors __typename owner } } """ XCTAssertEqual(document.name, "onUpdateModelMultipleOwner") XCTAssertEqual(document.stringValue, expectedQueryDocument) guard let variables = document.variables else { XCTFail("The document doesn't contain variables") return } XCTAssertEqual(variables["owner"] as? String, "111") XCTAssertEqual(variables["editors"] as? String, "111") } // Only the 'owner' inherently has `.delete` operation, requiring the subscription operation to contain the input func testModelMultipleOwner_OnDeleteSubscription() { var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelType: ModelMultipleOwner.self, operationType: .subscription) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onDelete)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onDelete, "111"))) let document = documentBuilder.build() let expectedQueryDocument = """ subscription OnDeleteModelMultipleOwner($owner: String!) { onDeleteModelMultipleOwner(owner: $owner) { id content editors __typename owner } } """ XCTAssertEqual(document.name, "onDeleteModelMultipleOwner") XCTAssertEqual(document.stringValue, expectedQueryDocument) guard let variables = document.variables else { XCTFail("The document doesn't contain variables") return } XCTAssertEqual(variables["owner"] as? String, "111") } }
38.545455
117
0.61609
de6b4d0f58965b9a373e307105315834710a0bf1
1,104
// // NavigationState.swift // Meet // // Created by Benjamin Encz on 11/11/15. // Copyright © 2015 DigiTales. All rights reserved. // import ReSwift public enum RoutePresentationStyle { case normal case modal } public protocol RouteSegment { var presentationStyle: RoutePresentationStyle { get } func isEqual(to segment: RouteSegment?) -> Bool } extension RouteSegment { public var presentationStyle: RoutePresentationStyle { return .normal } } extension RouteSegment where Self: Equatable { public func isEqual(to segment: RouteSegment?) -> Bool { guard let segment = segment as? Self else { return false } return self == segment } } public struct IDRouteSegment<T: Equatable>: RouteSegment, Equatable { let identifier: T public init(_ identifier: T) { self.identifier = identifier } } public typealias Route = [RouteSegment] public struct NavigationState { public init() {} public var route: Route = [] var changeRouteAnimated: Bool = true } public protocol HasNavigationState { var navigationState: NavigationState { get set } }
19.714286
69
0.716486
235bfd060938071884c0a9b7e9def3a09ce102a5
293
import UIKit class VTags:VView { private weak var controller:CTags! override init(controller:CController) { super.init(controller:controller) self.controller = controller as? CTags } required init?(coder:NSCoder) { return nil } }
16.277778
46
0.617747
f5096f2e7bed95a65821d922d1f75f3b93dae7a1
1,613
// // utils.swift // DrawAR // // Created by Finn Voorhees on 22/05/2021. // import SceneKit import UIKit func + (left: SCNVector3, right: SCNVector3) -> SCNVector3 { return SCNVector3Make(left.x + right.x, left.y + right.y, left.z + right.z) } func * (vector: SCNVector3, scalar: Float) -> SCNVector3 { return SCNVector3Make(vector.x * scalar, vector.y * scalar, vector.z * scalar) } func - (left: SCNVector3, right: SCNVector3) -> SCNVector3 { return SCNVector3Make(left.x - right.x, left.y - right.y, left.z - right.z) } func / (vector: SCNVector3, scalar: Float) -> SCNVector3 { return SCNVector3Make(vector.x / scalar, vector.y / scalar, vector.z / scalar) } extension SCNVector3 { func length() -> Float { return sqrtf((x * x) + (y * y) + (z * z)) } } public extension UIColor { class func StringFromUIColor(color: UIColor) -> String { let components = color.cgColor.components ?? [] return "[\(components[0]), \(components[1]), \(components[2]), \(components[3])]" } class func UIColorFromString(string: String) -> UIColor { let componentsString = string.replacingOccurrences(of: "[", with: "").replacingOccurrences(of: "]", with: "") let components = componentsString.components(separatedBy: ", ") return UIColor(red: CGFloat((components[0] as NSString).floatValue), green: CGFloat((components[1] as NSString).floatValue), blue: CGFloat((components[2] as NSString).floatValue), alpha: CGFloat((components[3] as NSString).floatValue)) } }
33.604167
117
0.632362
91cbaadb44be730d559220bcd31bbe0c1f173bfc
1,005
// // RedditRSSReaderTests.swift // RedditRSSReaderTests // // Created by Marc Maguire on 2018-02-11. // Copyright © 2018 Marc Maguire. All rights reserved. // import XCTest @testable import RedditRSSReader class RedditRSSReaderTests: 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. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
27.162162
111
0.644776
69cb35d347672b5c490da4b53f4395e69dd2d21e
786
// // GetFriendsInteractor.swift // PhotoVK // // Created by Pavel Grechikhin on 07.04.2018. // Copyright © 2018 Pavel Grechikhin. All rights reserved. // import Foundation import Magics class GetFriendsInteractor: MagicsInteractor { var relativeURL: String = "friends.get?order=name&name_case=nom&fields=first_name, last_name, photo_50&access_token=\(VKApi.shared.tokenVK)&v=5.74" var respons = [GetFriendsModel()] func process(json: MagicsJSON, response: URLResponse?, api: MagicsAPI) { respons = api.arrayFrom(json: json["response"]["items"]) } } class GetFriendsModel: NSObject, MagicsModel { override required init() {} @objc var id = 0 @objc var first_name = "" @objc var last_name = "" @objc var photo_50 = "" }
25.354839
151
0.681934
e870bc9d8eaba657998e05b94769a2a4b3a4d688
3,725
// // PullToDismissable.swift // PullToDismissable // // Created by Ben Guild on 2018/06/20. // Copyright © 2018年 Ben Guild. All rights reserved. // import UIKit public protocol PullToDismissable where Self: UIViewController { var eligibleViewControllersForPullToDismiss: [UIViewController] { get } var isPullToDismissEnabled: Bool { get set } var pullToDismissTransition: PullToDismissTransition { get } func setupPullToDismiss() func setPullToDismissEnabled(_ isEnabled: Bool) } extension PullToDismissable where Self: UIViewController, Self: UIViewControllerTransitioningDelegate { public var eligibleViewControllersForPullToDismiss: [UIViewController] { var viewControllers = [UIViewController]() if let navigationController = navigationController { viewControllers.append(navigationController) } viewControllers.append(self) return viewControllers } public var isPullToDismissEnabled: Bool { get { return isPullToDismissEnabled(on: eligibleViewControllersForPullToDismiss) } set { guard newValue != isPullToDismissEnabled else { return } setPullToDismissEnabled(newValue) } } private func isPullToDismissEnabled(on eligibleViewControllers: [UIViewController]) -> Bool { return eligibleViewControllers.contains(where: { (viewController) -> Bool in viewController.transitioningDelegate === self }) } private func tearDownPullToDismiss(on viewController: UIViewController) { if viewController.transitioningDelegate === self { viewController.transitioningDelegate = nil } guard viewController.isViewLoaded else { return } viewController.view.gestureRecognizers?.forEach { guard $0.delegate === pullToDismissTransition else { return } viewController.view.removeGestureRecognizer($0) } } private func propagateChanges(to eligibleViewControllers: [UIViewController], isEnabled: Bool) { pullToDismissTransition.transitionDelegateObservation?.invalidate() eligibleViewControllers.reversed().forEach { viewController in if !isEnabled || eligibleViewControllers.first !== viewController { tearDownPullToDismiss(on: viewController) } else { viewController.transitioningDelegate = self pullToDismissTransition.transitionDelegateObservation = viewController.observe( \UIViewController.transitioningDelegate, options: [.new] ) { [weak self] _, _ in self?.setupPullToDismiss() } guard viewController.isViewLoaded else { return } guard !(viewController.view.gestureRecognizers?.contains( where: { (gestureRecognizer) -> Bool in gestureRecognizer.delegate === pullToDismissTransition } ) ?? false) else { return } viewController.view.addGestureRecognizer( pullToDismissTransition.additionalGestureRecognizerForTrigger() ) } } } public func setupPullToDismiss() { let eligibleViewControllers = eligibleViewControllersForPullToDismiss propagateChanges( to: eligibleViewControllers, isEnabled: isPullToDismissEnabled(on: eligibleViewControllers) ) } public func setPullToDismissEnabled(_ isEnabled: Bool) { propagateChanges(to: eligibleViewControllersForPullToDismiss, isEnabled: isEnabled) } }
34.813084
103
0.660671
ab2ce7bd95f49b617a7f6277a8473e69988db831
170
// // PinwheelEventPayload.swift // PinwheelSDK // // Created by Robby Abaya on 2/11/21. // import Foundation public protocol PinwheelEventPayload: Codable { }
13.076923
47
0.7
017fba7602fdff14fa4b517c18aea38bc81aab8c
2,025
// Copyright (c) 2021 Spotify AB. // // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. import Foundation /// Manage marker file entries protocol MarkerWriter { /// Saves all dependencies func enable(dependencies: [URL]) throws /// Disables mode marker func disable() throws } /// Saves a marker using a format matching .d one class FileMarkerWriter: MarkerWriter { static let delimiter = " \\" private let filePath: String private let fileAccessor: FileAccessor init(_ file: URL, fileAccessor: FileAccessor) { filePath = file.path self.fileAccessor = fileAccessor } func enable(dependencies: [URL]) throws { let lines = ["dependencies: "] + dependencies.map { $0.path } let fileContent = lines.joined(separator: "\(Self.delimiter)\n") try fileAccessor.write(toPath: filePath, contents: fileContent.data(using: .utf8)) } func disable() throws { if fileAccessor.fileExists(atPath: filePath) { try fileAccessor.removeItem(atPath: filePath) } } } /// Marker Writer that does nothing class NoopMarkerWriter: MarkerWriter { init(_ file: URL, fileManager: FileManager) {} func enable(dependencies: [URL]) throws {} func disable() throws {} }
32.66129
90
0.701728
e97d90d8cd1a8eccc6498387b35a83cf5a9aa757
599
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -primary-file %s -emit-ir | %FileCheck %s // REQUIRES: CPU=i386_or_x86_64 // <rdar://problem/13793646> struct OptionalStreamAdaptor<T : IteratorProtocol> { // CHECK: define hidden swiftcc void @_T015generic_ternary21OptionalStreamAdaptorV4next{{[_0-9a-zA-Z]*}}F(%TSq{{.*}}* noalias nocapture sret, %swift.type* %"OptionalStreamAdaptor<T>", %T15generic_ternary21OptionalStreamAdaptorV* nocapture swiftself dereferenceable({{.*}})) mutating func next() -> Optional<T.Element> { return x[0].next() } var x: [T] }
42.785714
275
0.729549
db58fce227e5044e31c29beada7d5aa06c86d20a
1,048
// // KeysPrefsViewController.swift // MonitorControl // // Created by Guillaume BRODER on 07/01/2018. // MIT Licensed. // import Cocoa import MASPreferences class KeysPrefsViewController: NSViewController, MASPreferencesViewController { var viewIdentifier: String = "Keys" var toolbarItemLabel: String? = NSLocalizedString("Keys", comment: "Shown in the main prefs window") var toolbarItemImage: NSImage? = NSImage.init(named: "KeyboardPref") let prefs = UserDefaults.standard @IBOutlet var listenFor: NSPopUpButton! override func viewDidLoad() { super.viewDidLoad() listenFor.selectItem(at: prefs.integer(forKey: Utils.PrefKeys.listenFor.rawValue)) } @IBAction func listenForChanged(_ sender: NSPopUpButton) { prefs.set(sender.selectedTag(), forKey: Utils.PrefKeys.listenFor.rawValue) #if DEBUG print("Toggle keys listened for state state -> \(sender.selectedItem?.title ?? "")") #endif NotificationCenter.default.post(name: Notification.Name.init(Utils.PrefKeys.listenFor.rawValue), object: nil) } }
28.324324
111
0.753817
219372e390f4b56f8ff26bb8246214f3b3eb7d62
303
import Foundation import FearlessUtils import SoraFoundation struct StakingUnbondConfirmViewModel { let senderAddress: AccountAddress let senderIcon: DrawableIcon let senderName: String? let amount: LocalizableResource<String> let hints: LocalizableResource<[TitleIconViewModel]> }
25.25
56
0.80198
72c96b0d5b30f24adf0c3804765d203775e5c1a1
1,242
// // SpawnController.swift // // // Created by Aaron Hinton on 6/12/21. // import Foundation import Vapor // Spawn a process by executing a given executable on a device. // Usage: simctl spawn [-w | --wait-for-debugger] [-s | --standalone] [-a <arch> | // --arch=<arch>] <device> <path to executable> [<argv 1> <argv 2> ... <argv n>] // // The path to the executable is searched using the following rules: // <path> contains no / characters: search the device's $PATH. This is similar to how most shells work, but searches // the device's path instead of the host's path. // <path> starts with /: Assume a literal path to the binary. This must start from the host's root. // <path> contains non-leading / characters: search relative to the current directory first, then // relative to the device's $SIMULATOR_ROOT. // // If you want to set environment variables in the resulting environment, set them in the calling environment with a // SIMCTL_CHILD_ prefix. class SpawnController: RouteCollection { func boot(routes: RoutesBuilder) throws { routes.post(["spawn"], use: spawn) } func spawn(_ req: Request) throws -> Response { return Response(status: .notImplemented) } }
36.529412
118
0.681159
9c48fb43e5c715cd7cd543434595c2ad7c0b8fa5
126
func min2(_ a: Int, _ b: Int) -> Int { if a < b { return a } else { return b } } print(min2(2, 3))
15.75
38
0.428571
d9d375e2c69d3c1db218388690f985647cd737c2
1,213
// // DataSource.swift // APLineGraph // // Created by Anton Plebanovich on 3/10/19. // Copyright © 2019 Anton Plebanovich. All rights reserved. // import Foundation private extension Constants { static let jsonName = "chart_data" static let jsonExtension = "json" } final class DataSource { // ******************************* MARK: - Public Properties let graphModels: [GraphModel]? // ******************************* MARK: - Initialization and Setup init() { guard let jsonURL = Bundle(for: DataSource.self).url(forResource: c.jsonName, withExtension: c.jsonExtension) else { print("Unable to get URL to plot data") self.graphModels = nil return } guard let data = Data(safeContentsOf: jsonURL) else { print("Unable to get plot data from file") self.graphModels = nil return } guard let graphData = JSONDecoder().safeDecode([GraphModel].self, from: data) else { print("Unable to decode plot data") self.graphModels = nil return } self.graphModels = graphData } }
25.270833
124
0.554823
b97719dde0fb9be1a35ab357ebbd08aa839e5a0a
7,295
/* Copyright (C) 2016 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: This is the deep layer network where we define and encode the correct layers on a command buffer as needed */ import MetalPerformanceShaders /** This class has our entire network with all layers to getting the final label Resources: * [Instructions](https://www.tensorflow.org/versions/r0.8/tutorials/mnist/pros/index.html#deep-mnist-for-experts) to run this network on TensorFlow. */ class MNIST_Deep_ConvNN: MNIST_Full_LayerNN{ // MPSImageDescriptors for different layers outputs to be put in let c1id = MPSImageDescriptor(channelFormat: MPSImageFeatureChannelFormat.float16, width: 28, height: 28, featureChannels: 32) let p1id = MPSImageDescriptor(channelFormat: MPSImageFeatureChannelFormat.float16, width: 14, height: 14, featureChannels: 32) let c2id = MPSImageDescriptor(channelFormat: MPSImageFeatureChannelFormat.float16, width: 14, height: 14, featureChannels: 64) let p2id = MPSImageDescriptor(channelFormat: MPSImageFeatureChannelFormat.float16, width: 7 , height: 7 , featureChannels: 64) let fc1id = MPSImageDescriptor(channelFormat: MPSImageFeatureChannelFormat.float16, width: 1 , height: 1 , featureChannels: 1024) // MPSImages and layers declared var c1Image, c2Image, p1Image, p2Image, fc1Image: MPSImage var conv1, conv2: MPSCNNConvolution var fc1, fc2: MPSCNNFullyConnected var pool: MPSCNNPoolingMax var relu: MPSCNNNeuronReLU override init(withCommandQueue commandQueueIn: MTLCommandQueue!) { // use device for a little while to initialize let device = commandQueueIn.device pool = MPSCNNPoolingMax(device: device, kernelWidth: 2, kernelHeight: 2, strideInPixelsX: 2, strideInPixelsY: 2) pool.offset = MPSOffset(x: 1, y: 1, z: 0); pool.edgeMode = MPSImageEdgeMode.clamp relu = MPSCNNNeuronReLU(device: device, a: 0) // Initialize MPSImage from descriptors c1Image = MPSImage(device: device, imageDescriptor: c1id) p1Image = MPSImage(device: device, imageDescriptor: p1id) c2Image = MPSImage(device: device, imageDescriptor: c2id) p2Image = MPSImage(device: device, imageDescriptor: p2id) fc1Image = MPSImage(device: device, imageDescriptor: fc1id) // setup convolution layers conv1 = SlimMPSCNNConvolution(kernelWidth: 5, kernelHeight: 5, inputFeatureChannels: 1, outputFeatureChannels: 32, neuronFilter: relu, device: device, kernelParamsBinaryName: "conv1") conv2 = SlimMPSCNNConvolution(kernelWidth: 5, kernelHeight: 5, inputFeatureChannels: 32, outputFeatureChannels: 64, neuronFilter: relu, device: device, kernelParamsBinaryName: "conv2") // same as a 1x1 convolution filter to produce 1x1x10 from 1x1x1024 fc1 = SlimMPSCNNFullyConnected(kernelWidth: 7, kernelHeight: 7, inputFeatureChannels: 64, outputFeatureChannels: 1024, neuronFilter: nil, device: device, kernelParamsBinaryName: "fc1") fc2 = SlimMPSCNNFullyConnected(kernelWidth: 1, kernelHeight: 1, inputFeatureChannels: 1024, outputFeatureChannels: 10, neuronFilter: nil, device: device, kernelParamsBinaryName: "fc2") super.init(withCommandQueue: commandQueueIn) } /** This function encodes all the layers of the network into given commandBuffer, it calls subroutines for each piece of the network - Parameters: - inputImage: Image coming in on which the network will run - imageNum: If the test set is being used we will get a value between 0 and 9999 for which of the 10,000 images is being evaluated - correctLabel: The correct label for the inputImage while testing - Returns: Guess of the network as to what the digit is as UInt */ override func forward(inputImage: MPSImage? = nil, imageNum: Int = 9999, correctLabel: UInt = 10) -> UInt{ var label = UInt(99) // to deliver optimal performance we leave some resources used in MPSCNN to be released at next call of autoreleasepool, // so the user can decide the appropriate time to release this autoreleasepool{ // Get command buffer to use in MetalPerformanceShaders. let commandBuffer = commandQueue.makeCommandBuffer() // output will be stored in this image let finalLayer = MPSImage(device: commandBuffer.device, imageDescriptor: did) // encode layers to metal commandBuffer if inputImage == nil { conv1.encode(commandBuffer: commandBuffer, sourceImage: srcImage, destinationImage: c1Image) } else{ conv1.encode(commandBuffer: commandBuffer, sourceImage: inputImage!, destinationImage: c1Image) } pool.encode (commandBuffer: commandBuffer, sourceImage: c1Image , destinationImage: p1Image) conv2.encode (commandBuffer: commandBuffer, sourceImage: p1Image , destinationImage: c2Image) pool.encode (commandBuffer: commandBuffer, sourceImage: c2Image , destinationImage: p2Image) fc1.encode (commandBuffer: commandBuffer, sourceImage: p2Image , destinationImage: fc1Image) fc2.encode (commandBuffer: commandBuffer, sourceImage: fc1Image , destinationImage: dstImage) softmax.encode(commandBuffer: commandBuffer, sourceImage: dstImage , destinationImage: finalLayer) // add a completion handler to get the correct label the moment GPU is done and compare it to the correct output or return it commandBuffer.addCompletedHandler { commandBuffer in label = self.getLabel(finalLayer: finalLayer) if(correctLabel == label){ __atomic_increment() } } // commit commandbuffer to run on GPU and wait for completion commandBuffer.commit() if imageNum == 9999 { commandBuffer.waitUntilCompleted() } } return label } }
49.290541
152
0.59109
3300972ce4ce7a81c45bde7028d752f55e117414
2,158
// // AppDelegate.swift // CMTextField // // Created by CM on 2017/6/6. // Copyright © 2017年 CM. 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 invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
45.914894
285
0.754402
7551fd24d966622755046a3f993400aba2b58520
970
// // StartViewController.swift // LoginApp // // Created by Safeen on 2/10/19. // Copyright © 2019 Safeen. All rights reserved. // import UIKit class StartViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func viewDidAppear(_ animated: Bool) { let isUserLoggedIn = UserDefaults.standard.bool(forKey: "isUserLoggedIn") if(isUserLoggedIn) { self.performSegue(withIdentifier: "mainView", sender: self) } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
24.25
106
0.638144
21c392458aed5edb288765718ad083e8179e01e2
2,181
// // TopicsTableViewCell.swift // Podcast // // Created by Mindy Lou on 12/27/17. // Copyright © 2017 Cornell App Development. All rights reserved. // import UIKit /// UITableViewCell class for displaying topics class TopicsTableViewCell: UITableViewCell { let imageWidthHeight: CGFloat = 18 let imageLeadingPadding: CGFloat = 18 let topicLeadingPadding: CGFloat = 18 let topPadding: CGFloat = 16.5 var topicImageView: UIImageView! var topicLabel: UILabel! override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) selectionStyle = .none accessoryType = .disclosureIndicator backgroundColor = .offWhite topicImageView = UIImageView(frame: .zero) addSubview(topicImageView) topicImageView.snp.makeConstraints { make in make.width.height.equalTo(imageWidthHeight) make.top.equalToSuperview().offset(topPadding) make.leading.equalToSuperview().offset(imageLeadingPadding) } topicLabel = UILabel(frame: .zero) topicLabel.textColor = .charcoalGrey topicLabel.font = ._14RegularFont() addSubview(topicLabel) topicLabel.snp.makeConstraints { make in make.top.equalToSuperview().offset(topPadding) make.leading.equalTo(topicImageView.snp.trailing).offset(topicLeadingPadding) } } func configure(for topic: Topic, isParentTopic: Bool = false, parentTopic: Topic? = nil) { if isParentTopic { // parent topic: See All ____ topicLabel.text = "See All \(topic.name)" } else { topicLabel.text = topic.name } if let topicType = topic.topicType { topicImageView.image = topicType.image } else if let parent = parentTopic, let parentTopicType = parent.topicType { // children topics: set image to parent topic image topicImageView.image = parentTopicType.image } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
33.045455
94
0.659331
18144b972588bd8f7aeecf273a1db24bcf5f3df8
2,630
// // prepare.swift // AR Video // // Created by Ahmed Bekhit on 10/16/17. // Copyright © 2017 Ahmed Fathi Bekhit. All rights reserved. // import ARKit /** A struct that identifies the application `UIViewController`s and their orientations. - Author: Ahmed Fathi Bekhit * [Github](http://github.com/AFathi) * [Website](http://ahmedbekhit.com) * [Twitter](http://twitter.com/iAFapps) * [Email](mailto:[email protected]) */ @available(iOS 11.0, *) @objc public class ViewAR: NSObject { /** A `UIInterfaceOrientationMask` object that returns the recommended orientations for a `UIViewController` with AR scenes. Recommended to return in the application delegate method `func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask`. */ @objc internal(set) public static var orientation: UIInterfaceOrientationMask {get {return mask;}set {mask = newValue}} internal static var orientations:[UIInterfaceOrientationMask] { var all:[UIInterfaceOrientationMask] = [] if let info = Bundle.main.infoDictionary { if let supportedOrientaions = info["UISupportedInterfaceOrientations"] as? NSArray { for orientation in supportedOrientaions { if let o = orientation as? String { if o == "UIInterfaceOrientationPortrait" { all.append(.portrait) }else if o == "UIInterfaceOrientationPortraitUpsideDown" { all.append(.portraitUpsideDown) }else if o == "UIInterfaceOrientationLandscapeLeft" { all.append(.landscapeLeft) }else if o == "UIInterfaceOrientationLandscapeRight" { all.append(.landscapeRight) } } } return all } } return all } //returns the application's delegate to check if the current UIViewController contains an ARView fileprivate static var delegate = UIApplication.shared.delegate //variable for the setter in `mask` fileprivate static var m: UIInterfaceOrientationMask = .portrait //returns the most appropriate orientation based on the content of the UIViewController. fileprivate static var mask: UIInterfaceOrientationMask {get {if let vc = delegate?.window??.inputViewController {if vc.hasARView {return .portrait}else{return UIInterfaceOrientationMask(orientations)}};return m;}set {m = newValue;}} }
46.140351
237
0.649049
c1c34ba04f2ee1c29a5ebbd290dcd66698318978
3,959
// // PlaylistViewController.swift // SmashMusic // // Created by Mubaarak Hassan on 03/11/2017. // Copyright © 2017 Mubaarak Hassan. All rights reserved. // import UIKit import CoreData class PlaylistViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! var arrayOfPlaylists = [PlaylistData]() var selectedImage:UIImage? var selectedTitle:String? var selectedDescription:String? var index:Int? override func viewDidLoad() { super.viewDidLoad() let fetchRequest: NSFetchRequest<PlaylistData> = PlaylistData.fetchRequest() do{ let playlists = try PersistenceService.context.fetch(fetchRequest) self.arrayOfPlaylists = playlists tableView.reloadData() }catch{ } // Do any additional setup after loading the view. } override func viewDidAppear(_ animated: Bool) { let fetchRequest: NSFetchRequest<PlaylistData> = PlaylistData.fetchRequest() do{ let playlists = try PersistenceService.context.fetch(fetchRequest) self.arrayOfPlaylists = playlists tableView.reloadData() }catch{ } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return arrayOfPlaylists.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = Bundle.main.loadNibNamed("PlaylistTableViewCell", owner: self, options: nil)?.first as! PlaylistTableViewCell let playlist = self.arrayOfPlaylists[indexPath.row] cell.updateView(playlist: playlist, vc: self, table: tableView) return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 67 } // MARK: - Navigation showPlaylistDetail func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { //let indexPath = tableView.indexPathForSelectedRow //optional, to get from any UIButton for example //let currentCell = tableView.cellForRow(at: indexPath!) as! PlaylistTableViewCell self.selectedImage = UIImage(data: (self.arrayOfPlaylists[indexPath.row].image as! NSData) as Data) self.selectedTitle = self.arrayOfPlaylists[indexPath.row].name self.selectedDescription = self.arrayOfPlaylists[indexPath.row].descriptions self.index = indexPath.row performSegue(withIdentifier: "showPlaylistDetail", sender: self) } // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. if segue.identifier == "showPlaylistDetail" { if let playlistDetailVC = (segue.destination as? PlaylistDetailViewController){ playlistDetailVC.playlistTitle = self.selectedTitle playlistDetailVC.playlistImage = self.selectedImage playlistDetailVC.playlistDescription = self.selectedDescription playlistDetailVC.currentPlaylist = self.arrayOfPlaylists[self.index!] playlistDetailVC.playlistVC = self } } if segue.identifier == "createPlaylist" { if let newPlaylistVC = (segue.destination as? CreatePlaylistViewController) { newPlaylistVC.playlistVC = self } } } }
35.666667
128
0.662036
8fe73bf32488b9d116f2e81c4db67f805948b3f4
3,723
// // GameScene.swift // ActionSample // // Created by 关东升 on 2017/1/20. // 本书网站:http://www.51work6.com // 智捷课堂在线课堂:http://www.zhijieketang.com/ // 智捷课堂微信公共号:zhijieketang // 作者微博:@tony_关东升 // 作者微信:tony关东升 // QQ:569418560 邮箱:[email protected] // QQ交流群:162030268 // import SpriteKit enum ActionTypes : Int { case kSequence = 100, kGroup, kRepeate, kRepeatForever, kReverse } class GameScene: SKScene { override func didMove(to view: SKView) { let labelSpace:CGFloat = 50 let sequenceLabel = WKLabelButton(text: "Sequence", fontNamed:"Chalkduster", callback: #selector(touchSequenceLabel)) sequenceLabel.position = CGPoint(x:self.frame.midX, y:self.frame.height - 60) self.addChild(sequenceLabel) let groupLabel = WKLabelButton(text: "Group", fontNamed:"Chalkduster", callback: #selector(touchGroupLabel)) groupLabel.position = CGPoint(x:self.frame.midX, y:sequenceLabel.position.y - labelSpace) self.addChild(groupLabel) let repeateLabel = WKLabelButton(text: "Repeate", fontNamed:"Chalkduster", callback: #selector(touchRepeateLabel)) repeateLabel.position = CGPoint(x:self.frame.midX, y:groupLabel.position.y - labelSpace) self.addChild(repeateLabel) let repeatForeverLabel = WKLabelButton(text: "RepeatForever", fontNamed:"Chalkduster", callback: #selector(touchRepeatForeverLabel)) repeatForeverLabel.position = CGPoint(x:self.frame.midX, y:repeateLabel.position.y - labelSpace) self.addChild(repeatForeverLabel) let reverseLabel = WKLabelButton(text: "Reverse", fontNamed:"Chalkduster", callback: #selector(touchReverseLabel)) reverseLabel.position = CGPoint(x:self.frame.midX, y:repeatForeverLabel.position.y - labelSpace) self.addChild(reverseLabel) } func touchSequenceLabel() { print("touchSequenceLabel") let doors = SKTransition.doorway(withDuration: 1.0) let actionScene = MyActionScene(fileNamed: "MyActionScene") actionScene?.scaleMode = .aspectFill actionScene?.selectedAction = .kSequence self.view?.presentScene(actionScene!, transition: doors) } func touchGroupLabel() { print("touchGroupLabel") let doors = SKTransition.doorway(withDuration: 1.0) let actionScene = MyActionScene(fileNamed: "MyActionScene") actionScene?.scaleMode = .aspectFill actionScene?.selectedAction = .kGroup self.view?.presentScene(actionScene!, transition: doors) } func touchRepeateLabel() { print("touchRepeateLabel") let doors = SKTransition.doorway(withDuration: 1.0) let actionScene = MyActionScene(fileNamed: "MyActionScene") actionScene?.scaleMode = .aspectFill actionScene?.selectedAction = .kRepeate self.view?.presentScene(actionScene!, transition: doors) } func touchRepeatForeverLabel() { print("touchRepeatForeverLabel") let doors = SKTransition.doorway(withDuration: 1.0) let actionScene = MyActionScene(fileNamed: "MyActionScene") actionScene?.scaleMode = .aspectFill actionScene?.selectedAction = .kRepeatForever self.view?.presentScene(actionScene!, transition: doors) } func touchReverseLabel() { print("touchReverseLabel") let doors = SKTransition.doorway(withDuration: 1.0) let actionScene = MyActionScene(fileNamed: "MyActionScene") actionScene?.scaleMode = .aspectFill actionScene?.selectedAction = .kReverse self.view?.presentScene(actionScene!, transition: doors) } }
39.189474
140
0.679022
e81b32404701b54719ed96c8ee41cbb6e1020c56
1,425
// // AppDelegate.swift // Cinema-iOS // // Created by Matheus Pedrosa on 10/27/19. // Copyright © 2019 matheusmpedrosa. All rights reserved. // import UIKit @UIApplicationMain 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. } }
37.5
179
0.748772
75f4c74b38d64dcee717268e0cd3cc06e0236c20
1,848
// // Double+Extensions.swift // Btc // // Created by Akshit Talwar on 31/12/2017. // Copyright © 2017 atalw. All rights reserved. // import Foundation extension Double { var asCurrency: String { let numberFormatter = NumberFormatter() numberFormatter.numberStyle = .currency let currency = GlobalValues.currency! if currency == "BTC" { return self.asBtcCurrency } for countryTuple in GlobalValues.countryList { if currency == countryTuple.1 { numberFormatter.locale = Locale.init(identifier: countryTuple.2) } } return numberFormatter.string(from: NSNumber(value: self))! } func asSelectedCurrency(currency: String) -> String { let numberFormatter = NumberFormatter() numberFormatter.numberStyle = .currency for countryTuple in GlobalValues.countryList { if currency == countryTuple.1 { numberFormatter.locale = Locale.init(identifier: countryTuple.2) return numberFormatter.string(from: NSNumber(value: self))! } } if currency == "BTC" { return self.asBtcCurrency } else if currency == "ETH" { return self.asEthCurrency } return "\(self) \(currency)" } var asBtcCurrency: String { var decimalValue = Decimal(self) var result = Decimal() NSDecimalRound(&result, &decimalValue, 8, .plain) return "₿ \(result)" } var asEthCurrency: String { var decimalValue = Decimal(self) var result = Decimal() NSDecimalRound(&result, &decimalValue, 8, .plain) return "\(result) ETH" } func asCurrencyWith(locale: Locale) -> String { let numberFormatter = NumberFormatter() numberFormatter.numberStyle = .currency numberFormatter.locale = locale return numberFormatter.string(from: NSNumber(value: self))! } }
25.315068
72
0.658009
0e620ec3081bda806a09c92cda43ce047dcd3cb8
609
// // CelebrityTableViewCell.swift // CelebrityLookAlikeDemo // // Created by John Henning on 1/12/18. // Copyright © 2018 Knock. All rights reserved. // import UIKit class CelebrityTableViewCell: UITableViewCell { @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var celebImageView: UIImageView! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
21.75
65
0.684729
1cfe4c7898792bda045cdeedced95b7591a1730d
3,392
// Copyright © T-Mobile USA Inc. All rights reserved. import UIKit import RIBs protocol NoNetworkPresentableListener: AnyObject { func callApi() } final class NoNetworkViewController: UIViewController, NoNetworkPresentable, NoNetworkViewControllable { weak var listener: NoNetworkPresentableListener? var imageView: UIImageView = { let imageView = UIImageView() return imageView }() var titleLabel: UILabel = { let titleLabel = UILabel() return titleLabel }() var detailLabel: UILabel = { let titleLabel = UILabel() return titleLabel }() var tryAgain: UIButton = { let tryAgain = UIButton() tryAgain.setTitle("Try Again", for: .normal) return tryAgain }() override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = .white self.view.alpha = 1 makeImageView() maketitleLabel() makeDetailLabel() makeTryAgainButton() } func makeImageView() { imageView.image = UIImage(named: "no-signal") let width = self.view.frame.width / 3 view.addSubview(imageView) imageView.snp.makeConstraints { make in make.top.equalToSuperview().offset(70) make.centerX.equalToSuperview() make.height.equalTo(width) } } func maketitleLabel() { titleLabel.text = "Having trouble \n connecting?" titleLabel.numberOfLines = 0 titleLabel.textColor = .black titleLabel.lineBreakMode = .byTruncatingTail titleLabel.textAlignment = .center titleLabel.font = UIFont.preferredFont(forTextStyle: .headline) view.addSubview(titleLabel) titleLabel.snp.makeConstraints { make in make.leading.trailing.equalToSuperview() make.top.equalTo(imageView.snp.bottom).offset(70) } } func makeDetailLabel() { detailLabel.text = "We've all been there. Check your network \n or Wi-Fi connection and refresh" detailLabel.font = UIFont.preferredFont(forTextStyle: .body) detailLabel.numberOfLines = 0 detailLabel.textColor = .black detailLabel.textAlignment = .center detailLabel.lineBreakMode = .byTruncatingTail view.addSubview(detailLabel) detailLabel.snp.makeConstraints { make in make.leading.trailing.equalToSuperview() make.top.equalTo(titleLabel.snp.bottom).offset(20) } } func makeTryAgainButton() { tryAgain.titleLabel?.font = UIFont.systemFont(ofSize: UIFont.buttonFontSize) tryAgain.backgroundColor = #colorLiteral(red: 0.8862745098, green: 0, blue: 0.4549019608, alpha: 1) tryAgain.setTitleColor(.white, for: .normal) tryAgain.sizeToFit() tryAgain.contentEdgeInsets = UIEdgeInsets(top: 15,left: 60,bottom: 15,right: 60) tryAgain.addTarget(self, action: #selector(reTryAPICall), for: .touchUpInside) view.addSubview(tryAgain) tryAgain.snp.makeConstraints { make in make.top.equalTo(detailLabel.snp.bottom).offset(20) make.centerX.equalToSuperview() make.height.equalTo(50) } } @objc func reTryAPICall() { listener?.callApi() } }
31.407407
107
0.631191
e9dab276ff986322b7fa32b8002961c115caa29b
341
// // Int+Addition.swift // WMProject // // Created by cloud on 2019/2/11. // Copyright © 2019 Yedao Inc. All rights reserved. // import Foundation public extension Int { public func accountPointConvert() -> String? { let pointDecimal = Decimal(self).dividing(by: 100) return "\(pointDecimal)".priceFormat() } }
21.3125
58
0.653959
e5e5caec2b1b2a7e369d57e9372d81bc6265ecc0
542
// // HomeRouter.swift // Marvel // // Created by Víctor Vicente on 11/11/2018. // Copyright © 2018 DevSouls. All rights reserved. // import Foundation import UIKit class HomeRouter { var viewController: UIViewController init(view: UIViewController) { viewController = view } } extension HomeRouter: HomeRouterContract { func goToComicDetail(comic: Comic) { let detailVC = DetailConfigurator.createDetailStack(comic: comic) self.viewController.navigationController?.pushViewController(detailVC, animated: true) } }
18.689655
88
0.749077
0e1a0b51dfc1417628e1d201b7c502a3ef8469e4
175
import UIKit import RxSwift example(of: "Hello RxSwift") { let helloRx = Observable.just("Hello RxSwift") helloRx.subscribe { (value) in print(value) } }
17.5
50
0.651429
7a6c6e90cf9d061ec782660ef6fb5feef801669f
493
// // LineColorToLineStringTransformationPolicy.swift // TPGWatch // // Created by Yannick Heinrich on 05.08.16. // Copyright © 2016 Yageek. All rights reserved. // import CoreData import UIKit final class LineColorToLineStringTransformationPolicy: NSEntityMigrationPolicy { @objc func colorToColorHex(_ color: UIColor) -> String { return color.hexString } @objc func colorHexToColor(_ colorHex: String) -> UIColor { return UIColor(rgba: colorHex) } }
21.434783
80
0.716024
bbb3a7889b89cc2a3c441205bee043a5dfa3ce4e
3,712
/* * Copyright (c) 2021 Adventech <[email protected]> * * 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 FirebaseAuth import FirebaseDatabase import WidgetKit import SwiftUI struct TodayWidgetProvider: TimelineProvider { let database: DatabaseReference = Database.database().reference() static let placeholderDay: Day = Day.init(title: "-------") func placeholder(in context: Context) -> TodayWidgetEntry { TodayWidgetEntry(date: Date.init(), lessonInfo: LessonInfoWidgetProvider.placeholderLessonInfo, day: TodayWidgetProvider.placeholderDay) } func getSnapshot(in context: Context, completion: @escaping (TodayWidgetEntry) -> ()) { WidgetInteractor.getLessonInfo { (quarterly: Quarterly?, lessonInfo: LessonInfo?) in if let lessonInfo = lessonInfo, let day = WidgetInteractor.getTodayFromLessonInfo(lessonInfo: lessonInfo) { completion(TodayWidgetEntry(date: Date.init(), lessonInfo: lessonInfo, day: day)) } else { completion(TodayWidgetEntry(date: Date.init(), lessonInfo: LessonInfoWidgetProvider.placeholderLessonInfo, day: TodayWidgetProvider.placeholderDay)) } } } func getTimeline(in context: Context, completion: @escaping (Timeline<TodayWidgetEntry>) -> ()) { var entries: [TodayWidgetEntry] = [] WidgetInteractor.getLessonInfo { (quarterly: Quarterly?, lessonInfo: LessonInfo?) in let currentDate = Date() let midnight = Calendar.current.startOfDay(for: currentDate) let nextMidnight = Calendar.current.date(byAdding: .day, value: 1, to: midnight)! if let lessonInfo = lessonInfo { var day = TodayWidgetProvider.placeholderDay if let dbDay = WidgetInteractor.getTodayFromLessonInfo(lessonInfo: lessonInfo) { day = dbDay } entries.append(TodayWidgetEntry(date: currentDate, lessonInfo: lessonInfo, day: day)) for offset in 0..<24 { let entryDate = Calendar.current.date(byAdding: .hour, value: offset, to: midnight)! entries.append(TodayWidgetEntry(date: entryDate, lessonInfo: lessonInfo, day: day)) } } else { entries.append(TodayWidgetEntry(date: Calendar.current.date(byAdding: .minute, value: 1, to: Date())!, lessonInfo: LessonInfoWidgetProvider.placeholderLessonInfo, day: TodayWidgetProvider.placeholderDay)) } let timeline = Timeline(entries: entries, policy: .after(nextMidnight)) completion(timeline) } } }
51.555556
220
0.686961
1ed3c69bd77c58a6d765980d0edb8dfbcd30124f
780
// // APIService.swift // EKLongTouch // // Created by Erik Kamalov on 6/14/19. // Copyright © 2019 E K. All rights reserved. // import Foundation class APIService { class func fetchHitFeeds(completion: @escaping (Result<HitFeeds,Error>) -> Void) { DispatchQueue.global().async { if let path = Bundle.main.path(forResource: "HitFeed", ofType: "json") { do { let fileUrl = URL(fileURLWithPath: path) let data = try Data(contentsOf: fileUrl) let res = try JSONDecoder().decode(HitFeeds.self, from: data) completion(.success(res)) } catch { completion(.failure(error)) } } } } }
26.896552
86
0.528205
89037e17324021a1e369c79af895d1b687b9f1c6
1,627
// // TableViewForm.swift // // Created by Vladimir Espinola on 1/3/19. // Copyright © 2019 vel. All rights reserved. // import UIKit typealias FormSections = [Section] class Section { var index: Int! var headerFor: ((Int) -> UIView?)? = nil var headerHeight: CGFloat! = .leastNormalMagnitude //view footer section var footerFor: ((Int) -> UIView?)? = nil var footerHeight: CGFloat! = .leastNormalMagnitude var cells: [Field] = [] init(_ cells: [Field]? = nil){ guard let newCells = cells else { return } self.cells = newCells } func add(_ cell: Field) { self.cells.append(cell) } func add(_ cells: [Field]){ self.cells += cells } @discardableResult func configure(_ handler: (Section) -> Void) -> Self { handler(self) return self } func removeAllCells() { cells.removeAll() } } class Field { var cell: ((IndexPath) -> UITableViewCell)! var onSelect: ((IndexPath) -> Void)? var height = UITableView.automaticDimension init(for cell: ((IndexPath) -> UITableViewCell)? = nil) { self.cell = cell } @discardableResult func performOnSelection(_ handler: @escaping (IndexPath) -> Void) -> Self { self.onSelect = handler return self } @discardableResult func set(height: CGFloat) -> Self { self.height = height return self } } extension Section: Equatable { static func == (lhs: Section, rhs: Section) -> Bool { return lhs.index == rhs.index } }
21.407895
79
0.582667
d7bb4819b50e169a4729ae2b4831bc7cf3660bb8
2,996
// Copyright © 2017-2020 Khaos Wallet. // // This file is part of Trust. The full Trust copyright notice, including // terms governing use, modification, and redistribution, is contained in the // file LICENSE at the root of the source code distribution tree. import WalletCore import XCTest class PolkadotTests: XCTestCase { func testAddressValidation() { let polkadot = CoinType.polkadot // cosmos XCTAssertFalse(polkadot.validate(address: "cosmos1l4f4max9w06gqrvsxf74hhyzuqhu2l3zyf0480")) // Bitcoin p2sh XCTAssertFalse(polkadot.validate(address: "3317oFJC9FvxU2fwrKVsvgnMGCDzTZ5nyf")) // Kusama XCTAssertFalse(polkadot.validate(address: "ELmaX1aPkyEF7TSmYbbyCjmSgrBpGHv9EtpwR2tk1kmpwvG")) // polkadot sr25519 XCTAssertTrue(polkadot.validate(address: "14PhJGbzPxhQbiq7k9uFjDQx3MNiYxnjFRSiVBvBBBfnkAoM")) } func testAddress() { let key = PrivateKey(data: Data(hexString: "0xd65ed4c1a742699b2e20c0c1f1fe780878b1b9f7d387f934fe0a7dc36f1f9008")!)! let pubkey = key.getPublicKeyEd25519() let address = AnyAddress(publicKey: pubkey, coin: .polkadot) let addressFromString = AnyAddress(string: "12twBQPiG5yVSf3jQSBkTAKBKqCShQ5fm33KQhH3Hf6VDoKW", coin: .polkadot)! XCTAssertEqual(pubkey.data.hexString, "53d82211c4aadb8c67e1930caef2058a93bc29d7af86bf587fba4aa3b1515037") XCTAssertEqual(address.description, addressFromString.description) XCTAssertEqual(address.data, pubkey.data) } func testSigningBond() { // https://polkadot.subscan.io/extrinsic/0x5ec2ec6633b4b6993d9cf889ef42c457a99676244dc361a9ae17935d331dc39a // real key in 1p test let wallet = HDWallet.test let key = wallet.getKey(coin: .polkadot, derivationPath: "m/44'/354'/0'") let address = CoinType.polkadot.deriveAddress(privateKey: key) let genesisHash = Data(hexString: "0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3")! let input = PolkadotSigningInput.with { $0.genesisHash = genesisHash $0.blockHash = genesisHash $0.nonce = 0 $0.specVersion = 17 $0.network = .polkadot $0.transactionVersion = 3 $0.privateKey = key.data $0.stakingCall.bond = PolkadotStaking.Bond.with { $0.controller = address $0.rewardDestination = .staked // 0.01 $0.value = Data(hexString: "0x02540be400")! } } let output: PolkadotSigningOutput = AnySigner.sign(input: input, coin: .polkadot) XCTAssertEqual(output.encoded.hexString, "3902848d96660f14babe708b5e61853c9f5929bc90dd9874485bf4d6dc32d3e6f22eaa00a559867d1304cc95bac7cfe5d1b2fd49aed9f43c25c7d29b9b01c1238fa1f6ffef34b9650e42325de41e20fd502af7b074c67a9ec858bd9a1ba6d4212e3e0d0f00000007008d96660f14babe708b5e61853c9f5929bc90dd9874485bf4d6dc32d3e6f22eaa0700e40b540200") } }
47.555556
340
0.716956
670324a32483a0e53dfaa438d0a3d0b7a3827431
1,765
// // SWPageTitleViewConfigure.swift // SmartWalnut // // Created by lixiaomeng on 2018/6/15. // Copyright © 2018年 com.hetao101. All rights reserved. // import UIKit public enum IndicatorStyle { /// 下划线样式 case underLine /// 遮盖样式 case cover } open class SWPageTitleViewConfigure: NSObject { /** 是否让标题按钮文字有渐变效果,默认为 true */ public var isTitleGradientEffect: Bool = true /** 是否开启标题按钮文字缩放效果,默认为 false */ public var isOpenTitleTextZoom: Bool = false /** 标题文字缩放比,默认为 0.1f,取值范围 0 ~ 0.3f */ public var titleTextScaling: CGFloat = 0.1 /* SWPageTitleView 底部分割线颜色,默认为 lightGrayColor */ public var bottomSeparatorColor: UIColor = UIColor.lightGray /** 普通状态下标题按钮文字的颜色,默认为黑色 */ public var titleColor: UIColor = UIColor.black /** 选中状态下标题按钮文字的颜色,默认为红色 */ public var titleSelectedColor: UIColor = UIColor.red /** 标题文字字号大小,默认 15 号字体 */ public var titleFont: UIFont = UIFont.systemFont(ofSize: 15) /** 按钮之间的间距,默认为 20.0f */ public var spacingBetweenButtons: CGFloat = 20.0 /** 指示器高度,默认为 2.0f */ public var indicatorHeight: CGFloat = 2.0 /** 指示器颜色,默认为红色 */ public var indicatorColor: UIColor = UIColor.red /** 指示器的额外宽度,介于按钮文字宽度与按钮宽度之间 */ public var indicatorAdditionalWidth: CGFloat = 0 /** 指示器动画时间,默认为 0.1f,取值范围 0 ~ 0.3f */ public var indicatorAnimationTime: TimeInterval = 0.1 /** 指示器样式,默认为 SWIndicatorStyleDefault */ public var indicatorStyle: IndicatorStyle = .underLine /** 指示器遮盖样式下的圆角大小,默认为 0.1f */ public var indicatorCornerRadius: CGFloat = 0.1 /** 指示器遮盖样式下的边框宽度,默认为 0.0f */ public var indicatorBorderWidth: CGFloat = 0.0 /** 指示器遮盖样式下的边框颜色,默认为 clearColor */ public var indicatorBorderColor: UIColor = UIColor.clear /** SWPageTitleView 是否需要弹性效果,默认为 true */ public var isNeedBounces: Bool = true }
32.685185
62
0.718414
03992e302b7a0abe9792509a6784a399ac9d175d
1,324
// // ImageViewController.swift // GestureConflict // // Created by HLH on 2017/2/22. // Copyright © 2017年 胡良海. All rights reserved. // import UIKit import PhotoBrowser class ImageViewController: UIViewController { let imageView = UIImageView() let scrollView = UIScrollView() override func viewDidLoad() { super.viewDidLoad() initialize() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func initialize() { view.backgroundColor = .lightGray let array = ["http://odvxpvqb8.qnssl.com/%E7%86%8A%E7%8C%AB%E9%95%87/%E6%89%AF%E7%9D%80%E6%B7%A1/_image/%E6%8A%B5%E5%88%B6.jpg","http://odvxpvqb8.qnssl.com/%E7%86%8A%E7%8C%AB%E9%95%87/%E6%89%AF%E7%9D%80%E6%B7%A1/_image/%E7%8B%BC%E6%9D%A5%E4%BA%86.jpg","http://odvxpvqb8.qnssl.com/%E7%86%8A%E7%8C%AB%E9%95%87/%E6%89%AF%E7%9D%80%E6%B7%A1/_image/%E5%AF%BC%E6%B8%B8.jpg"] let pageController = PBPageViewController.init(sourceData: array as NSArray?, currentPhotoUrl: "http://odvxpvqb8.qnssl.com/%E7%86%8A%E7%8C%AB%E9%95%87/%E6%89%AF%E7%9D%80%E6%B7%A1/_image/%E5%AF%BC%E6%B8%B8.jpg", showStyle: PBStyle.OnlyPhotoStyle) pageController.showInViewController(viewController: self) } }
36.777778
375
0.673716
876293fb49a3ee8084ea20936e357d5a0b22bdd2
1,972
// // ExpectationsTests.swift // ExpectationsTests // // Created by Paulo F. Andrade on 16/12/2018. // Copyright © 2018 Paulo F. Andrade. All rights reserved. // import XCTest import Expectations class ExpectationsTests: XCTestCase { func testSimpleWait() { let expectation = Expectation() var flag = false DispatchQueue.global().asyncAfter(deadline: .now() + 1) { flag = true expectation.fulfill() } let startDate = Date() expectation.wait(for: 5) let exitDate = Date() XCTAssertTrue(flag) XCTAssertTrue(exitDate.timeIntervalSince(startDate) < 1.3) } func testConditionWait() { let expectation = Expectation() let queue = OperationQueue() var flag = false let blockOperation = BlockOperation() blockOperation.addExecutionBlock { [unowned blockOperation] () -> Void in expectation.wait(until: Date.distantFuture, while: !blockOperation.isCancelled) if blockOperation.isCancelled { return } flag = true } queue.addOperation(blockOperation) Thread.sleep(forTimeInterval: 1.0) blockOperation.cancel() queue.waitUntilAllOperationsAreFinished() XCTAssertFalse(flag) } func testRunRunloop() { let expectation = Expectation() var flag = false // by scheduling in the main thread we assert that the runloop is running DispatchQueue.main.asyncAfter(deadline: .now() + 1) { flag = true expectation.fulfill() } let startDate = Date() expectation.wait(for: 5, runRunloop: true) let exitDate = Date() XCTAssertTrue(flag) XCTAssertTrue(exitDate.timeIntervalSince(startDate) < 1.3) } }
26.648649
91
0.575051
7aec17250b4b31a768d4e3fabbebf12463ebd7da
2,395
// // NSObject+Binding.swift // // CotEditor // https://coteditor.com // // Created by 1024jp on 2018-10-27. // // --------------------------------------------------------------------------- // // © 2018 1024jp // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import AppKit extension NSTextField { /// bind receiver's nullPlaceholder with initial value of correspondent UserDefaults key func bindNullPlaceholderToUserDefaults(_ binding: NSBindingName) { guard let bindingInfo = self.infoForBinding(binding), let object = bindingInfo[.observedObject] as? NSUserDefaultsController, let keyPath = bindingInfo[.observedKeyPath] as? String else { return assertionFailure() } let key = keyPath.replacingOccurrences(of: #keyPath(NSUserDefaultsController.values) + ".", with: "") guard let initialValue = object.initialValues?[key] else { return assertionFailure() } let placeholder = self.formatter?.string(for: initialValue) ?? initialValue self.rebind(binding) { options in options[.nullPlaceholder] = placeholder } } } private extension NSObject { /// update binding options func rebind(_ binding: NSBindingName, updateHandler: (_ options: inout [NSBindingOption: Any]) -> Void) { guard let bindingInfo = self.infoForBinding(binding), let object = bindingInfo[.observedObject], let keyPath = bindingInfo[.observedKeyPath] as? String else { return assertionFailure() } var options = bindingInfo[.options] as? [NSBindingOption: Any] ?? [:] updateHandler(&options) self.unbind(binding) self.bind(binding, to: object, withKeyPath: keyPath, options: options) } }
32.808219
109
0.63048
6a8f66494cb80aa991a35e8a370de46895bd8ecd
25,194
// RUN: %empty-directory(%t) // RUN: %target-build-swift %s -swift-version 5 -DPTR_SIZE_%target-ptrsize -o %t/OSLogPrototypeExecTest // RUN: %target-run %t/OSLogPrototypeExecTest // // RUN: %target-build-swift %s -O -swift-version 5 -DPTR_SIZE_%target-ptrsize -o %t/OSLogPrototypeExecTest // RUN: %target-run %t/OSLogPrototypeExecTest // REQUIRES: executable_test // REQUIRES: OS=macosx || OS=ios || OS=tvos || OS=watchos // Run-time tests for testing the new OS log APIs that accept string // interpolations. The new APIs are still prototypes and must be used only in // tests. import OSLogPrototype import StdlibUnittest import Foundation defer { runAllTests() } internal var OSLogTestSuite = TestSuite("OSLogTest") if #available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) { // Following tests check whether valid log calls execute without // compile-time and run-time errors. func logMessages(_ h: Logger) { // Test logging of simple messages. h.log("A message with no data") // Test logging at specific levels. h.debug("Minimum integer value: \(Int.min)") h.info("Maximum unsigned integer value: \(UInt.max, format: .hex)") let privateID: UInt = 0x79abcdef h.error("Private Identifier: \(privateID, format: .hex, privacy: .private)") let addr: UInt = 0x7afebabe h.fault("Invalid address: 0x\(addr, format: .hex, privacy: .public)") // Test logging with multiple arguments. let filePermissions: UInt = 0o777 let pid = 122225 h.error( """ Access prevented: process \(pid) initiated by \ user: \(privateID, privacy: .private) attempted resetting \ permissions to \(filePermissions, format: .octal) """) } OSLogTestSuite.test("log with default logger") { let h = Logger() logMessages(h) } OSLogTestSuite.test("log with custom logger") { let h = Logger(subsystem: "com.swift.test", category: "OSLogAPIPrototypeTest") logMessages(h) } OSLogTestSuite.test("escaping of percents") { let h = Logger() h.log("a = c % d") h.log("Process failed after 99% completion") h.log("Double percents: %%") } // A stress test that checks whether the log APIs handle messages with more // than 48 interpolated expressions. Interpolated expressions beyond this // limit must be ignored. OSLogTestSuite.test("messages with too many arguments") { let h = Logger() h.log( level: .error, """ \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \ \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \ \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \ \(1) \(1) \(1) \(1) \(1) \(48) \(49) """) // The number 49 should not appear in the logged message. } OSLogTestSuite.test("escape characters") { let h = Logger() h.log("\"Imagination is more important than knowledge\" - Einstein") h.log("\'Imagination is more important than knowledge\' - Einstein") h.log("Imagination is more important than knowledge \n - Einstein") h.log("Imagination is more important than knowledge - \\Einstein") h.log("The log message will be truncated here.\0 You won't see this") } OSLogTestSuite.test("unicode characters") { let h = Logger() h.log("dollar sign: \u{24}") h.log("black heart: \u{2665}") h.log("sparkling heart: \u{1F496}") } OSLogTestSuite.test("raw strings") { let h = Logger() let x = 10 h.log(#"There is no \(interpolated) value in this string"#) h.log(#"This is not escaped \n"#) h.log(##"'\b' is a printf escape character but not in Swift"##) h.log(##"The interpolated value is \##(x)"##) h.log(#"Sparkling heart should appear in the next line. \#n \#u{1F496}"#) } OSLogTestSuite.test("integer types") { let h = Logger() h.log("Smallest 32-bit integer value: \(Int32.min)") } OSLogTestSuite.test("dynamic strings") { let h = Logger() let smallString = "a" h.log("A small string: \(smallString, privacy: .public)") let largeString = "This is a large String" h.log("\(largeString, privacy: .public)") let concatString = "hello" + " - " + "world" h.log("A dynamic string: \(concatString, privacy: .public)") let interpolatedString = "\(31) trillion digits of pi are known so far" h.log("\(interpolatedString)") } OSLogTestSuite.test("NSObject") { let h = Logger() let smallNSString: NSString = "a" h.log("A small string: \(smallNSString, privacy: .public)") let largeNSString: NSString = "This is a large String" h.log("\(largeNSString, privacy: .public)") let nsArray: NSArray = [0, 1, 2] h.log("NS Array: \(nsArray, privacy: .public)") let nsDictionary: NSDictionary = [1 : ""] h.log("NS Dictionary: \(nsDictionary, privacy: .public)") } OSLogTestSuite.test("integer formatting") { let h = Logger() let unsignedOctal: UInt = 0o171 // format specifier "0o%lo" output: "0o171" h.log("\(unsignedOctal, format: .octal(includePrefix: true))") // format specifier: "%lX" output: "DEADBEEF" let unsignedValue: UInt = 0xdeadbeef h.log("\(unsignedValue, format: .hex(uppercase: true))") // format specifier: "%+ld" output: "+20" h.log("\(20, format: .decimal(explicitPositiveSign: true))") // format specifier: "+%lu" output: "+2" h.log("\(UInt(2), format: .decimal(explicitPositiveSign: true))") // format specifier: "%.10ld" output: "0000000010" h.log("\(10, format: .decimal(minDigits: 10))") // format specifier: "%10ld" output: " 10" h.log("\(10, align: .right(columns: 10))") // format specifier: "%-5ld" output: "10 " h.log("\(10, align: .left(columns: 5))") } OSLogTestSuite.test("string formatting") { let h = Logger() let smallString = "a" h.log("\(smallString, align: .right(columns: 10), privacy: .public)") } OSLogTestSuite.test("Floats and Doubles") { let h = Logger() let x = 1.2 + 0.5 let pi: Double = 3.141593 let floatPi: Float = 3.141593 h.log("A double value: \(x, privacy: .private)") h.log("pi as double: \(pi), pi as float: \(floatPi)") } } // The following tests check the correctness of the format string and the // byte buffer constructed by the APIs from a string interpolation. // These tests do not perform logging and do not require the os_log ABIs to // be available. internal var InterpolationTestSuite = TestSuite("OSLogInterpolationTest") internal let bitsPerByte = 8 /// A struct that exposes methods for checking whether a given byte buffer /// conforms to the format expected by the os_log ABI. This struct acts as /// a specification of the byte buffer format. internal struct OSLogBufferChecker { internal let buffer: UnsafeBufferPointer<UInt8> internal init(_ byteBuffer: UnsafeBufferPointer<UInt8>) { buffer = byteBuffer } /// Bit mask for setting bits in the peamble. The bits denoted by the bit /// mask indicate whether there is an argument that is private, and whether /// there is an argument that is non-scalar: String, NSObject or Pointer. internal enum PreambleBitMask: UInt8 { case privateBitMask = 0x1 case nonScalarBitMask = 0x2 } /// Check the summary bytes of the byte buffer. /// - Parameters: /// - argumentCount: number of arguments expected to be in the buffer. /// - hasPrivate: true iff there exists a private argument /// - hasNonScalar: true iff there exists a non-scalar argument internal func checkSummaryBytes( argumentCount: UInt8, hasPrivate: Bool, hasNonScalar: Bool ) { let preamble = buffer[0] let privateBit = preamble & PreambleBitMask.privateBitMask.rawValue expectEqual(hasPrivate, privateBit != 0) let nonScalarBit = preamble & PreambleBitMask.nonScalarBitMask.rawValue expectEqual(hasNonScalar, nonScalarBit != 0) expectEqual(argumentCount, buffer[1]) } /// The possible values for the argument flag as defined by the os_log ABI. /// This occupies four least significant bits of the first byte of the /// argument header. Two least significant bits are used to indicate privacy /// and the other two bits are reserved. internal enum ArgumentFlag: UInt8 { case autoFlag = 0 case privateFlag = 0x1 case publicFlag = 0x2 } /// The possible values for the argument type as defined by the os_log ABI. /// This occupies four most significant bits of the first byte of the /// argument header. internal enum ArgumentType: UInt8 { case scalar = 0, count, string, pointer, object // TODO: include wide string and errno here if needed. } /// Check the encoding of an argument headers in the byte buffer starting from /// the `startIndex` and return argument bytes. private func checkArgumentHeadersAndGetBytes( startIndex: Int, size: UInt8, flag: ArgumentFlag, type: ArgumentType ) -> [UInt8] { let argumentHeader = buffer[startIndex] expectEqual((type.rawValue << 4) | flag.rawValue, argumentHeader) expectEqual(size, buffer[startIndex + 1]) // Argument data starts after the two header bytes. let argumentBytes: [UInt8] = (0..<Int(size)).reduce(into: []) { (acc, index) in acc.append(buffer[startIndex + 2 + index]) } return argumentBytes } /// Check whether the bytes starting from `startIndex` contain the encoding /// for an Int. internal func checkInt<T>( startIndex: Int, flag: ArgumentFlag, expectedInt: T ) where T : FixedWidthInteger { let byteSize = UInt8(MemoryLayout<T>.size) let argumentBytes = checkArgumentHeadersAndGetBytes( startIndex: startIndex, size: byteSize, flag: flag, type: .scalar) withUnsafeBytes(of: expectedInt) { expectedBytes in for i in 0..<Int(byteSize) { expectEqual( expectedBytes[i], argumentBytes[i], "mismatch at byte number \(i) " + "of the expected value \(expectedInt)") } } } /// Check whether the bytes starting from `startIndex` contain the encoding /// for a string. internal func checkString( startIndex: Int, flag: ArgumentFlag, expectedString: String ) { let pointerSize = UInt8(MemoryLayout<UnsafePointer<Int8>>.size) let argumentBytes = checkArgumentHeadersAndGetBytes( startIndex: startIndex, size: pointerSize, flag: flag, type: .string) // Read the pointer to a string stored in the buffer and compare it with // the expected string using `strcmp`. Note that it is important we use a // C function here to compare the string as it more closely represents // the C os_log functions. var stringAddress: Int = 0 // Copy the bytes of the address byte by byte. Note that // RawPointer.load(fromByteOffset:,_) function cannot be used here as the // address: `buffer + offset` is not aligned for reading an Int. for i in 0..<Int(pointerSize) { stringAddress |= Int(argumentBytes[i]) << (8 * i) } let bufferDataPointer = UnsafePointer<Int8>(bitPattern: stringAddress) expectedString.withCString { let compareResult = strcmp($0, bufferDataPointer) expectEqual(0, compareResult, "strcmp returned \(compareResult)") } } /// Check whether the bytes starting from `startIndex` contain the encoding /// for an NSObject. internal func checkNSObject( startIndex: Int, flag: ArgumentFlag, expectedObject: NSObject ) { let pointerSize = UInt8(MemoryLayout<UnsafePointer<Int8>>.size) let argumentBytes = checkArgumentHeadersAndGetBytes( startIndex: startIndex, size: pointerSize, flag: flag, type: .object) // Convert data to a pointer and check if the addresses stored in the // pointer and the one in the buffer match. let objectAddress = Unmanaged .passUnretained(expectedObject) .toOpaque() withUnsafeBytes(of: objectAddress) { expectedBytes in for i in 0..<Int(pointerSize) { // Argument data starts after the two header bytes. expectEqual( expectedBytes[i], argumentBytes[i], "mismatch at byte number \(i) " + "of the expected object address \(objectAddress)") } } } internal func checkDouble( startIndex: Int, flag: ArgumentFlag, expectedValue: Double ) { let byteSize: UInt8 = 8 let argumentBytes = checkArgumentHeadersAndGetBytes( startIndex: startIndex, size: byteSize, flag: flag, type: .scalar) withUnsafeBytes(of: expectedValue) { expectedBytes in for i in 0..<Int(byteSize) { expectEqual( expectedBytes[i], argumentBytes[i], "mismatch at byte number \(i) " + "of the expected value \(expectedValue)") } } } /// Check the given assertions on the arguments stored in the byte buffer. /// - Parameters: /// - assertions: one assertion for each argument stored in the byte buffer. internal func checkArguments(_ assertions: [(Int) -> Void]) { var currentArgumentIndex = 2 for assertion in assertions { expectTrue(currentArgumentIndex < buffer.count) assertion(currentArgumentIndex) // Advance the index to the next argument by adding the size of the // current argument and the two bytes of headers. currentArgumentIndex += 2 + Int(buffer[currentArgumentIndex + 1]) } } /// Check a sequence of assertions on the arguments stored in the byte buffer. internal func checkArguments(_ assertions: (Int) -> Void ...) { checkArguments(assertions) } } InterpolationTestSuite.test("integer literal") { _checkFormatStringAndBuffer( "An integer literal \(10)", with: { (formatString, buffer) in expectEqual( "An integer literal %ld", formatString) let bufferChecker = OSLogBufferChecker(buffer) bufferChecker.checkSummaryBytes( argumentCount: 1, hasPrivate: false, hasNonScalar: false) bufferChecker.checkArguments({ bufferChecker.checkInt(startIndex: $0, flag: .autoFlag, expectedInt: 10) }) }) } InterpolationTestSuite.test("integer with formatting") { _checkFormatStringAndBuffer( "Minimum integer value: \(UInt.max, format: .hex)", with: { (formatString, buffer) in expectEqual( "Minimum integer value: %lx", formatString) let bufferChecker = OSLogBufferChecker(buffer) bufferChecker.checkSummaryBytes( argumentCount: 1, hasPrivate: false, hasNonScalar: false) bufferChecker.checkArguments({ bufferChecker.checkInt( startIndex: $0, flag: .autoFlag, expectedInt: UInt.max) }) }) } InterpolationTestSuite.test("integer with privacy and formatting") { let addr: UInt = 0x7afebabe _checkFormatStringAndBuffer( "Access to invalid address: \(addr, format: .hex, privacy: .private)", with: { (formatString, buffer) in expectEqual( "Access to invalid address: %{private}lx", formatString) let bufferChecker = OSLogBufferChecker(buffer) bufferChecker.checkSummaryBytes( argumentCount: 1, hasPrivate: true, hasNonScalar: false) bufferChecker.checkArguments({ bufferChecker.checkInt( startIndex: $0, flag: .privateFlag, expectedInt: addr) }) }) } InterpolationTestSuite.test("test multiple arguments") { let filePerms: UInt = 0o777 let pid = 122225 let privateID = 0x79abcdef _checkFormatStringAndBuffer( """ Access prevented: process \(pid, privacy: .public) initiated by \ user: \(privateID, privacy: .private) attempted resetting \ permissions to \(filePerms, format: .octal) """, with: { (formatString, buffer) in expectEqual( """ Access prevented: process %{public}ld initiated by \ user: %{private}ld attempted resetting permissions \ to %lo """, formatString) let bufferChecker = OSLogBufferChecker(buffer) bufferChecker.checkSummaryBytes( argumentCount: 3, hasPrivate: true, hasNonScalar: false) bufferChecker.checkArguments( { bufferChecker.checkInt( startIndex: $0, flag: .publicFlag, expectedInt: pid) }, { bufferChecker.checkInt( startIndex: $0, flag: .privateFlag, expectedInt: privateID) }, { bufferChecker.checkInt( startIndex: $0, flag: .autoFlag, expectedInt: filePerms) }) }) } InterpolationTestSuite.test("interpolation of too many arguments") { // The following string interpolation has 49 interpolated values. Only 48 // of these must be present in the generated format string and byte buffer. _checkFormatStringAndBuffer( """ \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \ \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \ \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \ \(1) \(1) \(1) \(1) \(1) \(1) \(1) """, with: { (formatString, buffer) in expectEqual( String( repeating: "%ld ", count: Int(maxOSLogArgumentCount)), formatString) let bufferChecker = OSLogBufferChecker(buffer) bufferChecker.checkSummaryBytes( argumentCount: maxOSLogArgumentCount, hasPrivate: false, hasNonScalar: false) bufferChecker.checkArguments( Array( repeating: { bufferChecker.checkInt( startIndex: $0, flag: .autoFlag, expectedInt: 1) }, count: Int(maxOSLogArgumentCount)) ) }) } InterpolationTestSuite.test("string interpolations with percents") { _checkFormatStringAndBuffer( "a = (c % d)%%", with: { (formatString, buffer) in expectEqual("a = (c %% d)%%%%", formatString) let bufferChecker = OSLogBufferChecker(buffer) bufferChecker.checkSummaryBytes( argumentCount: 0, hasPrivate: false, hasNonScalar: false) }) } InterpolationTestSuite.test("integer types") { _checkFormatStringAndBuffer("Int32 max: \(Int32.max)") { (formatString, buffer) in expectEqual("Int32 max: %d", formatString) let bufferChecker = OSLogBufferChecker(buffer) bufferChecker.checkSummaryBytes( argumentCount: 1, hasPrivate: false, hasNonScalar: false) bufferChecker.checkArguments({ bufferChecker.checkInt( startIndex: $0, flag: .autoFlag, expectedInt: Int32.max) }) } } InterpolationTestSuite.test("string arguments") { let small = "a" let large = "this is a large string" _checkFormatStringAndBuffer( "small: \(small, privacy: .public) large: \(large)") { (formatString, buffer) in expectEqual("small: %{public}s large: %s", formatString) let bufferChecker = OSLogBufferChecker(buffer) bufferChecker.checkSummaryBytes( argumentCount: 2, hasPrivate: false, hasNonScalar: true ) bufferChecker.checkArguments({ bufferChecker.checkString( startIndex: $0, flag: .publicFlag, expectedString: small) }, { bufferChecker.checkString( startIndex: $0, flag: .autoFlag, expectedString: large) }) } } InterpolationTestSuite.test("dynamic strings") { let concatString = "hello" + " - " + "world" let interpolatedString = "\(31) trillion digits of pi are known so far" _checkFormatStringAndBuffer( """ concat: \(concatString, privacy: .public) \ interpolated: \(interpolatedString, privacy: .private) """) { (formatString, buffer) in expectEqual("concat: %{public}s interpolated: %{private}s", formatString) let bufferChecker = OSLogBufferChecker(buffer) bufferChecker.checkSummaryBytes( argumentCount: 2, hasPrivate: true, hasNonScalar: true ) bufferChecker.checkArguments({ bufferChecker.checkString( startIndex: $0, flag: .publicFlag, expectedString: concatString) }, { bufferChecker.checkString( startIndex: $0, flag: .privateFlag, expectedString: interpolatedString) }) } } InterpolationTestSuite.test("NSObject") { let nsArray: NSArray = [0, 1, 2] let nsDictionary: NSDictionary = [1 : ""] _checkFormatStringAndBuffer( """ NSArray: \(nsArray, privacy: .public) \ NSDictionary: \(nsDictionary) """) { (formatString, buffer) in expectEqual("NSArray: %{public}@ NSDictionary: %@", formatString) let bufferChecker = OSLogBufferChecker(buffer) bufferChecker.checkSummaryBytes( argumentCount: 2, hasPrivate: false, hasNonScalar: true ) bufferChecker.checkArguments({ bufferChecker.checkNSObject( startIndex: $0, flag: .publicFlag, expectedObject: nsArray) }, { bufferChecker.checkNSObject( startIndex: $0, flag: .autoFlag, expectedObject: nsDictionary) }) } } // A generic function. func toString<T>(_ subject: T?) -> String { return "" } protocol TestProto { } InterpolationTestSuite.test("Interpolation of complex expressions") { class TestClass<T: TestProto>: NSObject { func testFunction() { // The following call should not crash. _checkFormatStringAndBuffer("A complex expression \(toString(self))") { (formatString, _) in expectEqual("A complex expression %s", formatString) } } } class B : TestProto { } TestClass<B>().testFunction() } InterpolationTestSuite.test("Include prefix formatting option") { let unsignedValue: UInt = 0o171 _checkFormatStringAndBuffer( "Octal with prefix: \(unsignedValue, format: .octal(includePrefix: true))") { (formatString, buffer) in expectEqual("Octal with prefix: 0o%lo", formatString) } } InterpolationTestSuite.test("Hex with uppercase formatting option") { let unsignedValue: UInt = 0xcafebabe _checkFormatStringAndBuffer( "Hex with uppercase: \(unsignedValue, format: .hex(uppercase: true))") { (formatString, buffer) in expectEqual("Hex with uppercase: %lX", formatString) } } InterpolationTestSuite.test("Integer with explicit positive sign") { let posValue = Int.max _checkFormatStringAndBuffer( "\(posValue, format: .decimal(explicitPositiveSign: true))") { (formatString, buffer) in expectEqual("%+ld", formatString) } } InterpolationTestSuite.test("Unsigned integer with explicit positive sign") { let posValue = UInt.max _checkFormatStringAndBuffer( "\(posValue, format: .decimal(explicitPositiveSign: true))") { (formatString, buffer) in expectEqual("+%lu", formatString) } } InterpolationTestSuite.test("Integer formatting with precision") { let intValue = 10 _checkFormatStringAndBuffer( "\(intValue, format: .decimal(minDigits: 10))") { (formatString, buffer) in expectEqual("%.10ld", formatString) } } InterpolationTestSuite.test("Integer formatting with alignment") { let intValue = 10 _checkFormatStringAndBuffer( """ \(intValue, align: .right(columns: 10)) \ \(intValue, align: .left(columns: 5), privacy: .private) """) { (formatString, buffer) in expectEqual("%10ld %{private}-5ld", formatString) } } InterpolationTestSuite.test("String with alignment") { let smallString = "a" + "b" let concatString = "hello" + " - " + "world" _checkFormatStringAndBuffer( """ \(smallString, align: .right(columns: 10)) \ \(concatString, align: .left(columns: 7), privacy: .public) """) { (formatString, buffer) in expectEqual("%10s %{public}-7s", formatString) } } InterpolationTestSuite.test("Floats and Doubles") { let x = 1.2 + 0.5 let pi: Double = 3.141593 let floatPi: Float = 3.141593 _checkFormatStringAndBuffer( """ A double value: \(x, privacy: .private) \ pi as double: \(pi), pi as float: \(floatPi) """) { (formatString, buffer) in expectEqual( """ A double value: %{private}f pi as double: %f, \ pi as float: %f """, formatString) let bufferChecker = OSLogBufferChecker(buffer) bufferChecker.checkSummaryBytes( argumentCount: 3, hasPrivate: true, hasNonScalar: false) bufferChecker.checkArguments( { bufferChecker.checkDouble( startIndex: $0, flag: .privateFlag, expectedValue: x) }, { bufferChecker.checkDouble( startIndex: $0, flag: .autoFlag, expectedValue: pi) }, { bufferChecker.checkDouble( startIndex: $0, flag: .autoFlag, expectedValue: Double(floatPi)) }) } }
30.72439
106
0.639517
213144179b66e939ff0f99804d11fe337132934d
453
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. import Foundation // RetentionDurationProtocol is retention duration. public protocol RetentionDurationProtocol : Codable { var count: Int32? { get set } var durationType: RetentionDurationTypeEnum? { get set } }
41.181818
96
0.750552
b9a6c97c3b6c7c6d7b89b43eadb72c4cb5dab56b
368
// // URL+QueryItems.swift // Giraffe // // Created by Derek on 9/4/19. // import Foundation public extension Parameters { func appendingParameters(_ parameters: Parameters) -> Parameters { return self.merging(parameters) { _, new in new } } mutating func appendParameters(_ parameters: Parameters) { self = appendingParameters(parameters) } }
19.368421
68
0.701087
f7184a1544b10cbbb9d83b3f05a9991241ed751d
1,753
//===----------------------------------------------------------------------===// // // This source file is part of the Swift Package Collection Generator open source project // // Copyright (c) 2021 Apple Inc. and the Swift Package Collection Generator project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Swift Package Collection Generator project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import Foundation import PackageCollectionsModel protocol PackageMetadataProvider { func get(_ packageURL: URL, callback: @escaping (Result<PackageBasicMetadata, Error>) -> Void) } enum AuthTokenType: Hashable, CustomStringConvertible { case github(_ host: String) var description: String { switch self { case .github(let host): return "github(\(host))" } } static func from(type: String, host: String) -> AuthTokenType? { switch type { case "github": return .github(host) default: return nil } } } struct PackageBasicMetadata: Equatable { let summary: String? let keywords: [String]? let readmeURL: URL? let license: PackageCollectionModel.V1.License? } // MARK: - Utility extension Result { var failure: Failure? { switch self { case .failure(let failure): return failure case .success: return nil } } var success: Success? { switch self { case .failure: return nil case .success(let value): return value } } }
24.690141
98
0.570451
89f9fd61ac573169f551049170079bccd13797d5
212
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing protocol a{struct S<T:f}struct Q{let g:A{f
35.333333
87
0.764151
db28513a7a2958331580714f14c9b9a9ba76c7ae
616
// // FSE+UIScrollView.swift // FSHelpers // // Created by Ildar Zalyalov on 27.07.16. // Copyright © 2016 FlatStack. All rights reserved. // import UIKit public extension UIScrollView{ var fs_contentWidth: CGFloat { set (contentWidth) {self.contentSize = CGSize(width: contentWidth, height: self.contentSize.height)} get {return self.contentSize.width} } var fs_contentHeight: CGFloat { set (contentHeight) {self.contentSize = CGSize(width: self.contentSize.width, height: contentHeight)} get {return self.contentSize.height} } }
25.666667
109
0.660714
39f81524b79c3d355c050ee3b4bd088ebce68720
509
// // ViewController.swift // Animnedia // // Created by Erick Sanchez on 04/12/17. // Copyright © 2017 App Builders. 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.576923
80
0.669941
3a1fb0f2f48cb9ca77e16c085b59eed2db9453f6
2,549
// // Copyright (c) 2021 Lucas Abijmil. All rights reserved. // import SwiftUI /// A `UIViewControllerRepresentable` that's display a `UIViewController` bridged. struct InteractiveSheetView<Content: View>: UIViewControllerRepresentable { @Binding var isPresented: Bool @ViewBuilder let content: Content let showsIndicator: Bool let background: Color let onDismiss: (() -> Void)? let mode: Mode enum Mode { case half case interactive } func makeCoordinator() -> Coordinator { return Coordinator(parent: self) } func makeUIViewController(context: Context) -> UIViewController { let controller = UIViewController() controller.view.backgroundColor = .clear return controller } func updateUIViewController(_ uiViewController: UIViewController, context: Context) { if isPresented { let sheetController = InteractiveSheetViewController(rootView: content, showIndicator: showsIndicator, background: background, mode: mode) sheetController.presentationController?.delegate = context.coordinator DispatchQueue.main.async { uiViewController.present(sheetController, animated: true) isPresented.toggle() } } } final class Coordinator: NSObject, UISheetPresentationControllerDelegate { private let parent: InteractiveSheetView init(parent: InteractiveSheetView) { self.parent = parent } func presentationControllerDidDismiss(_ presentationController: UIPresentationController) { parent.onDismiss?() } } } /// A `UIHostingController` that's display a `UIViewController`. final class InteractiveSheetViewController<Content: View>: UIHostingController<Content> { private let showsIndicator: Bool private let background: Color private let mode: InteractiveSheetView<Content>.Mode init(rootView: Content, showIndicator: Bool, background: Color, mode: InteractiveSheetView<Content>.Mode) { self.showsIndicator = showIndicator self.background = background self.mode = mode super.init(rootView: rootView) } @MainActor @objc required dynamic init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { if let presentationController = presentationController as? UISheetPresentationController { view.backgroundColor = UIColor(background) presentationController.detents = mode == .interactive ? [.medium(), .large()] : [.medium()] presentationController.prefersGrabberVisible = showsIndicator } } }
30.345238
144
0.737936
4ad8837aca7c77c71a4cc98f7e0899e1d46c637e
23,576
// // TextFinder.swift // // CotEditor // https://coteditor.com // // Created by 1024jp on 2015-01-03. // // --------------------------------------------------------------------------- // // © 2015-2019 1024jp // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Cocoa @objc protocol TextFinderClientProvider: AnyObject { func textFinderClient() -> NSTextView? } protocol TextFinderDelegate: AnyObject { func textFinder(_ textFinder: TextFinder, didFinishFindingAll findString: String, results: [TextFindResult], textView: NSTextView) func textFinder(_ textFinder: TextFinder, didFind numberOfFound: Int, textView: NSTextView) func textFinder(_ textFinder: TextFinder, didReplace numberOfReplaced: Int, textView: NSTextView) } struct TextFindResult { var range: NSRange var lineNumber: Int var attributedLineString: NSAttributedString var inlineRange: NSRange } private struct HighlightItem { var range: NSRange var color: NSColor } // MARK: - final class TextFinder: NSResponder, NSMenuItemValidation { static let shared = TextFinder() // MARK: Public Properties @objc dynamic var findString = "" { didSet { NSPasteboard.findString = self.findString } } @objc dynamic var replacementString = "" weak var delegate: TextFinderDelegate? // MARK: Private Properties private lazy var findPanelController = FindPanelController.instantiate(storyboard: "FindPanel") private lazy var multipleReplacementPanelController = NSWindowController.instantiate(storyboard: "MultipleReplacementPanel") // MARK: - // MARK: Lifecycle private override init() { super.init() // add to responder chain NSApp.nextResponder = self // observe application activation to sync find string with other apps NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive), name: NSApplication.didBecomeActiveNotification, object: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Menu Item Validation /// validate menu item func validateMenuItem(_ menuItem: NSMenuItem) -> Bool { guard let action = menuItem.action else { return false } switch action { case #selector(findNext(_:)), #selector(findPrevious(_:)), #selector(findSelectedText(_:)), #selector(findAll(_:)), #selector(highlight(_:)), #selector(unhighlight(_:)), #selector(replace(_:)), #selector(replaceAndFind(_:)), #selector(replaceAll(_:)), #selector(useSelectionForReplace(_:)), // replacement string accepts empty string #selector(centerSelectionInVisibleArea(_:)): return self.client != nil case #selector(useSelectionForFind(_:)): return self.selectedString != nil default: return true } } // MARK: Notifications /// sync search string on activating application @objc private func applicationDidBecomeActive(_ notification: Notification) { if let sharedFindString = NSPasteboard.findString { self.findString = sharedFindString } } // MARK: Public Methods /// target text view var client: NSTextView? { guard let provider = NSApp.target(forAction: #selector(TextFinderClientProvider.textFinderClient)) as? TextFinderClientProvider else { return nil } return provider.textFinderClient() } // MARK: Action Messages /// jump to selection in client @IBAction override func centerSelectionInVisibleArea(_ sender: Any?) { self.client?.centerSelectionInVisibleArea(sender) } /// activate find panel @IBAction func showFindPanel(_ sender: Any?) { self.findPanelController.showWindow(sender) } /// activate multiple replacement panel @IBAction func showMultipleReplacementPanel(_ sender: Any?) { self.multipleReplacementPanelController.showWindow(sender) } /// find next matched string @IBAction func findNext(_ sender: Any?) { // find backwards if Shift key pressed let isShiftPressed = NSEvent.modifierFlags.contains(.shift) self.find(forward: !isShiftPressed) } /// find previous matched string @IBAction func findPrevious(_ sender: Any?) { self.find(forward: false) } /// perform find action with the selected string @IBAction func findSelectedText(_ sender: Any?) { self.useSelectionForFind(sender) self.findNext(sender) } /// select all matched strings @IBAction func selectAllMatches(_ sender: Any?) { guard let (textView, textFind) = self.prepareTextFind(forEditing: false) else { return } var matchedRanges = [NSRange]() textFind.findAll { (matches: [NSRange], _) in matchedRanges.append(matches[0]) } textView.selectedRanges = matchedRanges as [NSValue] self.delegate?.textFinder(self, didFind: matchedRanges.count, textView: textView) UserDefaults.standard.appendHistory(self.findString, forKey: .findHistory) } /// find all matched strings and show results in a table @IBAction func findAll(_ sender: Any?) { self.findAll(showsList: true, actionName: "Find All".localized) } /// highlight all matched strings @IBAction func highlight(_ sender: Any?) { self.findAll(showsList: false, actionName: "Highlight".localized) } /// remove all of current highlights in the frontmost textView @IBAction func unhighlight(_ sender: Any?) { guard let textView = self.client else { return } let range = textView.string.nsRange textView.layoutManager?.removeTemporaryAttribute(.backgroundColor, forCharacterRange: range) } /// replace matched string in selection with replacementString @IBAction func replace(_ sender: Any?) { if self.replace() { self.client?.centerSelectionInVisibleArea(self) } else { NSSound.beep() } UserDefaults.standard.appendHistory(self.findString, forKey: .findHistory) UserDefaults.standard.appendHistory(self.replacementString, forKey: .replaceHistory) } /// replace matched string with replacementString and select the next match @IBAction func replaceAndFind(_ sender: Any?) { self.replace() self.find(forward: true) UserDefaults.standard.appendHistory(self.findString, forKey: .findHistory) UserDefaults.standard.appendHistory(self.replacementString, forKey: .replaceHistory) } /// replace all matched strings with given string @IBAction func replaceAll(_ sender: Any?) { guard let (textView, textFind) = self.prepareTextFind(forEditing: true) else { return } textView.isEditable = false let replacementString = self.replacementString // setup progress sheet let progress = TextFindProgress(format: .replacement) let indicator = ProgressViewController.instantiate(storyboard: "ProgressView") indicator.setup(progress: progress, message: "Replace All".localized) textView.viewControllerForSheet?.presentAsSheet(indicator) DispatchQueue.global(qos: .userInitiated).async { [weak self] in guard let self = self else { return } let (replacementItems, selectedRanges) = textFind.replaceAll(with: replacementString) { (flag, stop) in guard !progress.isCancelled else { stop = true return } switch flag { case .findProgress, .foundCount: break case .replacementProgress: progress.completedUnitCount += 1 } } DispatchQueue.main.sync { textView.isEditable = true guard !progress.isCancelled else { indicator.dismiss(nil) return } if !replacementItems.isEmpty { let replacementStrings = replacementItems.map { $0.string } let replacementRanges = replacementItems.map { $0.range } // apply found strings to the text view textView.replace(with: replacementStrings, ranges: replacementRanges, selectedRanges: selectedRanges, actionName: "Replace All".localized) } indicator.done() if replacementItems.isEmpty { NSSound.beep() progress.localizedDescription = "Not Found".localized } if UserDefaults.standard[.findClosesIndicatorWhenDone] { indicator.dismiss(nil) if let panel = self.findPanelController.window, panel.isVisible { panel.makeKey() } } let count = Int(progress.completedUnitCount) self.delegate?.textFinder(self, didReplace: count, textView: textView) } } UserDefaults.standard.appendHistory(self.findString, forKey: .findHistory) UserDefaults.standard.appendHistory(self.replacementString, forKey: .replaceHistory) } /// set selected string to find field @IBAction func useSelectionForFind(_ sender: Any?) { guard let selectedString = self.selectedString else { NSSound.beep() return } self.findString = selectedString // auto-disable regex UserDefaults.standard[.findUsesRegularExpression] = false } /// set selected string to replace field @IBAction func useSelectionForReplace(_ sender: Any?) { self.replacementString = self.selectedString ?? "" } // MARK: Private Methods /// selected string in the current tareget private var selectedString: String? { guard let textView = self.client else { return nil } return (textView.string as NSString).substring(with: textView.selectedRange) } /// find string of which line endings are standardized to LF private var sanitizedFindString: String { return self.findString.replacingLineEndings(with: .lf) } /// check Find can be performed and alert if needed private func prepareTextFind(forEditing: Bool) -> (NSTextView, TextFind)? { guard let textView = self.client, (!forEditing || (textView.isEditable && textView.window?.attachedSheet == nil)) else { NSSound.beep() return nil } guard self.findPanelController.window?.attachedSheet == nil else { self.findPanelController.showWindow(self) NSSound.beep() return nil } let string = textView.string.immutable let mode = TextFind.Mode(defaults: UserDefaults.standard) let inSelection = UserDefaults.standard[.findInSelection] let textFind: TextFind do { textFind = try TextFind(for: string, findString: self.sanitizedFindString, mode: mode, inSelection: inSelection, selectedRanges: textView.selectedRanges as! [NSRange]) } catch { switch error { case TextFind.Error.regularExpression: self.findPanelController.showWindow(self) self.presentError(error, modalFor: self.findPanelController.window!, delegate: nil, didPresent: nil, contextInfo: nil) default: break } NSSound.beep() return nil } return (textView, textFind) } /// perform "Find Next" or "Find Previous" and return number of found @discardableResult private func find(forward: Bool) -> Int { guard let (textView, textFind) = self.prepareTextFind(forEditing: false) else { return 0 } let result = textFind.find(forward: forward, isWrap: UserDefaults.standard[.findIsWrap]) // found feedback if let range = result.range { textView.selectedRange = range textView.scrollRangeToVisible(range) textView.showFindIndicator(for: range) if result.wrapped { if let view = textView.enclosingScrollView?.superview { let hudController = HUDController.instantiate(storyboard: "HUDView") hudController.symbol = .wrap hudController.isReversed = !forward hudController.show(in: view) } if let window = NSApp.mainWindow { NSAccessibility.post(element: window, notification: .announcementRequested, userInfo: [.announcement: "Search wrapped.".localized]) } } } else { NSSound.beep() } self.delegate?.textFinder(self, didFind: result.count, textView: textView) UserDefaults.standard.appendHistory(self.findString, forKey: .findHistory) return result.count } /// replace matched string in selection with replacementString @discardableResult private func replace() -> Bool { guard let (textView, textFind) = self.prepareTextFind(forEditing: true), let result = textFind.replace(with: self.replacementString) else { return false } // apply replacement to text view return textView.replace(with: result.string, range: result.range, selectedRange: NSRange(location: result.range.location, length: result.string.length), actionName: "Replace".localized) } /// find all matched strings and apply the result to views private func findAll(showsList: Bool, actionName: String) { guard let (textView, textFind) = self.prepareTextFind(forEditing: false) else { return } textView.isEditable = false let highlightColors = NSColor.textHighlighterColors(count: textFind.numberOfCaptureGroups + 1) let lineRegex = try! NSRegularExpression(pattern: "\n") // setup progress sheet let progress = TextFindProgress(format: .find) let indicator = ProgressViewController.instantiate(storyboard: "ProgressView") indicator.setup(progress: progress, message: actionName) textView.viewControllerForSheet?.presentAsSheet(indicator) DispatchQueue.global(qos: .userInitiated).async { [weak self] in guard let self = self else { return } var highlights = [HighlightItem]() var results = [TextFindResult]() // not used if showsList is false textFind.findAll { (matches: [NSRange], stop) in guard !progress.isCancelled else { stop = true return } // highlight highlights += matches.enumerated() .filter { !$0.element.isEmpty } .map { HighlightItem(range: $0.element, color: highlightColors[$0.offset]) } // build TextFindResult for table if showsList { let matchedRange = matches[0] // calculate line number let lastLineNumber = results.last?.lineNumber ?? 1 let lastLocation = results.last?.range.location ?? 0 let diffRange = NSRange(lastLocation..<matchedRange.location) let lineNumber = lastLineNumber + lineRegex.numberOfMatches(in: textFind.string, range: diffRange) // build a highlighted line string for result table let lineRange = (textFind.string as NSString).lineRange(for: matchedRange) let lineString = (textFind.string as NSString).substring(with: lineRange) let attrLineString = NSMutableAttributedString(string: lineString) for (index, range) in matches.enumerated() where !range.isEmpty { let color = highlightColors[index] let inlineRange = range.shifted(offset: -lineRange.location) attrLineString.addAttribute(.backgroundColor, value: color, range: inlineRange) } // calculate inline range let inlineRange = matchedRange.shifted(offset: -lineRange.location) results.append(TextFindResult(range: matchedRange, lineNumber: lineNumber, attributedLineString: attrLineString, inlineRange: inlineRange)) } progress.completedUnitCount += 1 } DispatchQueue.main.sync { textView.isEditable = true guard !progress.isCancelled else { indicator.dismiss(nil) return } // highlight if let layoutManager = textView.layoutManager { let wholeRange = textFind.string.nsRange (layoutManager as? ValidationIgnorable)?.ignoresDisplayValidation = true layoutManager.removeTemporaryAttribute(.backgroundColor, forCharacterRange: wholeRange) for highlight in highlights { layoutManager.addTemporaryAttribute(.backgroundColor, value: highlight.color, forCharacterRange: highlight.range) } (layoutManager as? ValidationIgnorable)?.ignoresDisplayValidation = false layoutManager.invalidateDisplay(forCharacterRange: wholeRange) } indicator.done() if highlights.isEmpty { NSSound.beep() progress.localizedDescription = "Not Found".localized } if showsList { self.delegate?.textFinder(self, didFinishFindingAll: textFind.findString, results: results, textView: textView) } // -> close also if result view has been shown if !results.isEmpty || UserDefaults.standard[.findClosesIndicatorWhenDone] { indicator.dismiss(nil) if let panel = self.findPanelController.window, panel.isVisible { panel.makeKey() } } } } UserDefaults.standard.appendHistory(self.findString, forKey: .findHistory) } } // MARK: - UserDefaults private extension UserDefaults { private static let MaxHistorySize = 20 /// append given string to history with the user defaults key func appendHistory(_ string: String, forKey key: DefaultKey<[String]>) { assert(key == .findHistory || key == .replaceHistory) guard !string.isEmpty else { return } // append new string to history var history = self[key] ?? [] history.remove(string) // remove duplicated item history.append(string) if history.count > UserDefaults.MaxHistorySize { // remove overflow history.removeFirst(history.count - UserDefaults.MaxHistorySize) } self[key] = history } } private extension TextFind.Mode { init(defaults: UserDefaults) { if defaults[.findUsesRegularExpression] { var options = NSRegularExpression.Options() if defaults[.findIgnoresCase] { options.update(with: .caseInsensitive) } if defaults[.findRegexIsSingleline] { options.update(with: .dotMatchesLineSeparators) } if defaults[.findRegexIsMultiline] { options.update(with: .anchorsMatchLines) } if defaults[.findRegexUsesUnicodeBoundaries] { options.update(with: .useUnicodeWordBoundaries) } self = .regularExpression(options: options, unescapesReplacement: defaults[.findRegexUnescapesReplacementString]) } else { var options = NSString.CompareOptions() if defaults[.findIgnoresCase] { options.update(with: .caseInsensitive) } if defaults[.findTextIsLiteralSearch] { options.update(with: .literal) } if defaults[.findTextIgnoresDiacriticMarks] { options.update(with: .diacriticInsensitive) } if defaults[.findTextIgnoresWidth] { options.update(with: .widthInsensitive) } self = .textual(options: options, fullWord: defaults[.findMatchesFullWord]) } } } // MARK: Pasteboard private extension NSPasteboard { /// find string from global domain class var findString: String? { get { let pasteboard = NSPasteboard(name: .find) return pasteboard.string(forType: .string) } set { guard let string = newValue, !string.isEmpty else { return } let pasteboard = NSPasteboard(name: .find) pasteboard.declareTypes([.string], owner: nil) pasteboard.setString(string, forType: .string) } } }
34.772861
179
0.575925
33e50a8df0d14c0ceb7e5218dd3aaed815de79f6
674
// // videoButton.swift // CustomPod // // Created by Mandar Choudhary on 28/09/20. // Copyright © 2020 Mandar Choudhary. All rights reserved. // import UIKit open class VideoButton: UIButton { override init(frame: CGRect){ super.init(frame: frame) } required public init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override open func layoutSubviews() { super.layoutSubviews() setup() } open func setup() { self.setImage(OUImageConstants.videoUnmuted.getUIImage(), for: .normal) self.setImage(OUImageConstants.videoMuted.getUIImage(), for: .selected) } }
21.741935
79
0.649852
48750e36df4b4f35d015602bc0c75c19c219c89c
306
// // Common.swift // ZhiBo // // Created by mac on 16/10/29. // Copyright © 2016年 mac. All rights reserved. // import UIKit let kStatusBarH:CGFloat = 20 let kNavgationBarH:CGFloat = 44 let kTabbarH :CGFloat = 44 let kScreenH = UIScreen.main.bounds.height let kScreenW = UIScreen.main.bounds.width
17
47
0.715686
395bf1d0d69102105f8127e14deaa7bd939613f2
2,596
// // AppDelegate.swift // DTMvvm // // Created by [email protected] on 09/25/2018. // Copyright (c) 2018 [email protected]. All rights reserved. // import UIKit import DTMvvm @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. DependencyManager.shared.registerDefaults() window = UIWindow(frame: UIScreen.main.bounds) let page = ExampleMenuPage(viewModel: HomeMenuPageViewModel()) let rootPage = NavigationPage(rootViewController: page) rootPage.statusBarStyle = .default window?.rootViewController = rootPage window?.makeKeyAndVisible() return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.357143
285
0.74037
891a8f035e71b7b57e8cd62205da6e7de42184e1
394
// // MusicNavigationController.swift // Example // // Created by John Blaine on 11/24/20. // Copyright © 2020 John Blaine. All rights reserved. // import UIKit class MusicNavigationController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() let vc = MusicViewController() self.pushViewController(vc, animated: false) } }
18.761905
57
0.677665
387474e31fc70be5b671434477558e727cee7f80
6,447
import UIKit final public class AnimatedTextField: UITextField { enum TextFieldType { case text case password case numeric case selection } fileprivate let defaultPadding: CGFloat = -16 fileprivate let clearButtonPadding: CGFloat = -8 var rightViewPadding: CGFloat weak public var textInputDelegate: TextInputDelegate? public var textAttributes: [NSAttributedStringKey: Any]? public var contentInset: UIEdgeInsets = .zero fileprivate var disclosureButtonAction: (() -> Void)? override init(frame: CGRect) { self.rightViewPadding = defaultPadding super.init(frame: frame) setup() } required public init?(coder aDecoder: NSCoder) { self.rightViewPadding = defaultPadding super.init(coder: aDecoder) setup() } fileprivate func setup() { delegate = self addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged) } @discardableResult override public func becomeFirstResponder() -> Bool { if let alignment = (textAttributes?[NSAttributedStringKey.paragraphStyle] as? NSMutableParagraphStyle)?.alignment { textAlignment = alignment } return super.becomeFirstResponder() } override public func rightViewRect(forBounds bounds: CGRect) -> CGRect { return super.rightViewRect(forBounds: bounds).offsetBy(dx: rightViewPadding, dy: 0) } override public func clearButtonRect(forBounds bounds: CGRect) -> CGRect { return super.clearButtonRect(forBounds: bounds).offsetBy(dx: clearButtonPadding, dy: 0) } override public func textRect(forBounds bounds: CGRect) -> CGRect { var width = bounds.width if clearButtonMode == .always || clearButtonMode == .unlessEditing { width = bounds.width - clearButtonRect(forBounds: bounds).width * 2 } return CGRect(x: bounds.origin.x + contentInset.left, y: bounds.origin.y + contentInset.top, width: width - contentInset.left - contentInset.right, height: bounds.height - contentInset.top - contentInset.bottom) } override public func editingRect(forBounds bounds: CGRect) -> CGRect { var width = bounds.width if clearButtonMode != .never { width = bounds.width - clearButtonRect(forBounds: bounds).width * 2 } else if let _ = rightView { width = bounds.width - rightViewRect(forBounds: bounds).width * 2 } return CGRect(x: bounds.origin.x + contentInset.left, y: bounds.origin.y + contentInset.top, width: width - contentInset.left - contentInset.right, height: bounds.height - contentInset.top - contentInset.bottom) } func add(disclosureButton button: UIButton, action: @escaping (() -> Void)) { let selector = #selector(disclosureButtonPressed) if disclosureButtonAction != nil, let previousButton = rightView as? UIButton { previousButton.removeTarget(self, action: selector, for: .touchUpInside) } disclosureButtonAction = action button.addTarget(self, action: selector, for: .touchUpInside) rightView = button } @objc fileprivate func disclosureButtonPressed() { disclosureButtonAction?() } @objc fileprivate func textFieldDidChange() { if let text = text { var cursorPosition: Int? if let selectedRange = self.selectedTextRange { cursorPosition = self.offset(from: self.beginningOfDocument, to: selectedRange.start) } attributedText = NSAttributedString(string: text, attributes: textAttributes) if let cursorPosition = cursorPosition, let newPosition = self.position(from: self.beginningOfDocument, offset: cursorPosition) { self.selectedTextRange = self.textRange(from: newPosition, to: newPosition) } } textInputDelegate?.textInputDidChange(textInput: self) } } extension AnimatedTextField: TextInput { public func configureInputView(newInputView: UIView) { inputView = newInputView } public func changeReturnKeyType(with newReturnKeyType: UIReturnKeyType) { returnKeyType = newReturnKeyType } public func currentPosition(from: UITextPosition, offset: Int) -> UITextPosition? { return position(from: from, offset: offset) } public func changeClearButtonMode(with newClearButtonMode: UITextFieldViewMode) { clearButtonMode = newClearButtonMode } public var currentText: String? { get { return text } set { self.text = newValue } } public var currentSelectedTextRange: UITextRange? { get { return self.selectedTextRange } set { self.selectedTextRange = newValue } } open var currentBeginningOfDocument: UITextPosition? { get { return self.beginningOfDocument } } } extension AnimatedTextField: TextInputError { public func configureErrorState(with message: String?) { placeholder = message } public func removeErrorHintMessage() { placeholder = nil } } extension AnimatedTextField: UITextFieldDelegate { public func textFieldDidBeginEditing(_ textField: UITextField) { textInputDelegate?.textInputDidBeginEditing(textInput: self) } public func textFieldDidEndEditing(_ textField: UITextField) { textInputDelegate?.textInputDidEndEditing(textInput: self) } public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { return textInputDelegate?.textInput(textInput: self, shouldChangeCharactersInRange: range, replacementString: string) ?? true } public func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { return textInputDelegate?.textInputShouldBeginEditing(textInput: self) ?? true } public func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { return textInputDelegate?.textInputShouldEndEditing(textInput: self) ?? true } public func textFieldShouldReturn(_ textField: UITextField) -> Bool { return textInputDelegate?.textInputShouldReturn(textInput: self) ?? true } }
35.229508
141
0.67163
1d4801fbc762a60772da3dbf931a36e75a03503c
5,918
// // XMLMap.swift // XMLMapper // // Created by Giorgos Charitakis on 14/09/2017. // // import Foundation public enum XMLMappingType { case fromXML case toXML } public final class XMLMap { public internal(set) var XML: [String: Any] = [:] public let mappingType: XMLMappingType public internal(set) var isKeyPresent = false public internal(set) var currentValue: Any? public internal(set) var currentKey: String? var keyIsNested = false public internal(set) var nestedKeyDelimiter: String = "." private var isAttribute = false public let toObject: Bool // indicates whether the mapping is being applied to an existing object public init(mappingType: XMLMappingType, XML: [String: Any], toObject: Bool = false) { self.mappingType = mappingType self.XML = XML self.toObject = toObject } /// Sets the current mapper value and key. /// The Key paramater can be a period separated string (ex. "distance.value") to access sub objects. public subscript(key: String) -> XMLMap { // save key and value associated to it return self[key, delimiter: ".", ignoreNil: false] } public subscript(key: String, delimiter delimiter: String) -> XMLMap { let nested = key.contains(delimiter) return self[key, nested: nested, delimiter: delimiter, ignoreNil: false] } public subscript(key: String, nested nested: Bool) -> XMLMap { return self[key, nested: nested, delimiter: ".", ignoreNil: false] } public subscript(key: String, nested nested: Bool, delimiter delimiter: String) -> XMLMap { return self[key, nested: nested, delimiter: delimiter, ignoreNil: false] } public subscript(key: String, ignoreNil ignoreNil: Bool) -> XMLMap { return self[key, delimiter: ".", ignoreNil: ignoreNil] } public subscript(key: String, delimiter delimiter: String, ignoreNil ignoreNil: Bool) -> XMLMap { let nested = key.contains(delimiter) return self[key, nested: nested, delimiter: delimiter, ignoreNil: ignoreNil] } public subscript(key: String, nested nested: Bool, ignoreNil ignoreNil: Bool) -> XMLMap { return self[key, nested: nested, delimiter: ".", ignoreNil: ignoreNil] } public subscript(key: String, nested nested: Bool, delimiter delimiter: String, ignoreNil ignoreNil: Bool) -> XMLMap { // save key and value associated to it currentKey = key keyIsNested = nested nestedKeyDelimiter = delimiter if isAttribute { currentKey = "_\(key)" keyIsNested = false isAttribute = false } if mappingType == .fromXML { // check if a value exists for the current key // do this pre-check for performance reasons if let currentKey = currentKey, !keyIsNested { let object = XML[currentKey] let isNSNull = object is NSNull isKeyPresent = isNSNull ? true : object != nil currentValue = isNSNull ? nil : object } else { // break down the components of the key that are separated by . (isKeyPresent, currentValue) = valueFor(ArraySlice(key.components(separatedBy: delimiter)), dictionary: XML) } // update isKeyPresent if ignoreNil is true if ignoreNil && currentValue == nil { isKeyPresent = false } } return self } public func value<T>() -> T? { return currentValue as? T } public var attributes: XMLMap { isAttribute = true return self } public var innerText: XMLMap { return self[XMLParserConstant.Key.text] } } /// Fetch value from XML dictionary, loop through keyPathComponents until we reach the desired object private func valueFor(_ keyPathComponents: ArraySlice<String>, dictionary: [String: Any]) -> (Bool, Any?) { // Implement it as a tail recursive function. if keyPathComponents.isEmpty { return (false, nil) } if let keyPath = keyPathComponents.first { let object = dictionary[keyPath] if object is NSNull { return (true, nil) } else if keyPathComponents.count > 1, let dict = object as? [String: Any] { let tail = keyPathComponents.dropFirst() return valueFor(tail, dictionary: dict) } else if keyPathComponents.count > 1, let array = object as? [Any] { let tail = keyPathComponents.dropFirst() return valueFor(tail, array: array) } else { return (object != nil, object) } } return (false, nil) } /// Fetch value from XML Array, loop through keyPathComponents them until we reach the desired object private func valueFor(_ keyPathComponents: ArraySlice<String>, array: [Any]) -> (Bool, Any?) { // Implement it as a tail recursive function. if keyPathComponents.isEmpty { return (false, nil) } //Try to convert keypath to Int as index if let keyPath = keyPathComponents.first, let index = Int(keyPath) , index >= 0 && index < array.count { let object = array[index] if object is NSNull { return (true, nil) } else if keyPathComponents.count > 1, let array = object as? [Any] { let tail = keyPathComponents.dropFirst() return valueFor(tail, array: array) } else if keyPathComponents.count > 1, let dict = object as? [String: Any] { let tail = keyPathComponents.dropFirst() return valueFor(tail, dictionary: dict) } else { return (true, object) } } return (false, nil) }
35.22619
124
0.611017
fbcbd73cc1b7098fc61a91408a08316d74923e23
8,871
import XCTest @testable import GeoJSONKitTurf import GeoJSONKit class BoundingBoxTests: XCTestCase { func testAllPositive() { let coordinates = [ GeoJSON.Position(latitude: 1, longitude: 2), GeoJSON.Position(latitude: 2, longitude: 1) ] let bbox = GeoJSON.BoundingBox(positions: coordinates, allowSpanningAntimeridian: true) XCTAssertFalse(bbox.spansAntimeridian) XCTAssertEqual(bbox.southWesterlyLatitude, 1) XCTAssertEqual(bbox.southWesterlyLongitude,1) XCTAssertEqual(bbox.northEasterlyLatitude, 2) XCTAssertEqual(bbox.northEasterlyLongitude, 2) } func testAllNegative() { let coordinates = [ GeoJSON.Position(latitude: -1, longitude: -2), GeoJSON.Position(latitude: -2, longitude: -1) ] let bbox = GeoJSON.BoundingBox(positions: coordinates, allowSpanningAntimeridian: true) XCTAssertFalse(bbox.spansAntimeridian) XCTAssertEqual(bbox.southWesterlyLatitude, -2) XCTAssertEqual(bbox.southWesterlyLongitude, -2) XCTAssertEqual(bbox.northEasterlyLatitude, -1) XCTAssertEqual(bbox.northEasterlyLongitude, -1) } func testPositiveLatNegativeLon() { let coordinates = [ GeoJSON.Position(latitude: 1, longitude: -2), GeoJSON.Position(latitude: 2, longitude: -1) ] let bbox = GeoJSON.BoundingBox(positions: coordinates, allowSpanningAntimeridian: true) XCTAssertFalse(bbox.spansAntimeridian) XCTAssertEqual(bbox.southWesterlyLatitude, 1) XCTAssertEqual(bbox.southWesterlyLongitude,-2) XCTAssertEqual(bbox.northEasterlyLatitude, 2) XCTAssertEqual(bbox.northEasterlyLongitude, -1) } func testNegativeLatPositiveLon() { let coordinates = [ GeoJSON.Position(latitude: -1, longitude: 2), GeoJSON.Position(latitude: -2, longitude: 1) ] let bbox = GeoJSON.BoundingBox(positions: coordinates, allowSpanningAntimeridian: true) XCTAssertFalse(bbox.spansAntimeridian) XCTAssertEqual(bbox.southWesterlyLatitude, -2) XCTAssertEqual(bbox.southWesterlyLongitude, 1) XCTAssertEqual(bbox.northEasterlyLatitude, -1) XCTAssertEqual(bbox.northEasterlyLongitude, 2) } /// From GeoJSON Specs /// /// Consider a set of point Features within the Fiji archipelago, /// straddling the antimeridian between 16 degrees S and 20 degrees S. /// The southwest corner of the box containing these Features is at 20 /// degrees S and 177 degrees E, and the northwest corner is at 16 /// degrees S and 178 degrees W. The antimeridian-spanning GeoJSON /// bounding box for this FeatureCollection is /// /// `"bbox": [177.0, -20.0, -178.0, -16.0]` /// /// and covers 5 degrees of longitude. func testFijiBoundingBox() { let southWest = GeoJSON.Position(latitude: -20, longitude: 177) let northEast = GeoJSON.Position(latitude: -16, longitude: -178) let box = GeoJSON.BoundingBox(positions: [southWest, northEast], allowSpanningAntimeridian: true) XCTAssertTrue(box.spansAntimeridian) XCTAssertEqual(box.northEasterlyLatitude, northEast.latitude) XCTAssertEqual(box.northEasterlyLongitude, northEast.longitude) XCTAssertEqual(box.southWesterlyLatitude, southWest.latitude) XCTAssertEqual(box.southWesterlyLongitude, southWest.longitude) } func testAntimeridianCrossExtendingEast() throws { var box = try GeoJSON.BoundingBox(coordinates: [175, 9, 176, 10]) XCTAssertFalse(box.spansAntimeridian) box.append(.init(latitude: 8, longitude: -178), allowSpanningAntimeridian: true) XCTAssertTrue(box.spansAntimeridian) XCTAssertEqual(box.northEasterlyLatitude, 10) XCTAssertEqual(box.northEasterlyLongitude, -178) XCTAssertEqual(box.southWesterlyLatitude, 8) XCTAssertEqual(box.southWesterlyLongitude, 175) } func testAntimeridianCrossExtendingWest() throws { var box = try GeoJSON.BoundingBox(coordinates: [-178, 9, -177, 10]) XCTAssertFalse(box.spansAntimeridian) box.append(.init(latitude: 8, longitude: 179), allowSpanningAntimeridian: true) XCTAssertTrue(box.spansAntimeridian) XCTAssertEqual(box.northEasterlyLatitude, 10) XCTAssertEqual(box.northEasterlyLongitude, -177) XCTAssertEqual(box.southWesterlyLatitude, 8) XCTAssertEqual(box.southWesterlyLongitude, 179) } func testExtendingGiantEastAcrossAntimeridian() throws { var box = try GeoJSON.BoundingBox(coordinates: [-170, 9, 178, 10]) XCTAssertFalse(box.spansAntimeridian) box.append(.init(latitude: 8, longitude: -179), allowSpanningAntimeridian: true) XCTAssertTrue(box.spansAntimeridian) XCTAssertEqual(box.northEasterlyLatitude, 10) XCTAssertEqual(box.northEasterlyLongitude, -179) XCTAssertEqual(box.southWesterlyLatitude, 8) XCTAssertEqual(box.southWesterlyLongitude, -170) } func testExtendingGiantWestNotAcrossAntimeridian() throws { var box = try GeoJSON.BoundingBox(coordinates: [-170, 9, 178, 10]) XCTAssertFalse(box.spansAntimeridian) box.append(.init(latitude: 8, longitude: -171), allowSpanningAntimeridian: true) XCTAssertFalse(box.spansAntimeridian) XCTAssertEqual(box.northEasterlyLatitude, 10) XCTAssertEqual(box.northEasterlyLongitude, 178) XCTAssertEqual(box.southWesterlyLatitude, 8) XCTAssertEqual(box.southWesterlyLongitude, -171) } func testExtendingGiantWestAcrossAntimeridian() throws { var box = try GeoJSON.BoundingBox(coordinates: [-178, 9, 170, 10]) XCTAssertFalse(box.spansAntimeridian) box.append(.init(latitude: 8, longitude: 179), allowSpanningAntimeridian: true) XCTAssertTrue(box.spansAntimeridian) XCTAssertEqual(box.northEasterlyLatitude, 10) XCTAssertEqual(box.northEasterlyLongitude, 170) XCTAssertEqual(box.southWesterlyLatitude, 8) XCTAssertEqual(box.southWesterlyLongitude, 179) } func testExtendingGiantEastNotAcrossAntimeridian() throws { var box = try GeoJSON.BoundingBox(coordinates: [-178, 9, 170, 10]) XCTAssertFalse(box.spansAntimeridian) box.append(.init(latitude: 8, longitude: 171), allowSpanningAntimeridian: true) XCTAssertFalse(box.spansAntimeridian) XCTAssertEqual(box.northEasterlyLatitude, 10) XCTAssertEqual(box.northEasterlyLongitude, 171) XCTAssertEqual(box.southWesterlyLatitude, 8) XCTAssertEqual(box.southWesterlyLongitude, -178) } func testAntimeridianExtendSouthOnPositive() throws { var box = try GeoJSON.BoundingBox(coordinates: [178, 9, -178, 10]) XCTAssertTrue(box.spansAntimeridian) box.append(.init(latitude: 8, longitude: 179), allowSpanningAntimeridian: true) XCTAssertTrue(box.spansAntimeridian) XCTAssertEqual(box.northEasterlyLatitude, 10) XCTAssertEqual(box.northEasterlyLongitude, -178) XCTAssertEqual(box.southWesterlyLatitude, 8) XCTAssertEqual(box.southWesterlyLongitude, 178) } func testAntimeridianExtendSouthOnNegative() throws { var box = try GeoJSON.BoundingBox(coordinates: [178, 9, -178, 10]) XCTAssertTrue(box.spansAntimeridian) box.append(.init(latitude: 8, longitude: -179), allowSpanningAntimeridian: true) XCTAssertTrue(box.spansAntimeridian) XCTAssertEqual(box.northEasterlyLatitude, 10) XCTAssertEqual(box.northEasterlyLongitude, -178) XCTAssertEqual(box.southWesterlyLatitude, 8) XCTAssertEqual(box.southWesterlyLongitude, 178) } func testContains() { let coordinate = GeoJSON.Position(latitude: 1, longitude: 1) let coordinates = [ GeoJSON.Position(latitude: 0, longitude: 0), GeoJSON.Position(latitude: 2, longitude: 2) ] let bbox = GeoJSON.BoundingBox(positions: coordinates, allowSpanningAntimeridian: true) XCTAssertTrue(bbox.contains(coordinate)) } func testDoesNotContain() { let coordinate = GeoJSON.Position(latitude: 2, longitude: 3) let coordinates = [ GeoJSON.Position(latitude: 0, longitude: 0), GeoJSON.Position(latitude: 2, longitude: 2) ] let bbox = GeoJSON.BoundingBox(positions: coordinates, allowSpanningAntimeridian: true) XCTAssertFalse(bbox.contains(coordinate)) } func testContainsAtBoundary() { let coordinate = GeoJSON.Position(latitude: 0, longitude: 2) let coordinates = [ GeoJSON.Position(latitude: 0, longitude: 0), GeoJSON.Position(latitude: 2, longitude: 2) ] let bbox = GeoJSON.BoundingBox(positions: coordinates, allowSpanningAntimeridian: true) XCTAssertFalse(bbox.contains(coordinate, ignoreBoundary: true)) XCTAssertTrue(bbox.contains(coordinate, ignoreBoundary: false)) XCTAssertFalse(bbox.contains(coordinate)) } func testAntimeridianContains() throws { let box = try GeoJSON.BoundingBox(coordinates: [175, 8, -179, 10]) XCTAssertTrue(box.contains(.init(latitude: 9, longitude: 179))) XCTAssertTrue(box.contains(.init(latitude: 9, longitude: -179))) } }
40.140271
101
0.742983
1cf02a06f90d90da61f504d2a3e8b06e610ce920
131
// Dismiss your keyboard when you are // scrolling your tableView down interactively. tableView.keyboardDismissMode = .interactive
32.75
47
0.816794
db64ffd2aa52177c09b5bf2221eea094cefa1418
17,225
// // ParserTests.swift // FlyingMonkeyTests // // Created by Ahmad Alhashemi on 2017-08-20. // Copyright © 2017 Ahmad Alhashemi. All rights reserved. // import XCTest class ParserTests: XCTestCase { func testLetStatements() { let tests: [(input: String, expectedIdentifier: String, expectedValue: Any)] = [ ("let x = 5;", "x", 5), ("let y = true;", "y", true), ("let foobar = y;", "foobar", "y"), ] for tt in tests { let l = Lexer(tt.input) let p = Parser(l) let program = p.parseProgram() XCTAssertEqual(p.errors.count, 0) XCTAssertEqual(program.statements.count, 1) let stmt = program.statements[0] _testLetStatement(stmt, tt.expectedIdentifier) guard let val = (stmt as? LetStatement)?.value else { XCTFail() return } _testLiteralExpression(val, tt.expectedValue) } } func testReturnStatements() { let input = """ return 5; return 10; return 993322; """ let l = Lexer(input) let p = Parser(l) let program = p.parseProgram() XCTAssertEqual(p.errors.count, 0) XCTAssertEqual(program.statements.count, 3) for stmt in program.statements { guard let returnStmt = stmt as? ReturnStatement else { XCTFail() return } XCTAssertEqual(returnStmt.tokenLiteral, "return") } } func _testLetStatement(_ s: Statement, _ name: String) { XCTAssertEqual(s.tokenLiteral, "let") guard let letStmt = s as? LetStatement else { XCTFail() return } XCTAssertEqual(letStmt.name.value, name) XCTAssertEqual(letStmt.name.tokenLiteral, name) } func testIdentifierExpression() { let input = "foobar;" let l = Lexer(input) let p = Parser(l) let program = p.parseProgram() XCTAssertEqual(p.errors.count, 0) XCTAssertEqual(program.statements.count, 1) guard let stmt = program.statements[0] as? ExpressionStatement else { XCTFail() return } guard let ident = stmt.expression as? Identifier else { XCTFail() return } XCTAssertEqual(ident.value, "foobar") XCTAssertEqual(ident.tokenLiteral, "foobar") } func testIntegerLiteralExpression() { let input = "5;" let l = Lexer(input) let p = Parser(l) let program = p.parseProgram() XCTAssertEqual(p.errors.count, 0) XCTAssertEqual(program.statements.count, 1) guard let stmt = program.statements[0] as? ExpressionStatement else { XCTFail() return } guard let literal = stmt.expression as? IntegerLiteral else { XCTFail() return } XCTAssertEqual(literal.value, 5) XCTAssertEqual(literal.tokenLiteral, "5") } func _testIntegerLiteral(_ il: Expression, _ value: Int64) { guard let int = il as? IntegerLiteral else { XCTFail() return } XCTAssertEqual(int.value, value) } func _testBooleanLiteral(_ bl: Expression, _ value: Bool) { guard let bool = bl as? BooleanLiteral else { XCTFail() return } XCTAssertEqual(bool.value, value) } func testParsingPrefixExpressions() { let tests: [(input: String, op: String, integerValue: Int64)] = [ ("!5;", "!", 5), ("-15;", "-", 15), ] for tt in tests { let l = Lexer(tt.input) let p = Parser(l) let program = p.parseProgram() XCTAssertEqual(p.errors.count, 0) XCTAssertEqual(program.statements.count, 1) guard let stmt = program.statements[0] as? ExpressionStatement else { XCTFail() return } guard let exp = stmt.expression as? PrefixExpression else { XCTFail() return } guard let right = exp.right else { XCTFail() return } _testIntegerLiteral(right, tt.integerValue) } } func testParsingInfixExpressions() { let tests: [(input: String, leftValue: Int64, op: String, rightValue: Int64)] = [ ("5 + 5;", 5, "+", 5), ("5 - 5;", 5, "-", 5), ("5 * 5;", 5, "*", 5), ("5 / 5;", 5, "/", 5), ("5 > 5;", 5, ">", 5), ("5 < 5;", 5, "<", 5), ("5 == 5;", 5, "==", 5), ("5 != 5;", 5, "!=", 5), ] for tt in tests { let l = Lexer(tt.input) let p = Parser(l) let program = p.parseProgram() XCTAssertEqual(p.errors.count, 0) XCTAssertEqual(program.statements.count, 1) guard let stmt = program.statements[0] as? ExpressionStatement else { XCTFail() return } guard let exp = stmt.expression as? InfixExpression else { XCTFail() return } guard let right = exp.right else { XCTFail() return } _testIntegerLiteral(exp.left, tt.leftValue) _testIntegerLiteral(right, tt.rightValue) } } func testOperatorPrecedenceParsing() { let tests: [(input: String, expected: String)] = [ ("-a * b", "((-a) * b)"), ("!-a", "(!(-a))"), ("a + b + c", "((a + b) + c)"), ("a + b - c", "((a + b) - c)"), ("a * b * c", "((a * b) * c)"), ("a * b / c", "((a * b) / c)"), ("a + b / c", "(a + (b / c))"), ("a + b * c + d / e - f", "(((a + (b * c)) + (d / e)) - f)"), ("3 + 4; -5 * 5", "(3 + 4)((-5) * 5)"), ("5 > 4 == 3 < 4", "((5 > 4) == (3 < 4))"), ("5 < 4 != 3 > 4", "((5 < 4) != (3 > 4))"), ("3 + 4 * 5 == 3 * 1 + 4 * 5", "((3 + (4 * 5)) == ((3 * 1) + (4 * 5)))"), ("true", "true"), ("false", "false"), ("3 > 5 == false", "((3 > 5) == false)"), ("3 < 5 == true", "((3 < 5) == true)"), ("1 + (2 + 3) + 4", "((1 + (2 + 3)) + 4)"), ("(5 + 5) * 2", "((5 + 5) * 2)"), ("2 / (5 + 5)", "(2 / (5 + 5))"), ("(5 + 5) * 2 * (5 + 5)", "(((5 + 5) * 2) * (5 + 5))"), ("-(5 + 5)", "(-(5 + 5))"), ("!(true == true)", "(!(true == true))"), ("a + add(b * c) + d", "((a + add((b * c))) + d)"), ("add(a, b, 1, 2 * 3, 4 + 5, add(6, 7 * 8))", "add(a, b, 1, (2 * 3), (4 + 5), add(6, (7 * 8)))"), ("add(a + b + c * d / f + g)", "add((((a + b) + ((c * d) / f)) + g))"), ] for tt in tests { let l = Lexer(tt.input) let p = Parser(l) let program = p.parseProgram() XCTAssertEqual(p.errors.count, 0) XCTAssertEqual(program.string, tt.expected) } } func testBooleanExpression() { let tests: [(input: String, expectedBoolean: Bool)] = [ ("true;", true), ("false;", false) ] for tt in tests { let l = Lexer(tt.input) let p = Parser(l) let program = p.parseProgram() XCTAssertEqual(p.errors.count, 0) XCTAssertEqual(program.statements.count, 1) guard let stmt = program.statements[0] as? ExpressionStatement else { XCTFail() return } guard let boolean = stmt.expression as? BooleanLiteral else { XCTFail() return } XCTAssertEqual(boolean.value, tt.expectedBoolean) } } func testIfExpression() { let input = "if (x < y) { x }" let l = Lexer(input) let p = Parser(l) let program = p.parseProgram() XCTAssertEqual(p.errors.count, 0) XCTAssertEqual(program.statements.count, 1) guard let stmt = program.statements[0] as? ExpressionStatement else { XCTFail() return } guard let exp = stmt.expression as? IfExpression else { XCTFail() return } guard let condition = exp.condition else { XCTFail() return } _testInfixExpression(condition, "x", "<", "y") XCTAssertEqual(exp.consequence.statements.count, 1) guard let consequence = exp.consequence.statements[0] as? ExpressionStatement else { XCTFail() return } guard let consequenceExpression = consequence.expression else { XCTFail() return } _testIdentifier(consequenceExpression, "x") XCTAssertNil(exp.alternative) } func testIfElseExpression() { let input = "if (x < y) { x } else { y }" let l = Lexer(input) let p = Parser(l) let program = p.parseProgram() XCTAssertEqual(p.errors.count, 0) XCTAssertEqual(program.statements.count, 1) guard let stmt = program.statements[0] as? ExpressionStatement else { XCTFail() return } guard let exp = stmt.expression as? IfExpression else { XCTFail() return } guard let condition = exp.condition else { XCTFail() return } _testInfixExpression(condition, "x", "<", "y") XCTAssertEqual(exp.consequence.statements.count, 1) guard let consequence = exp.consequence.statements[0] as? ExpressionStatement else { XCTFail() return } guard let consequenceExpression = consequence.expression else { XCTFail() return } _testIdentifier(consequenceExpression, "x") XCTAssertEqual(exp.alternative?.statements.count ?? 0, 1) guard let alternative = exp.alternative?.statements[0] as? ExpressionStatement else { XCTFail() return } guard let alternativeExpression = alternative.expression else { XCTFail() return } _testIdentifier(alternativeExpression, "y") } func testFunctionLiteralParsing() { let input = "fn(x, y) { x + y; }" let l = Lexer(input) let p = Parser(l) let program = p.parseProgram() XCTAssertEqual(p.errors.count, 0) XCTAssertEqual(program.statements.count, 1) guard let stmt = program.statements[0] as? ExpressionStatement else { XCTFail() return } guard let function = stmt.expression as? FunctionLiteral else { XCTFail() return } guard let parameters = function.parameters else { XCTFail() return } XCTAssertEqual(parameters.count, 2) _testLiteralExpression(parameters[0], "x") _testLiteralExpression(parameters[1], "y") XCTAssertEqual(function.body.statements.count, 1) guard let bodyStmt = function.body.statements[0] as? ExpressionStatement else { XCTFail() return } guard let bodyStmtExpression = bodyStmt.expression else { XCTFail() return } _testInfixExpression(bodyStmtExpression, "x", "+", "y") } func testFunctionParameterParsing() { let tests: [(input: String, expectedParams: [String])] = [ ("fn() {};", []), ("fn(x) {};", ["x"]), ("fn(x, y, z) {};", ["x", "y", "z"]) ] for tt in tests { let l = Lexer(tt.input) let p = Parser(l) let program = p.parseProgram() XCTAssertEqual(p.errors.count, 0) guard let stmt = program.statements[0] as? ExpressionStatement else { XCTFail() return } guard let function = stmt.expression as? FunctionLiteral else { XCTFail() return } guard let parameters = function.parameters else { XCTFail() return } for (idx, ident) in tt.expectedParams.enumerated() { _testIdentifier(parameters[idx], ident) } } } func testCallExpressionParsing() { let input = "add(1, 2 * 3, 4 + 5);" let l = Lexer(input) let p = Parser(l) let program = p.parseProgram() XCTAssertEqual(p.errors.count, 0) XCTAssertEqual(program.statements.count, 1) guard let stmt = program.statements[0] as? ExpressionStatement else { XCTFail() return } guard let exp = stmt.expression as? CallExpression else { XCTFail() return } _testIdentifier(exp.function, "add") guard let arguments = exp.arguments else { XCTFail() return } XCTAssertEqual(arguments.count, 3) _testLiteralExpression(arguments[0], 1) _testInfixExpression(arguments[1], 2, "*", 3) _testInfixExpression(arguments[2], 4, "+", 5) } func testCallExpressionParameterParsing() { let tests: [(input: String, expectedIdent: String, expectedArgs: [String])] = [ ("add();", "add", []), ("add(1);", "add", ["1"]), ("add(1, 2 * 3, 4 + 5);", "add", ["1", "(2 * 3)", "(4 + 5)"]) ] for tt in tests { let l = Lexer(tt.input) let p = Parser(l) let program = p.parseProgram() XCTAssertEqual(p.errors.count, 0) guard let stmt = program.statements[0] as? ExpressionStatement else { XCTFail() return } guard let exp = stmt.expression as? CallExpression else { XCTFail() return } _testIdentifier(exp.function, tt.expectedIdent) guard let arguments = exp.arguments else { XCTFail() return } XCTAssertEqual(arguments.map { $0.string }, tt.expectedArgs) } } func _testIdentifier(_ exp: Expression, _ value: String) { guard let ident = exp as? Identifier else { XCTFail() return } XCTAssertEqual(ident.value, value) XCTAssertEqual(ident.tokenLiteral, value) } func _testLiteralExpression(_ exp: Expression, _ expected: Any) { switch expected { case let int as Int: _testIntegerLiteral(exp, Int64(int)) case let int as Int64: _testIntegerLiteral(exp, int) case let string as String: _testIdentifier(exp, string) case let bool as Bool: _testBooleanLiteral(exp, bool) default: XCTFail() } } func _testInfixExpression(_ exp: Expression, _ left: Any, _ op: String, _ right: Any) { guard let opExp = exp as? InfixExpression else { XCTFail() return } _testLiteralExpression(opExp.left, left) XCTAssertEqual(opExp.op, op) guard let expRight = opExp.right else { XCTFail() return } _testLiteralExpression(expRight, right) } }
29.145516
109
0.453062
908472d0579d755dba199cf470f8766d9e52a333
4,291
// // AssetPicker.swift // ComponentKit // // Created by William Lee on 23/12/17. // Copyright © 2018 William Lee. All rights reserved. // import UIKit import Photos import ApplicationKit import MobileCoreServices public class AssetPicker: NSObject { private static let shared = AssetPicker() private var isOrigin: Bool = false private var completeHandle: CompleteHandle? public override init() { super.init() } } // MARK: - Public public extension AssetPicker { enum Source { case camera case photoLibrary } typealias CompleteHandle = ([PHAsset], [UIImage]) -> Void class func video(source: Source, isOrigin: Bool = true, limited count: Int = 1, completion handle: @escaping CompleteHandle) { switch source { case .camera: guard UIImagePickerController.isSourceTypeAvailable(.camera) else { return } shared.completeHandle = handle shared.isOrigin = isOrigin let imagePicker = UIImagePickerController() imagePicker.modalPresentationStyle = .fullScreen imagePicker.delegate = shared imagePicker.sourceType = .camera imagePicker.mediaTypes = [kUTTypeVideo as String] Presenter.present(imagePicker) case .photoLibrary: AssetAlbumViewController.select(limit: count, content: .video, completion: handle) } } class func image(source: Source, isOrigin: Bool = true, limited count: Int = 1, completion handle: @escaping CompleteHandle) { switch source { case .camera: guard UIImagePickerController.isSourceTypeAvailable(.camera) else { return } shared.completeHandle = handle shared.isOrigin = isOrigin let imagePicker = UIImagePickerController() imagePicker.modalPresentationStyle = .fullScreen imagePicker.delegate = shared imagePicker.sourceType = .camera imagePicker.mediaTypes = [kUTTypeImage as String] Presenter.present(imagePicker) case .photoLibrary: AssetAlbumViewController.select(limit: count, content: .image, completion: handle) } } } // MARK: - UIImagePickerControllerDelegate, UINavigationControllerDelegate extension AssetPicker: UIImagePickerControllerDelegate, UINavigationControllerDelegate { public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { var assets: [PHAsset] = [] var images: [UIImage] = [] defer { picker.dismiss(animated: true, completion: { self.completeHandle?(assets, images) self.completeHandle = nil }) } if #available(iOS 11.0, *), let phAsset = info[.phAsset] as? PHAsset { assets.append(phAsset) } if picker.mediaTypes.contains(kUTTypeVideo as String) { // Nothing } if picker.mediaTypes.contains(kUTTypeImage as String), let originImage = info[.originalImage] as? UIImage { if isOrigin == true { images.append(originImage) } else if let image = draw(originImage) { images.append(image) } else { } } } public func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { defer { picker.dismiss(animated: true) } // 因为是全局的,用完一次就可以清除回调 completeHandle = nil } } // MARK: - Private private extension AssetPicker { func draw(_ image: UIImage) -> UIImage? { var drawedSize = UIScreen.main.bounds.size let imageSize = image.size let scale: CGFloat = drawedSize.width / imageSize.width drawedSize = CGSize(width: Int(imageSize.width * scale), height: Int(imageSize.height * scale)) let tailoredRect = CGRect(origin: .zero, size: drawedSize) UIGraphicsBeginImageContextWithOptions(drawedSize, true, 0) image.draw(in: tailoredRect) let tailoredImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return tailoredImage } }
25.694611
114
0.639012
d9f9a3bcc5e18a6093960a71ba2e2447b7fe9b32
685
// // PersonCell.swift // FirstDemo // // Created by WY on 15/11/25. // Copyright © 2015年 WY. All rights reserved. // import UIKit class PersonCell: UITableViewCell { @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var ageLabel: UILabel! var person : Person { set { // self.nameLabel.text = person.name self.nameLabel.text = newValue.name // self.ageLabel.text = person.age self.ageLabel.text = newValue.age } get { self.person.name = self.nameLabel.text self.person.age = self.ageLabel.text! return self.person } } }
19.571429
50
0.559124
e071da52afcd080646f6e8f2455d8de8a07baaed
14,036
// // SwiftyMessage.swift // SwiftyMessages // // Created by Mohammed Imran on 10/03/17. // Copyright (c) 2017# Imran. All rights reserved. // import UIKit public enum SwiftyMessageType { case success case error case warning case info } public enum SwiftyMessagePosition { case top case bottom } public enum SwiftyMessageAnimation { case slide case fade } public enum SwiftyMessageOption { case animation(SwiftyMessageAnimation) case animationDuration(TimeInterval) case autoHide(Bool) case autoHideDelay(Double) // Second case height(Double) case hideOnTap(Bool) case position(SwiftyMessagePosition) case textColor(UIColor) case textPadding(Double) case textAlignment(NSTextAlignment) case textNumberOfLines(Int) case customBgColor(UIColor) case customFont(UIFont) } extension UIViewController { public func showMessage(_ text: String, type: SwiftyMessageType, options: [SwiftyMessageOption]? = nil) { SwiftyMessage.showMessageAddedTo(text, type: type, options: options, inView: view, inViewController: self) } public func hideMessage() { view.hideMessage() } } extension UIView { public func showMessage(_ text: String, type: SwiftyMessageType, options: [SwiftyMessageOption]? = nil) { SwiftyMessage.showMessageAddedTo(text, type: type, options: options, inView: self, inViewController: nil) } public func hideMessage() { installedMessage?.hide() } } public class SwiftyMessage { public static var font : UIFont = UIFont.systemFont(ofSize: 14) public static var successBackgroundColor : UIColor = UIColor(red: 76.0/255, green: 175.0/255, blue: 80.0/255, alpha: 0.98) public static var warningBackgroundColor : UIColor = UIColor(red: 255.0/255, green: 152.0/255, blue: 0.0/255, alpha: 0.98) public static var errorBackgroundColor : UIColor = UIColor(red: 216.0/255, green: 67.0/255, blue: 21.0/255, alpha: 0.98) public static var infoBackgroundColor : UIColor = UIColor(red: 96.0/255, green: 125.0/255, blue: 139.0/255, alpha: 0.98) class func showMessageAddedTo(_ text: String, type: SwiftyMessageType, options: [SwiftyMessageOption]?, inView: UIView, inViewController: UIViewController?) { if inView.installedMessage != nil && inView.uninstallMessage == nil { inView.hideMessage() } if inView.installedMessage == nil { SwiftyMessage(text: text, type: type, options: options, inView: inView, inViewController: inViewController).show() } } func show() { if inView?.installedMessage != nil { return } inView?.installedMessage = self inView?.addSubview(messageView) updateFrames() if animation == .fade { messageView.alpha = 0 UIView.animate(withDuration: animationDuration, animations: { self.messageView.alpha = 1 }) } else if animation == .slide && position == .top { messageView.transform = CGAffineTransform(translationX: 0, y: -messageHeight) UIView.animate(withDuration: animationDuration, animations: { self.messageView.transform = CGAffineTransform(translationX: 0, y: 0) }) } else if animation == .slide && position == .bottom { inView?.endEditing(true) messageView.transform = CGAffineTransform(translationX: 0, y: height) UIView.animate(withDuration: animationDuration, animations: { self.messageView.transform = CGAffineTransform(translationX: 0, y: 0) }) } if autoHide { GS_GCDAfter(autoHideDelay) { self.hide() } } } func hide() { if inView?.installedMessage !== self || inView?.uninstallMessage != nil { return } inView?.uninstallMessage = self inView?.installedMessage = nil if animation == .fade { UIView.animate(withDuration: self.animationDuration, animations: { [weak self] in if let this = self { this.messageView.alpha = 0 } }, completion: { [weak self] finished in self?.removeFromSuperview() } ) } else if animation == .slide && position == .top { UIView.animate(withDuration: self.animationDuration, animations: { [weak self] in if let this = self { this.messageView.transform = CGAffineTransform(translationX: 0, y: -this.messageHeight) } }, completion: { [weak self] finished in self?.removeFromSuperview() } ) } else if animation == .slide && position == .bottom { UIView.animate(withDuration: self.animationDuration, animations: { [weak self] in if let this = self { this.messageView.transform = CGAffineTransform(translationX: 0, y: this.height) } }, completion: { [weak self] finished in self?.removeFromSuperview() } ) } } fileprivate(set) weak var inView: UIView! fileprivate(set) weak var inViewController: UIViewController? fileprivate(set) var messageView: UIView! fileprivate(set) var messageText: UILabel! fileprivate(set) var animation: SwiftyMessageAnimation = .slide fileprivate(set) var animationDuration: TimeInterval = 0.3 fileprivate(set) var autoHide: Bool = true fileprivate(set) var autoHideDelay: Double = 3 fileprivate(set) var backgroundColor: UIColor! fileprivate(set) var height: CGFloat = 44 fileprivate(set) var hideOnTap: Bool = true fileprivate(set) var offsetY: CGFloat = 0 fileprivate(set) var position: SwiftyMessagePosition = .top fileprivate(set) var textColor: UIColor = UIColor.white fileprivate(set) var textFont: UIFont? fileprivate(set) var textPadding: CGFloat = 30 fileprivate(set) var textAlignment: NSTextAlignment = .center fileprivate(set) var textNumberOfLines: Int = 1 fileprivate(set) var y: CGFloat = 0 fileprivate var messageHeight: CGFloat { return offsetY + height } init(text: String, type: SwiftyMessageType, options: [SwiftyMessageOption]?, inView: UIView, inViewController: UIViewController?) { var inView = inView switch type { case .success: backgroundColor = SwiftyMessage.successBackgroundColor case .warning: backgroundColor = SwiftyMessage.warningBackgroundColor case .error: backgroundColor = SwiftyMessage.errorBackgroundColor case .info: backgroundColor = SwiftyMessage.infoBackgroundColor } if let options = options { for option in options { switch (option) { case let .animation(value): animation = value case let .animationDuration(value): animationDuration = value case let .autoHide(value): autoHide = value case let .autoHideDelay(value): autoHideDelay = value case let .height(value): height = CGFloat(value) case let .hideOnTap(value): hideOnTap = value case let .position(value): position = value case let .textColor(value): textColor = value case let .textPadding(value): textPadding = CGFloat(value) case let .textAlignment(value): textAlignment = value case let .textNumberOfLines(value): textNumberOfLines = value case let .customBgColor(value): backgroundColor = value case let .customFont(value): textFont = value } } } if inViewController is UITableViewController { if let lastWindow = UIApplication.shared.windows.last { inView = lastWindow as UIView } } messageView = UIView() messageView.backgroundColor = backgroundColor messageText = UILabel() messageText.text = text messageText.font = textFont ?? SwiftyMessage.font messageText.textColor = textColor messageText.textAlignment = textAlignment messageText.numberOfLines = textNumberOfLines messageView.addSubview(messageText) if textNumberOfLines == 0 { height = max(text.boundingRect(with: CGSize(width: inView.frame.size.width - textPadding * 2, height: .greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: textFont ?? SwiftyMessage.font], context: nil).height + (height - " ".boundingRect(with: CGSize(width: inView.frame.size.width, height: .greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: textFont ?? SwiftyMessage.font], context: nil).height), height) } NotificationCenter.default.addObserver(self, selector: #selector(updateFrames), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil) if position == .bottom { NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil) } if hideOnTap { messageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))) } self.inView = inView self.inViewController = inViewController } deinit { NotificationCenter.default.removeObserver(self) } @objc fileprivate func handleTap(_ tapGesture: UITapGestureRecognizer) { hide() } @objc fileprivate func updateFrames() { guard let inView = inView else { return } y = 0 offsetY = 0 switch position { case .top: if let viewController = inViewController { if viewController.edgesForExtendedLayout == [] { offsetY = 0 } else { let navigation = viewController.navigationController ?? (viewController as? UINavigationController) let navigationBarHidden = (navigation?.isNavigationBarHidden ?? true) let navigationBarTranslucent = (navigation?.navigationBar.isTranslucent ?? false) let navigationBarHeight = (navigation?.navigationBar.frame.size.height ?? 44) let statusBarHidden = UIApplication.shared.isStatusBarHidden if !navigationBarHidden && navigationBarTranslucent && !statusBarHidden { offsetY += 20 } if !navigationBarHidden && navigationBarTranslucent { offsetY += navigationBarHeight } if (navigationBarHidden && !statusBarHidden) { offsetY += 20 } } } y = max(0 - inView.frame.origin.y, 0) case .bottom: y = inView.bounds.size.height - height } messageView.frame = CGRect(x: 0, y: y, width: inView.bounds.size.width, height: messageHeight) messageText.frame = CGRect(x: textPadding, y: offsetY, width: messageView.bounds.size.width - textPadding * 2, height: height) } @objc fileprivate func keyboardWillShow(notification: NSNotification) { // RESET THE FRAMES FIRST updateFrames() // Handle Keyboard Updated Frame guard let inView = self.inView else { return } if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue { if inView.frame.origin.y + inView.frame.height > keyboardSize.origin.y { var diff = inView.frame.origin.y + inView.frame.height - keyboardSize.origin.y if let navigation = inView.window?.rootViewController as? UINavigationController { let navigationBarHidden = navigation.isNavigationBarHidden let navigationBarTranslucent = navigation.navigationBar.isTranslucent let navigationBarHeight = navigation.navigationBar.frame.size.height let statusBarHidden = UIApplication.shared.isStatusBarHidden if !navigationBarTranslucent && !navigationBarHidden && (inViewController == nil) { diff += navigationBarHeight if !statusBarHidden { diff += 20 } } } messageView.frame.origin.y -= diff } } } @objc fileprivate func keyboardWillHide(notification: NSNotification) { updateFrames() } fileprivate func removeFromSuperview() { messageView.removeFromSuperview() inView?.uninstallMessage = nil } } extension UIView { fileprivate var installedMessage: SwiftyMessage? { get { return objc_getAssociatedObject(self, &installedMessageKey) as? SwiftyMessage } set { objc_setAssociatedObject(self, &installedMessageKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } fileprivate var uninstallMessage: SwiftyMessage? { get { return objc_getAssociatedObject(self, &uninstallMessageKey) as? SwiftyMessage } set { objc_setAssociatedObject(self, &uninstallMessageKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } private var installedMessageKey = "" private var uninstallMessageKey = "" private func GS_GCDAfter(_ delay:Double, closure:@escaping ()->()) { DispatchQueue.main.asyncAfter( deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure) }
42.923547
503
0.636079
161bd2d8b437e92ad6ad49c6c0b1bab42d30752f
12,464
// // BaseAVPlayerViewController.swift // TopsProSys // 基础播放器 // Created by 李桂盛 on 2019/12/6. // Copyright © 2019 com.topscommmac01. All rights reserved. // import UIKit import AVFoundation //MARK:- AVPlayer支持的视频格式 public enum VideoType: String { case WMV case AVI case MKV case RMVB case RM case XVID case MP4 case ThreeGP = "3GP" case MPG } open class BaseAVPlayerViewController: BaseUIViewViewController { open var url: String = "" open var type:VideoType = .MP4 private var player: AVPlayer = AVPlayer.init() private var playItem: AVPlayerItem! private var playerLayer:AVPlayerLayer! //MARK:- 高度比例(只对竖屏状态下有效) private var orientation = UIInterfaceOrientation.portrait open var heightRadio: CGFloat = 1.0 private var link: CADisplayLink? //播放器下方控件 private var containner: UIView = UIView() private var timeLabel: UILabel = UILabel() private var playBtn: UIButton = UIButton() private var slider: UISlider = UISlider() private var sliding: Bool = false private var isPlaying: Bool = true private var progress: UIProgressView = UIProgressView() fileprivate let path = Bundle(for: ProgressWebViewController.self).resourcePath! + "/topsiOSPro.bundle" lazy var rotateBarButtonItem: UIBarButtonItem = { let path = Bundle(for: ProgressWebViewController.self).resourcePath! + "/topsiOSPro.bundle" let bundle = Bundle(path: path)! let image = UIImage(named: "screen", in: bundle, compatibleWith: nil)! return UIBarButtonItem(image: image, style: .plain, target: self, action: #selector(rotateDidClick(sender:))) }() open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) checkVideoType() self.navigationItem.rightBarButtonItem = rotateBarButtonItem } override open func viewDidLoad() { super.viewDidLoad() } open func checkVideoType() { if self.type == .WMV || self.type == .AVI || self.type == .MKV || self.type == .RMVB || self.type == .RM || self.type == .XVID || self.type == .MP4 || self.type == .ThreeGP || self.type == .MPG { if url != "" { self.downloadVideo() } } else { self.show(text: "暂不支持该格式") DispatchQueue.main.asyncAfter(deadline: .now() + 1) { self.navigationController?.popViewController(animated: true) } } } //MARK:-下载 返回播放路径 open func downloadVideo() { self.downloadVideo(url: url) { (path) in ///Users/liguicheng/Library/Developer/CoreSimulator/Devices/513E70F9-529C-47A4-A293-174E51044741/data/Containers/Data/Application/58638383-8E65-4B00-B181-FDEDA96833AD/Documents/aaaa (1).mp4 self.playItem = AVPlayerItem.init(url: URL.init(fileURLWithPath: path)) // 监听缓冲进度改变 self.playItem.addObserver(self, forKeyPath: "loadedTimeRanges", options: NSKeyValueObservingOptions.new, context: nil) // 监听状态改变 self.playItem.addObserver(self, forKeyPath: "status", options: NSKeyValueObservingOptions.new, context: nil) self.link = CADisplayLink.init(target: self, selector: #selector(self.updateTime)) self.link?.add(to: RunLoop.main, forMode: RunLoop.Mode.default) self.setupUI() } } //MARK: -设置播放/暂停 播放进度 时间 等控件 private func setupUI() { self.player = AVPlayer(playerItem: self.playItem) self.playerLayer = AVPlayerLayer(player: self.player) self.playerLayer.videoGravity = .resizeAspect self.baseView.layer.addSublayer(self.playerLayer) //横竖屏 var frame = CGRect.zero if self.orientation == .portrait { frame = CGRect.init(x: self.baseView.X, y: 0, width: self.baseView.W, height: self.baseView.H * heightRadio) playerLayer.backgroundColor = UIColor.black.cgColor self.playerLayer.frame = frame } else { self.playerLayer.frame = self.baseView.bounds } let bundle = Bundle(path: path)! self.baseView.addSubview(containner) self.containner.backgroundColor = .clear self.containner.frame = CGRect.init(x: frame.origin.x, y: playerLayer.frame.size.height-40, width: playerLayer.frame.size.width, height: CGFloat(ConstantsHelp.labelHeight)) self.playBtn = UIButton.init() self.containner.addSubview(playBtn) playBtn.snp.makeConstraints { (make) in make.left.equalToSuperview().offset(ConstantsHelp.normalPadding * 2) make.height.equalToSuperview() make.width.equalTo(35) } playBtn.setImage(UIImage(named: "pause", in: bundle, compatibleWith: nil), for: .normal) playBtn.addTarget(self, action: #selector(playBtnClick(_ :)), for: .touchUpInside) self.containner.addSubview(timeLabel) self.timeLabel.textColor = .white self.timeLabel.font = .systemFont(ofSize: 12) self.timeLabel.snp.makeConstraints { (make) in make.right.equalTo(containner.snp.right).offset(ConstantsHelp.rightMargin * 2) make.height.equalToSuperview() } self.containner.addSubview(progress) progress.backgroundColor = .lightGray progress.tintColor = .red progress.progress = 0.0 progress.snp.makeConstraints { (make) in make.left.equalTo(playBtn.snp.right).offset(ConstantsHelp.normalPadding * 2) make.right.equalTo(timeLabel.snp.left).offset(ConstantsHelp.rightMargin * 2) make.centerY.equalTo(containner.snp.centerY) } self.containner.addSubview(slider) let image = UIImage(named: "Artboard", in: bundle, compatibleWith: nil)! slider.setThumbImage(image, for: .normal) slider.maximumValue = 1.0 slider.minimumValue = 0.0 slider.value = 0.0 // 从最大值滑向最小值时杆的颜色 slider.maximumTrackTintColor = UIColor.clear // 从最小值滑向最大值时杆的颜色 slider.minimumTrackTintColor = UIColor.white // 按下的时候 slider.addTarget(self, action: #selector(sliderTouchDown(_ :)), for: .touchDown) // 弹起的时候 slider.addTarget(self, action: #selector(sliderTouchUpOut(_ :)), for: .touchUpOutside) slider.addTarget(self, action: #selector(sliderTouchUpOut(_ :)), for: .touchUpInside) slider.addTarget(self, action: #selector(sliderTouchUpOut(_ :)), for: .touchCancel) slider.snp.makeConstraints { (make) in make.left.equalTo(progress.snp.left) make.right.equalTo(timeLabel.snp.left).offset(ConstantsHelp.rightMargin) make.centerY.equalTo(progress.snp.centerY) make.height.equalTo(2) } } @objc func playBtnClick(_ sender:UIButton) { self.isPlaying = !isPlaying let bundle = Bundle(path: path)! if #available(iOS 13.0, *) { self.playBtn.setImage(isPlaying ? UIImage.init(named: "pause", in: bundle, with: nil) : UIImage.init(named: "play", in: bundle, with: nil) , for: .normal) self.isPlaying ? self.player.play() : self.player.pause() } else { if isPlaying { let image = UIImage(named: "pause", in: bundle, compatibleWith: nil)! self.playBtn.setImage(image, for: .normal) self.player.play() } else { let image = UIImage(named: "play", in: bundle, compatibleWith: nil)! self.playBtn.setImage(image, for: .normal) self.player.pause() } } } //MARK:-需要在Appdelegate的func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?)返回支持的方向 @objc open func rotateDidClick(sender: AnyObject) { //转屏 switch self.orientation { case .portrait: UIDevice.current.setValue(UIInterfaceOrientation.landscapeRight.rawValue, forKey: "orientation") self.orientation = .landscapeRight case .landscapeRight: UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation") self.orientation = .portrait default: break; } self.updateFrame() } private func updateFrame() { var frame = CGRect.zero if self.orientation == .portrait { frame = CGRect.init(x: self.baseView.X, y: 0, width: self.baseView.W, height: self.baseView.H * heightRadio) playerLayer.backgroundColor = UIColor.black.cgColor self.playerLayer.frame = frame } else { frame = self.baseView.bounds self.playerLayer.frame = frame } self.containner.frame = CGRect.init(x: frame.origin.x, y: playerLayer.frame.size.height-40, width: playerLayer.frame.size.width, height: CGFloat(ConstantsHelp.labelHeight)) } @objc func updateTime() { let currentTime = CMTimeGetSeconds(self.player.currentTime()) let totalTime = TimeInterval(playItem.duration.value) / TimeInterval(playItem.duration.timescale) let timeStr = "\(formatPlayTime(secounds: currentTime))/\(formatPlayTime(secounds: totalTime))" self.timeLabel.text = timeStr if !self.sliding { self.slider.value = Float(currentTime) / Float(totalTime) } } @objc func sliderTouchDown(_ slider:UISlider){ self.sliding = true } @objc func sliderTouchUpOut(_ slider:UISlider){ if self.player.status == .readyToPlay { let duration = slider.value * Float(CMTimeGetSeconds(self.player.currentItem!.duration)) let seekTime = CMTimeMake(value: Int64(duration), timescale: 1) self.player.seek(to: seekTime) { _ in self.sliding = false } } } open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard let playerItem = object as? AVPlayerItem else { return } if keyPath == "loadedTimeRanges"{ // 通过监听AVPlayerItem的"loadedTimeRanges",可以实时知道当前视频的进度缓冲 let loadedTime = avalableDurationWithplayerItem() let totalTime = CMTimeGetSeconds(playerItem.duration) let percent = loadedTime/totalTime self.progress.progress = Float(percent) }else if keyPath == "status"{ // AVPlayerItemStatusUnknown,AVPlayerItemStatusReadyToPlay, AVPlayerItemStatusFailed。只有当status为AVPlayerItemStatusReadyToPlay是调用 AVPlayer的play方法视频才能播放。 if playerItem.status == AVPlayerItem.Status.readyToPlay{ // 只有在这个状态下才能播放 self.player.play() }else{ print("加载异常") } } } private func avalableDurationWithplayerItem()->TimeInterval{ guard let loadedTimeRanges = player.currentItem?.loadedTimeRanges,let first = loadedTimeRanges.first else {fatalError()} let timeRange = first.timeRangeValue let startSeconds = CMTimeGetSeconds(timeRange.start) let durationSecound = CMTimeGetSeconds(timeRange.duration) let result = startSeconds + durationSecound return result } private func formatPlayTime(secounds:TimeInterval)->String{ if secounds.isNaN{ return "00:00" } let Min = Int(secounds / 60) let Sec = Int(secounds.truncatingRemainder(dividingBy: 60)) return String(format: "%02d:%02d", Min, Sec) } } //MARK:-子类重写父类关于旋转的方法 extension BaseAVPlayerViewController{ open override var shouldAutorotate: Bool{ return true } override open var supportedInterfaceOrientations: UIInterfaceOrientationMask{ return .all } open override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation{ return .portrait } }
41.546667
201
0.622593
d6423806b5092ae50b4cd089829e47fcd75a8701
1,364
class GuidePresenter { weak var view: IGuideView? private let parser: IGuideParser private let router: IGuideRouter private let interactor: IGuideInteractor private let guide: Guide private var fontSize: Int = 17 private var guideContent: String? init(guide: Guide, parser: IGuideParser, router: IGuideRouter, interactor: IGuideInteractor) { self.guide = guide self.parser = parser self.router = router self.interactor = interactor } private func syncViewItems() { guard let guideContent = guideContent else { return } view?.set(viewItems: parser.viewItems(guideContent: guideContent, fontSize: fontSize)) } } extension GuidePresenter: IGuideViewDelegate { func onLoad() { view?.setSpinner(visible: true) interactor.fetchGuideContent(url: guide.fileUrl) } func onTapFontSize() { router.showFontSize(selected: fontSize) { [weak self] fontSize in self?.fontSize = fontSize self?.syncViewItems() self?.view?.refresh() } } } extension GuidePresenter: IGuideInteractorDelegate { func didFetch(guideContent: String) { self.guideContent = guideContent view?.setSpinner(visible: false) syncViewItems() view?.refresh() } }
23.929825
98
0.645161
235a71782e3f02189ebf053a397546c1326e39ab
805
// RUN: %empty-directory(%t) // RUN: %target-build-swift -Xfrontend -enable-experimental-concurrency %s -module-name main -o %t/main // RUN: %target-codesign %t/main // RUN: %target-run %t/main | %FileCheck %s // REQUIRES: concurrency // REQUIRES: executable_test // UNSUPPORTED: use_os_stdlib // UNSUPPORTED: CPU=arm64e func sayHello() async { print("hello") } func sayGeneric<T>(_ msg: T) async { await sayHello() print(msg) } func sayWithClosure(_ action: () async -> ()) async { await action() print("hallo welt") } runAsync { // CHECK: hello await sayHello() // CHECK: hello // CHECK: world await sayGeneric("world") // CHECK: hello // CHECK: and now in german // CHECK: hallo welt await sayWithClosure { await sayHello() print("and now in german") } }
18.72093
103
0.657143
4b37fcadbfaef8fe9d4db0f615085c9102b71e59
5,802
// // AppDelegate.swift // ManagedSoftwareCenter // // Created by Greg Neagle on 5/27/18. // Copyright © 2018-2020 The Munki Project. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDelegate { @IBOutlet weak var mainWindowController: MainWindowController! @IBOutlet weak var statusController: MSCStatusController! @IBOutlet weak var passwordAlertController: MSCPasswordAlertController! func applicationDidFinishLaunching(_ aNotification: Notification) { // NSApplication delegate method called at launch NSLog("%@", "Finished launching") if let info_dict = Bundle.main.infoDictionary { if let vers = info_dict["CFBundleShortVersionString"] as? String { //print(vers) msc_log("MSC", "launched", msg: "VER=\(vers)") } } // setup client logging setup_logging() if let userInfo = aNotification.userInfo { if let ourNotification = userInfo["NSApplicationLaunchUserNotificationKey"] as? NSUserNotification { // we get this notification at launch because it's too early to have declared ourself // a NSUserNotificationCenterDelegate NSLog("%@", "Launched via Notification interaction") userNotificationCenter(NSUserNotificationCenter.default, didActivate: ourNotification) } } // Prevent automatic relaunching at login on Lion+ if NSApp.responds(to: #selector(NSApplication.disableRelaunchOnLogin)) { NSApp.disableRelaunchOnLogin() } // set ourself as a delegate for NSUserNotificationCenter notifications NSUserNotificationCenter.default.delegate = self // have the statuscontroller register for its own notifications statusController.registerForNotifications() // user may have launched the app manually, or it may have // been launched by /usr/local/munki/managedsoftwareupdate // to display available updates var lastcheck = pref("LastCheckDate") as? Date ?? Date.distantPast if thereAreUpdatesToBeForcedSoon(hours: 2) { // skip the check and just display the updates // by pretending the lastcheck is now lastcheck = Date() } let max_cache_age = pref("CheckResultsCacheSeconds") as? Int ?? 0 if lastcheck.timeIntervalSinceNow * -1 > TimeInterval(max_cache_age) { // check for updates if the last check is over the // configured manualcheck cache age max. mainWindowController.checkForUpdates() } else if updateCheckNeeded() { //check for updates if we have optional items selected for install // or removal that have not yet been processed mainWindowController.checkForUpdates() } // load the initial view only if we are not already loading something else. // enables launching the app to a specific panel, eg. from URL handler if !mainWindowController.webView.isLoading { mainWindowController.loadInitialView() } } func applicationWillFinishLaunching(_ notification: Notification) { // Installs URL handler for calls outside the app eg. web clicks let manager = NSAppleEventManager.shared() manager.setEventHandler(self, andSelector: #selector(self.openURL(_:with:)), forEventClass: AEEventClass(kInternetEventClass), andEventID: AEEventID(kAEGetURL)) } @objc func openURL(_ event: NSAppleEventDescriptor, with replyEvent: NSAppleEventDescriptor) { let keyword = AEKeyword(keyDirectObject) let urlDescriptor = event.paramDescriptor(forKeyword: keyword) if let urlString = urlDescriptor?.stringValue { msc_log("MSC", "Called by external URL: \(urlString)") if let url = URL(string: urlString) { mainWindowController.handleMunkiURL(url) } else { msc_debug_log("\(urlString) is not a valid URL") return } } } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply { // Called if user selects 'Quit' from menu return self.mainWindowController.appShouldTerminate() } func userNotificationCenter(_ center: NSUserNotificationCenter, didActivate notification: NSUserNotification) { // User clicked on a Notification Center alert guard let user_info = notification.userInfo else { return } if user_info["action"] as? String ?? "" == "open_url" { let urlString = user_info["value"] as? String ?? "munki://updates" msc_log("MSC", "Got user notification to open \(urlString)") if let url = URL(string: urlString) { mainWindowController.handleMunkiURL(url) } center.removeDeliveredNotification(notification) } else { msc_log("MSC", "Got user notification with unrecognized userInfo") } } func userNotificationCenter(_ center: NSUserNotificationCenter, shouldPresent notification: NSUserNotification) -> Bool { return true } func userNotificationCenter(_ center: NSUserNotificationCenter, didDeliver notification: NSUserNotification) { // we don't currently handle this } }
42.977778
125
0.644605
18a676a0ebb84d3a8c7091fdb564d7db6060944b
613
// // CategoryListViewModel.swift // Demo // // Created by jdj on 2020/01/31. // Copyright © 2020 mac-00018. All rights reserved. // import Foundation import SwiftUI import Combine final class CategoryListViewModel: ObservableObject { init() { fetchCategories() } @Published var categories = [Category]() { didSet { didChange.send(self) } } private func fetchCategories() { ApiService().getAllCategories { self.categories = $0 } } let didChange = PassthroughSubject<CategoryListViewModel, Never>() }
19.15625
70
0.610114
165f40cbfa8cd66bf173df4ebd6bdec62a3ad435
1,484
//: ## High Pass Butterworth Filter //: A high-pass filter takes an audio signal as an input, and cuts out the //: low-frequency components of the audio signal, allowing for the higher frequency //: components to "pass through" the filter. //: import AudioKitPlaygrounds import AudioKit let file = try AKAudioFile(readFileName: playgroundAudioFiles[0]) let player = try AKAudioPlayer(file: file) player.looping = true var filter = AKHighPassButterworthFilter(player) filter.cutoffFrequency = 6_900 // Hz AKManager.output = filter try AKManager.start() player.play() //: User Interface Set up import AudioKitUI class LiveView: AKLiveViewController { override func viewDidLoad() { addTitle("High Pass Butterworth Filter") addView(AKResourcesAudioFileLoaderView(player: player, filenames: playgroundAudioFiles)) addView(AKButton(title: "Stop") { button in filter.isStarted ? filter.stop() : filter.play() button.title = filter.isStarted ? "Stop" : "Start" }) addView(AKSlider(property: "Cutoff Frequency", value: filter.cutoffFrequency, range: 20 ... 22_050, taper: 5, format: "%0.1f Hz" ) { sliderValue in filter.cutoffFrequency = sliderValue }) } } import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true PlaygroundPage.current.liveView = LiveView()
29.68
96
0.66779
395c07d3cfca6d7b42831051c4e41215644a7e32
515
// // ViewController.swift // ItsLitstagram // // Created by Sarah Gemperle on 3/10/17. // Copyright © 2017 Sarah Gemperle. 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.807692
80
0.673786
466b799e48b738208de3976457396cb55a119756
8,516
/** * Copyright IBM Corporation 2016 * * 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 // MARK: JSON Paths internal protocol JSONPathType { func value(in dictionary: [String: Any]) throws -> JSONWrapper func value(in array: [Any]) throws -> JSONWrapper } extension String: JSONPathType { internal func value(in dictionary: [String: Any]) throws -> JSONWrapper { guard let json = dictionary[self] else { throw JSONWrapper.Error.keyNotFound(key: self) } return JSONWrapper(json: json) } internal func value(in array: [Any]) throws -> JSONWrapper { throw JSONWrapper.Error.unexpectedSubscript(type: String.self) } } extension Int: JSONPathType { internal func value(in dictionary: [String: Any]) throws -> JSONWrapper { throw JSONWrapper.Error.unexpectedSubscript(type: Int.self) } internal func value(in array: [Any]) throws -> JSONWrapper { let json = array[self] return JSONWrapper(json: json) } } // MARK: - JSON /// Used internally to serialize and deserialize JSON. /// Will soon be removed in favor of Swift 4's `Codable` protocol. public struct JSONWrapper { fileprivate let json: Any internal init(json: Any) { self.json = json } internal init(string: String) throws { guard let data = string.data(using: .utf8) else { throw Error.encodingError } json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) } internal init(data: Data) throws { json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) } internal init(dictionary: [String: Any]) { json = dictionary } internal init(array: [Any]) { json = array } internal func serialize() throws -> Data { return try JSONSerialization.data(withJSONObject: json, options: []) } internal func serializeString() throws -> String { let data = try serialize() guard let string = String(data: data, encoding: .utf8) else { throw Error.stringSerializationError } return string } private func value(at path: JSONPathType) throws -> JSONWrapper { if let dictionary = json as? [String: Any] { return try path.value(in: dictionary) } if let array = json as? [Any] { return try path.value(in: array) } throw Error.unexpectedSubscript(type: type(of: path)) } private func value(at path: [JSONPathType]) throws -> JSONWrapper { var value = self for fragment in path { value = try value.value(at: fragment) } return value } internal func decode<Decoded: JSONDecodable>(at path: JSONPathType..., type: Decoded.Type = Decoded.self) throws -> Decoded { return try Decoded(json: value(at: path)) } internal func getDouble(at path: JSONPathType...) throws -> Double { return try Double(json: value(at: path)) } internal func getInt(at path: JSONPathType...) throws -> Int { return try Int(json: value(at: path)) } internal func getString(at path: JSONPathType...) throws -> String { return try String(json: value(at: path)) } internal func getBool(at path: JSONPathType...) throws -> Bool { return try Bool(json: value(at: path)) } internal func getArray(at path: JSONPathType...) throws -> [JSONWrapper] { let json = try value(at: path) guard let array = json.json as? [Any] else { throw Error.valueNotConvertible(value: json, to: [JSONWrapper].self) } return array.map { JSONWrapper(json: $0) } } internal func decodedArray<Decoded: JSONDecodable>(at path: JSONPathType..., type: Decoded.Type = Decoded.self) throws -> [Decoded] { let json = try value(at: path) guard let array = json.json as? [Any] else { throw Error.valueNotConvertible(value: json, to: [Decoded].self) } return try array.map { try Decoded(json: JSONWrapper(json: $0)) } } internal func decodedDictionary<Decoded: JSONDecodable>(at path: JSONPathType..., type: Decoded.Type = Decoded.self) throws -> [String: Decoded] { let json = try value(at: path) guard let dictionary = json.json as? [String: Any] else { throw Error.valueNotConvertible(value: json, to: [String: Decoded].self) } var decoded = [String: Decoded](minimumCapacity: dictionary.count) for (key, value) in dictionary { decoded[key] = try Decoded(json: JSONWrapper(json: value)) } return decoded } internal func getJSON(at path: JSONPathType...) throws -> Any { return try value(at: path).json } internal func getDictionary(at path: JSONPathType...) throws -> [String: JSONWrapper] { let json = try value(at: path) guard let dictionary = json.json as? [String: Any] else { throw Error.valueNotConvertible(value: json, to: [String: JSONWrapper].self) } return dictionary.map { JSONWrapper(json: $0) } } internal func getDictionaryObject(at path: JSONPathType...) throws -> [String: Any] { let json = try value(at: path) guard let dictionary = json.json as? [String: Any] else { throw Error.valueNotConvertible(value: json, to: [String: JSONWrapper].self) } return dictionary } } // MARK: - JSON Errors extension JSONWrapper { internal enum Error: Swift.Error { case indexOutOfBounds(index: Int) case keyNotFound(key: String) case unexpectedSubscript(type: JSONPathType.Type) case valueNotConvertible(value: JSONWrapper, to: Any.Type) case encodingError case stringSerializationError } } // MARK: - JSON Protocols internal protocol JSONDecodable { init(json: JSONWrapper) throws } internal protocol JSONEncodable { func toJSON() -> JSONWrapper func toJSONObject() -> Any } extension JSONEncodable { internal func toJSON() -> JSONWrapper { return JSONWrapper(json: self.toJSONObject()) } } extension Double: JSONDecodable { internal init(json: JSONWrapper) throws { let any = json.json if let double = any as? Double { self = double } else if let int = any as? Int { self = Double(int) } else if let string = any as? String, let double = Double(string) { self = double } else { throw JSONWrapper.Error.valueNotConvertible(value: json, to: Double.self) } } } extension Int: JSONDecodable { internal init(json: JSONWrapper) throws { let any = json.json if let int = any as? Int { self = int } else if let double = any as? Double, double <= Double(Int.max) { self = Int(double) } else if let string = any as? String, let int = Int(string) { self = int } else { throw JSONWrapper.Error.valueNotConvertible(value: json, to: Int.self) } } } extension Bool: JSONDecodable { internal init(json: JSONWrapper) throws { let any = json.json if let bool = any as? Bool { self = bool } else { throw JSONWrapper.Error.valueNotConvertible(value: json, to: Bool.self) } } } extension String: JSONDecodable { internal init(json: JSONWrapper) throws { let any = json.json if let string = any as? String { self = string } else if let int = any as? Int { self = String(int) } else if let bool = any as? Bool { self = String(bool) } else if let double = any as? Double { self = String(double) } else { throw JSONWrapper.Error.valueNotConvertible(value: json, to: String.self) } } }
32.015038
150
0.621653
28ae373ea7e856eacf17969d89dfe771b5114b44
1,673
// // UserInfoHeaderView.swift // ForYouAndMe // // Created by Leonardo Passeri on 16/09/2020. // import UIKit class UserInfoHeaderView: UIView { private let titleLabel: UILabel = { let label = UILabel() label.numberOfLines = 0 return label }() private let titleLabelAttributedTextStyle = AttributedTextStyle(fontStyle: .title, colorType: .secondaryText) init() { super.init(frame: .zero) self.addGradientView(GradientView(type: .primaryBackground)) let stackView = UIStackView() stackView.axis = .vertical stackView.spacing = 39.0 stackView.addHeaderImage(image: ImagePalette.image(withName: .mainLogo), height: 100.0) stackView.addArrangedSubview(self.titleLabel) self.addSubview(stackView) stackView.autoPinEdgesToSuperviewSafeArea(with: UIEdgeInsets(top: 20.0, left: Constants.Style.DefaultHorizontalMargins, bottom: 30.0, right: Constants.Style.DefaultHorizontalMargins)) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Public Methods public func setTitle(_ text: String) { self.titleLabel.attributedText = NSAttributedString.create(withText: text, attributedTextStyle: self.titleLabelAttributedTextStyle) } }
33.46
123
0.559474
0abfc9c66b4b30ee782eed53955bf4456db56b66
5,417
import Foundation import Dispatch import enum Result.NoError precedencegroup BindingPrecedence { associativity: right // Binds tighter than assignment but looser than everything else higherThan: AssignmentPrecedence } infix operator <~ : BindingPrecedence // FIXME: Swift 4.x - Conditional Conformance // public protocol BindingSource: SignalProducerConvertible where Error == NoError {} // extension Signal: BindingSource where Error == NoError {} // extension SignalProducer: BindingSource where Error == NoError {} /// Describes a source which can be bound. public protocol BindingSource: SignalProducerConvertible { // FIXME: Swift 4 compiler regression. // All requirements are replicated to workaround the type checker issue. // https://bugs.swift.org/browse/SR-5090 associatedtype Value associatedtype Error: Swift.Error var producer: SignalProducer<Value, Error> { get } } extension Signal: BindingSource {} extension SignalProducer: BindingSource {} /// Describes an entity which be bond towards. public protocol BindingTargetProvider { associatedtype Value var bindingTarget: BindingTarget<Value> { get } } extension BindingTargetProvider { /// Binds a source to a target, updating the target's value to the latest /// value sent by the source. /// /// - note: The binding will automatically terminate when the target is /// deinitialized, or when the source sends a `completed` event. /// /// ```` /// let property = MutableProperty(0) /// let signal = Signal({ /* do some work after some time */ }) /// property <~ signal /// ```` /// /// ```` /// let property = MutableProperty(0) /// let signal = Signal({ /* do some work after some time */ }) /// let disposable = property <~ signal /// ... /// // Terminates binding before property dealloc or signal's /// // `completed` event. /// disposable.dispose() /// ```` /// /// - parameters: /// - target: A target to be bond to. /// - source: A source to bind. /// /// - returns: A disposable that can be used to terminate binding before the /// deinitialization of the target or the source's `completed` /// event. @discardableResult public static func <~ <Source: BindingSource> (provider: Self, source: Source) -> Disposable? where Source.Value == Value, Source.Error == NoError { return source.producer .take(during: provider.bindingTarget.lifetime) .startWithValues(provider.bindingTarget.action) } /// Binds a source to a target, updating the target's value to the latest /// value sent by the source. /// /// - note: The binding will automatically terminate when the target is /// deinitialized, or when the source sends a `completed` event. /// /// ```` /// let property = MutableProperty(0) /// let signal = Signal({ /* do some work after some time */ }) /// property <~ signal /// ```` /// /// ```` /// let property = MutableProperty(0) /// let signal = Signal({ /* do some work after some time */ }) /// let disposable = property <~ signal /// ... /// // Terminates binding before property dealloc or signal's /// // `completed` event. /// disposable.dispose() /// ```` /// /// - parameters: /// - target: A target to be bond to. /// - source: A source to bind. /// /// - returns: A disposable that can be used to terminate binding before the /// deinitialization of the target or the source's `completed` /// event. @discardableResult public static func <~ <Source: BindingSource> (provider: Self, source: Source) -> Disposable? where Value == Source.Value?, Source.Error == NoError { return provider <~ source.producer.optionalize() } } /// A binding target that can be used with the `<~` operator. public struct BindingTarget<Value>: BindingTargetProvider { public let lifetime: Lifetime public let action: (Value) -> Void public var bindingTarget: BindingTarget<Value> { return self } /// Creates a binding target which consumes values on the specified scheduler. /// /// If no scheduler is specified, the binding target would consume the value /// immediately. /// /// - parameters: /// - scheduler: The scheduler on which the `action` consumes the values. /// - lifetime: The expected lifetime of any bindings towards `self`. /// - action: The action to consume values. public init(on scheduler: Scheduler = ImmediateScheduler(), lifetime: Lifetime, action: @escaping (Value) -> Void) { self.lifetime = lifetime if scheduler is ImmediateScheduler { self.action = action } else { self.action = { value in scheduler.schedule { action(value) } } } } #if swift(>=3.2) /// Creates a binding target which consumes values on the specified scheduler. /// /// If no scheduler is specified, the binding target would consume the value /// immediately. /// /// - parameters: /// - scheduler: The scheduler on which the key path consumes the values. /// - lifetime: The expected lifetime of any bindings towards `self`. /// - object: The object to consume values. /// - keyPath: The key path of the object that consumes values. public init<Object: AnyObject>(on scheduler: Scheduler = ImmediateScheduler(), lifetime: Lifetime, object: Object, keyPath: WritableKeyPath<Object, Value>) { self.init(on: scheduler, lifetime: lifetime) { [weak object] in object?[keyPath: keyPath] = $0 } } #endif }
32.244048
158
0.68285
e9b6b0d4e006dbd12c3fd8fd7e17d7925b259c0d
2,883
/* This source file is part of the Swift.org open source project Copyright 2015 - 2016 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import PackageGraph import PackageModel func xcscheme(container: String, graph: PackageGraph, enableCodeCoverage: Bool, printer print: (String) -> Void) { print("<?xml version=\"1.0\" encoding=\"UTF-8\"?>") print("<Scheme LastUpgradeVersion = \"9999\" version = \"1.3\">") print(" <BuildAction parallelizeBuildables = \"YES\" buildImplicitDependencies = \"YES\">") print(" <BuildActionEntries>") // Create buildable references for non-test modules. for module in graph.modules where !module.isTest { // Ignore system modules. // // FIXME: We shouldn't need to manually do this here, instead this // should be phrased in terms of the set of targets we computed. if module.type == .systemModule { continue } print(" <BuildActionEntry buildForTesting = \"YES\" buildForRunning = \"YES\" buildForProfiling = \"YES\" buildForArchiving = \"YES\" buildForAnalyzing = \"YES\">") print(" <BuildableReference") print(" BuildableIdentifier = \"primary\"") print(" BuildableName = \"\(module.buildableName)\"") print(" BlueprintName = \"\(module.blueprintName)\"") print(" ReferencedContainer = \"container:\(container)\">") print(" </BuildableReference>") print(" </BuildActionEntry>") } print(" </BuildActionEntries>") print(" </BuildAction>") print(" <TestAction") print(" buildConfiguration = \"Debug\"") print(" selectedDebuggerIdentifier = \"Xcode.DebuggerFoundation.Debugger.LLDB\"") print(" selectedLauncherIdentifier = \"Xcode.DebuggerFoundation.Launcher.LLDB\"") print(" shouldUseLaunchSchemeArgsEnv = \"YES\"") print(" codeCoverageEnabled = \"\(enableCodeCoverage ? "YES" : "NO")\">") print(" <Testables>") // Create testable references. for module in graph.modules where module.isTest { print(" <TestableReference") print(" skipped = \"NO\">") print(" <BuildableReference") print(" BuildableIdentifier = \"primary\"") print(" BuildableName = \"\(module.buildableName)\"") print(" BlueprintName = \"\(module.blueprintName)\"") print(" ReferencedContainer = \"container:\(container)\">") print(" </BuildableReference>") print(" </TestableReference>") } print(" </Testables>") print(" </TestAction>") print("</Scheme>") }
43.029851
177
0.613597
11b2c289c6093e1f8ea165c0565f70fb1ec5f3ce
8,762
// Copyright © 2016 Alexey Vlaskin. All rights reserved. @testable import BrainPlusLanguageInterpreter import XCTest import Foundation class BPTests: XCTestCase { func testBrainPlusInterpreter1() { var result = false let program = ">>" let instructionSet:[InterpreterCommand] = [IncreaseData(),DecreaseData()] let i = BrainPlusInterpreter(program: program, instructions:instructionSet) let vm = BrainPlusVM() let (res, passed) = i.run(brainfvm: vm) if vm.dataPointer != 2 { result = false } else if !passed || res.characters.count > 0 { result = false } else if passed && res.characters.count == 0 { result = true } XCTAssertTrue(result, "Test move pointer failed #1") } func testBrainPlusInterpreter2() { var result = false let program = ">>++" let instructionSet:[InterpreterCommand] = [IncreaseData(),DecreaseData(),DecreaseData(),DecreasePointer(),IncreasePointer()] let i = BrainPlusInterpreter(program: program, instructions:instructionSet) let vm = BrainPlusVM() let (res, passed) = i.run(brainfvm: vm) if !passed || res.characters.count > 0 { result = false } else if vm.dataPointer != 2 { result = false } else if vm.getPointerValue() != 2 { print("Error : expected 2 == \(vm.getPointerValue())") print("\(vm.description())") result = false } else { result = true } XCTAssertTrue(result, "Test move pointer failed #2") } func testBrainPlusInterpreter3() { let program = ">>++" let instructionSet:[InterpreterCommand] = [IncreaseData(),DecreaseData(),DecreaseData(),DecreasePointer(),IncreasePointer()] let i = BrainPlusInterpreter(program: program, instructions:instructionSet) let vm = BrainPlusVM() let (res, passed) = i.run(brainfvm: vm) XCTAssertTrue(passed || res.characters.count == 0, "Test move and increase pointer failed $3") XCTAssertTrue(vm.dataPointer == 2,"Test move and increase pointer failed") XCTAssertTrue(vm.getPointerValue() == 2, "Error : expected 2") } func testBrainPlusInterpreter4() { let program = ">>+-" let instructionSet:[InterpreterCommand] = [IncreaseData(),DecreaseData(),DecreasePointer(),IncreasePointer()] let i = BrainPlusInterpreter(program: program, instructions:instructionSet) let vm = BrainPlusVM() let (res, passed) = i.run(brainfvm: vm) XCTAssertTrue(passed || res.characters.count == 0, "Test move and increase/decrease pointer failed #4") XCTAssertTrue(vm.dataPointer == 2,"Test move pointer failed #4") XCTAssertTrue(vm.getPointerValue() == 0, "Error : expected 0 #4") } func testBrainPlusInterpreter5() { let program = ">>+--" let instructionSet:[InterpreterCommand] = [IncreaseData(),DecreaseData(),DecreasePointer(),IncreasePointer()] let i = BrainPlusInterpreter(program: program, instructions:instructionSet) let vm = BrainPlusVM() let (res, passed) = i.run(brainfvm: vm) XCTAssertTrue(passed || res.characters.count == 0, "Test move and increase/decrease pointer failed #5") XCTAssertTrue(vm.dataPointer == 2,"Test move pointer failed #5") XCTAssertTrue(vm.getPointerValue() == 255, "Overflow Error : expected 255 #5") } func testBrainPlusInterpreter6() { let program = ">>+--." let instructionSet:[InterpreterCommand] = [ IncreaseData(), DecreaseData(), DecreasePointer(), IncreasePointer(), Output()] let i = BrainPlusInterpreter(program: program, instructions:instructionSet) let vm = BrainPlusVM() let (res, passed) = i.run(brainfvm: vm) XCTAssertTrue(passed || res.characters.count == 1, "Test failed #6") XCTAssertTrue(vm.dataPointer == 2,"Test move pointer failed #6") XCTAssertTrue(vm.getPointerValue() == 255, "Overflow Error : expected 255 #6") } func testBrainPlusInterpreter7() { //This should be the test for input, but I will skip it for now let program = ">>+--." let instructionSet:[InterpreterCommand] = [ IncreaseData(), DecreaseData(), DecreasePointer(), IncreasePointer(), //Input(), Output()] let i = BrainPlusInterpreter(program: program, instructions:instructionSet) let vm = BrainPlusVM() let (res, passed) = i.run(brainfvm: vm) XCTAssertTrue(passed || res.characters.count == 1, "Test failed #7") XCTAssertTrue(vm.dataPointer == 2,"Test move pointer failed #7") XCTAssertTrue(vm.getPointerValue() == 255, "Overflow Error : expected 255 #7") } func testBrainPlusInterpreter8() { //This tests invalid brackets let program = ">>+--[" let instructionSet:[InterpreterCommand] = [ IncreaseData(), DecreaseData(), DecreasePointer(), IncreasePointer(), Output()] let i = BrainPlusInterpreter(program: program, instructions:instructionSet) let vm = BrainPlusVM() let (res, passed) = i.run(brainfvm: vm) XCTAssertFalse(passed, "Test failed #8") // Res should have an error description XCTAssertTrue(res.characters.count > 0, "Test failed #8") } func testBrainPlusInterpreter9() { //This tests invalid brackets let program = "+++++++++[.-]" let instructionSet:[InterpreterCommand] = [ IncreaseData(), DecreaseData(), DecreasePointer(), IncreasePointer(), Output(), LoopStart(), LoopEnd()] let i = BrainPlusInterpreter(program: program, instructions:instructionSet) let vm = BrainPlusVM() let (res, passed) = i.run(brainfvm: vm) XCTAssertTrue(passed || res.characters.count > 8, "Test failed #9") } func testBrainPlusInterpreter10() { //This tests should show hello world let expectedResult = "Hello world!" let program = "--[>--->->->++>-<<<<<-------]>--.>---------.>--..+++.>----.>+++++++++.<<.+++.------.<-.>>+." let instructionSet:[InterpreterCommand] = [ IncreaseData(), DecreaseData(), DecreasePointer(), IncreasePointer(), Output(), LoopStart(), LoopEnd()] let i = BrainPlusInterpreter(program: program, instructions:instructionSet) let vm = BrainPlusVM() let (res, passed) = i.run(brainfvm: vm) XCTAssertTrue(passed, "Test program failed #10") XCTAssertEqual(res, expectedResult, "Test program Hello World - failed #10") } func testBrainPlusInterpreter11() { //This tests should show hello world let expectedResult = "Hello World!\n" let program = "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++." let instructionSet:[InterpreterCommand] = [ IncreaseData(), DecreaseData(), DecreasePointer(), IncreasePointer(), Output(), LoopStart(), LoopEnd()] let i = BrainPlusInterpreter(program: program, instructions:instructionSet) let vm = BrainPlusVM() let (res, passed) = i.run(brainfvm: vm) XCTAssertTrue(passed, "Test program failed #11") XCTAssertEqual(res, expectedResult, "Test program Hello World - failed #11") } func testBrainPlusInterpreter12() { //This is a slightly more complex variant that often triggers interpreter bugs let expectedResult = "Hello World!\n" let program = ">++++++++[-<+++++++++>]<.>>+>-[+]++>++>+++[>[->+++<<+++>]<<]>-----.>->+++..+++.>-.<<+[>[+>+]>>]<--------------.>>.+++.------.--------.>+.>+." let instructionSet:[InterpreterCommand] = [ IncreaseData(), DecreaseData(), DecreasePointer(), IncreasePointer(), Output(), LoopStart(), LoopEnd()] let i = BrainPlusInterpreter(program: program, instructions:instructionSet) let vm = BrainPlusVM() let (res, passed) = i.run(brainfvm: vm) XCTAssertTrue(passed, "Test program failed #12") XCTAssertEqual(res, expectedResult, "Test program Hello World - failed #12") } }
41.72381
164
0.575097
abfda13e9c8905c28feef400379b3dc34baf6b76
766
// // Parser.swift // Community // // Created by Vlad Z. on 6/13/21. // import Foundation extension JSONDecoder { static let defaultDecoder: JSONDecoder = { let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase decoder.dateDecodingStrategy = .formatted(.yearMonthDay) return decoder }() } extension Data { func map<T>(to: T.Type) throws -> T where T: Decodable { try JSONDecoder.defaultDecoder.decode(T.self, from: self) } } extension DateFormatter { static let yearMonthDay: DateFormatter = { var dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" return dateFormatter }() }
21.885714
64
0.614883
1d8e112c27790b1d53d4a196c7767847d90ed79d
463
// // APIService.swift // RxTips // // Created by Yu Sugawara on 2019/11/06. // Copyright © 2019 Yu Sugawara. All rights reserved. // import RxSwift final class APIService { } extension APIService: APIServiceType { func request() -> Single<Void> { return Single.just(()) .delay( RxTimeInterval.seconds(1), scheduler: ConcurrentDispatchQueueScheduler(qos: .default) ) .observeOn(MainScheduler.instance) } }
17.807692
66
0.650108
62796f50668e87b5bc0ffb738bf4bd895c7686a7
240
// // SearchResult.swift // AppStore // // Created by Andres Vazquez on 2019-03-05. // Copyright © 2019 Andavazgar. All rights reserved. // import UIKit struct SearchResult: Codable { let resultCount: Int let results: [App] }
16
53
0.679167
9bc6cdfd33d4b5ff4d1c36faaf66bd6ab08b8f40
2,676
// RUN: %target-run-simple-swift( -Xfrontend -disable-availability-checking %import-libdispatch -parse-as-library) | %FileCheck %s --dump-input always // REQUIRES: executable_test // REQUIRES: concurrency // REQUIRES: libdispatch // rdar://76038845 // REQUIRES: concurrency_runtime // UNSUPPORTED: back_deployment_runtime import Dispatch @available(SwiftStdlib 5.5, *) func asyncEcho(_ value: Int) async -> Int { value } // FIXME: this is a workaround since (A, B) today isn't inferred to be Sendable // and causes an error, but should be a warning (this year at least) @available(SwiftStdlib 5.5, *) struct SendableTuple2<A: Sendable, B: Sendable>: Sendable { let first: A let second: B init(_ first: A, _ second: B) { self.first = first self.second = second } } @available(SwiftStdlib 5.5, *) func test_taskGroup_cancel_then_completions() async { // CHECK: test_taskGroup_cancel_then_completions print("before \(#function)") let result: Int = await withTaskGroup(of: SendableTuple2<Int, Bool>.self) { group in print("group cancelled: \(group.isCancelled)") // CHECK: group cancelled: false let spawnedFirst = group.spawnUnlessCancelled { print("start first") await Task.sleep(1_000_000_000) print("done first") return SendableTuple2(1, Task.isCancelled) } print("spawned first: \(spawnedFirst)") // CHECK: spawned first: true assert(spawnedFirst) let spawnedSecond = group.spawnUnlessCancelled { print("start second") await Task.sleep(3_000_000_000) print("done second") return SendableTuple2(2, Task.isCancelled) } print("spawned second: \(spawnedSecond)") // CHECK: spawned second: true assert(spawnedSecond) group.cancelAll() print("cancelAll") // CHECK: cancelAll // let outerCancelled = await outer // should not be cancelled // print("outer cancelled: \(outerCancelled)") // COM: CHECK: outer cancelled: false // print("group cancelled: \(group.isCancelled)") // COM: CHECK: outer cancelled: false let one = await group.next() print("first: \(one)") // CHECK: first: Optional(main.SendableTuple2<Swift.Int, Swift.Bool>(first: 1, let two = await group.next() print("second: \(two)") // CHECK: second: Optional(main.SendableTuple2<Swift.Int, Swift.Bool>(first: 2, let none = await group.next() print("none: \(none)") // CHECK: none: nil return (one?.first ?? 0) + (two?.first ?? 0) + (none?.first ?? 0) } print("result: \(result)") // CHECK: result: 3 } @available(SwiftStdlib 5.5, *) @main struct Main { static func main() async { await test_taskGroup_cancel_then_completions() } }
32.634146
150
0.683483
38633ea1b2dfc8c1bb125de80ba8d3c51096ece9
179
// // UserInfoView.swift // YYNib-swift // // Created by 昭荣伊 on 16/6/6. // Copyright © 2016年 昭荣伊. All rights reserved. // import UIKit class UserInfoView: YYNibView { }
12.785714
47
0.648045
e9b95d4530309f23fc99343b58ae145a14ae0afe
1,887
import NIO import StubKit import XCTest @testable import Domain enum Expect<Success> { case success((Success) throws -> Void) case failure((Error) throws -> Void) func receive<E>(result: Result<Success, E>) throws { switch (self, result) { case (let .success(matcher), let .success(value)): try matcher(value) case (let .failure(matcher), let .failure(error)): try matcher(error) case (.failure(_), .success(_)): XCTFail("expect failure but got success") case (.success(_), .failure(_)): XCTFail("expect success but got failure") } } } class CreatePostUseCaseTests: XCTestCase { func testCreate() async throws { class Mock: PostRepositoryMock { let eventLoop: EventLoop func create(input: CreatePost.Request) async throws -> Post { let post = try! Stub.make(Post.self) return post } init( eventLoop: EventLoop ) { self.eventLoop = eventLoop } } let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1) let mock = Mock(eventLoop: eventLoopGroup.next()) typealias Input = ( request: CreatePostUseCase.Request, expect: Expect<CreatePostUseCase.Response> ) let input: Input = try! ( request: Stub.make(), expect: .success { res in XCTAssertNotNil(res.id) } ) let useCase = CreatePostUseCase( repository: mock, eventLoop: eventLoopGroup.next() ) let response = try await useCase((input.request)) try input.expect.receive(result: Result { response }) } }
29.952381
77
0.540541
4a690aff2b2e08cff535f3453e29c2beecc02f53
3,510
extension String { // formatting text for currency textField func currencyInputFormatting(divide: Bool = true) -> String { var number: NSNumber! let formatter = NumberFormatter() formatter.numberStyle = .decimal formatter.locale = Locale(identifier: "pt-BR") formatter.maximumFractionDigits = 2 formatter.minimumFractionDigits = 2 var amountWithPrefix = self // remove from String: "$", ".", "," let regex = try! NSRegularExpression(pattern: "[^0-9]", options: .caseInsensitive) amountWithPrefix = regex.stringByReplacingMatches(in: amountWithPrefix, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, self.count), withTemplate: "") let double = (amountWithPrefix as NSString).doubleValue guard divide else { return formatter.string(from: NSNumber(value: double)) ?? "" } number = NSNumber(value: (double / 100)) // if first number is 0 or all numbers were deleted guard number != 0 as NSNumber else { return "" } return formatter.string(from: number)?.replacingOccurrences(of: ".", with: "") ?? "" } /// Convert HTML to NSAttributedString public func convertHtml(textColor: UIColor = .darkGray) -> NSAttributedString { guard let data = data(using: .utf16) else { return NSAttributedString() } if let attributedString = try? NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) { let string = NSMutableAttributedString(attributedString: attributedString) // Apply text color string.addAttributes([.foregroundColor: textColor], range: NSRange(location: 0, length: attributedString.length)) // Update fonts let regularFont = UIFont.customFont(ofSize: 15, weight: .regular) // DEFAULT FONT (REGUALR) let boldFont = UIFont.customFont(ofSize: 15, weight: .bold) // BOLD FONT /// add other fonts if you have them string.enumerateAttribute(.font, in: NSMakeRange(0, attributedString.length), options: NSAttributedString.EnumerationOptions(rawValue: 0), using: { (value, range, stop) -> Void in /// Update to our font // Bold font if let oldFont = value as? UIFont, oldFont.fontName.lowercased().contains("bold") { string.removeAttribute(.font, range: range) string.addAttribute(.font, value: boldFont, range: range) } // Default font else { string.addAttribute(.font, value: regularFont, range: range) } }) return string } return NSAttributedString() } func formatDate(format: String, fromFormat: String = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") -> String { let dateFormatterGet = DateFormatter() dateFormatterGet.dateFormat = fromFormat let dateFormatterPrint = DateFormatter() dateFormatterPrint.locale = Locale(identifier: "pt-BR") dateFormatterPrint.dateFormat = format if let date = dateFormatterGet.date(from: self) { return dateFormatterPrint.string(from: date).uppercased().replacingOccurrences(of: ".", with: "") } else { print("There was an error decoding the string") } return "" } }
43.875
191
0.623647
28fc3a11610182e04ccff06623840d5cd4f6666a
232
// // CustomRowsApp.swift // CustomRows // // Created by Edgar Nzokwe on 7/27/21. // import SwiftUI @main struct CustomRowsApp: App { var body: some Scene { WindowGroup { ContentView() } } }
12.888889
39
0.568966
1aca32afda77d2cb5e0557e473a422f0e5d7e34b
36,247
// // ISO3166.swift // Moody // // Created by Daniel Eggert on 12/05/2015. // Copyright (c) 2015 objc.io. All rights reserved. // import Foundation public struct ISO3166 { public enum Country: Int16 { case guy = 328 case pol = 616 case ltu = 440 case nic = 558 case isl = 352 case lao = 418 case btn = 64 case plw = 585 case hkg = 344 case cze = 203 case dza = 12 case civ = 384 case grl = 304 case msr = 500 case cub = 192 case bwa = 72 case nor = 578 case swz = 748 case fin = 246 case uga = 800 case alb = 8 case cym = 136 case eri = 232 case blz = 84 case mnp = 580 case tur = 792 case hun = 348 case sjm = 744 case ven = 862 case egy = 818 case nru = 520 case twn = 158 case mex = 484 case abw = 533 case vgb = 92 case gab = 266 case can = 124 case imn = 833 case gum = 316 case sen = 686 case gib = 292 case cok = 184 case tuv = 798 case brb = 52 case bdi = 108 case blm = 652 case ssd = 728 case syc = 690 case gha = 288 case lva = 428 case nam = 516 case brn = 96 case nld = 528 case jor = 400 case glp = 312 case che = 756 case aia = 660 case svk = 703 case com = 174 case irl = 372 case shn = 654 case bvt = 74 case mlt = 470 case sgp = 702 case ton = 776 case tgo = 768 case nzl = 554 case bel = 56 case sle = 694 case jpn = 392 case vut = 548 case bmu = 60 case mac = 446 case npl = 524 case mdv = 462 case kgz = 417 case tun = 788 case prt = 620 case tto = 780 case ind = 356 case pry = 600 case ner = 562 case lie = 438 case bhs = 44 case kaz = 398 case dnk = 208 case cri = 188 case phl = 608 case nfk = 574 case bes = 535 case lbn = 422 case fro = 234 case dom = 214 case blr = 112 case chn = 156 case vat = 336 case grd = 308 case bra = 76 case gmb = 270 case mng = 496 case tcd = 148 case mwi = 454 case lbr = 430 case moz = 508 case ago = 24 case kna = 659 case atg = 28 case ury = 858 case grc = 300 case arm = 51 case hmd = 334 case esp = 724 case cuw = 531 case cpv = 132 case cod = 180 case mli = 466 case dma = 212 case khm = 116 case aus = 36 case cog = 178 case ben = 204 case fsm = 583 case pse = 275 case are = 784 case gin = 324 case bfa = 854 case irq = 368 case bhr = 48 case aut = 40 case iot = 86 case som = 706 case afg = 4 case zaf = 710 case dji = 262 case hnd = 340 case mhl = 584 case rus = 643 case vct = 670 case est = 233 case gbr = 826 case qat = 634 case mtq = 474 case per = 604 case ecu = 218 case srb = 688 case jam = 388 case mkd = 807 case col = 170 case kor = 410 case tls = 626 case lca = 662 case tza = 834 case smr = 674 case hti = 332 case gtm = 320 case lso = 426 case deu = 276 case mmr = 104 case idn = 360 case ncl = 540 case pak = 586 case hrv = 191 case esh = 732 case flk = 238 case pan = 591 case irn = 364 case and = 20 case umi = 581 case svn = 705 case bih = 70 case fra = 250 case tca = 796 case kwt = 414 case stp = 678 case ant = 530 case tkm = 795 case tkl = 772 case cyp = 196 case eth = 231 case prk = 408 case sgs = 239 case ggy = 831 case yem = 887 case mus = 480 case aze = 31 case guf = 254 case cxr = 162 case ken = 404 case lka = 144 case asm = 16 case pyf = 258 case rwa = 646 case atf = 260 case mdg = 450 case mrt = 478 case sxm = 534 case fji = 242 case png = 598 case lux = 442 case mda = 498 case isr = 376 case bol = 68 case sau = 682 case swe = 752 case spm = 666 case usa = 840 case caf = 140 case sdn = 736 case slb = 90 case zmb = 894 case cck = 166 case ala = 248 case kir = 296 case mys = 458 case myt = 175 case mco = 492 case pri = 630 case rou = 642 case vnm = 704 case tha = 764 case vir = 850 case ata = 10 case arg = 32 case bgr = 100 case chl = 152 case tjk = 762 case wsm = 882 case niu = 570 case ita = 380 case geo = 268 case wlf = 876 case jey = 832 case gnq = 226 case cmr = 120 case gnb = 624 case reu = 638 case zwe = 716 case ukr = 804 case pcn = 612 case mar = 504 case uzb = 860 case bgd = 50 case maf = 663 case sur = 740 case syr = 760 case slv = 222 case lby = 434 case omn = 512 case mne = 499 case nga = 566 case unknown = 0 } public enum Continent: Int16 { case na = 10001 case an = 10002 case eu = 10003 case af = 10004 case `as` = 10005 case sa = 10006 case oc = 10007 } } private let countriesAndContinents: [(ISO3166.Continent, ISO3166.Country)] = [ (.as, .afg), (.eu, .alb), (.an, .ata), (.af, .dza), (.oc, .asm), (.eu, .and), (.af, .ago), (.na, .atg), (.eu, .aze), (.as, .aze), (.sa, .arg), (.oc, .aus), (.eu, .aut), (.na, .bhs), (.as, .bhr), (.as, .bgd), (.eu, .arm), (.as, .arm), (.na, .brb), (.eu, .bel), (.na, .bmu), (.as, .btn), (.sa, .bol), (.eu, .bih), (.af, .bwa), (.an, .bvt), (.sa, .bra), (.na, .blz), (.as, .iot), (.oc, .slb), (.na, .vgb), (.as, .brn), (.eu, .bgr), (.as, .mmr), (.af, .bdi), (.eu, .blr), (.as, .khm), (.af, .cmr), (.na, .can), (.af, .cpv), (.na, .cym), (.af, .caf), (.as, .lka), (.af, .tcd), (.sa, .chl), (.as, .chn), (.as, .twn), (.as, .cxr), (.as, .cck), (.sa, .col), (.af, .com), (.af, .myt), (.af, .cog), (.af, .cod), (.oc, .cok), (.na, .cri), (.eu, .hrv), (.na, .cub), (.eu, .cyp), (.as, .cyp), (.eu, .cze), (.af, .ben), (.eu, .dnk), (.na, .dma), (.na, .dom), (.sa, .ecu), (.na, .slv), (.af, .gnq), (.af, .eth), (.af, .eri), (.eu, .est), (.eu, .fro), (.sa, .flk), (.an, .sgs), (.oc, .fji), (.eu, .fin), (.eu, .ala), (.eu, .fra), (.sa, .guf), (.oc, .pyf), (.an, .atf), (.af, .dji), (.af, .gab), (.eu, .geo), (.as, .geo), (.af, .gmb), (.as, .pse), (.eu, .deu), (.af, .gha), (.eu, .gib), (.oc, .kir), (.eu, .grc), (.na, .grl), (.na, .grd), (.na, .glp), (.oc, .gum), (.na, .gtm), (.af, .gin), (.sa, .guy), (.na, .hti), (.an, .hmd), (.eu, .vat), (.na, .hnd), (.as, .hkg), (.eu, .hun), (.eu, .isl), (.as, .ind), (.as, .idn), (.as, .irn), (.as, .irq), (.eu, .irl), (.as, .isr), (.eu, .ita), (.af, .civ), (.na, .jam), (.as, .jpn), (.eu, .kaz), (.as, .kaz), (.as, .jor), (.af, .ken), (.as, .prk), (.as, .kor), (.as, .kwt), (.as, .kgz), (.as, .lao), (.as, .lbn), (.af, .lso), (.eu, .lva), (.af, .lbr), (.af, .lby), (.eu, .lie), (.eu, .ltu), (.eu, .lux), (.as, .mac), (.af, .mdg), (.af, .mwi), (.as, .mys), (.as, .mdv), (.af, .mli), (.eu, .mlt), (.na, .mtq), (.af, .mrt), (.af, .mus), (.na, .mex), (.eu, .mco), (.as, .mng), (.eu, .mda), (.eu, .mne), (.na, .msr), (.af, .mar), (.af, .moz), (.as, .omn), (.af, .nam), (.oc, .nru), (.as, .npl), (.eu, .nld), (.na, .ant), (.na, .cuw), (.na, .abw), (.na, .sxm), (.na, .bes), (.oc, .ncl), (.oc, .vut), (.oc, .nzl), (.na, .nic), (.af, .ner), (.af, .nga), (.oc, .niu), (.oc, .nfk), (.eu, .nor), (.oc, .mnp), (.oc, .umi), (.na, .umi), (.oc, .fsm), (.oc, .mhl), (.oc, .plw), (.as, .pak), (.na, .pan), (.oc, .png), (.sa, .pry), (.sa, .per), (.as, .phl), (.oc, .pcn), (.eu, .pol), (.eu, .prt), (.af, .gnb), (.as, .tls), (.na, .pri), (.as, .qat), (.af, .reu), (.eu, .rou), (.eu, .rus), (.as, .rus), (.af, .rwa), (.na, .blm), (.af, .shn), (.na, .kna), (.na, .aia), (.na, .lca), (.na, .maf), (.na, .spm), (.na, .vct), (.eu, .smr), (.af, .stp), (.as, .sau), (.af, .sen), (.eu, .srb), (.af, .syc), (.af, .sle), (.as, .sgp), (.eu, .svk), (.as, .vnm), (.eu, .svn), (.af, .som), (.af, .zaf), (.af, .zwe), (.eu, .esp), (.af, .ssd), (.af, .esh), (.af, .sdn), (.sa, .sur), (.eu, .sjm), (.af, .swz), (.eu, .swe), (.eu, .che), (.as, .syr), (.as, .tjk), (.as, .tha), (.af, .tgo), (.oc, .tkl), (.oc, .ton), (.na, .tto), (.as, .are), (.af, .tun), (.eu, .tur), (.as, .tur), (.as, .tkm), (.na, .tca), (.oc, .tuv), (.af, .uga), (.eu, .ukr), (.eu, .mkd), (.af, .egy), (.eu, .gbr), (.eu, .ggy), (.eu, .jey), (.eu, .imn), (.af, .tza), (.na, .usa), (.na, .vir), (.af, .bfa), (.sa, .ury), (.as, .uzb), (.sa, .ven), (.oc, .wlf), (.oc, .wsm), (.as, .yem), (.af, .zmb), ] extension ISO3166.Continent { init?(country: ISO3166.Country) { let cc = countriesAndContinents.first { $0.1 == country } guard let (continent, _) = cc else { return nil } self = continent } } extension ISO3166.Country { public static func fromISO3166(_ s: String) -> ISO3166.Country { switch (s.lowercased()) { case "guy": return .guy case "pol": return .pol case "ltu": return .ltu case "nic": return .nic case "isl": return .isl case "lao": return .lao case "btn": return .btn case "plw": return .plw case "hkg": return .hkg case "cze": return .cze case "dza": return .dza case "civ": return .civ case "grl": return .grl case "msr": return .msr case "cub": return .cub case "bwa": return .bwa case "nor": return .nor case "swz": return .swz case "fin": return .fin case "uga": return .uga case "alb": return .alb case "cym": return .cym case "eri": return .eri case "blz": return .blz case "mnp": return .mnp case "tur": return .tur case "hun": return .hun case "sjm": return .sjm case "ven": return .ven case "egy": return .egy case "nru": return .nru case "twn": return .twn case "mex": return .mex case "abw": return .abw case "vgb": return .vgb case "gab": return .gab case "can": return .can case "imn": return .imn case "gum": return .gum case "sen": return .sen case "gib": return .gib case "cok": return .cok case "tuv": return .tuv case "brb": return .brb case "bdi": return .bdi case "blm": return .blm case "ssd": return .ssd case "syc": return .syc case "gha": return .gha case "lva": return .lva case "nam": return .nam case "brn": return .brn case "nld": return .nld case "jor": return .jor case "glp": return .glp case "che": return .che case "aia": return .aia case "svk": return .svk case "com": return .com case "irl": return .irl case "shn": return .shn case "bvt": return .bvt case "mlt": return .mlt case "sgp": return .sgp case "ton": return .ton case "tgo": return .tgo case "nzl": return .nzl case "bel": return .bel case "sle": return .sle case "jpn": return .jpn case "vut": return .vut case "bmu": return .bmu case "mac": return .mac case "npl": return .npl case "mdv": return .mdv case "kgz": return .kgz case "tun": return .tun case "prt": return .prt case "tto": return .tto case "ind": return .ind case "pry": return .pry case "ner": return .ner case "lie": return .lie case "bhs": return .bhs case "kaz": return .kaz case "dnk": return .dnk case "cri": return .cri case "phl": return .phl case "nfk": return .nfk case "bes": return .bes case "lbn": return .lbn case "fro": return .fro case "dom": return .dom case "blr": return .blr case "chn": return .chn case "vat": return .vat case "grd": return .grd case "bra": return .bra case "gmb": return .gmb case "mng": return .mng case "tcd": return .tcd case "mwi": return .mwi case "lbr": return .lbr case "moz": return .moz case "ago": return .ago case "kna": return .kna case "atg": return .atg case "ury": return .ury case "grc": return .grc case "arm": return .arm case "hmd": return .hmd case "esp": return .esp case "cuw": return .cuw case "cpv": return .cpv case "cod": return .cod case "mli": return .mli case "dma": return .dma case "khm": return .khm case "aus": return .aus case "cog": return .cog case "ben": return .ben case "fsm": return .fsm case "pse": return .pse case "are": return .are case "gin": return .gin case "bfa": return .bfa case "irq": return .irq case "bhr": return .bhr case "aut": return .aut case "iot": return .iot case "som": return .som case "afg": return .afg case "zaf": return .zaf case "dji": return .dji case "hnd": return .hnd case "mhl": return .mhl case "rus": return .rus case "vct": return .vct case "est": return .est case "gbr": return .gbr case "qat": return .qat case "mtq": return .mtq case "per": return .per case "ecu": return .ecu case "srb": return .srb case "jam": return .jam case "mkd": return .mkd case "col": return .col case "kor": return .kor case "tls": return .tls case "lca": return .lca case "tza": return .tza case "smr": return .smr case "hti": return .hti case "gtm": return .gtm case "lso": return .lso case "deu": return .deu case "mmr": return .mmr case "idn": return .idn case "ncl": return .ncl case "pak": return .pak case "hrv": return .hrv case "esh": return .esh case "flk": return .flk case "pan": return .pan case "irn": return .irn case "and": return .and case "umi": return .umi case "svn": return .svn case "bih": return .bih case "fra": return .fra case "tca": return .tca case "kwt": return .kwt case "stp": return .stp case "ant": return .ant case "tkm": return .tkm case "tkl": return .tkl case "cyp": return .cyp case "eth": return .eth case "prk": return .prk case "sgs": return .sgs case "ggy": return .ggy case "yem": return .yem case "mus": return .mus case "aze": return .aze case "guf": return .guf case "cxr": return .cxr case "ken": return .ken case "lka": return .lka case "asm": return .asm case "pyf": return .pyf case "rwa": return .rwa case "atf": return .atf case "mdg": return .mdg case "mrt": return .mrt case "sxm": return .sxm case "fji": return .fji case "png": return .png case "lux": return .lux case "mda": return .mda case "isr": return .isr case "bol": return .bol case "sau": return .sau case "swe": return .swe case "spm": return .spm case "usa": return .usa case "caf": return .caf case "sdn": return .sdn case "slb": return .slb case "zmb": return .zmb case "cck": return .cck case "ala": return .ala case "kir": return .kir case "mys": return .mys case "myt": return .myt case "mco": return .mco case "pri": return .pri case "rou": return .rou case "vnm": return .vnm case "tha": return .tha case "vir": return .vir case "ata": return .ata case "arg": return .arg case "bgr": return .bgr case "chl": return .chl case "tjk": return .tjk case "wsm": return .wsm case "niu": return .niu case "ita": return .ita case "geo": return .geo case "wlf": return .wlf case "jey": return .jey case "gnq": return .gnq case "cmr": return .cmr case "gnb": return .gnb case "reu": return .reu case "zwe": return .zwe case "ukr": return .ukr case "pcn": return .pcn case "mar": return .mar case "uzb": return .uzb case "bgd": return .bgd case "maf": return .maf case "sur": return .sur case "syr": return .syr case "slv": return .slv case "lby": return .lby case "omn": return .omn case "mne": return .mne case "nga": return .nga case "gy": return .guy case "pl": return .pol case "lt": return .ltu case "ni": return .nic case "is": return .isl case "la": return .lao case "bt": return .btn case "pw": return .plw case "hk": return .hkg case "cz": return .cze case "dz": return .dza case "ci": return .civ case "gl": return .grl case "ms": return .msr case "cu": return .cub case "bw": return .bwa case "no": return .nor case "sz": return .swz case "fi": return .fin case "ug": return .uga case "al": return .alb case "ky": return .cym case "er": return .eri case "bz": return .blz case "mp": return .mnp case "tr": return .tur case "hu": return .hun case "sj": return .sjm case "ve": return .ven case "eg": return .egy case "nr": return .nru case "tw": return .twn case "mx": return .mex case "aw": return .abw case "vg": return .vgb case "ga": return .gab case "ca": return .can case "im": return .imn case "gu": return .gum case "sn": return .sen case "gi": return .gib case "ck": return .cok case "tv": return .tuv case "bb": return .brb case "bi": return .bdi case "bl": return .blm case "ss": return .ssd case "sc": return .syc case "gh": return .gha case "lv": return .lva case "na": return .nam case "bn": return .brn case "nl": return .nld case "jo": return .jor case "gp": return .glp case "ch": return .che case "ai": return .aia case "sk": return .svk case "km": return .com case "ie": return .irl case "sh": return .shn case "bv": return .bvt case "mt": return .mlt case "sg": return .sgp case "to": return .ton case "tg": return .tgo case "nz": return .nzl case "be": return .bel case "sl": return .sle case "jp": return .jpn case "vu": return .vut case "bm": return .bmu case "mo": return .mac case "np": return .npl case "mv": return .mdv case "kg": return .kgz case "tn": return .tun case "pt": return .prt case "tt": return .tto case "in": return .ind case "py": return .pry case "ne": return .ner case "li": return .lie case "bs": return .bhs case "kz": return .kaz case "dk": return .dnk case "cr": return .cri case "ph": return .phl case "nf": return .nfk case "bq": return .bes case "lb": return .lbn case "fo": return .fro case "do": return .dom case "by": return .blr case "cn": return .chn case "va": return .vat case "gd": return .grd case "br": return .bra case "gm": return .gmb case "mn": return .mng case "td": return .tcd case "mw": return .mwi case "lr": return .lbr case "mz": return .moz case "ao": return .ago case "kn": return .kna case "ag": return .atg case "uy": return .ury case "gr": return .grc case "am": return .arm case "hm": return .hmd case "es": return .esp case "cw": return .cuw case "cv": return .cpv case "cd": return .cod case "ml": return .mli case "dm": return .dma case "kh": return .khm case "au": return .aus case "cg": return .cog case "bj": return .ben case "fm": return .fsm case "ps": return .pse case "ae": return .are case "gn": return .gin case "bf": return .bfa case "iq": return .irq case "bh": return .bhr case "at": return .aut case "io": return .iot case "so": return .som case "af": return .afg case "za": return .zaf case "dj": return .dji case "hn": return .hnd case "mh": return .mhl case "ru": return .rus case "vc": return .vct case "ee": return .est case "gb": return .gbr case "qa": return .qat case "mq": return .mtq case "pe": return .per case "ec": return .ecu case "rs": return .srb case "jm": return .jam case "mk": return .mkd case "co": return .col case "kr": return .kor case "tl": return .tls case "lc": return .lca case "tz": return .tza case "sm": return .smr case "ht": return .hti case "gt": return .gtm case "ls": return .lso case "de": return .deu case "mm": return .mmr case "id": return .idn case "nc": return .ncl case "pk": return .pak case "hr": return .hrv case "eh": return .esh case "fk": return .flk case "pa": return .pan case "ir": return .irn case "ad": return .and case "um": return .umi case "si": return .svn case "ba": return .bih case "fr": return .fra case "tc": return .tca case "kw": return .kwt case "st": return .stp case "an": return .ant case "tm": return .tkm case "tk": return .tkl case "cy": return .cyp case "et": return .eth case "kp": return .prk case "gs": return .sgs case "gg": return .ggy case "ye": return .yem case "mu": return .mus case "az": return .aze case "gf": return .guf case "cx": return .cxr case "ke": return .ken case "lk": return .lka case "as": return .asm case "pf": return .pyf case "rw": return .rwa case "tf": return .atf case "mg": return .mdg case "mr": return .mrt case "sx": return .sxm case "fj": return .fji case "pg": return .png case "lu": return .lux case "md": return .mda case "il": return .isr case "bo": return .bol case "sa": return .sau case "se": return .swe case "pm": return .spm case "us": return .usa case "cf": return .caf case "sd": return .sdn case "sb": return .slb case "zm": return .zmb case "cc": return .cck case "ax": return .ala case "ki": return .kir case "my": return .mys case "yt": return .myt case "mc": return .mco case "pr": return .pri case "ro": return .rou case "vn": return .vnm case "th": return .tha case "vi": return .vir case "aq": return .ata case "ar": return .arg case "bg": return .bgr case "cl": return .chl case "tj": return .tjk case "ws": return .wsm case "nu": return .niu case "it": return .ita case "ge": return .geo case "wf": return .wlf case "je": return .jey case "gq": return .gnq case "cm": return .cmr case "gw": return .gnb case "re": return .reu case "zw": return .zwe case "ua": return .ukr case "pn": return .pcn case "ma": return .mar case "uz": return .uzb case "bd": return .bgd case "mf": return .maf case "sr": return .sur case "sy": return .syr case "sv": return .slv case "ly": return .lby case "om": return .omn case "me": return .mne case "ng": return .nga default: return .unknown } } } extension ISO3166.Country { public var threeLetterName: String { switch self { case .guy: return "guy" case .pol: return "pol" case .ltu: return "ltu" case .nic: return "nic" case .isl: return "isl" case .lao: return "lao" case .btn: return "btn" case .plw: return "plw" case .hkg: return "hkg" case .cze: return "cze" case .dza: return "dza" case .civ: return "civ" case .grl: return "grl" case .msr: return "msr" case .cub: return "cub" case .bwa: return "bwa" case .nor: return "nor" case .swz: return "swz" case .fin: return "fin" case .uga: return "uga" case .alb: return "alb" case .cym: return "cym" case .eri: return "eri" case .blz: return "blz" case .mnp: return "mnp" case .tur: return "tur" case .hun: return "hun" case .sjm: return "sjm" case .ven: return "ven" case .egy: return "egy" case .nru: return "nru" case .twn: return "twn" case .mex: return "mex" case .abw: return "abw" case .vgb: return "vgb" case .gab: return "gab" case .can: return "can" case .imn: return "imn" case .gum: return "gum" case .sen: return "sen" case .gib: return "gib" case .cok: return "cok" case .tuv: return "tuv" case .brb: return "brb" case .bdi: return "bdi" case .blm: return "blm" case .ssd: return "ssd" case .syc: return "syc" case .gha: return "gha" case .lva: return "lva" case .nam: return "nam" case .brn: return "brn" case .nld: return "nld" case .jor: return "jor" case .glp: return "glp" case .che: return "che" case .aia: return "aia" case .svk: return "svk" case .com: return "com" case .irl: return "irl" case .shn: return "shn" case .bvt: return "bvt" case .mlt: return "mlt" case .sgp: return "sgp" case .ton: return "ton" case .tgo: return "tgo" case .nzl: return "nzl" case .bel: return "bel" case .sle: return "sle" case .jpn: return "jpn" case .vut: return "vut" case .bmu: return "bmu" case .mac: return "mac" case .npl: return "npl" case .mdv: return "mdv" case .kgz: return "kgz" case .tun: return "tun" case .prt: return "prt" case .tto: return "tto" case .ind: return "ind" case .pry: return "pry" case .ner: return "ner" case .lie: return "lie" case .bhs: return "bhs" case .kaz: return "kaz" case .dnk: return "dnk" case .cri: return "cri" case .phl: return "phl" case .nfk: return "nfk" case .bes: return "bes" case .lbn: return "lbn" case .fro: return "fro" case .dom: return "dom" case .blr: return "blr" case .chn: return "chn" case .vat: return "vat" case .grd: return "grd" case .bra: return "bra" case .gmb: return "gmb" case .mng: return "mng" case .tcd: return "tcd" case .mwi: return "mwi" case .lbr: return "lbr" case .moz: return "moz" case .ago: return "ago" case .kna: return "kna" case .atg: return "atg" case .ury: return "ury" case .grc: return "grc" case .arm: return "arm" case .hmd: return "hmd" case .esp: return "esp" case .cuw: return "cuw" case .cpv: return "cpv" case .cod: return "cod" case .mli: return "mli" case .dma: return "dma" case .khm: return "khm" case .aus: return "aus" case .cog: return "cog" case .ben: return "ben" case .fsm: return "fsm" case .pse: return "pse" case .are: return "are" case .gin: return "gin" case .bfa: return "bfa" case .irq: return "irq" case .bhr: return "bhr" case .aut: return "aut" case .iot: return "iot" case .som: return "som" case .afg: return "afg" case .zaf: return "zaf" case .dji: return "dji" case .hnd: return "hnd" case .mhl: return "mhl" case .rus: return "rus" case .vct: return "vct" case .est: return "est" case .gbr: return "gbr" case .qat: return "qat" case .mtq: return "mtq" case .per: return "per" case .ecu: return "ecu" case .srb: return "srb" case .jam: return "jam" case .mkd: return "mkd" case .col: return "col" case .kor: return "kor" case .tls: return "tls" case .lca: return "lca" case .tza: return "tza" case .smr: return "smr" case .hti: return "hti" case .gtm: return "gtm" case .lso: return "lso" case .deu: return "deu" case .mmr: return "mmr" case .idn: return "idn" case .ncl: return "ncl" case .pak: return "pak" case .hrv: return "hrv" case .esh: return "esh" case .flk: return "flk" case .pan: return "pan" case .irn: return "irn" case .and: return "and" case .umi: return "umi" case .svn: return "svn" case .bih: return "bih" case .fra: return "fra" case .tca: return "tca" case .kwt: return "kwt" case .stp: return "stp" case .ant: return "ant" case .tkm: return "tkm" case .tkl: return "tkl" case .cyp: return "cyp" case .eth: return "eth" case .prk: return "prk" case .sgs: return "sgs" case .ggy: return "ggy" case .yem: return "yem" case .mus: return "mus" case .aze: return "aze" case .guf: return "guf" case .cxr: return "cxr" case .ken: return "ken" case .lka: return "lka" case .asm: return "asm" case .pyf: return "pyf" case .rwa: return "rwa" case .atf: return "atf" case .mdg: return "mdg" case .mrt: return "mrt" case .sxm: return "sxm" case .fji: return "fji" case .png: return "png" case .lux: return "lux" case .mda: return "mda" case .isr: return "isr" case .bol: return "bol" case .sau: return "sau" case .swe: return "swe" case .spm: return "spm" case .usa: return "usa" case .caf: return "caf" case .sdn: return "sdn" case .slb: return "slb" case .zmb: return "zmb" case .cck: return "cck" case .ala: return "ala" case .kir: return "kir" case .mys: return "mys" case .myt: return "myt" case .mco: return "mco" case .pri: return "pri" case .rou: return "rou" case .vnm: return "vnm" case .tha: return "tha" case .vir: return "vir" case .ata: return "ata" case .arg: return "arg" case .bgr: return "bgr" case .chl: return "chl" case .tjk: return "tjk" case .wsm: return "wsm" case .niu: return "niu" case .ita: return "ita" case .geo: return "geo" case .wlf: return "wlf" case .jey: return "jey" case .gnq: return "gnq" case .cmr: return "cmr" case .gnb: return "gnb" case .reu: return "reu" case .zwe: return "zwe" case .ukr: return "ukr" case .pcn: return "pcn" case .mar: return "mar" case .uzb: return "uzb" case .bgd: return "bgd" case .maf: return "maf" case .sur: return "sur" case .syr: return "syr" case .slv: return "slv" case .lby: return "lby" case .omn: return "omn" case .mne: return "mne" case .nga: return "nga" default: return "Unknown" } } } extension ISO3166.Country: CustomStringConvertible { public var description: String { return threeLetterName } } extension ISO3166.Continent: CustomStringConvertible { public var description: String { return NSLocalizedString(localizationKey, tableName: nil, bundle: Bundle(for: Continent.self), value: localizationKey, comment: "") } fileprivate var localizationKey: String { switch (self) { case .na: return "continent.NorthAmerica" case .an: return "continent.Antarctica" case .eu: return "continent.Europe" case .af: return "continent.Africa" case .as: return "continent.Asia" case .sa: return "continent.SouthAmerica" case .oc: return "continent.Oceania" } } } extension ISO3166.Country: LocalizedStringConvertible { public var localizedDescription: String { let loc = NSLocale.current return (loc as NSLocale).displayName(forKey: NSLocale.Key.countryCode, value: threeLetterName) ?? NSLocalizedString("country.Unknown", tableName: nil, bundle: Bundle(for: Continent.self), value: "country.Unknown", comment: "") } } extension ISO3166.Continent: LocalizedStringConvertible { public var localizedDescription: String { return String(describing: self) } }
26.969494
167
0.470853
212bc41a44df022fad40b0f18e0416679740f0c3
3,696
// // SettingsViewController.swift // tips // // Created by Edward Xue on 12/31/15. // Copyright © 2015 eidehua. All rights reserved. // import UIKit class SettingsViewController: UIViewController { @IBOutlet weak var defaultTipControl: UISegmentedControl! @IBOutlet weak var tipField: UITextField! let defaults = NSUserDefaults.standardUserDefaults() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // This is a good place to retrieve the default tip percentage from NSUserDefaults // and use it to update the tip amount let tipIndex = defaults.integerForKey("default_tip_index") //defaults to 0 defaultTipControl.selectedSegmentIndex = tipIndex updateTipSegments() //Update the text field with current selected default tip amount let tipPercentage = defaultTipControl.titleForSegmentAtIndex(tipIndex)! //eg 18%, and make sure its not optional print(tipPercentage) let tipNumber = String(tipPercentage.characters.dropLast()) tipField.text = tipNumber } func updateTipSegments(){ //Update default tip value that shows up. let tipPercentages = defaults.arrayForKey("default_tip_percentages") for i in 0...2 { //0,1,2 let tipPercentage = (tipPercentages![i]) as! NSNumber let tipStringPercentage = "\(tipPercentage)%" //lets me string this NSNumber defaultTipControl.setTitle(tipStringPercentage, forSegmentAtIndex: i) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ @IBAction func onDefaultChanged(sender: AnyObject) { let index = defaultTipControl.selectedSegmentIndex defaults.setInteger(index, forKey: "default_tip_index") //Update the text field with current selected default tip amount let tipPercentage = defaultTipControl.titleForSegmentAtIndex(index)! //eg 18% let tipNumber = String(tipPercentage.characters.dropLast()) tipField.text = tipNumber } //This is for the text field, and will be called on value changed @IBAction func onUpdateTip(sender: AnyObject) { let tipNumber = tipField.text! let tipDouble = NSString(string: tipNumber).doubleValue // I cant let tipPercentage which is a String? = a double let tipInt = NSString(string: tipNumber).integerValue let tipStringPercentage = tipNumber + "%" //eg 18% let tipFraction = tipDouble/100.0 //eg .18 //Update default tip value that shows up. defaultTipControl.setTitle(tipStringPercentage, forSegmentAtIndex: defaultTipControl.selectedSegmentIndex) //update the array var tipPercentages = defaults.arrayForKey("default_tip_percentages") tipPercentages![defaultTipControl.selectedSegmentIndex] = (tipInt) defaults.setValue(tipPercentages, forKey: "default_tip_percentages") } @IBAction func onTap(sender: AnyObject) { view.endEditing(true) } }
39.319149
121
0.681548
695ae8900badef6e49fd1cbfdb8e11fb1fcbd68a
4,271
// // WeatherServiceTestCase.swift // BaluchonTests // // Created by Elodie-Anne Parquer on 14/11/2019. // Copyright © 2019 Elodie-Anne Parquer. All rights reserved. // @testable import Baluchon import XCTest class WeatherServiceTestCase: XCTestCase { func testGetWeather_WhenErrorIsOccured_ThenShouldReturnFailedCallBack() { //Given let weatherService = WeatherService(session: URLSessionFake(data: nil, response: nil, error: FakeResponseData.error)) //When let expectation = XCTestExpectation(description: "Wait for queue change") weatherService.getWeather { result in guard case .failure(let error) = result else { XCTFail("The rate recovery request method with an error failed") return } XCTAssertNotNil(error) expectation.fulfill() } wait(for: [expectation], timeout: 0.01) } func testGetWeather_WhenDataIsNil_ThenShouldReturnFailedCallBack() { //Given let weatherService = WeatherService(session: URLSessionFake(data: nil, response: nil, error: nil)) //When let expectation = XCTestExpectation(description: "Wait for queue change") weatherService.getWeather { result in guard case .failure(let error) = result else { XCTFail("The weather request method with an error failed") return } XCTAssertNotNil(error) expectation.fulfill() } wait(for: [expectation], timeout: 0.01) } func testGetWeather_WhenResponseIsInccorect_ThenShouldReturnFailedCallBack() { //Given let weatherService = WeatherService(session: URLSessionFake(data: FakeResponseData.exchangeCorrectData, response: FakeResponseData.responseKO, error: nil)) //When let expectation = XCTestExpectation(description: "Wait for queue change.") weatherService.getWeather { result in guard case .failure(let error) = result else { XCTFail("The weather request method with an error failed") return } XCTAssertNotNil(error) expectation.fulfill() } wait(for: [expectation], timeout: 0.01) } func testGetWeather_WhenDataIsInccorect_ThenShouldReturnFailedCallBack() { //Given let weatherService = WeatherService(session: URLSessionFake(data: FakeResponseData.exchangeIncorrectData, response: FakeResponseData.responseOK, error: nil)) //When let expectation = XCTestExpectation(description: "Wait for queue change.") weatherService.getWeather { result in guard case .failure(let error) = result else { XCTFail("The weather request method with an error failed") return } XCTAssertNotNil(error) expectation.fulfill() } wait(for: [expectation], timeout: 0.01) } func testGetWeather_WhenCorrectDataAndResponseArePassed_ThenShouldReturnFailedCallBack() { //Given let weatherService = WeatherService(session: URLSessionFake(data: FakeResponseData.weatherCorrectData, response: FakeResponseData.responseOK, error: nil)) //When let expectation = XCTestExpectation(description: "Wait for queue change.") weatherService.getWeather { result in guard case .success(let results) = result else { XCTFail("The weather request method with an error failed") return } XCTAssertNotNil(results.list[0].main.temp) XCTAssertNotNil(results.list[1].main.temp) XCTAssertEqual(results.list[0].weather[0].weatherDescription, "couvert") XCTAssertEqual(results.list[1].weather[0].weatherDescription, "légère pluie") XCTAssertNotNil(results.list[0].weather[0].icon) XCTAssertNotNil(results.list[1].weather[0].icon) expectation.fulfill() } wait(for: [expectation], timeout: 0.01) } }
39.546296
94
0.621166
4833e537c3c132e0486e602090e8193657a9532d
2,535
/// Copyright (c) 2019 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. /// /// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, /// distribute, sublicense, create a derivative work, and/or sell copies of the /// Software in any work that is designed, intended, or marketed for pedagogical or /// instructional purposes related to programming, coding, application development, /// or information technology. Permission for such use, copying, modification, /// merger, publication, distribution, sublicensing, creation of derivative works, /// or sale is expressly withheld. /// /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN /// THE SOFTWARE. import UIKit protocol MessageBubbleTableViewCellDelegate { //셀을 두번 탭할 때 일어나는 작업을 정의하는 프로토콜 func doubleTapForCell(_ cell: MessageBubbleTableViewCell) } class MessageBubbleTableViewCell: UITableViewCell { var delegate: MessageBubbleTableViewCellDelegate? //추가 @IBOutlet var messageLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() let gesture = UITapGestureRecognizer(target: self, action: #selector(doubleTapped)) gesture.numberOfTapsRequired = 2 gesture.cancelsTouchesInView = true contentView.addGestureRecognizer(gesture) //제스처를 추가한다. } override func prepareForReuse() { messageLabel.text = "" } @objc func doubleTapped() { //더블 탭 시 호출될 메서드 delegate?.doubleTapForCell(self) } } //Setting up the delegate for MessageBubbleTableViewCell //더블 탭 시 작업을 처리하는 프로토콜을 정의하고 delegate를 만든다.
41.557377
87
0.751479
2654d7aead1016b269cf84ab3630ad6b8b0fa130
1,984
// Copyright 2016-2017 Skyscanner Ltd // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing permissions // and limitations under the License. import UIKit class CustomLayoutViewController: UIViewController { @IBOutlet var textField: IconTextField? @IBOutlet var addErrorButton: UIButton? @IBAction func addError() { let localizedAddError = NSLocalizedString( "Add error", tableName: "SkyFloatingLabelTextField", comment: "add error button title" ) if addErrorButton?.title(for: .normal) == localizedAddError { textField?.errorMessage = NSLocalizedString( "error message", tableName: "SkyFloatingLabelTextField", comment: "error message" ) addErrorButton?.setTitle( NSLocalizedString( "Clear error", tableName: "SkyFloatingLabelTextField", comment: "clear errors button title" ), for: .normal ) } else { textField?.errorMessage = "" addErrorButton?.setTitle( NSLocalizedString( "Add error", tableName: "SkyFloatingLabelTextField", comment: "add error button title" ), for: .normal ) } } @IBAction func resignTextField() { textField?.resignFirstResponder() } }
32.52459
95
0.58619
717a565ed3365e3ff32883c56bf903c80133cafc
1,297
// // OrderedDictionary.swift // // // Created by Jann Schafranek on 18.03.20. // import Foundation public struct OrderedDictionary<Key: Equatable, Value>: Sequence { private var keys: [Key] = [] private var values: [Value] = [] public init() {} public subscript(key: Key) -> Value? { get { if let index = keys.firstIndex(of: key) { return values[index] } return nil } set { if let index = keys.firstIndex(of: key) { if let newValue = newValue { values[index] = newValue } else { keys.remove(at: index) values.remove(at: index) } } else { if let newValue = newValue { keys.append(key) values.append(newValue) } } } } public var count: Int { return keys.count } public func makeIterator() -> IndexingIterator<[(Key, Value)]> { (0..<keys.count).map { (index) -> (Key, Value) in return (keys[index], values[index]) }.makeIterator() } } extension OrderedDictionary: Equatable where Value: Equatable {}
24.942308
68
0.480339
f983958db880479ac6b5e051e3ab314dd2b7664a
686
// // BaseSrollView.swift // ban // // Created by mba on 16/7/18. // Copyright © 2016年 mbalib. All rights reserved. // import UIKit class BaseSrollView: UIScrollView { override init(frame: CGRect) { super.init(frame: frame) setDefaultUI() setUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setDefaultUI() { showsVerticalScrollIndicator = false showsHorizontalScrollIndicator = false isPagingEnabled = true bounces = false } func setUI() { } func updateUI() { } }
17.15
59
0.561224
f91e2cc19f24f2885adf03509a3930fa6092e75c
8,402
// // SettingView.swift // mPillowTalk // // Created by Lakr Aream on 4/29/21. // import SwiftUI #if DEBUG import FLEX #endif struct SettingView: View { @StateObject var windowObserver = WindowObserver() var body: some View { Group { ScrollView { VStack(spacing: 12) { Section { VStack(spacing: 4) { Group { NavigationLink(destination: SettingGeneralView()) { SettingElementView(icon: "gear", title: NSLocalizedString("GENERAL", comment: "General"), subTitle: NSLocalizedString("GENERAL_SETTING_TINT", comment: "Configure the main features of Pillow Talk")) } .buttonStyle(PlainButtonStyle()) Divider() NavigationLink(destination: SettingAppearanceView()) { SettingElementView(icon: "paintbrush", title: NSLocalizedString("APPERANCE", comment: "Appearance"), subTitle: NSLocalizedString("APPERANCE_SETTING_TINT", comment: "Make the app in your taste")) } .buttonStyle(PlainButtonStyle()) Divider() NavigationLink(destination: SettingMonitorView()) { SettingElementView(icon: "metronome", title: NSLocalizedString("MONITORING", comment: "Monitoring"), subTitle: NSLocalizedString("MONITORING_SETTING_TINT", comment: "Adjust monitoring rate and others")) } .buttonStyle(PlainButtonStyle()) Divider() NavigationLink(destination: SettingAccountView()) { SettingElementView(icon: "rectangle.stack.person.crop", title: NSLocalizedString("KEY", comment: "Key"), subTitle: NSLocalizedString("ACCOUNTS_SETTING_TINT", comment: "Manage accounts and keys associated with your server")) } .buttonStyle(PlainButtonStyle()) } .padding(.horizontal, 8) } .background(Color.lightGray) .cornerRadius(12) } Section { VStack(spacing: 4) { Group { NavigationLink(destination: SettingDiagView()) { SettingElementView(icon: "cross.case", title: NSLocalizedString("DIAGNOSTIC", comment: "Diagnostic"), subTitle: NSLocalizedString("DIAGNOSTIC_SETTING_TINT", comment: "Get here if something goes wrong")) } .buttonStyle(PlainButtonStyle()) Divider() NavigationLink(destination: Text("Usage")) { SettingElementView(icon: "loupe", title: NSLocalizedString("USAGE", comment: "Usage"), subTitle: NSLocalizedString("USAGE_SETTING_TINT", comment: "Show the usage of the app")) } .buttonStyle(PlainButtonStyle()) } .padding(.horizontal, 8) } .background(Color.lightGray) .cornerRadius(12) } Section { VStack(spacing: 4) { Group { NavigationLink(destination: Text("Experimental")) { SettingElementView(icon: "pyramid", title: NSLocalizedString("EXPERIMENTAL", comment: "Experimental"), subTitle: NSLocalizedString("EXPERIMENTAL_SETTING_TINT", comment: "Testing new features here")) } .buttonStyle(PlainButtonStyle()) } .padding(.horizontal, 8) } .background(Color.lightGray) .cornerRadius(12) } Section { VStack(spacing: 4) { Group { NavigationLink(destination: Text("FAQ")) { SettingElementView(icon: "questionmark.circle", title: "FAQ", subTitle: NSLocalizedString("FAQ_SETTING_TINT", comment: "Frequently asked questions")) } .buttonStyle(PlainButtonStyle()) Divider() NavigationLink(destination: Text("Support")) { SettingElementView(icon: "highlighter", title: NSLocalizedString("SUPPORT", comment: "Support"), subTitle: NSLocalizedString("SUPPORT_SETTING_TINT", comment: "Contact us if you still have questions")) } .buttonStyle(PlainButtonStyle()) } .padding(.horizontal, 8) } .background(Color.lightGray) .cornerRadius(12) } #if DEBUG debugArea #endif } .padding() } } .navigationTitle(NSLocalizedString("SETTINGS", comment: "Settings")) .background( HostingWindowFinder { [weak windowObserver] window in windowObserver?.window = window } ) } #if DEBUG var debugArea: some View { VStack(alignment: .leading, spacing: 12) { Divider() Text("Developer Area") .bold() Button { FLEXManager.shared.showExplorer() } label: { HStack { Label("Show FLEX Debugger".uppercased(), systemImage: "ladybug") Spacer() } .padding() .frame(height: 40) .background( Color.lightGray ) .cornerRadius(8) } Button { askAndSetBootFailed(window: windowObserver.window) } label: { HStack { Label("Simulate Boot Failure".uppercased(), systemImage: "ladybug") Spacer() } .padding() .frame(height: 40) .background( Color.lightGray ) .cornerRadius(8) } } } #endif } struct SettingView_Previews: PreviewProvider { static var previews: some View { SettingView() .previewLayout(.fixed(width: 800, height: 500)) } }
47.468927
173
0.387408
38b8c81d774967222b84b5092eb11ae8b454550a
1,251
// // BasicAuth.swift // // // Created by Mathieu Perrais on 1/29/21. // // ---- -TODO //import Foundation //public protocol BasicAuthDelegate: AnyObject { // func basicAuth(_ loader: BasicAuth, retrieveCredentials callback: @escaping (BasicCredentials?) -> Void) //} // //public class BasicAuth: HTTPLoader { // public weak var delegate: BasicAuthDelegate? // // private var credentials: BasicCredentials? // private var pendingTasks = Array<HTTPTask>() // // public override func load(task: HTTPTask) { // if let customCredentials = task.request.basicCredentials { // self.apply(customCredentials, to: task) // } else if let mainCredentials = credentials { // self.apply(mainCredentials, to: task) // } else { // self.pendingTasks.append(task) // // TODO: ask delegate for credentials // } // } // // private func apply(_ credentials: BasicCredentials, to task: HTTPTask) { // let joined = credentials.username + ":" + credentials.password // let data = Data(joined.utf8) // let encoded = data.base64EncodedString() // let header = "Basic \(encoded)" // task.request[header: "Authorization"] = header // } //}
29.785714
110
0.625899
162651ba2f67adfbc5b0837a04b133543a93d347
514
// // AppDelegate.swift // SimpleAudioUnit // // Created by Ryan Francesconi on 5/4/18. // Copyright © 2018 Ryan Francesconi. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ aNotification: Notification) { // Insert code here to initialize your application } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } }
22.347826
71
0.723735
56670b409340d65ffe433a969a81e0a27296b5ce
1,065
import UIKit class ToggleButton: UIButton { init(normalTitle: String, normalColor: UIColor, selectedTitle: String, selectedColor: UIColor) { super.init(frame: .zero) self.titleLabel?.font = UIFont.customBody(size: 14.0) self.setTitle(normalTitle, for: .normal) self.setTitle(selectedTitle, for: .selected) self.setTitleColor(normalColor, for: .normal) self.setTitleColor(selectedColor, for: .selected) self.layer.cornerRadius = 6.0 self.layer.borderWidth = 1.0 updateColors() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override var isSelected: Bool { didSet { updateColors() } } private func updateColors() { guard let color = isSelected ? titleColor(for: .selected) : titleColor(for: .normal) else { return } self.backgroundColor = color.withAlphaComponent(0.1) self.layer.borderColor = color.withAlphaComponent(0.5).cgColor } }
33.28125
108
0.641315