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
4a62fe1fb1b448cb085c044c793a6bef44247eb9
398
// Copyright © 2020 Christian Tietze. All rights reserved. Distributed under the MIT License. import Cocoa class ApplicationCellView: NSTableCellView { static let identifier = NSUserInterfaceItemIdentifier("ApplicationCell") func configure(application: Application) { self.textField?.stringValue = application.name self.imageView?.image = application.icon?.image } }
33.166667
94
0.751256
efdb39cd99f985c3683cb44eb05cf074c3426bb3
16,829
// // SFNTFontFace.swift // // The MIT License // Copyright (c) 2015 - 2021 Susan Cheng. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // struct SFNTFontFace: FontFaceBase { var table: [Signature<BEUInt32>: Data] var head: SFNTHEAD var os2: SFNTOS2? var cmap: SFNTCMAP var maxp: SFNTMAXP var post: SFNTPOST var name: SFNTNAME var hhea: SFNTHHEA var hmtx: Data var vhea: SFNTVHEA? var vmtx: Data? var ltag: SFNTLTAG? var glyf: SFNTGLYF? var sbix: SFNTSBIX? var feat: SFNTFEAT? var morx: SFNTMORX? var gdef: OTFGDEF? var gpos: OTFGPOS? var gsub: OTFGSUB? var cff: CFFFontFace? var cff2: CFF2Decoder? init(table: [Signature<BEUInt32>: Data]) throws { guard let head = try table["head"].map({ try SFNTHEAD($0) }) else { throw FontCollection.Error.InvalidFormat("head not found.") } guard let cmap = try table["cmap"].map({ try SFNTCMAP($0) }) else { throw FontCollection.Error.InvalidFormat("cmap not found.") } guard let maxp = try table["maxp"].map({ try SFNTMAXP($0) }) else { throw FontCollection.Error.InvalidFormat("maxp not found.") } guard let post = try table["post"].map({ try SFNTPOST($0) }) else { throw FontCollection.Error.InvalidFormat("post not found.") } guard let name = try table["name"].map({ try SFNTNAME($0) }) else { throw FontCollection.Error.InvalidFormat("name not found.") } guard let hhea = try table["hhea"].map({ try SFNTHHEA($0) }) else { throw FontCollection.Error.InvalidFormat("hhea not found.") } guard let hmtx = table["hmtx"] else { throw FontCollection.Error.InvalidFormat("hmtx not found.") } guard maxp.numGlyphs >= hhea.numOfLongHorMetrics else { throw ByteDecodeError.endOfData } let hMetricSize = Int(hhea.numOfLongHorMetrics) << 2 let hBearingSize = (Int(maxp.numGlyphs) - Int(hhea.numOfLongHorMetrics)) << 1 guard hmtx.count >= hMetricSize + hBearingSize else { throw ByteDecodeError.endOfData } self.table = table self.head = head self.cmap = cmap self.maxp = maxp self.post = post self.name = name self.hhea = hhea self.hmtx = hmtx self.os2 = try table["OS/2"].map { try SFNTOS2($0) } self.ltag = try table["ltag"].map { try SFNTLTAG($0) } self.feat = try table["feat"].map { try SFNTFEAT($0) } self.morx = try table["morx"].map { try SFNTMORX($0) } self.gdef = try table["GDEF"].map { try OTFGDEF($0) } self.gpos = try table["GPOS"].map { try OTFGPOS($0) } self.gsub = try table["GSUB"].map { try OTFGSUB($0) } if let vhea = try table["vhea"].map({ try SFNTVHEA($0) }), maxp.numGlyphs >= vhea.numOfLongVerMetrics, let vmtx = table["vmtx"] { let vMetricSize = Int(vhea.numOfLongVerMetrics) << 2 let vBearingSize = (Int(maxp.numGlyphs) - Int(vhea.numOfLongVerMetrics)) << 1 if vmtx.count >= vMetricSize + vBearingSize { self.vhea = vhea self.vmtx = vmtx } } if let loca = table["loca"], let glyf = table["glyf"] { self.glyf = try SFNTGLYF(format: Int(head.indexToLocFormat), numberOfGlyphs: Int(maxp.numGlyphs), loca: loca, glyf: glyf) } self.sbix = try table["sbix"].map { try SFNTSBIX($0) } self.cff = try table["CFF "].flatMap { try CFFDecoder($0).faces.first } self.cff2 = try table["CFF2"].map { try CFF2Decoder($0) } if glyf == nil && sbix == nil && cff == nil && cff2 == nil { throw FontCollection.Error.InvalidFormat("outlines not found.") } } } extension SFNTFontFace { var numberOfGlyphs: Int { return Int(maxp.numGlyphs) } var coveredCharacterSet: CharacterSet { return cmap.table.format.coveredCharacterSet } } extension SFNTFontFace { func shape(forGlyph glyph: Int) -> [Shape.Component] { if let shape = cff?.shape(glyph: glyph) { return shape } if let shape = glyf?.outline(glyph: glyph)?.1 { return shape } return [] } func graphic(forGlyph glyph: Int) -> [Font.Graphic]? { if let sbix = sbix { func fetch(_ strike: SFNTSBIX.Strike, glyph: Int) -> Font.Graphic? { guard let record = strike.glyph(glyph: glyph) else { return nil } switch record.graphicType { case "dupe": return record.data.count == 2 ? fetch(strike, glyph: Int(record.data.load(as: BEUInt16.self))) : nil case "mask": return nil default: break } return Font.Graphic(type: Font.GraphicType(record.graphicType), unitsPerEm: Double(strike.ppem), resolution: Double(strike.resolution), origin: Point(x: Double(record.originOffsetX), y: Double(record.originOffsetY)), data: record.data) } return sbix.compactMap { $0.flatMap { fetch($0, glyph: glyph) } } } return nil } } extension SFNTFontFace { var isVariationSelectors: Bool { return cmap.uvs != nil } var isGraphic: Bool { return sbix != nil } func glyph(with unicode: UnicodeScalar) -> Int { return cmap.table.format[unicode.value] } func glyph(with unicode: UnicodeScalar, _ uvs: UnicodeScalar) -> Int? { if let result = cmap.uvs?.mapping(unicode.value, uvs.value) { switch result { case .none: return nil case .default: return self.glyph(with: unicode) case let .glyph(id): return Int(id) } } return nil } func substitution(glyphs: [Int], layout: Font.LayoutSetting, features: [FontFeature: Int]) -> [Int] { if let morx = morx { var _features: [SFNTMORX.FeatureSetting] = [] for (feature, value) in features { guard let feature = feature.base as? AATFontFeatureBase else { continue } guard let value = UInt16(exactly: value) else { continue } if let setting = feature.setting { switch value { case 0: _features.append(SFNTMORX.FeatureSetting(type: feature.feature, setting: setting | 1)) case 1: _features.append(SFNTMORX.FeatureSetting(type: feature.feature, setting: setting & ~1)) default: break } } else { _features.append(SFNTMORX.FeatureSetting(type: feature.feature, setting: value)) } } return morx.substitution(glyphs: glyphs, numberOfGlyphs: numberOfGlyphs, layout: layout, features: Set(_features)) } return glyphs } } struct AATFontFeatureBase: FontFeatureBase, Hashable { var feature: UInt16 var setting: UInt16? var name: String? var settingNames: [Int: String] var defaultSetting: Int var availableSettings: Set<Int> func hash(into hasher: inout Hasher) { hasher.combine(feature) hasher.combine(setting) } static func ==(lhs: AATFontFeatureBase, rhs: AATFontFeatureBase) -> Bool { return lhs.feature == rhs.feature && lhs.setting == rhs.setting } var description: String { return name ?? "unkonwn" } func name(for setting: Int) -> String? { return settingNames[setting] } } extension SFNTFontFace { func availableFeatures() -> Set<FontFeature> { if let feat = feat { var result: [AATFontFeatureBase] = [] for feature in feat { guard let feature = feature else { continue } if feature.isExclusive { let name = queryName(Int(feature.nameIndex), nil) let defaultSetting = feature[feature.defaultSetting]?.setting var settingNames: [Int: String] = [:] var availableSettings: [Int] = [] for setting in feature { guard let setting = setting else { continue } availableSettings.append(Int(setting.setting)) settingNames[Int(setting.setting)] = queryName(Int(setting.nameIndex), nil) } result.append(AATFontFeatureBase( feature: UInt16(feature.feature), setting: nil, name: name, settingNames: settingNames, defaultSetting: defaultSetting.map { Int($0) } ?? 0, availableSettings: Set(availableSettings)) ) } else { for setting in feature { guard let setting = setting else { continue } let name = queryName(Int(setting.nameIndex), nil) result.append(AATFontFeatureBase( feature: UInt16(feature.feature), setting: UInt16(setting.setting), name: name, settingNames: [0: "Disable", 1: "Enable"], defaultSetting: 0, availableSettings: [0, 1]) ) } } } return Set(result.map(FontFeature.init)) } return [] } } extension SFNTFontFace { private struct Metric { var advance: BEUInt16 var bearing: BEInt16 func _font_metric() -> Font.Metric { return Font.Metric(advance: Double(advance), bearing: Double(bearing)) } } func metric(glyph: Int) -> Font.Metric { let hMetricCount = Int(hhea.numOfLongHorMetrics) let index = glyph < hMetricCount ? glyph : hMetricCount - 1 return hmtx.typed(as: Metric.self)[index]._font_metric() } func verticalMetric(glyph: Int) -> Font.Metric { if let vhea = self.vhea, let vmtx = self.vmtx { let vMetricCount = Int(vhea.numOfLongVerMetrics) let index = glyph < vMetricCount ? glyph : vMetricCount - 1 return vmtx.typed(as: Metric.self)[index]._font_metric() } return Font.Metric(advance: 0, bearing: 0) } } extension SFNTFontFace { var isVertical: Bool { return self.vhea != nil && self.vmtx != nil } var ascender: Double { return Double(hhea.ascent) } var descender: Double { return Double(hhea.descent) } var lineGap: Double { return Double(hhea.lineGap) } var verticalAscender: Double? { return (vhea?.vertTypoAscender).map(Double.init) } var verticalDescender: Double? { return (vhea?.vertTypoDescender).map(Double.init) } var verticalLineGap: Double? { return (vhea?.vertTypoLineGap).map(Double.init) } var unitsPerEm: Double { return Double(head.unitsPerEm) } var boundingRectForFont: Rect { let minX = Double(head.xMin) let minY = Double(head.yMin) let maxX = Double(head.xMax) let maxY = Double(head.yMax) return Rect(x: minX, y: minY, width: maxX - minX, height: maxY - minY) } var italicAngle: Double { return post.italicAngle.representingValue } var weight: Int? { return (os2?.usWeightClass).map(Int.init) } var stretch: Int? { return (os2?.usWidthClass).map(Int.init) } var xHeight: Double? { return (os2?.sxHeight).map(Double.init) } var capHeight: Double? { return (os2?.sCapHeight).map(Double.init) } var familyClass: Font.FamilyClass? { switch Int(os2?.sFamilyClass ?? 0) >> 8 { case 1: return .oldStyleSerifs case 2: return .transitionalSerifs case 3: return .modernSerifs case 4: return .clarendonSerifs case 5: return .slabSerifs case 7: return .freeformSerifs case 8: return .sansSerif case 9: return .ornamentals case 10: return .scripts case 12: return .symbolic default: return nil } } var isFixedPitch: Bool { return post.isFixedPitch != 0 } var isItalic: Bool { return head.macStyle & 2 != 0 } var isBold: Bool { return head.macStyle & 1 != 0 } var isExpanded: Bool { return head.macStyle & 64 != 0 } var isCondensed: Bool { return head.macStyle & 32 != 0 } var strikeoutPosition: Double? { return (os2?.yStrikeoutPosition).map(Double.init) } var strikeoutThickness: Double? { return (os2?.yStrikeoutSize).map(Double.init) } var underlinePosition: Double { return Double(post.underlinePosition) } var underlineThickness: Double { return Double(post.underlineThickness) } } extension SFNTFontFace { var names: Set<Int> { return Set(name.record.map { Int($0.name) }) } var languages: Set<String> { var languages = name.record.compactMap { $0.iso_language } if let ltag = ltag { languages += ltag.compactMap { $0 } } return Set(languages) } func queryName(_ id: Int, _ language: String?) -> String? { if let language = language { let lang = ltag?.indexed().first { $0.1 == language }?.0 for (idx, record) in name.record.indexed() where record.name == id { guard record.platform.encoding != nil else { continue } if record.platform.platform == 0 { if let lang = lang, record.language == lang { return self.name[idx] } } else if record.iso_language == language { return self.name[idx] } } } for (idx, record) in name.record.indexed() where record.name == id { guard record.platform.encoding != nil else { continue } return self.name[idx] } return nil } var fontName: String? { return queryName(6, "en") ?? queryName(6, nil) } var familyName: String? { return queryName(1, "en") ?? queryName(6, nil) } var faceName: String? { return queryName(2, "en") ?? queryName(6, nil) } var uniqueName: String? { return queryName(3, "en") ?? queryName(6, nil) } var displayName: String? { return queryName(4, "en") ?? queryName(6, nil) } }
33.193294
251
0.543764
5dcf82d39ac243e2f9acd0c1d65e05759aa9114e
2,374
// // DDragonVersions.swift // LeagueAPI // // Created by Antoine Clop on 8/14/18. // Copyright © 2018 Antoine Clop. All rights reserved. // import Foundation internal class DDragonVersions: Decodable { public var patch: String public var item: String public var rune: String public var mastery: String public var summoner: String public var champion: String public var profileIcon: String public var map: String public var language: String public var sticker: String enum CodingKeys: String, CodingKey { case entry = "n" case patch = "v" case item = "item" case rune = "rune" case mastery = "mastery" case summoner = "summoner" case champion = "champion" case profileIcon = "profileicon" case map = "map" case language = "language" case sticker = "sticker" } public init(patch: String, item: String, rune: String, mastery: String, summoner: String, champion: String, profileIcon: String, map: String, language: String, sticker: String) { self.patch = patch self.item = item self.rune = rune self.mastery = mastery self.summoner = summoner self.champion = champion self.profileIcon = profileIcon self.map = map self.language = language self.sticker = sticker } public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.patch = try container.decode(String.self, forKey: .patch) let versions = try container.nestedContainer(keyedBy: CodingKeys.self, forKey: .entry) self.item = try versions.decode(String.self, forKey: .item) self.rune = try versions.decode(String.self, forKey: .rune) self.mastery = try versions.decode(String.self, forKey: .mastery) self.summoner = try versions.decode(String.self, forKey: .summoner) self.champion = try versions.decode(String.self, forKey: .champion) self.profileIcon = try versions.decode(String.self, forKey: .profileIcon) self.map = try versions.decode(String.self, forKey: .map) self.language = try versions.decode(String.self, forKey: .language) self.sticker = try versions.decode(String.self, forKey: .sticker) } }
35.969697
182
0.648694
3a4b22e6d22a8d0859525a484efd5bb7d6a471c3
4,902
// UIMongolAlertController // version 1.0 import UIKit class UIMongolAlertController: UIViewController, UIGestureRecognizerDelegate { // TODO: Create this view controller entirely programmatically @IBOutlet weak var alertTitle: UIMongolLabel! @IBOutlet weak var alertMessage: UIMongolLabel! @IBOutlet weak var alertContainerView: UIView! @IBOutlet weak var topButton: UIMongolLabel! @IBOutlet weak var bottomButton: UIMongolLabel! @IBOutlet weak var widthConstraint: NSLayoutConstraint! @IBOutlet weak var buttonContainerWidthConstraint: NSLayoutConstraint! @IBOutlet weak var horizontalDividerWidthConstraint: NSLayoutConstraint! @IBOutlet weak var verticalDividerHeightConstraint: NSLayoutConstraint! @IBOutlet weak var buttonEqualHeightsConstraint: NSLayoutConstraint! @IBOutlet weak var bottomButtonHeightConstraint: NSLayoutConstraint! var titleText: String? var messageText: String? var numberOfButtons = 1 var buttonOneText: String? var buttonTwoText: String? var buttonOneAction: (()->Void)? var buttonTwoAction: (()->Void)? var alertWidth: CGFloat? let renderer = MongolUnicodeRenderer.sharedInstance fileprivate let buttonTapHighlightColor = UIColor.lightGray override func viewDidLoad() { super.viewDidLoad() // all alerts view.backgroundColor = UIColor(white: 0, alpha: 0.4) widthConstraint.constant = alertWidth ?? 200 alertContainerView.layer.cornerRadius = 13 alertContainerView.clipsToBounds = true if let unwrappedTitle = titleText { alertTitle.text = renderer.unicodeToGlyphs(unwrappedTitle) } if let unwrappedMessage = messageText { alertMessage.text = renderer.unicodeToGlyphs(unwrappedMessage) } // No buttons if numberOfButtons == 0 { // tap to dismiss let tapGesture = UITapGestureRecognizer(target: self, action: #selector(dismissMongolAlert)) tapGesture.delegate = self view.addGestureRecognizer(tapGesture) // hide buttons buttonContainerWidthConstraint.constant = 0 horizontalDividerWidthConstraint.constant = 0 return } // top button if let buttonOneText = buttonOneText { topButton.text = renderer.unicodeToGlyphs(buttonOneText) } let tapOne = UILongPressGestureRecognizer(target: self, action: #selector(buttonOneHandler)) tapOne.minimumPressDuration = 0 topButton.addGestureRecognizer(tapOne) if numberOfButtons == 1 { verticalDividerHeightConstraint.constant = 0 buttonEqualHeightsConstraint.isActive = false bottomButtonHeightConstraint.constant = 0 return } // bottom button if let buttonTwoText = buttonTwoText { bottomButton.text = renderer.unicodeToGlyphs(buttonTwoText) } let tapTwo = UILongPressGestureRecognizer(target: self, action: #selector(buttonTwoHandler)) tapTwo.minimumPressDuration = 0 bottomButton.addGestureRecognizer(tapTwo) } func buttonOneHandler(_ gesture: UITapGestureRecognizer) { if gesture.state == .began{ topButton.backgroundColor = buttonTapHighlightColor } else if gesture.state == UIGestureRecognizerState.changed { // cancel gesture gesture.isEnabled = false gesture.isEnabled = true topButton.backgroundColor = UIColor.clear } else if gesture.state == .ended { topButton.backgroundColor = UIColor.clear if let action = self.buttonOneAction { action() } dismissMongolAlert() } } func buttonTwoHandler(_ gesture: UITapGestureRecognizer) { if gesture.state == .began { bottomButton.backgroundColor = buttonTapHighlightColor } else if gesture.state == UIGestureRecognizerState.changed { // cancel gesture gesture.isEnabled = false gesture.isEnabled = true bottomButton.backgroundColor = UIColor.clear } else if gesture.state == .ended { bottomButton.backgroundColor = UIColor.clear if let action = self.buttonTwoAction { action() } dismissMongolAlert() } } func dismissMongolAlert() { self.dismiss(animated: true, completion: nil) } }
32.68
104
0.617299
76ad0b5eb1b918cf79a4997f37ff3e53650803b0
3,710
/* Copyright 2017-2018 Ryuichi Laboratories and the Yanagiba project contributors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import XCTest @testable import AST class ParserOptionalPatternTests: XCTestCase { func testIdentifierOptional() { parsePatternAndTest("foo?", "foo?", testClosure: { pttrn in guard let optionalPattern = pttrn as? OptionalPattern, case .identifier(let id) = optionalPattern.kind else { XCTFail("Failed in parsing an optional pattern with identifier.") return } ASTTextEqual(id.identifier, "foo") XCTAssertNil(id.typeAnnotation) }) } func testWildcardOptional() { parsePatternAndTest("_?", "_?", forPatternMatching: true, testClosure: { pttrn in guard let optionalPattern = pttrn as? OptionalPattern, case .wildcard = optionalPattern.kind else { XCTFail("Failed in parsing an optional pattern with wildcard.") return } }) } func testEnumCasePatternOptional() { let enumCases = [ ".foo", "A.b", ".foo()", ".foo(a, b)", "Foo.bar(a, b)", ] for enumCaseString in enumCases { let optEnumCase = "\(enumCaseString)?" parsePatternAndTest(optEnumCase, optEnumCase, forPatternMatching: true, testClosure: { pttrn in guard let optionalPattern = pttrn as? OptionalPattern, case .enumCase(let enumCase) = optionalPattern.kind else { XCTFail("Failed in parsing an optional pattern with enum-case.") return } XCTAssertEqual(enumCase.textDescription, enumCaseString) }) } } func testTuplePatternOptional() { let tuples = [ "()", "(a)", "(a, b)", "(a?, b?)", ] for tupleString in tuples { let optTuple = "\(tupleString)?" parsePatternAndTest(optTuple, optTuple, forPatternMatching: true, testClosure: { pttrn in guard let optionalPattern = pttrn as? OptionalPattern, case .tuple(let tuple) = optionalPattern.kind else { XCTFail("Failed in parsing an optional pattern with enum-case.") return } XCTAssertEqual(tuple.textDescription, tupleString) }) } } func testSourceRange() { parsePatternAndTest("foo?", "foo?", testClosure: { pttrn in XCTAssertEqual(pttrn.sourceRange, getRange(1, 1, 1, 5)) }) parsePatternAndTest("_?", "_?", forPatternMatching: true, testClosure: { pttrn in XCTAssertEqual(pttrn.sourceRange, getRange(1, 1, 1, 3)) }) parsePatternAndTest(".foo?", ".foo?", forPatternMatching: true, testClosure: { pttrn in XCTAssertEqual(pttrn.sourceRange, getRange(1, 1, 1, 6)) }) parsePatternAndTest("(x, y)?", "(x, y)?", forPatternMatching: true, testClosure: { pttrn in XCTAssertEqual(pttrn.sourceRange, getRange(1, 1, 1, 8)) }) } static var allTests = [ ("testIdentifierOptional", testIdentifierOptional), ("testWildcardOptional", testWildcardOptional), ("testEnumCasePatternOptional", testEnumCasePatternOptional), ("testTuplePatternOptional", testTuplePatternOptional), ("testSourceRange", testSourceRange), ] }
32.26087
101
0.659569
ed4fec01e0b2cc1810c34d4a2af0233397e9e28d
1,786
// // Sink.swift // RxSwift // // Created by Krunoslav Zaher on 2/19/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // class Sink<Observer: ObserverType>: Disposable { fileprivate let observer: Observer fileprivate let cancel: Cancelable private let disposed = AtomicInt(0) #if DEBUG private let synchronizationTracker = SynchronizationTracker() #endif init(observer: Observer, cancel: Cancelable) { #if TRACE_RESOURCES _ = Resources.incrementTotal() #endif self.observer = observer self.cancel = cancel } final func forwardOn(_ event: Event<Observer.Element>) { #if DEBUG self.synchronizationTracker.register(synchronizationErrorMessage: .default) defer { self.synchronizationTracker.unregister() } #endif if isFlagSet(self.disposed, 1) { return } self.observer.on(event) } final func forwarder() -> SinkForward<Observer> { SinkForward(forward: self) } final var isDisposed: Bool { isFlagSet(self.disposed, 1) } func dispose() { fetchOr(self.disposed, 1) self.cancel.dispose() } deinit { #if TRACE_RESOURCES _ = Resources.decrementTotal() #endif } } final class SinkForward<Observer: ObserverType>: ObserverType { typealias Element = Observer.Element private let forward: Sink<Observer> init(forward: Sink<Observer>) { self.forward = forward } final func on(_ event: Event<Element>) { switch event { case .next: self.forward.observer.on(event) case .error, .completed: self.forward.observer.on(event) self.forward.cancel.dispose() } } }
23.5
87
0.62374
e0bc1f720b9f777ac98d6d362d4480ae83dcd86f
848
// // Mirror+ReflectedProperties.swift // ExtendedFoundation // // Created by Astemir Eleev on 23/02/2020. // Copyright © 2018 Astemir Eleev. All rights reserved. // import Foundation extension Mirror { static func reflectProperties<T>(of target: Any, matchingType type: T.Type = T.self, recursively: Bool = false, using closure: (T) -> Void) { let mirror = Mirror(reflecting: target) for child in mirror.children { (child.value as? T).map(closure) guard recursively else { continue } Mirror.reflectProperties(of: child.value, recursively: true, using: closure) } } }
31.407407
72
0.497642
ab838fa0de746810cc8c0db6c61b58fa7624db5a
1,161
// // AppDelegate.swift // LocalNotification // // Created by Alexandr Kirilov on 15/03/2020. // Copyright © 2020 Alexandr Kirilov. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: Optional<UIWindow> = nil; func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { if #available (iOS 13.0, *) {} else { window = UIWindow(frame: UIScreen.main.bounds); self.window?.rootViewController = MainViewController() as UIViewController; self.window?.makeKeyAndVisible(); } return true; } // MARK: UISceneSession Lifecycle @available(iOS 13.0, *) func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role); } @available(iOS 13.0, *) func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {} }
29.025
176
0.760551
3988917a2a26d3f60150e7398bc42300c7770aa6
3,700
// // ScrollableValueController.swift // Lunar // // Created by Alin on 25/12/2017. // Copyright © 2017 Alin. All rights reserved. // import Cocoa class ScrollableContrast: NSView { @IBOutlet var label: NSTextField! @IBOutlet var minValue: ScrollableTextField! @IBOutlet var maxValue: ScrollableTextField! @IBOutlet var currentValue: ScrollableTextField! @IBOutlet var minValueCaption: ScrollableTextFieldCaption! @IBOutlet var maxValueCaption: ScrollableTextFieldCaption! @IBOutlet var currentValueCaption: ScrollableTextFieldCaption! var onMinValueChanged: ((Int) -> Void)? var onMaxValueChanged: ((Int) -> Void)? var disabled = false { didSet { minValue.disabled = disabled maxValue.disabled = disabled } } var display: Display! { didSet { update(from: display) } } var name: String! { didSet { label?.stringValue = name } } var displayMinValue: Int { get { return (display.value(forKey: "minContrast") as! NSNumber).intValue } set { display.setValue(newValue, forKey: "minContrast") } } var displayMaxValue: Int { get { return (display.value(forKey: "maxContrast") as! NSNumber).intValue } set { display.setValue(newValue, forKey: "maxContrast") } } var displayValue: Int { get { return (display.value(forKey: "contrast") as! NSNumber).intValue } set { display.setValue(newValue, forKey: "contrast") } } func update(from _: Display) { minValue?.intValue = Int32(displayMinValue) minValue?.upperLimit = displayMaxValue - 1 maxValue?.intValue = Int32(displayMaxValue) maxValue?.lowerLimit = displayMinValue + 1 currentValue?.intValue = Int32(displayValue) } override init(frame frameRect: NSRect) { super.init(frame: frameRect) setup() } required init?(coder: NSCoder) { super.init(coder: coder) setup() } func setup() { minValue?.onValueChangedInstant = onMinValueChanged minValue?.onValueChanged = { (value: Int) in self.maxValue?.lowerLimit = value + 1 if self.display != nil { self.displayMinValue = value } } maxValue?.onValueChangedInstant = onMaxValueChanged maxValue?.onValueChanged = { (value: Int) in self.minValue?.upperLimit = value - 1 if self.display != nil { self.displayMaxValue = value } } minValue?.caption = minValueCaption maxValue?.caption = maxValueCaption } override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) minValue?.onValueChangedInstant = minValue?.onValueChangedInstant ?? onMinValueChanged minValue?.onValueChanged = minValue?.onValueChanged ?? { (value: Int) in self.maxValue?.lowerLimit = value + 1 if self.display != nil { self.displayMinValue = value } } maxValue?.onValueChangedInstant = maxValue?.onValueChangedInstant ?? onMaxValueChanged maxValue?.onValueChanged = maxValue?.onValueChanged ?? { (value: Int) in self.minValue?.upperLimit = value - 1 if self.display != nil { self.displayMaxValue = value } } minValue?.caption = minValue?.caption ?? minValueCaption maxValue?.caption = maxValue?.caption ?? maxValueCaption } }
29.133858
94
0.592703
fb269a29aebf82cf8f01513ea4a6502f3c27aaa6
3,745
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2021 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore // MARK: Paginators extension ConnectContactLens { /// Provides a list of analysis segments for a real-time analysis session. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listRealtimeContactAnalysisSegmentsPaginator<Result>( _ input: ListRealtimeContactAnalysisSegmentsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListRealtimeContactAnalysisSegmentsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listRealtimeContactAnalysisSegments, inputKey: \ListRealtimeContactAnalysisSegmentsRequest.nextToken, outputKey: \ListRealtimeContactAnalysisSegmentsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listRealtimeContactAnalysisSegmentsPaginator( _ input: ListRealtimeContactAnalysisSegmentsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListRealtimeContactAnalysisSegmentsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listRealtimeContactAnalysisSegments, inputKey: \ListRealtimeContactAnalysisSegmentsRequest.nextToken, outputKey: \ListRealtimeContactAnalysisSegmentsResponse.nextToken, on: eventLoop, onPage: onPage ) } } extension ConnectContactLens.ListRealtimeContactAnalysisSegmentsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> ConnectContactLens.ListRealtimeContactAnalysisSegmentsRequest { return .init( contactId: self.contactId, instanceId: self.instanceId, maxResults: self.maxResults, nextToken: token ) } }
43.546512
168
0.66008
fba9f21ad2f2ed9a6c3590291fa46d1d71124b4b
14,846
// // TagListView.swift // TagListViewDemo // // Created by Dongyuan Liu on 2015-05-09. // Copyright (c) 2015 Ela. All rights reserved. // import UIKit @objc public protocol TagListViewDelegate { @objc optional func tagPressed(_ title: String, tagView: TagView, sender: TagListView) -> Void @objc optional func tagRemoveButtonPressed(_ title: String, tagView: TagView, sender: TagListView) -> Void } @IBDesignable open class TagListView: UIView { @IBInspectable open dynamic var numberOfRows: Int = 0 { didSet { self.maximumRow = numberOfRows } } private(set) var maximumRow = 0 { didSet { invalidateIntrinsicContentSize() } } @IBInspectable open dynamic var textColor: UIColor = .white { didSet { tagViews.forEach { $0.textColor = textColor } } } @IBInspectable open dynamic var selectedTextColor: UIColor = .white { didSet { tagViews.forEach { $0.selectedTextColor = selectedTextColor } } } @IBInspectable open dynamic var tagLineBreakMode: NSLineBreakMode = .byTruncatingMiddle { didSet { tagViews.forEach { $0.titleLineBreakMode = tagLineBreakMode } } } @IBInspectable open dynamic var tagBackgroundColor: UIColor = UIColor.gray { didSet { tagViews.forEach { $0.tagBackgroundColor = tagBackgroundColor } } } @IBInspectable open dynamic var tagHighlightedBackgroundColor: UIColor? { didSet { tagViews.forEach { $0.highlightedBackgroundColor = tagHighlightedBackgroundColor } } } @IBInspectable open dynamic var tagSelectedBackgroundColor: UIColor? { didSet { tagViews.forEach { $0.selectedBackgroundColor = tagSelectedBackgroundColor } } } @IBInspectable open dynamic var cornerRadius: CGFloat = 0 { didSet { tagViews.forEach { $0.cornerRadius = cornerRadius } } } @IBInspectable open dynamic var borderWidth: CGFloat = 0 { didSet { tagViews.forEach { $0.borderWidth = borderWidth } } } @IBInspectable open dynamic var borderColor: UIColor? { didSet { tagViews.forEach { $0.borderColor = borderColor } } } @IBInspectable open dynamic var selectedBorderColor: UIColor? { didSet { tagViews.forEach { $0.selectedBorderColor = selectedBorderColor } } } @IBInspectable open dynamic var paddingY: CGFloat = 2 { didSet { defer { rearrangeViews() } tagViews.forEach { $0.paddingY = paddingY } } } @IBInspectable open dynamic var paddingX: CGFloat = 5 { didSet { defer { rearrangeViews() } tagViews.forEach { $0.paddingX = paddingX } } } @IBInspectable open dynamic var marginY: CGFloat = 2 { didSet { rearrangeViews() } } @IBInspectable open dynamic var marginX: CGFloat = 5 { didSet { rearrangeViews() } } @IBInspectable open dynamic var minWidth: CGFloat = 0 { didSet { rearrangeViews() } } @objc public enum Alignment: Int { case left case center case right case leading case trailing } @IBInspectable open var alignment: Alignment = .leading { didSet { rearrangeViews() } } @IBInspectable open dynamic var shadowColor: UIColor = .white { didSet { rearrangeViews() } } @IBInspectable open dynamic var shadowRadius: CGFloat = 0 { didSet { rearrangeViews() } } @IBInspectable open dynamic var shadowOffset: CGSize = .zero { didSet { rearrangeViews() } } @IBInspectable open dynamic var shadowOpacity: Float = 0 { didSet { rearrangeViews() } } @IBInspectable open dynamic var enableRemoveButton: Bool = false { didSet { defer { rearrangeViews() } tagViews.forEach { $0.enableRemoveButton = enableRemoveButton } } } @IBInspectable open dynamic var removeButtonIconSize: CGFloat = 12 { didSet { defer { rearrangeViews() } tagViews.forEach { $0.removeButtonIconSize = removeButtonIconSize } } } @IBInspectable open dynamic var removeIconLineWidth: CGFloat = 1 { didSet { defer { rearrangeViews() } tagViews.forEach { $0.removeIconLineWidth = removeIconLineWidth } } } @IBInspectable open dynamic var removeIconLineColor: UIColor = UIColor.white.withAlphaComponent(0.54) { didSet { defer { rearrangeViews() } tagViews.forEach { $0.removeIconLineColor = removeIconLineColor } } } @objc open dynamic var textFont: UIFont = .systemFont(ofSize: 12) { didSet { defer { rearrangeViews() } tagViews.forEach { $0.textFont = textFont } } } @IBOutlet open weak var delegate: TagListViewDelegate? open private(set) var tagViews: [TagView] = [] private(set) var tagBackgroundViews: [UIView] = [] private(set) var rowViews: [UIView] = [] private(set) var tagViewHeight: CGFloat = 0 private(set) var rows = 0 { didSet { invalidateIntrinsicContentSize() } } // MARK: - Interface Builder open override func prepareForInterfaceBuilder() { addTag("Welcome") addTag("to") addTag("TagListView").isSelected = true } // MARK: - Layout open override func layoutSubviews() { defer { rearrangeViews() } super.layoutSubviews() } private func rearrangeViews() { let views = tagViews as [UIView] + tagBackgroundViews + rowViews views.forEach { $0.removeFromSuperview() } rowViews.removeAll(keepingCapacity: true) var isRtl: Bool = false if #available(iOS 10.0, tvOS 10.0, *) { isRtl = effectiveUserInterfaceLayoutDirection == .rightToLeft } else if #available(iOS 9.0, *) { isRtl = UIView.userInterfaceLayoutDirection(for: semanticContentAttribute) == .rightToLeft } else if let shared = UIApplication.value(forKey: "sharedApplication") as? UIApplication { isRtl = shared.userInterfaceLayoutDirection == .leftToRight } var alignment = self.alignment if alignment == .leading { alignment = isRtl ? .right : .left } else if alignment == .trailing { alignment = isRtl ? .left : .right } var currentRow = 0 var currentRowView: UIView! var currentRowTagCount = 0 var currentRowWidth: CGFloat = 0 let frameWidth = frame.width let directionTransform = isRtl ? CGAffineTransform(scaleX: -1.0, y: 1.0) : CGAffineTransform.identity for (index, tagView) in tagViews.enumerated() { tagView.frame.size = tagView.intrinsicContentSize tagViewHeight = tagView.frame.height if currentRowTagCount == 0 || currentRowWidth + tagView.frame.width > frameWidth { guard maximumRow == 0 || currentRow < maximumRow else { return } currentRow += 1 currentRowWidth = 0 currentRowTagCount = 0 currentRowView = UIView() currentRowView.transform = directionTransform currentRowView.frame.origin.y = CGFloat(currentRow - 1) * (tagViewHeight + marginY) rowViews.append(currentRowView) addSubview(currentRowView) tagView.frame.size.width = min(tagView.frame.size.width, frameWidth) } let tagBackgroundView = tagBackgroundViews[index] tagBackgroundView.transform = directionTransform tagBackgroundView.frame.origin = CGPoint( x: currentRowWidth, y: 0) tagBackgroundView.frame.size = tagView.bounds.size tagView.frame.size.width = max(minWidth, tagView.frame.size.width) tagBackgroundView.layer.shadowColor = shadowColor.cgColor tagBackgroundView.layer.shadowPath = UIBezierPath(roundedRect: tagBackgroundView.bounds, cornerRadius: cornerRadius).cgPath tagBackgroundView.layer.shadowOffset = shadowOffset tagBackgroundView.layer.shadowOpacity = shadowOpacity tagBackgroundView.layer.shadowRadius = shadowRadius tagBackgroundView.addSubview(tagView) currentRowView.addSubview(tagBackgroundView) currentRowTagCount += 1 currentRowWidth += tagView.frame.width + marginX switch alignment { case .leading: fallthrough // switch must be exahutive case .left: currentRowView.frame.origin.x = 0 case .center: currentRowView.frame.origin.x = (frameWidth - (currentRowWidth - marginX)) / 2 case .trailing: fallthrough // switch must be exahutive case .right: currentRowView.frame.origin.x = frameWidth - (currentRowWidth - marginX) } currentRowView.frame.size.width = currentRowWidth currentRowView.frame.size.height = max(tagViewHeight, currentRowView.frame.height) } rows = currentRow invalidateIntrinsicContentSize() } // MARK: - Manage tags override open var intrinsicContentSize: CGSize { var height = CGFloat(rows) * (tagViewHeight + marginY) if rows > 0 { height -= marginY } return CGSize(width: frame.width, height: height) } private func createNewTagView(_ title: String) -> TagView { let tagView = TagView(title: title) tagView.textColor = textColor tagView.selectedTextColor = selectedTextColor tagView.tagBackgroundColor = tagBackgroundColor tagView.highlightedBackgroundColor = tagHighlightedBackgroundColor tagView.selectedBackgroundColor = tagSelectedBackgroundColor tagView.titleLineBreakMode = tagLineBreakMode tagView.cornerRadius = cornerRadius tagView.borderWidth = borderWidth tagView.borderColor = borderColor tagView.selectedBorderColor = selectedBorderColor tagView.paddingX = paddingX tagView.paddingY = paddingY tagView.textFont = textFont tagView.removeIconLineWidth = removeIconLineWidth tagView.removeButtonIconSize = removeButtonIconSize tagView.enableRemoveButton = enableRemoveButton tagView.removeIconLineColor = removeIconLineColor tagView.addTarget(self, action: #selector(tagPressed(_:)), for: .touchUpInside) tagView.removeButton.addTarget(self, action: #selector(removeButtonPressed(_:)), for: .touchUpInside) // On long press, deselect all tags except this one tagView.onLongPress = { [unowned self] this in self.tagViews.forEach { $0.isSelected = $0 == this } } return tagView } @discardableResult open func addTag(_ title: String) -> TagView { defer { rearrangeViews() } return addTagView(createNewTagView(title)) } @discardableResult open func addTags(_ titles: [String]) -> [TagView] { return addTagViews(titles.map(createNewTagView)) } @discardableResult open func addTagView(_ tagView: TagView) -> TagView { defer { rearrangeViews() } tagViews.append(tagView) tagBackgroundViews.append(UIView(frame: tagView.bounds)) return tagView } @discardableResult open func addTagViews(_ tagViewList: [TagView]) -> [TagView] { defer { rearrangeViews() } tagViewList.forEach { tagViews.append($0) tagBackgroundViews.append(UIView(frame: $0.bounds)) } return tagViews } @discardableResult open func insertTag(_ title: String, at index: Int) -> TagView { return insertTagView(createNewTagView(title), at: index) } @discardableResult open func insertTagView(_ tagView: TagView, at index: Int) -> TagView { defer { rearrangeViews() } tagViews.insert(tagView, at: index) tagBackgroundViews.insert(UIView(frame: tagView.bounds), at: index) return tagView } open func setTitle(_ title: String, at index: Int) { tagViews[index].titleLabel?.text = title } open func removeTag(_ title: String) { tagViews.reversed().filter({ $0.currentTitle == title }).forEach(removeTagView) } open func removeTagView(_ tagView: TagView) { defer { rearrangeViews() } tagView.removeFromSuperview() if let index = tagViews.firstIndex(of: tagView) { tagViews.remove(at: index) tagBackgroundViews.remove(at: index) } } open func removeAllTags() { defer { tagViews = [] tagBackgroundViews = [] rearrangeViews() } let views: [UIView] = tagViews + tagBackgroundViews views.forEach { $0.removeFromSuperview() } } open func selectedTags() -> [TagView] { return tagViews.filter { $0.isSelected } } // MARK: - Events @objc func tagPressed(_ sender: TagView!) { sender.onTap?(sender) delegate?.tagPressed?(sender.currentTitle ?? "", tagView: sender, sender: self) } @objc func removeButtonPressed(_ closeButton: CloseButton!) { if let tagView = closeButton.tagView { delegate?.tagRemoveButtonPressed?(tagView.currentTitle ?? "", tagView: tagView, sender: self) } } }
31.254737
135
0.578472
46dbd339654ee105791b8481cbcfb91cf18491e3
6,350
// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-silgen -primary-file %s | %FileCheck %s struct B { var i : Int, j : Float var c : C } struct C { var x : Int init() { x = 17 } } struct D { var (i, j) : (Int, Double) = (2, 3.5) } // CHECK-LABEL: sil hidden [transparent] @_T019default_constructor1DV1iSivfi : $@convention(thin) () -> (Int, Double) // CHECK: [[FN:%.*]] = function_ref @_T0S2iBi2048_22_builtinIntegerLiteral_tcfC : $@convention(method) (Builtin.Int2048, @thin Int.Type) -> Int // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin Int.Type // CHECK-NEXT: [[VALUE:%.*]] = integer_literal $Builtin.Int2048, 2 // CHECK-NEXT: [[LEFT:%.*]] = apply [[FN]]([[VALUE]], [[METATYPE]]) : $@convention(method) (Builtin.Int2048, @thin Int.Type) -> Int // CHECK: [[FN:%.*]] = function_ref @_T0S2dBf{{64|80}}_20_builtinFloatLiteral_tcfC : $@convention(method) (Builtin.FPIEEE{{64|80}}, @thin Double.Type) -> Double // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin Double.Type // CHECK-NEXT: [[VALUE:%.*]] = float_literal $Builtin.FPIEEE{{64|80}}, {{0x400C000000000000|0x4000E000000000000000}} // CHECK-NEXT: [[RIGHT:%.*]] = apply [[FN]]([[VALUE]], [[METATYPE]]) : $@convention(method) (Builtin.FPIEEE{{64|80}}, @thin Double.Type) -> Double // CHECK-NEXT: [[RESULT:%.*]] = tuple ([[LEFT]] : $Int, [[RIGHT]] : $Double) // CHECK-NEXT: return [[RESULT]] : $(Int, Double) // CHECK-LABEL: sil hidden @_T019default_constructor1DV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thin D.Type) -> D // CHECK: [[THISBOX:%[0-9]+]] = alloc_box ${ var D } // CHECK: [[THIS:%[0-9]+]] = mark_uninit // CHECK: [[PB_THIS:%.*]] = project_box [[THIS]] // CHECK: [[INIT:%[0-9]+]] = function_ref @_T019default_constructor1DV1iSivfi // CHECK: [[RESULT:%[0-9]+]] = apply [[INIT]]() // CHECK: [[INTVAL:%[0-9]+]] = tuple_extract [[RESULT]] : $(Int, Double), 0 // CHECK: [[FLOATVAL:%[0-9]+]] = tuple_extract [[RESULT]] : $(Int, Double), 1 // CHECK: [[IADDR:%[0-9]+]] = struct_element_addr [[PB_THIS]] : $*D, #D.i // CHECK: assign [[INTVAL]] to [[IADDR]] // CHECK: [[JADDR:%[0-9]+]] = struct_element_addr [[PB_THIS]] : $*D, #D.j // CHECK: assign [[FLOATVAL]] to [[JADDR]] class E { var i = Int64() } // FIXME(integers): the following checks should be updated for the new way + // gets invoked. <rdar://problem/29939484> // XCHECK-LABEL: sil hidden [transparent] @_T019default_constructor1EC1is5Int64Vvfi : $@convention(thin) () -> Int64 // XCHECK: [[FN:%.*]] = function_ref @_T0s5Int64VABycfC : $@convention(method) (@thin Int64.Type) -> Int64 // XCHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin Int64.Type // XCHECK-NEXT: [[VALUE:%.*]] = apply [[FN]]([[METATYPE]]) : $@convention(method) (@thin Int64.Type) -> Int64 // XCHECK-NEXT: return [[VALUE]] : $Int64 // CHECK-LABEL: sil hidden @_T019default_constructor1EC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned E) -> @owned E // CHECK: bb0([[SELFIN:%[0-9]+]] : $E) // CHECK: [[SELF:%[0-9]+]] = mark_uninitialized // CHECK: [[INIT:%[0-9]+]] = function_ref @_T019default_constructor1EC1is5Int64Vvfi : $@convention(thin) () -> Int64 // CHECK-NEXT: [[VALUE:%[0-9]+]] = apply [[INIT]]() : $@convention(thin) () -> Int64 // CHECK-NEXT: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK-NEXT: [[IREF:%[0-9]+]] = ref_element_addr [[BORROWED_SELF]] : $E, #E.i // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[IREF]] : $*Int64 // CHECK-NEXT: assign [[VALUE]] to [[WRITE]] : $*Int64 // CHECK-NEXT: end_access [[WRITE]] : $*Int64 // CHECK-NEXT: end_borrow [[BORROWED_SELF]] from [[SELF]] // CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK-NEXT: destroy_value [[SELF]] // CHECK-NEXT: return [[SELF_COPY]] : $E class F : E { } // CHECK-LABEL: sil hidden @_T019default_constructor1FCACycfc : $@convention(method) (@owned F) -> @owned F // CHECK: bb0([[ORIGSELF:%[0-9]+]] : $F) // CHECK-NEXT: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var F } // CHECK-NEXT: [[SELF:%[0-9]+]] = mark_uninitialized [derivedself] [[SELF_BOX]] // CHECK-NEXT: [[PB:%.*]] = project_box [[SELF]] // CHECK-NEXT: store [[ORIGSELF]] to [init] [[PB]] : $*F // CHECK-NEXT: [[SELFP:%[0-9]+]] = load [take] [[PB]] : $*F // CHECK-NEXT: [[E:%[0-9]]] = upcast [[SELFP]] : $F to $E // CHECK: [[E_CTOR:%[0-9]+]] = function_ref @_T019default_constructor1ECACycfc : $@convention(method) (@owned E) -> @owned E // CHECK-NEXT: [[ESELF:%[0-9]]] = apply [[E_CTOR]]([[E]]) : $@convention(method) (@owned E) -> @owned E // CHECK-NEXT: [[ESELFW:%[0-9]+]] = unchecked_ref_cast [[ESELF]] : $E to $F // CHECK-NEXT: store [[ESELFW]] to [init] [[PB]] : $*F // CHECK-NEXT: [[SELFP:%[0-9]+]] = load [copy] [[PB]] : $*F // CHECK-NEXT: destroy_value [[SELF]] : ${ var F } // CHECK-NEXT: return [[SELFP]] : $F // <rdar://problem/19780343> Default constructor for a struct with optional doesn't compile // This shouldn't get a default init, since it would be pointless (bar can never // be reassigned). It should get a memberwise init though. struct G { let bar: Int32? } // CHECK-NOT: default_constructor.G.init() // CHECK-LABEL: default_constructor.G.init(bar: Swift.Optional<Swift.Int32>) // CHECK-NEXT: sil hidden @_T019default_constructor1GV{{[_0-9a-zA-Z]*}}fC // CHECK-NOT: default_constructor.G.init() struct H<T> { var opt: T? // CHECK-LABEL: sil hidden @_T019default_constructor1HVACyxGqd__clufC : $@convention(method) <T><U> (@in U, @thin H<T>.Type) -> @out H<T> { // CHECK: [[INIT_FN:%[0-9]+]] = function_ref @_T019default_constructor1HV3optxSgvfi : $@convention(thin) <τ_0_0> () -> @out Optional<τ_0_0> // CHECK-NEXT: [[OPT_T:%[0-9]+]] = alloc_stack $Optional<T> // CHECK-NEXT: apply [[INIT_FN]]<T>([[OPT_T]]) : $@convention(thin) <τ_0_0> () -> @out Optional<τ_0_0> init<U>(_: U) { } } // <rdar://problem/29605388> Member initializer for non-generic type with generic constructor doesn't compile struct I { var x: Int = 0 // CHECK-LABEL: sil hidden @_T019default_constructor1IVACxclufC : $@convention(method) <T> (@in T, @thin I.Type) -> I { // CHECK: [[INIT_FN:%[0-9]+]] = function_ref @_T019default_constructor1IV1xSivfi : $@convention(thin) () -> Int // CHECK: [[RESULT:%[0-9]+]] = apply [[INIT_FN]]() : $@convention(thin) () -> Int // CHECK: [[X_ADDR:%[0-9]+]] = struct_element_addr {{.*}} : $*I, #I.x // CHECK: assign [[RESULT]] to [[X_ADDR]] : $*Int init<T>(_: T) {} }
51.209677
165
0.623465
edd637c877006051ecf86d2b6644eda8a46a375f
1,233
// // tipNgUITests.swift // tipNgUITests // // Created by Jonathan Ng on 8/18/16. // Copyright © 2016 programNg. All rights reserved. // import XCTest class tipNgUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
33.324324
182
0.660178
dbe9dd4e4e9b0b868e7450bdfab581f88e0d1a57
559
// // DefaultProvider+Tokens.swift // ZKSyncSDK // // Created by Eugene Belyakov on 13/01/2021. // import Foundation extension DefaultProvider { public func tokens(completion: @escaping (ZKSyncResult<Tokens>) -> Void) { if let tokens = self.tokensCache { completion(.success(tokens)) } else { self.transport.send(method: "tokens", params: [String]()) { (result: TransportResult<Tokens>) in self.tokensCache = try? result.get() completion(result) } } } }
25.409091
108
0.59034
4b0e5f069ea2aa1f6538d7f6df87ad1618b97d81
2,708
/// 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 final class NetworkImageOperation: AsyncOperation { var image: UIImage? private let url: URL private let completionHandler: ((Data?, URLResponse?, Error?) -> Void)? init(url: URL, completionHandler: ((Data?, URLResponse?, Error?) -> Void)? = nil) { self.url = url self.completionHandler = completionHandler super.init() } convenience init?(string: String, completionHandler: ((Data?, URLResponse?, Error?) -> Void)? = nil) { guard let url = URL(string: string) else { return nil } self.init(url: url, completionHandler: completionHandler) } override func main() { URLSession.shared.dataTask(with: url) { [weak self] data, response, error in guard let self = self else { return } defer { self.state = .finished } if let completionHandler = self.completionHandler { completionHandler(data, response, error) return } guard error == nil, let data = data else { return } self.image = UIImage(data: data) }.resume() } }
39.823529
104
0.714919
167bd0baa74d763b34965f253074d8ac0bc0f206
256
//// /// NotificationOverrides.swift // class Keyboard { static let shared = Keyboard() var options = UIView.AnimationOptions.curveLinear var duration: Double = 0.0 } struct Preloader { func preloadImages(_ jsonables: [Model]) { } }
17.066667
53
0.667969
2233e8cc199c7d3d1b654a6a0c196e99468329cb
1,972
// RUN: %target-swift-frontend -primary-file %s -module-name Swift -g -module-link-name swiftCore -O -parse-as-library -parse-stdlib -emit-module -emit-module-path - -o /dev/null | %target-sil-func-extractor -module-name="Swift" -func='$ss1XV4testyyF' | %FileCheck %s // RUN: %target-swift-frontend -primary-file %s -module-name Swift -g -O -parse-as-library -parse-stdlib -emit-sib -o - | %target-sil-func-extractor -module-name="Swift" -func='$ss1XV4testyyF' | %FileCheck %s -check-prefix=SIB-CHECK // CHECK: import Builtin // CHECK: import Swift // CHECK: func unknown() // CHECK: struct X { // CHECK-NEXT: @usableFromInline // CHECK-NEXT: @inlinable func test() // CHECK-NEXT: init // CHECK-NEXT: } // CHECK-LABEL: sil [serialized] [canonical] [ossa] @$ss1XV4testyyF : $@convention(method) (X) -> () // CHECK: bb0 // CHECK-NEXT: function_ref // CHECK-NEXT: function_ref @unknown : $@convention(thin) () -> () // CHECK-NEXT: apply // CHECK-NEXT: tuple // CHECK-NEXT: return // CHECK: sil [canonical] @unknown : $@convention(thin) () -> () // CHECK-NOT: sil {{.*}} @$ss1XVABycfC : $@convention(thin) (@thin X.Type) -> X // SIB-CHECK: import Builtin // SIB-CHECK: import Swift // SIB-CHECK: func unknown() // SIB-CHECK: struct X { // SIB-CHECK-NEXT: @usableFromInline // SIB-CHECK-NEXT: @inlinable func test() // SIB-CHECK-NEXT: init // SIB-CHECK-NEXT: } // SIB-CHECK-LABEL: sil [serialized] [canonical] [ossa] @$ss1XV4testyyF : $@convention(method) (X) -> () // SIB-CHECK: bb0 // SIB-CHECK-NEXT: function_ref // SIB-CHECK-NEXT: function_ref @unknown : $@convention(thin) () -> () // SIB-CHECK-NEXT: apply // SIB-CHECK-NEXT: tuple // SIB-CHECK-NEXT: return // SIB-CHECK: sil [canonical] @unknown : $@convention(thin) () -> () // SIB-CHECK-NOT: sil {{.*}} @$ss1XVABycfC : $@convention(thin) (@thin X.Type) -> X @_silgen_name("unknown") public func unknown() -> () public struct X { @usableFromInline @inlinable func test() { unknown() } }
32.327869
267
0.659229
ef46fd4e8b7bce06d53ee9f0b913640b58a2b06a
2,999
// // XcodeThemeConsoleTests.swift // DVTColorTheme // // Created by Red Davis on 12/04/2018. // Copyright © 2018 Red Davis. All rights reserved. // import XCTest @testable import DVTColorTheme internal final class ConsoleTests: XCTestCase { // Internal internal var themeOneDictionary: [String : Any]! // MARK: Setup override func setUp() { super.setUp() self.themeOneDictionary = self.themeDictionary(filename: "Theme1.dvtcolortheme") } override func tearDown() { super.tearDown() } // MARK: Colors internal func testEditorColors() { do { let console = try DVTColorTheme.Console(dictionary: self.themeOneDictionary) // Debugger input let debuggerInputColor = NSColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0) XCTAssertEqualOptional(debuggerInputColor, console.debuggerInput.color) XCTAssertEqualOptional("SFMono-Bold", console.debuggerInput.font?.name) // Debugger output XCTAssertEqualOptional(debuggerInputColor, console.debuggerOutput.color) XCTAssertEqualOptional("SFMono-Regular", console.debuggerOutput.font?.name) // Debugger prompt XCTAssertEqualOptional(debuggerInputColor, console.debuggerPrompt.color) XCTAssertEqualOptional("SFMono-Bold", console.debuggerPrompt.font?.name) // Debugger prompt XCTAssertEqualOptional(debuggerInputColor, console.debuggerPrompt.color) XCTAssertEqualOptional("SFMono-Bold", console.debuggerPrompt.font?.name) // Executable input XCTAssertEqualOptional(debuggerInputColor, console.executableInput.color) XCTAssertEqualOptional("SFMono-Regular", console.executableInput.font?.name) // Executable output XCTAssertEqualOptional(debuggerInputColor, console.executableOutput.color) XCTAssertEqualOptional("SFMono-Bold", console.executableOutput.font?.name) // Background color let backgroundColor = NSColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0) XCTAssertEqual(backgroundColor, console.backgroundColor) // Text selection color let textSelectionColor = NSColor(red: 0.642038, green: 0.802669, blue: 0.999195, alpha: 1.0) XCTAssertEqual(textSelectionColor, console.textSelectionColor) // Cursor color XCTAssertEqual(debuggerInputColor, console.cursorColor) // Instruction pointer color let instructionPointerColor = NSColor(red: 0.705792, green: 0.8, blue: 0.544, alpha: 1.0) XCTAssertEqual(instructionPointerColor, console.instructionPointerColor) } catch { XCTFail() } } }
34.872093
104
0.623541
14398d76e5751452a3710db9629da170f868ac7a
210
import swift_event class Test { private var _somethingHappened:Event<String> public var somethingHappened: Event<String> { return self._somethingHappened } public init() { } }
17.5
49
0.666667
1617b7dafd013a3e2c1294e8046aeab4aea9cda1
526
// // UIColorExtension.swift // KidCalculator // // Created by Aidy Sun on 2020/3/12. // Copyright © 2020 Aidy. All rights reserved. // #if !os(macOS) import UIKit #endif import Foundation extension UIColor { private class func rgbValue(_ f: CGFloat) -> CGFloat { return f / 255 } class func initWithRGB255(red r: CGFloat, green g: CGFloat, blue b: CGFloat, alpha a: CGFloat = 1.0) -> UIColor { return UIColor(red: rgbValue(r), green: rgbValue(g), blue: rgbValue(b), alpha: a) } }
21.916667
118
0.644487
79abf87065b6100288bae11f25adb9b2aa46d454
826
// // Copyright (c) 2020 Adyen N.V. // // This file is open source and available under the MIT license. See the LICENSE file for more info. // import Foundation /// Stored Blik payment. public struct StoredBLIKPaymentMethod: StoredPaymentMethod { /// :nodoc: public let type: String /// :nodoc: public let name: String /// :nodoc: public let identifier: String /// :nodoc: public let supportedShopperInteractions: [ShopperInteraction] /// :nodoc: public func buildComponent(using builder: PaymentComponentBuilder) -> PaymentComponent? { builder.build(paymentMethod: self) } // MARK: - Decoding private enum CodingKeys: String, CodingKey { case type case name case identifier = "id" case supportedShopperInteractions } }
21.179487
100
0.659806
ff1929f32ec44e2310fcbfcedc33b9e57cf4f680
2,094
// // Copyright © 2020 Jesús Alfredo Hernández Alarcón. All rights reserved. // import EssentialFeed import EssentialFeediOS import Foundation import XCTest extension ImageCommentsUIIntegrationTests { func assertThat( _ sut: ImageCommentsViewController, isRendering comments: [(model: ImageComment, presentable: PresentableImageComment)], file: StaticString = #filePath, line: UInt = #line ) { guard sut.numberOfRenderedComments() == comments.count else { return XCTFail( "Expected \(comments.count) comments, but got \(sut.numberOfRenderedComments()) instead.", file: file, line: line ) } comments.enumerated().forEach { index, comment in assertThat(sut, hasViewConfiguredFor: comment, at: index) } } func assertThat( _ sut: ImageCommentsViewController, hasViewConfiguredFor comment: (model: ImageComment, presentable: PresentableImageComment), at index: Int, file: StaticString = #filePath, line: UInt = #line ) { let view = sut.commentView(at: index) let model = comment.model let presentable = comment.presentable guard let cell = view else { return XCTFail("Expected \(ImageCommentCell.self) instance, got \(String(describing: view)) instead", file: file, line: line) } XCTAssertEqual( cell.usernameText, model.author, "Expected username text to be \(model.author), but got \(String(describing: cell.usernameText)) instead" ) XCTAssertEqual( cell.commentText, model.message, "Expected message text to be \(model.author), but got \(String(describing: cell.commentText)) instead" ) XCTAssertEqual( cell.createdAtText, presentable.createdAt, "Expected created at text to be \(presentable.createdAt), but got \(String(describing: cell.createdAtText)) instead" ) } }
33.774194
137
0.619389
d744f83bf5d1a3604def9f72e6234c1ccf487dcb
2,002
// // TriangleMetalView.swift // MetalTriangle // // Created by quockhai on 2019/3/5. // Copyright © 2019 Polymath. All rights reserved. // import UIKit import MetalKit class MetalParticleView: MTKView { var queue: MTLCommandQueue! var cps: MTLComputePipelineState! override init(frame frameRect: CGRect, device: MTLDevice?) { super.init(frame: frameRect, device: device) self.framebufferOnly = false if let defaultDevice = MTLCreateSystemDefaultDevice() { self.device = defaultDevice self.queue = self.device!.makeCommandQueue() registerShaders() } else { print("[MetalKit]: Your device is not supported Metal 🤪") } } required init(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func registerShaders() { do { let library = device!.makeDefaultLibrary()! let kernel = library.makeFunction(name: "compute")! cps = try device!.makeComputePipelineState(function: kernel) } catch let e { Swift.print("\(e)") } } override func draw(_ rect: CGRect) { super.draw(rect) if let drawable = currentDrawable, let commandBuffer = queue.makeCommandBuffer(), let commandEncoder = commandBuffer.makeComputeCommandEncoder() { commandEncoder.setComputePipelineState(cps) commandEncoder.setTexture(drawable.texture, index: 0) let threadGroupCount = MTLSizeMake(8, 8, 1) let threadGroups = MTLSizeMake(drawable.texture.width / threadGroupCount.width, drawable.texture.height / threadGroupCount.height, 1) commandEncoder.dispatchThreadgroups(threadGroups, threadsPerThreadgroup: threadGroupCount) commandEncoder.endEncoding() commandBuffer.present(drawable) commandBuffer.commit() } } }
30.8
145
0.623377
dbc55d747764420741a6af4c9d4c31efd8d78ee0
1,786
// // DetailModel.swift // Model // // Created by marty-suzuki on 2021/09/26. // import Combine import Foundation public protocol DetailModel { var isExecutingPublisher: AnyPublisher<Bool, Never> { get } var movieDetailPublisher: AnyPublisher<MovieDetail, Never> { get } func loadMovieDetail(movieID: Movie.ID) -> AnyPublisher<Result<Void, Error>, Never> } public final class DetailModelImpl: DetailModel { public var isExecutingPublisher: AnyPublisher<Bool, Never> { $isExecuting.eraseToAnyPublisher() } public var movieDetailPublisher: AnyPublisher<MovieDetail, Never> { $movieDetail .flatMap { movieDetail -> AnyPublisher<MovieDetail, Never> in movieDetail.map { Just($0).eraseToAnyPublisher() } ?? Empty().eraseToAnyPublisher() } .eraseToAnyPublisher() } private let service: TheMovieDatabaseService @Published var movieDetail: MovieDetail? @Published var isExecuting = false public init( service: TheMovieDatabaseService ) { self.service = service } public func loadMovieDetail(movieID: Movie.ID) -> AnyPublisher<Result<Void, Error>, Never> { isExecuting = true return service.movieDetail(movieID: movieID) .handleEvents( receiveOutput: { [weak self] in self?.movieDetail = $0 }, receiveCompletion: { [weak self] _ in self?.isExecuting = false } ) .map { _ in Result<Void, Error>.success(()) } .catch { Just(Result<Void, Error>.failure($0)) } .eraseToAnyPublisher() } }
28.806452
96
0.589026
d9d9ef34de8ccf1835ece312c24c3677403b40a3
5,033
// // GameViewController.swift // SCNHighlight // // Created by Alberto Taiuti on 07/06/2019. // Copyright © 2019 Alberto Taiuti. All rights reserved. // import UIKit import QuartzCore import SceneKit fileprivate let highlightMaskValue: Int = 2 fileprivate let normalMaskValue: Int = 1 class GameViewController: UIViewController { private let scnView = SCNView() override func viewDidLoad() { super.viewDidLoad() // Generic stuff setupHierarchy() setupSCNScene() // Here we load the technique we'll use to achieve a highlight effect around // selected nodes if let fileUrl = Bundle.main.url(forResource: "RenderOutlineTechnique", withExtension: "plist"), let data = try? Data(contentsOf: fileUrl) { if var result = try? PropertyListSerialization.propertyList(from: data, options: [], format: nil) as? [String: Any] { // [String: Any] which ever it is // Here we update the size and scale factor in the original technique file // to whichever size and scale factor the current device is so that // we avoid crazy aliasing let nativePoints = UIScreen.main.bounds let nativeScale = UIScreen.main.nativeScale result[keyPath: "targets.MASK.size"] = "\(nativePoints.width)x\(nativePoints.height)" result[keyPath: "targets.MASK.scaleFactor"] = nativeScale guard let technique = SCNTechnique(dictionary: result) else { fatalError("This shouldn't be happening! 🤔") } scnView.technique = technique } } else { fatalError("This shouldn't be happening! Has someone been naughty and deleted the file? 🤔") } } // Tap to set/unset the highlight @objc private func handleTap(_ gestureRecognize: UIGestureRecognizer) { // check what nodes are tapped let p = gestureRecognize.location(in: scnView) let hitResults = scnView.hitTest(p, options: [:]) // check that we clicked on at least one object guard let first = hitResults.first else { return } // Highlight it / remove highlight if first.node.categoryBitMask == highlightMaskValue { first.node.setCategoryBitMaskForAllHierarchy(normalMaskValue) } else if first.node.categoryBitMask == normalMaskValue { first.node.setCategoryBitMaskForAllHierarchy(highlightMaskValue) } else { fatalError("Unsupported category bit mask value") } } override var shouldAutorotate: Bool { return true } override var prefersStatusBarHidden: Bool { return true } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { if UIDevice.current.userInterfaceIdiom == .phone { return .allButUpsideDown } else { return .all } } } extension GameViewController { private func setupHierarchy() { dispatchPrecondition(condition: .onQueue(.main)) scnView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(scnView) scnView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true scnView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true scnView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true scnView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true // add a tap gesture recognizer let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:))) scnView.addGestureRecognizer(tapGesture) } private func setupSCNScene() { // create a new scene let scene = SCNScene(named: "art.scnassets/ship.scn")! // create and add a camera to the scene let cameraNode = SCNNode() cameraNode.camera = SCNCamera() scene.rootNode.addChildNode(cameraNode) // place the camera cameraNode.simdPosition.z = 15 // create and add a light to the scene let lightNode = SCNNode() lightNode.light = SCNLight() lightNode.light!.type = .omni lightNode.simdPosition = simd_float3(0, 10, 10) scene.rootNode.addChildNode(lightNode) // create and add an ambient light to the scene let ambientLightNode = SCNNode() ambientLightNode.light = SCNLight() ambientLightNode.light!.type = .ambient ambientLightNode.light!.color = UIColor.darkGray scene.rootNode.addChildNode(ambientLightNode) // retrieve the ship node let ship = scene.rootNode.childNode(withName: "ship", recursively: true)! // animate the 3d object ship.runAction(SCNAction.repeatForever(SCNAction.rotateBy(x: 0, y: 2, z: 0, duration: 1))) // Set its highlight ship.setCategoryBitMaskForAllHierarchy(highlightMaskValue) // set the scene to the view scnView.scene = scene // allows the user to manipulate the camera scnView.allowsCameraControl = true // show statistics such as fps and timing information scnView.showsStatistics = true // configure the view scnView.backgroundColor = UIColor.black } }
31.85443
157
0.693026
892f0f37495b0c82259e6bdecabf580ddb289267
325
// // Application.swift // Python App // // Created by Adrian Labbé on 26-05-20. // Copyright © 2020 Adrian Labbé. All rights reserved. // import Foundation @objc class Application: NSObject { // Methods shared with Python here @objc func helloWorld() -> String { return "Hello World" } }
17.105263
55
0.630769
e97fb84a9052acff85a2f13c6c51cd9b352ab449
1,724
// // AsyncImageScreen.swift // Demo // // Created by Daniel Saidi on 2020-11-26. // Copyright © 2020 Daniel Saidi. All rights reserved. // import SwiftUI struct AsyncImageScreen: View { @State private var urlString = "https://picsum.photos/200/300" @StateObject private var sheetContext = SheetContext() var body: some View { MenuList("AsyncImage") { Section { MenuListText("This view can fetch images async from urls.") } Section(header: Text("URL")) { TextField("Enter URL", text: $urlString) } Section(header: Text("Actions")) { MenuListItem(icon: .photo, title: "Load image") .button(action: loadImage) .enabled(hasUrl) } }.sheet(context: sheetContext) } } private extension AsyncImageScreen { var hasUrl: Bool { url != nil } var url: URL? { URL(string: urlString) } var spinner: some View { #if os(iOS) || os(tvOS) || os(watchOS) return CircularProgressView() #else return Text("...") #endif } func loadImage() { guard let url = url else { return } sheetContext.present( NavigationView { AsyncImage(url: url, placeholder: { spinner }) .cornerRadius(10) .padding() .navigationTitle("Image, ohoy!") } ) } } struct AsyncImageScreen_Previews: PreviewProvider { static var previews: some View { NavigationView { AsyncImageScreen() } } }
24.28169
75
0.518561
6a30f5a7e93746ed3053d88e00b84e1a19da22f3
503
// swift-tools-version:5.1 import PackageDescription let package = Package( name: "T21KeyboardState", products: [ .library( name: "T21KeyboardState", targets: ["T21KeyboardState"]), ], dependencies: [ .package(url: "https://github.com/worldline-spain/T21Notifier-iOS.git", from: "2.1.0"), ], targets: [ .target( name: "T21KeyboardState", dependencies: ["T21Notifier"], path: "./src"), ] )
22.863636
95
0.54672
64e0582e4cfede33a2e7575b45461f585a7f28cf
1,372
import SwiftUI struct CheerView: View { var body: some View { VStack { Spacer() ZStack { Circle() .fill(.orange) .frame(width: 200, height: 200) .onTapGesture { print("CLICK 2") } Text("🍺") .font(.largeTitle) ._colorMonochrome(.white) } BeverageGroup() } } } private struct BeverageGroup: View { var rows: [GridItem] = [.init(.fixed(40), spacing: 40), .init(.fixed(40), spacing: 40)] var body: some View { LazyHGrid(rows: rows, alignment: .bottom, spacing: 80) { Circle().fill(Color.gray) .frame(width: 46, height: 46) Circle().fill(Color.gray) .frame(width: 46, height: 46) Circle().fill(Color.gray) .frame(width: 46, height: 46) Circle().fill(Color.gray) .frame(width: 46, height: 46) Circle().fill(Color.gray) .frame(width: 46, height: 46) Circle().fill(Color.gray) .frame(width: 46, height: 46) } } } struct CheerView_Previews: PreviewProvider { static var previews: some View { CheerView() } }
26.901961
64
0.456268
4bb37f7eb5c65957d1e333fed1479b1e559b0aff
1,000
// // PetModelTests.swift // AllFritzTests // // Created by Christopher Kelly on 5/15/19. // Copyright © 2019 Fritz Labs Incorporated. All rights reserved. // import Foundation import FritzVisionPetSegmentationModelFast import XCTest class FritzVisionPetSegmentationModelTests: FritzTestCase { lazy var petModel = FritzVisionPetSegmentationModelFast() func testPetPrediction() { let cat = TestImage.cat.fritzImage let segmentationResult = try! petModel.predict(cat) let classesArray = segmentationResult.getArrayOfMostLikelyClasses() var total: Int32 = 0 for val in classesArray { total += val } // Total pixels below from previous run of working model. let expectedTotalCatPixels: Int32 = 21877 XCTAssertEqual(Float(expectedTotalCatPixels), Float(total), accuracy: 10.0) let expectedEvents: [SessionEvent.EventType] = [ .modelInstalled, .prediction, ] XCTAssertEqual(self.trackedEventTypes(), expectedEvents) } }
27.027027
79
0.733
187ca5258e65a1ee67a413b0f5e81b0daa67c4dd
2,059
// // FlutterNativePlugin.swift // Runner // // Created by pet on 2020/10/27. // import UIKit import Flutter class FlutterNativePlugin: NSObject, FlutterPlugin { private let kSecretKeyOfSMS = "c1bf727e20320049de30e52ada3802c7" static func register(with registrar: FlutterPluginRegistrar) { let channel = FlutterMethodChannel.init(name: "flutter_ios", binaryMessenger: registrar.messenger()) let instance = FlutterNativePlugin.init() registrar.addMethodCallDelegate(instance, channel: channel) } func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { if call.method == "func_AES256" { var resultStr : String = "" if let arguments = call.arguments as? [String : Any], let encode = arguments["encode"] as? String, let phone = arguments["phone"] as? String, let areaCode = arguments["areaCode"] as? String { resultStr = handleSecretParams(encode: encode, phone: phone, areaCode: areaCode) ?? "" } result(resultStr) }else{ result(FlutterMethodNotImplemented) } } func handleSecretParams(encode: String?, phone: String, areaCode: String) -> String? { /*然後到時後發短訊的流程就會是 1.先call 一個api, 最得加密過的([resultA]AES256) 2.前台解密 AES256 + SecretKey 解密 -> 得到resultA 3.再用SecretKey 加密成 ([resultA + Phone + "N" + AreaCode] AES256) = resultB 4.然後把這個resultB 傳到sms接口的header 中 */ guard let encode = encode else { return nil } // 做解密处理,拿到时间戳 guard let secretKey = kSecretKeyOfSMS.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else { return nil } let resultA = AES256Helper.aes256Decrypt(with: encode, key: secretKey) // 拼接成特定格式的字符串 let targetStr = "\(resultA)\(phone)N\(areaCode)" // 加密 let resultB = AES256Helper.aes256Encrypt(with: targetStr, key: secretKey) return resultB } }
36.122807
115
0.626518
7adc821885d4c1eb7322e2c4f08cc6baaa95bf9c
3,434
// // CommonViewController.swift // Flix // // Created by Pann Cherry on 4/6/22. // Copyright © 2022 Pann Cherry. All rights reserved. // import UIKit import AlamofireImage class CommonViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } func configureCustomWhiteNavigationBar(title: String) { self.navigationItem.title = title self.extendedLayoutIncludesOpaqueBars = true self.navigationController?.navigationBar.barTintColor = .white self.navigationController?.navigationBar.tintColor = .white self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.black, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 20, weight: .bold)] self.navigationController?.navigationBar.shadowImage = UIImage() self.navigationController?.view.backgroundColor = .white } func setupRegularTitleNavigationBar(title: String, font: UIFont, color: UIColor) { self.navigationItem.title = title self.navigationController?.navigationBar.prefersLargeTitles = false self.navigationController?.navigationBar.titleTextAttributes = [.foregroundColor: color, .font: font] } func setupLargeTitleNavigationBar(title: String, font: UIFont, color: UIColor) { self.navigationController?.navigationBar.prefersLargeTitles = true self.navigationItem.title = title self.navigationController?.navigationBar.largeTitleTextAttributes = [.foregroundColor: color, .font: font] } func addCutsomLeftNavigationTitle(title: String) { let titleLabel = UILabel() titleLabel.text = "\(title)" titleLabel.sizeToFit() titleLabel.textColor = .black titleLabel.font = UIFont.systemFont(ofSize: 32, weight: .bold) let leftItem = UIBarButtonItem(customView: titleLabel) self.navigationItem.leftBarButtonItem = leftItem self.navigationItem.largeTitleDisplayMode = .never } @objc func back() { self.navigationController?.popViewController(animated: true) } func leftNavigationBarCustomBackButton(imageName: String = "Back", selector: Selector = #selector(back)) { self.extendedLayoutIncludesOpaqueBars = true self.navigationController?.navigationBar.barTintColor = .white self.navigationController?.navigationBar.tintColor = .black let button = UIButton(type: UIButton.ButtonType.custom) let origImage = UIImage(named: imageName) let tintedImage = origImage?.withRenderingMode(.alwaysTemplate) button.setImage(tintedImage, for: .normal) button.addTarget(self, action: selector, for: .touchUpInside) let barButton = UIBarButtonItem(customView: button) self.navigationItem.leftBarButtonItems = [barButton] } func networkErrorAlert(title:String, message:String, completionHandler: @escaping () -> Void){ let networkErrorAlert = UIAlertController(title: "Network Error", message: "The internet connection appears to be offline. Please try again later.", preferredStyle: UIAlertController.Style.alert) networkErrorAlert.addAction(UIAlertAction(title: "Try again", style: UIAlertAction.Style.default, handler: { (action) in completionHandler() })) self.present(networkErrorAlert, animated: true, completion: nil) } }
43.468354
203
0.721025
91cefa93952b77d914c4cd655e79e31fdf487e27
1,500
// // CityViewModelTest.swift // POC_C-MVVM-RXTests // // Created by Pierre jonny cau on 21/05/2020. // Copyright © 2020 Pierre Jonny Cau. All rights reserved. // @testable import POC_C_MVVM_RX import XCTest class CityViewModelTest: XCTestCase { private let sampleJSON: [String: Location] = [ "name": Location(name: "location") ] private let location = Location(name: "Location") private var cityViewModel: CityViewModel! override func setUp() { super.setUp() cityViewModel = CityViewModel(city: location) } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func test_Name_ReturnsLocationName() { XCTAssertEqual(cityViewModel.name, "Location") } func test_InitFromJSON_AllFieldsAreCorrect() { let encoder = JSONEncoder() guard let jsonData = try? encoder.encode(sampleJSON), let viewmodel = try? JSONDecoder().decode(CityViewModel.self, from: jsonData) else { return XCTFail("Cannot decoder jsonData to CityViewModel struct") } XCTAssertEqual(viewmodel.name, "location") } func test_EqualityForEqualLocation_ReturnsTrue() { let cityViewModel1 = CityViewModel(city: Location(name: "location")) let cityViewModel2 = CityViewModel(city: Location(name: "location")) XCTAssertEqual(cityViewModel1, cityViewModel2) } }
29.411765
146
0.682
752162377ccd5ef131002b1a208778ec976e413f
2,015
// // Localizer+SwitchLanguage.swift // Localizer // // Created by Nicolas Degen on 28.08.18. // Copyright © 2018 Nicolas Degen. All rights reserved. // import Foundation extension Localizer { public class func setLanguage(languageId: String) { // TODO : Check if languageId available! UserDefaults.standard.set(languageId, forKey: currentLanguageUserDefaultsKey) // Call all registered callbacks for callback in Localizer.onLanguageDidChangeCallbackList { callback() } Localizer.overrideDeviceLanguage = true NotificationCenter.default.post(name: Notification.Name(rawValue: didSwitchLanguageNotificationKey), object: nil) } open class func availableLanguages(excludeBase: Bool = true, forBundle bundle: Bundle = mainBundle) -> Set<String> { var availableLanguages = Set<String>() if useOnlyMainBundleLanguages { mainBundle.localizations.forEach { localization in availableLanguages.insert(localization) } } else { for (bundle, _) in bundleTableHierarchy { bundle.localizations.forEach { localization in availableLanguages.insert(localization) } } } // If excludeBase = true, don't include "Base" in available languages if let indexOfBase = availableLanguages.firstIndex(of: "Base") , excludeBase == true { availableLanguages.remove(at: indexOfBase) } return availableLanguages } open class func displayNameForLanguageId(_ languageId: String) -> String { let locale = NSLocale(localeIdentifier: currentLanguage) if let displayName = locale.displayName(forKey: NSLocale.Key.identifier, value: languageId) { return displayName } return String() } open class func nativeNameForLanguageId(_ languageId: String) -> String { let locale = NSLocale(localeIdentifier: languageId) if let displayName = locale.displayName(forKey: NSLocale.Key.identifier, value: languageId) { return displayName } return String() } }
33.583333
118
0.714144
fcbec538382a960d292e84a0310d3e5a16e6fd26
2,534
// // SelectObjectTableView.swift // FilterPlayground // // Created by Leo Thomas on 09.04.18. // Copyright © 2018 Leo Thomas. All rights reserved. // import UIKit class SelectObjectTableView: UITableView, UITableViewDelegate, UITableViewDataSource { var objects: [[SelectObjectViewControllerPresentable]]! { didSet { if oldValue != nil { reloadData() } } } var sectionTitles: [String]? fileprivate var callback: ((SelectObjectViewControllerPresentable, SelectObjectTableView) -> Void)! private let cellReuseIdentifier = "reuseIdentifier" init(frame: CGRect, objects: [[SelectObjectViewControllerPresentable]], style: UITableViewStyle = .plain, callback: @escaping (SelectObjectViewControllerPresentable, SelectObjectTableView) -> Void) { self.objects = objects self.callback = callback super.init(frame: frame, style: style) delegate = self dataSource = self } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // MARK: - Table view data source func numberOfSections(in _: UITableView) -> Int { return objects.count } func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int { return objects[section].count } func tableView(_: UITableView, titleForHeaderInSection section: Int) -> String? { guard let titles = sectionTitles, titles.count > section else { return nil } return titles[section] } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) ?? UITableViewCell(style: .subtitle, reuseIdentifier: cellReuseIdentifier) let object = objects[indexPath.section][indexPath.row] cell.textLabel?.text = object.title cell.detailTextLabel?.text = object.subtitle cell.textLabel?.numberOfLines = 0 cell.imageView?.image = object.image cell.isUserInteractionEnabled = object.interactionEnabled cell.accessoryType = object.interactionEnabled ? .disclosureIndicator : .none return cell } func tableView(_: UITableView, didSelectRowAt indexPath: IndexPath) { let object = objects[indexPath.section][indexPath.row] callback(object, self) } }
33.342105
203
0.652328
fced4a82968f7b5972f67ecd5aaeebacb78b6544
346
import XCTest #if !canImport(ObjectiveC) public func allTests() -> [XCTestCaseEntry] { return [ testCase(KeychainWrapperTests.allTests), testCase(KeychainWrapperDeleteTests.allTests), testCase(KeychainWrapperPrimitiveValueTests.allTests), testCase(KeychainWrapperDefaultWrapperTests.allTests), ] } #endif
26.615385
62
0.736994
e243502d1b19625bfe1b229607f53e1a0b347a73
7,156
// // UIActivity+FBSDKSharing.swift // ARFacebookShareKitActivity // // Created by alexruperez on 2/6/16. // Copyright © 2016 CocoaPods. All rights reserved. // import FBSDKShareKit fileprivate extension DispatchQueue { private static var _onceTracker = [String]() class func once(token: String, block:()->Void) { objc_sync_enter(self); defer { objc_sync_exit(self) } if _onceTracker.contains(token) { return } _onceTracker.append(token) block() } } public extension UIActivity { fileprivate struct AssociatedKeys { static var ActivityContent = "ar_ActivityContent" } var activityContent: FBSDKCopying? { get { return objc_getAssociatedObject(self, &AssociatedKeys.ActivityContent) as? FBSDKCopying } set { if let newValue = newValue { objc_setAssociatedObject( self, &AssociatedKeys.ActivityContent, newValue as FBSDKCopying?, .OBJC_ASSOCIATION_RETAIN_NONATOMIC ) } } } private static let _onceToken = NSUUID().uuidString public class func replaceFacebookSharing() { let klass: AnyClass = NSClassFromString("UISoc"+"ialAct"+"ivity")! if self != klass { return } DispatchQueue.once(token: _onceToken) { ARSwizzleInstanceMethod(klass, originalSelector: #selector(UIActivity.prepare(withActivityItems:)), swizzledSelector: #selector(UIActivity.ar_prepare(withActivityItems:))) ARSwizzleInstanceMethod(klass, originalSelector: #selector(UIActivity.canPerform(withActivityItems:)), swizzledSelector: #selector(UIActivity.ar_canPerform(withActivityItems:))) ARSwizzleInstanceMethod(klass, originalSelector: Selector("UIActivity.perform"), swizzledSelector: #selector(UIActivity.ar_perform)) } } private static func ar_defaultFacebookActivityType() -> UIActivityType? { struct Static { static var token: Int = 0 static var activityType: UIActivityType? = nil } DispatchQueue.once(token: _onceToken) { Static.activityType = UIActivityType(["com", "apple", "UIKit", "activity", "PostToFacebook"].joined(separator: ".")) } return Static.activityType } private static func ar_canShowFacebookShareDialog() -> Bool { return FBSDKShareDialog().canShow() } private static func ar_canShowFacebookAppInviteDialog() -> Bool { return FBSDKAppInviteDialog().canShow() } private func ar_canUseFacebookActivityOverride() -> Bool { return activityType == type(of: self).ar_defaultFacebookActivityType() && (type(of: self).ar_canShowFacebookShareDialog() || type(of: self).ar_canShowFacebookAppInviteDialog()) } @objc func ar_canPerform(withActivityItems activityItems: [Any]) -> Bool { return ar_canUseFacebookActivityOverride() || ar_canPerform(withActivityItems:activityItems) } @objc func ar_prepare(withActivityItems activityItems: [AnyObject]) { if !ar_canUseFacebookActivityOverride() { ar_prepare(withActivityItems:activityItems) return } var sharedURL: URL? = nil var sharedText: String? = nil for itemSource in activityItems { var item: AnyObject? = nil if itemSource.conforms(to: UIActivityItemSource.self) { if let activityType = activityType { item = (itemSource as? UIActivityItemSource)?.activityViewController(activityViewController as! UIActivityViewController, itemForActivityType: activityType) as AnyObject? } } else { item = itemSource } if let item = item as? URL { sharedURL = item } else if let item = item as? String { sharedText = item } } if sharedURL == nil && sharedText == nil { activityDidFinish(false) return } var isAppInvite = false if let sharedURL = sharedURL { if let branchUniversalLinkDomains = Bundle.main.infoDictionary?["branch_universal_link_domains"] { if let oneDomain = branchUniversalLinkDomains as? String { if sharedURL.host?.contains(oneDomain) == true { isAppInvite = true } } else if let branchUniversalLinkDomains = branchUniversalLinkDomains as? [String] { for oneDomain: String in branchUniversalLinkDomains { if sharedURL.host?.contains(oneDomain) == true { isAppInvite = true } } } } let branchDomains = ["bnc.lt", "app.link", "test-app.link"] for oneDomain in branchDomains { if sharedURL.host?.contains(oneDomain) == true { isAppInvite = true } } } if isAppInvite { let appInviteContent = FBSDKAppInviteContent() appInviteContent.promotionText = sharedText appInviteContent.appLinkURL = sharedURL activityContent = appInviteContent } else { let linkContent = FBSDKShareLinkContent() linkContent.quote = sharedText linkContent.contentURL = sharedURL activityContent = linkContent } } @objc func ar_perform() { if !ar_canUseFacebookActivityOverride() { ar_perform() return } if activityContent == nil { activityDidFinish(false) return } if let activityContent = activityContent as? FBSDKAppInviteContent { FBSDKAppInviteDialog.show(from: activityViewController, with: activityContent, delegate: self) } else if let activityContent = activityContent as? FBSDKSharingContent { FBSDKShareDialog.show(from: activityViewController, with: activityContent, delegate: self) } } private static func ARSwizzleInstanceMethod(_ klass: AnyClass, originalSelector: Selector, swizzledSelector: Selector) { let originalMethod = class_getInstanceMethod(klass, originalSelector) let swizzledMethod = class_getInstanceMethod(klass, swizzledSelector) let didAddMethod = class_addMethod(klass, originalSelector, method_getImplementation(swizzledMethod!), method_getTypeEncoding(swizzledMethod!)) if didAddMethod { class_replaceMethod(klass, swizzledSelector, method_getImplementation(originalMethod!), method_getTypeEncoding(originalMethod!)) } else { method_exchangeImplementations(originalMethod!, swizzledMethod!) } } }
36.697436
190
0.607183
d52ec0b22361a6a8f6b88500eec852a1a18a69f8
1,504
// SPDX-License-Identifier: MIT // Copyright © 2018-2019 WireGuard LLC. All Rights Reserved. import Foundation import os.log extension FileManager { static var appGroupId: String? { #if os(iOS) let appGroupIdInfoDictionaryKey = "com.wireguard.ios.app_group_id" #elseif os(macOS) let appGroupIdInfoDictionaryKey = "com.wireguard.macos.app_group_id" #else #error("Unimplemented") #endif return Bundle.main.object(forInfoDictionaryKey: appGroupIdInfoDictionaryKey) as? String } private static var sharedFolderURL: URL? { guard let appGroupId = FileManager.appGroupId else { os_log("Cannot obtain app group ID from bundle", log: OSLog.default, type: .error) return nil } guard let sharedFolderURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroupId) else { wg_log(.error, message: "Cannot obtain shared folder URL") return nil } return sharedFolderURL } static var logFileURL: URL? { return sharedFolderURL?.appendingPathComponent("tunnel-log.bin") } static var networkExtensionLastErrorFileURL: URL? { return sharedFolderURL?.appendingPathComponent("last-error.txt") } static func deleteFile(at url: URL) -> Bool { do { try FileManager.default.removeItem(at: url) } catch { return false } return true } }
32
126
0.652261
7570f325e789579e85c29edea9f7d7fcfae1fe2e
3,524
// // ImportableObject.swift // CoreStore // // Copyright © 2015 John Rommel Estropia // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation import CoreData // MARK: - ImportableObject /** `NSManagedObject` subclasses that conform to the `ImportableObject` protocol can be imported from a specified `ImportSource`. This allows transactions to create and insert instances this way: ``` class MyPersonEntity: NSManagedObject, ImportableObject { typealias ImportSource = NSDictionary // ... } CoreStore.beginAsynchronous { (transaction) -> Void in let json: NSDictionary = // ... let person = try! transaction.importObject( Into(MyPersonEntity), source: json ) // ... transaction.commit() } ``` */ public protocol ImportableObject: class { /** The data type for the import source. This is most commonly an `NSDictionary` or another external source such as an `NSUserDefaults`. */ associatedtype ImportSource /** Return `true` if an object should be created from `source`. Return `false` to ignore and skip `source`. The default implementation returns `true`. - parameter source: the object to import from - parameter transaction: the transaction that invoked the import. Use the transaction to fetch or create related objects if needed. - returns: `true` if an object should be created from `source`. Return `false` to ignore. */ static func shouldInsertFromImportSource(source: ImportSource, inTransaction transaction: BaseDataTransaction) -> Bool /** Implements the actual importing of data from `source`. Implementers should pull values from `source` and assign them to the receiver's attributes. Note that throwing from this method will cause subsequent imports that are part of the same `importObjects(:sourceArray:)` call to be cancelled. - parameter source: the object to import from - parameter transaction: the transaction that invoked the import. Use the transaction to fetch or create related objects if needed. */ func didInsertFromImportSource(source: ImportSource, inTransaction transaction: BaseDataTransaction) throws } // MARK: - ImportableObject (Default Implementations) public extension ImportableObject { static func shouldInsertFromImportSource(source: ImportSource, inTransaction transaction: BaseDataTransaction) -> Bool { return true } }
40.976744
296
0.73042
90488fade2a3dd71b55e29284a1376bd05e972f4
353
import Parsing extension NotesDoc { /// Parses a ``NotesDoc`` from a ``Substring`` /// - Returns: The ``Parser`` static func parser() -> AnyParser<TextDocument, NotesDoc> { Parse(NotesDoc.init(items:)) { blankDocLines DocLine("Notes:") List.parser() } .eraseToAnyParser() } }
23.533333
63
0.546742
91a47439dbb0ee2ada81c8a5272c99b194f651e0
1,906
// swift-tools-version:5.5 //===----------------------------------------------------------*- swift -*-===// // // This source file is part of the Swift Argument Parser open source project // // Copyright (c) 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // //===----------------------------------------------------------------------===// import PackageDescription let package = Package( name: "swift-argument-parser", platforms: [.macOS(.v10_15)], products: [ .library( name: "ArgumentParser", targets: ["ArgumentParser"]), ], dependencies: [], targets: [ .target( name: "ArgumentParser", dependencies: ["ArgumentParserToolInfo"], exclude: ["CMakeLists.txt"]), .target( name: "ArgumentParserTestHelpers", dependencies: ["ArgumentParser", "ArgumentParserToolInfo"], exclude: ["CMakeLists.txt"]), .target( name: "ArgumentParserToolInfo", dependencies: [], exclude: ["CMakeLists.txt"]), .testTarget( name: "ArgumentParserEndToEndTests", dependencies: ["ArgumentParser", "ArgumentParserTestHelpers"], exclude: ["CMakeLists.txt"]), .testTarget( name: "ArgumentParserUnitTests", dependencies: ["ArgumentParser", "ArgumentParserTestHelpers"], exclude: ["CMakeLists.txt"]), .testTarget( name: "ArgumentParserPackageManagerTests", dependencies: ["ArgumentParser", "ArgumentParserTestHelpers"], exclude: ["CMakeLists.txt"]), .testTarget( name: "ArgumentParserExampleTests", dependencies: ["ArgumentParserTestHelpers"]), ] )
34.654545
80
0.551941
1e0d2d9951cbf01af9c1384d69ad23af5312a663
2,668
// // FeatureViewoutView.swift // Module.X.Demo // // Created by Valery Top on 21.11.2021. // import Foundation import UIKit import TopModule class FeatureViewoutView: UIView, AtomViewProtocol { var atomViewModel: AnyViewModel<FeatureViewoutSenses.ViewSense, FeatureViewoutSenses.ViewModelSense>? var sendToViewModel = Sender<FeatureViewoutSenses.ViewSense>() // Viewout private let colorView = UIView() // Action private let prevoiusButton = UIButton() private let nextButton = UIButton() func sensor(iSense: FeatureViewoutSenses.ViewModelSense) { switch iSense { case .changeColor(let counterColors): changeColor(number: counterColors) case .setupViews: setupViews() configureViews() } } private func changeColor(number: Int) { let colors: [UIColor] = [.black, .white, .green, .red, .yellow] colorView.backgroundColor = colors[number] } private func configureViews() { // Viewout colorView.backgroundColor = .black // Action prevoiusButton.backgroundColor = .black prevoiusButton.setTitle("<-", for: .normal) prevoiusButton.addTarget(self, action: #selector(previousButtonAction), for: .touchUpInside) // Action nextButton.backgroundColor = .black nextButton.setTitle("->", for: .normal) nextButton.addTarget(self, action: #selector(nextButtonAction), for: .touchUpInside) } private func setupViews() { addSubview(prevoiusButton) prevoiusButton.snp.makeConstraints { $0.top.equalToSuperview() $0.left.equalToSuperview() $0.height.equalTo(20) $0.width.equalTo(40) } addSubview(nextButton) nextButton.snp.makeConstraints { $0.top.equalToSuperview() $0.left.equalTo(prevoiusButton.snp.right).offset(50) $0.right.equalToSuperview() $0.height.equalTo(20) $0.width.equalTo(40) } addSubview(colorView) colorView.snp.makeConstraints { $0.top.equalTo(nextButton.snp.bottom).offset(30) $0.bottom.equalToSuperview() $0.centerX.equalToSuperview() $0.height.width.equalTo(50) } } // Action @objc private func previousButtonAction() { sendToViewModel.express(.clickPreviousFromViewout) } // Action @objc private func nextButtonAction() { sendToViewModel.express(.clickNextFromViewout) } }
28.382979
105
0.610945
c189d76e19ac6f64369ee3569fa94b177ac96523
437
// // StringUtils.swift // MonTransit // // Created by Thibault on 16-01-18. // Copyright © 2016 Thibault. All rights reserved. // import Foundation extension String { func trunc(length: Int, trailing: String? = ".") -> String { if self.characters.count > length { return self.substringToIndex(self.startIndex.advancedBy(length)) + (trailing ?? "") } else { return self } } }
23
95
0.601831
2378ff27e626d7a42f433edcc0dba942e464f24d
2,679
// // LoginViewController.swift // SwiftUIApp // // Created by Alexey Naumov on 13.09.2020. // Copyright © 2020 Alexey Naumov. All rights reserved. // import SwiftUI import UIKit import Combine class LoginViewController: UIHostingController<LoginView> { private let viewModel: LoginViewModel init(viewModel: LoginViewModel) { self.viewModel = viewModel super.init(rootView: LoginView(viewModel: viewModel)) } @objc required dynamic init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - View struct LoginView: View { @ObservedObject var viewModel: LoginViewModel var body: some View { VStack { Text(viewModel.textIO.message) .font(.footnote) .multilineTextAlignment(.center) .padding(10) if viewModel.progress.status.isLoading { ProgressView() .padding(10) Button(action: { self.viewModel.cancelLoading() }, label: { Text(viewModel.loginButton.title) }) } else { TextField(viewModel.textIO.loginTitle, text: $viewModel.textIO.login) .modifier(TextFieldAppearance()) TextField(viewModel.textIO.passwordTitle, text: $viewModel.textIO.password) .modifier(TextFieldAppearance()) Button(action: { self.viewModel.authenticate() }, label: { Text(viewModel.loginButton.title) .foregroundColor(Color(.systemBackground)) }) .frame(maxWidth: .infinity) .padding(EdgeInsets(top: 2, leading: 4, bottom: 2, trailing: 4)) .background( RoundedRectangle(cornerRadius: 4) .fill(Color(viewModel.loginButton.isEnabled ? .systemBlue : .systemGray))) .disabled(!viewModel.loginButton.isEnabled) } } .frame(width: 200) } } extension LoginView { struct TextFieldAppearance: ViewModifier { func body(content: Content) -> some View { content .padding(EdgeInsets(top: 2, leading: 4, bottom: 2, trailing: 4)) .background( RoundedRectangle(cornerRadius: 4) .stroke(Color(.separator), lineWidth: 1)) } } } // MARK: - Preview struct LoginView_Previews: PreviewProvider { static var previews: some View { LoginView(viewModel: .init(container: FakeLoginStageContainer())) } }
31.892857
102
0.571109
acd12383ba0ddd7ae35d0b6e852f75f4c4a87136
519
// // Restaurant.swift // PatternsExample // // Created by Yaroslav Voloshyn on 18/03/2017. // Copyright © 2017 voloshynslavik. All rights reserved. // final class Restaurant { let name: String var orderSoupCalback: (() -> Void)? init(name: String) { self.name = name } func orderSoup() { print("Order soup") self.orderSoupCalback?() } } extension Restaurant: VisitorHandler { func visit(visitor: Visitor) { visitor.visitRestaurant(self) } }
15.727273
57
0.61657
4abf35ec75dae7d4fefa0fa12c05f76765f87e5c
447
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck extension{protocol c{struct c{let e={enum T{case
44.7
79
0.758389
2215fbe3fe474f98cd80f44a683095fb6348368c
5,945
// Copyright (c) 2015-2016 David Turnbull // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and/or associated documentation files (the // "Materials"), to deal in the Materials without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Materials, and to // permit persons to whom the Materials are 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 Materials. // // THE MATERIALS ARE 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 // MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. public struct Vector4b : BooleanVectorType, Hashable { public typealias BooleanVector = Vector4b public var x:Bool, y:Bool, z:Bool, w:Bool public var r:Bool { get {return x} set {x = newValue} } public var g:Bool { get {return y} set {y = newValue} } public var b:Bool { get {return z} set {z = newValue} } public var a:Bool { get {return w} set {w = newValue} } public var s:Bool { get {return x} set {x = newValue} } public var t:Bool { get {return y} set {y = newValue} } public var p:Bool { get {return z} set {z = newValue} } public var q:Bool { get {return w} set {w = newValue} } public var elements: [Bool] { return [x, y, z, w] } public func makeIterator() -> IndexingIterator<Array<Bool>> { return elements.makeIterator() } public subscript(index: Int) -> Bool { get { switch(index) { case 0: return x case 1: return y case 2: return z case 3: return w default: preconditionFailure("Vector index out of range") } } set { switch(index) { case 0: x = newValue case 1: y = newValue case 2: z = newValue case 3: w = newValue default: preconditionFailure("Vector index out of range") } } } public var debugDescription: String { return String(describing: type(of:self)) + "(\(x), \(y), \(z), \(w))" } // public var hashValue: Int { // return SGLMath.hash(x.hashValue, y.hashValue, z.hashValue, w.hashValue) // } public func hash(into hasher: inout Hasher) { hasher.combine(x) hasher.combine(y) hasher.combine(z) hasher.combine(w) } public init () { self.x = false self.y = false self.z = false self.w = false } public init (_ v:Bool) { self.x = v self.y = v self.z = v self.w = v } public init (_ x:Bool, _ y:Bool, _ z:Bool, _ w:Bool) { self.x = x self.y = y self.z = z self.w = w } public init(_ v:Vector3b, _ w:Bool) { self.x = v.x self.y = v.y self.z = v.z self.w = w } public init (_ x:Bool, _ v:Vector3b) { self.x = x self.y = v.x self.z = v.y self.w = v.z } public init (_ v:Vector2b, _ z:Bool, _ w:Bool) { self.x = v.x self.y = v.y self.z = z self.w = w } public init (_ x:Bool, _ y:Bool, _ v:Vector2b) { self.x = x self.y = y self.z = v.x self.w = v.y } public init (_ x:Bool, _ v:Vector2b, _ w:Bool) { self.x = x self.y = v.x self.z = v.y self.w = w } public init (_ v1:Vector2b, _ v2:Vector2b) { self.x = v1.x self.y = v1.y self.z = v2.x self.w = v2.y } public init (x:Bool, y:Bool, z:Bool, w:Bool) { self.x = x self.y = y self.z = z self.w = w } public init (r:Bool, g:Bool, b:Bool, a:Bool) { self.x = r self.y = g self.z = b self.w = a } public init (s:Bool, t:Bool, p:Bool, q:Bool) { self.x = s self.y = t self.z = p self.w = q } public init (_ v:Vector4b) { self.x = v.x self.y = v.y self.z = v.z self.w = v.w } public init (_ s:Bool, _ v:Vector4b, _ op:(_:Bool, _:Bool) -> Bool) { self.x = op(s, v.x) self.y = op(s, v.y) self.z = op(s, v.z) self.w = op(s, v.w) } public init (_ v:Vector4b, _ s:Bool, _ op:(_:Bool, _:Bool) -> Bool) { self.x = op(v.x, s) self.y = op(v.y, s) self.z = op(v.z, s) self.w = op(v.w, s) } public init(_ v: Vector4b, _ op:(_:Bool) -> Bool) { self.x = op(v[0]) self.y = op(v[1]) self.z = op(v[2]) self.w = op(v[3]) } public init<T:VectorType>(_ v: T, _ op:(_:T.Element) -> Bool) where T.BooleanVector == BooleanVector { self.x = op(v[0]) self.y = op(v[1]) self.z = op(v[2]) self.w = op(v[3]) } public init<T1:VectorType, T2:VectorType>(_ v1:T1, _ v2:T2, _ op:(_:T1.Element, _:T2.Element) -> Bool) where T1.BooleanVector == BooleanVector, T2.BooleanVector == BooleanVector { self.x = op(v1[0], v2[0]) self.y = op(v1[1], v2[1]) self.z = op(v1[2], v2[2]) self.w = op(v1[3], v2[3]) } public static func ==(v1: Vector4b, v2: Vector4b) -> Bool { return v1.x == v2.x && v1.y == v2.y && v1.z == v2.z && v1.w == v2.w } }
27.651163
112
0.531203
39505459e0a483b910353b15dc4dc389162c05fb
2,419
import Foundation // Bunch of Danger runtime util funcs public enum Runtime { public static let supportedPaths = [ "Dangerfile.swift", "Danger.swift", "danger/Dangerfile.swift", "Danger/Dangerfile.swift" ] /// Finds a Dangerfile from the current working directory public static func getDangerfile() -> String? { supportedPaths.first { FileManager.default.fileExists(atPath: $0) } } /// Is this a dev build: e.g. running inside a cloned danger/danger-swift public static let potentialLibraryFolders = [ ".build/debug", // Working in Xcode / CLI ".build/x86_64-unknown-linux/debug", // Danger Swift's CI ".build/release", // Testing prod "/usr/local/lib/danger" // Homebrew installs lib stuff to here ] /// Finds a path to add at runtime to the compiler, which links /// to the library Danger public static func getLibDangerPath() -> String? { let fileManager = FileManager.default // Was danger-swift installed via marathon? // e.g "~/.marathon/Scripts/Temp/https:--github.com-danger-danger-swift.git/clone/.build/release" let marathonDangerDLDir = NSHomeDirectory() + "/.marathon/Scripts/Temp/" let marathonScripts = try? fileManager.contentsOfDirectory(atPath: marathonDangerDLDir) var depManagerDangerLibPaths: [String] = [] if marathonScripts != nil { // TODO: Support running from a fork? let dangerSwiftPath = marathonScripts!.first { $0.contains("danger-swift") } if dangerSwiftPath != nil { let path = marathonDangerDLDir + dangerSwiftPath! + "/clone/.build/release" depManagerDangerLibPaths.append(path) } } // Check and find where we can link to libDanger from let libPaths = potentialLibraryFolders + depManagerDangerLibPaths func isTheDangerLibPath(path: String) -> Bool { fileManager.fileExists(atPath: path + "/libDanger.dylib") || // OSX fileManager.fileExists(atPath: path + "/libDanger.so") // Linux } guard let path = libPaths.first(where: isTheDangerLibPath) else { return nil } // Always return an absolute path if path.starts(with: "/") { return path } return fileManager.currentDirectoryPath + "/" + path } }
37.796875
105
0.63332
91eb670b885499594570dc5c0383f5a2462058a9
3,812
/*: ## App Exercise - Workout Types >These exercises reinforce Swift concepts in the context of a fitness tracking app. You fitness tracking app may allow users to track different kinds of workouts. When architecting the app, you may decide to have a `Workout` base class from which other types of workout classes inherit. Below are three classes. `Workout` is the base class with `time` and `distance` properties, and `Run` and `Swim` are subclasses that add more specific properties to the `Workout` class. Also provided is a `workouts` array that represents a log of past workouts. You'll use these classes and the array for the exercises below. */ class Workout { let time: Double let distance: Double init(time: Double, distance: Double) { self.time = time self.distance = distance } } class Run: Workout { let cadence: Double init(cadence: Double, time: Double, distance: Double) { self.cadence = cadence super.init(time: time, distance: distance) } } class Swim: Workout { let stroke: String init(stroke: String, time: Double, distance: Double) { self.stroke = stroke super.init(time: time, distance: distance) } } var workouts: [Workout] = [ Run(cadence: 80, time: 1200, distance: 4000), Swim(stroke: "Freestyle", time: 32.1, distance: 50), Swim(stroke: "Butterfly", time: 36.8, distance: 50), Swim(stroke: "Freestyle", time: 523.6, distance: 500), Run(cadence: 90, time: 358.9, distance: 1600) ] /*: Write simple functions called `describeRun(runningWorkout:)` and `describeSwim(swimmingWorkout:)` that take a `Run` object and a `Swim` object, respectively. Neither should return values. Each function should print a description of the workout, including the run's cadence or the swim's stroke. Time is represented in seconds, distance is represented in meters, and cadence is represented in steps per minute. */ func describeRun(runningWorkout: Run) { let str = "Activity: Run\nCadence: \(runningWorkout.cadence)\tTime (Seconds): \(runningWorkout.time)\tDistance (in meters): \(runningWorkout.distance)" print(str) } func describeSwim(swimmingWorkout: Swim) { let str = "Activity: Swim\nStroke: \(swimmingWorkout.stroke)\tTime (Seconds): \(swimmingWorkout.time)\tDistance (in meters): \(swimmingWorkout.distance)" print(str) } /*: Now loop through each workout in `workouts` and, using type casting, call either `describeRun(runningWorkout:)` or `describeSwim(swimmingWorkout:)` on each. Observe what is printed to the console. */ workouts.forEach { el in if let obj = el as? Run { describeRun(runningWorkout: obj) } } /*: _Copyright © 2018 Apple Inc._ _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._ */ //: [Previous](@previous) | page 2 of 2
46.487805
463
0.731375
d78a7ee124d4387affde680d93f1c89ad50edbbd
479
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck import a enum S<f{class B<I{ let i{struct A:OptionSetType{struct B<a where I.e:a
39.916667
79
0.753653
16f682c7fce136e70a1ec88adbaec349d5743e4d
409
// Copyright 2017-2020 Fitbit, Inc // SPDX-License-Identifier: Apache-2.0 // // AppDelegate.swift // GoldenGateHost-macOS // // Created by Marcel Jackwerth on 4/4/18. // import Cocoa import Foundation @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { func applicationWillFinishLaunching(_ notification: Notification) { Component.instance.nodeSimulator.start() } }
21.526316
71
0.740831
9142c9bdfaea9befb11c67a1fe9ad8eed8f0afb8
11,613
import XCTest @testable import fearless import SoraKeystore import Cuckoo import RobinHood import IrohaCrypto import SoraFoundation import BigInt class StakingMainTests: XCTestCase { func testNominatorStateSetup() throws { // given let settings = InMemorySettingsManager() let keychain = InMemoryKeychain() try AccountCreationHelper.createAccountFromMnemonic(cryptoType: .sr25519, networkType: .westend, keychain: keychain, settings: settings) let storageFacade = SubstrateStorageTestFacade() let operationManager = OperationManager() let eventCenter = MockEventCenterProtocol().applyingDefaultStub() let view = MockStakingMainViewProtocol() let wireframe = MockStakingMainWireframeProtocol() let providerFactory = SingleValueProviderFactoryStub.westendNominatorStub() let calculatorService = RewardCalculatorServiceStub(engine: WestendStub.rewardCalculator) let runtimeCodingService = try RuntimeCodingServiceStub.createWestendService() let eraValidatorService = EraValidatorServiceStub.westendStub() let primitiveFactory = WalletPrimitiveFactory(settings: settings) let viewModelFacade = StakingViewModelFacade(primitiveFactory: primitiveFactory) let analyticsRewardsViewModelFactoryBuilder: AnalyticsRewardsViewModelFactoryBuilder = { chain, balance in AnalyticsRewardsViewModelFactory( chain: chain, balanceViewModelFactory: balance, amountFormatterFactory: AmountFormatterFactory(), asset: primitiveFactory.createAssetForAddressType(chain.addressType), calendar: .init(identifier: .gregorian) ) } let stateViewModelFactory = StakingStateViewModelFactory( primitiveFactory: primitiveFactory, analyticsRewardsViewModelFactoryBuilder: analyticsRewardsViewModelFactoryBuilder, logger: Logger.shared ) let networkViewModelFactory = NetworkInfoViewModelFactory(primitiveFactory: primitiveFactory) let dataValidatingFactory = StakingDataValidatingFactory(presentable: wireframe) let presenter = StakingMainPresenter(stateViewModelFactory: stateViewModelFactory, networkInfoViewModelFactory: networkViewModelFactory, viewModelFacade: viewModelFacade, dataValidatingFactory: dataValidatingFactory, logger: Logger.shared) let substrateProviderFactory = SubstrateDataProviderFactory(facade: storageFacade, operationManager: operationManager) let operationFactory = MockNetworkStakingInfoOperationFactoryProtocol() let accountRepository: CoreDataRepository<AccountItem, CDAccountItem> = UserDataStorageTestFacade().createRepository() let anyAccountRepository = AnyDataProviderRepository(accountRepository) let accountRepositoryFactory = AccountRepositoryFactory( storageFacade: UserDataStorageFacade.shared, operationManager: OperationManagerFacade.sharedManager, logger: Logger.shared ) let eraCountdownOperationFactory = EraCountdownOperationFactoryStub(eraCountdown: .testStub) let interactor = StakingMainInteractor(providerFactory: providerFactory, substrateProviderFactory: substrateProviderFactory, accountRepositoryFactory: accountRepositoryFactory, settings: settings, eventCenter: eventCenter, primitiveFactory: primitiveFactory, eraValidatorService: eraValidatorService, calculatorService: calculatorService, runtimeService: runtimeCodingService, accountRepository: anyAccountRepository, operationManager: operationManager, eraInfoOperationFactory: operationFactory, applicationHandler: ApplicationHandler(), eraCountdownOperationFactory: eraCountdownOperationFactory, logger: Logger.shared) presenter.view = view presenter.wireframe = wireframe presenter.interactor = interactor interactor.presenter = presenter dataValidatingFactory.view = view // when let accountExpectation = XCTestExpectation() let nominatorStateExpectation = XCTestExpectation() let chainExpectation = XCTestExpectation() let networkStakingInfoExpectation = XCTestExpectation() let networkStakingInfoExpandedExpectation = XCTestExpectation() stub(operationFactory) { stub in when(stub).networkStakingOperation().then { _ in CompoundOperationWrapper.createWithResult( NetworkStakingInfo( totalStake: BigUInt.zero, minStakeAmongActiveNominators: BigUInt.zero, minimalBalance: BigUInt.zero, activeNominatorsCount: 0, lockUpPeriod: 0 ) ) } } stub(view) { stub in stub.didReceive(viewModel: any()).then { _ in accountExpectation.fulfill() } stub.didReceiveChainName(chainName: any()).then { _ in chainExpectation.fulfill() } stub.didRecieveNetworkStakingInfo(viewModel: any()).then { _ in networkStakingInfoExpectation.fulfill() } stub.didReceiveStakingState(viewModel: any()).then { state in if case .nominator = state { nominatorStateExpectation.fulfill() } } stub.expandNetworkInfoView(any()).then { _ in networkStakingInfoExpandedExpectation.fulfill() } } presenter.setup() // prepare and save stash account and that should allow to resolve state to nominator by state machine let stashAccountId = WestendStub.ledgerInfo.item!.stash let stash = try SS58AddressFactory().addressFromAccountId(data: stashAccountId, type: .genericSubstrate) let controller = settings.selectedAccount!.address let stashItem = StashItem(stash: stash, controller: controller) let repository: CoreDataRepository<StashItem, CDStashItem> = storageFacade.createRepository() let saveStashItemOperation = repository.saveOperation( { [stashItem] }, { [] }) DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(100)) { operationManager.enqueue(operations: [saveStashItemOperation], in: .transient) } // then let expectations = [ accountExpectation, nominatorStateExpectation, chainExpectation, networkStakingInfoExpectation, networkStakingInfoExpandedExpectation ] wait(for: expectations, timeout: 5) } func testManageStakingBalanceAction() { // given let options: [StakingManageOption] = [ .stakingBalance, .pendingRewards, .changeValidators(count: 16) ] let wireframe = MockStakingMainWireframeProtocol() let showStakingBalanceExpectation = XCTestExpectation() stub(wireframe) { stub in when(stub).showStakingBalance(from: any()).then { _ in showStakingBalanceExpectation.fulfill() } } // when let presenter = performStakingManageTestSetup(for: wireframe) presenter.modalPickerDidSelectModelAtIndex(0, context: options as NSArray) // then wait(for: [showStakingBalanceExpectation], timeout: Constants.defaultExpectationDuration) } func testManageStakingValidatorsAction() { // given let options: [StakingManageOption] = [ .stakingBalance, .pendingRewards, .changeValidators(count: 16) ] let wireframe = MockStakingMainWireframeProtocol() let showValidatorsExpectation = XCTestExpectation() stub(wireframe) { stub in when(stub).showNominatorValidators(from: any()).then { _ in showValidatorsExpectation.fulfill() } } // when let presenter = performStakingManageTestSetup(for: wireframe) presenter.modalPickerDidSelectModelAtIndex(2, context: options as NSArray) // then wait(for: [showValidatorsExpectation], timeout: Constants.defaultExpectationDuration) } private func performStakingManageTestSetup( for wireframe: StakingMainWireframeProtocol ) -> StakingMainPresenter { let interactor = StakingMainInteractorInputProtocolStub() let settings = InMemorySettingsManager() let primitiveFactory = WalletPrimitiveFactory(settings: settings) let viewModelFacade = StakingViewModelFacade(primitiveFactory: primitiveFactory) let analyticsRewardsViewModelFactoryBuilder: AnalyticsRewardsViewModelFactoryBuilder = { chain, balance in AnalyticsRewardsViewModelFactory( chain: chain, balanceViewModelFactory: balance, amountFormatterFactory: AmountFormatterFactory(), asset: primitiveFactory.createAssetForAddressType(chain.addressType), calendar: .init(identifier: .gregorian) ) } let stateViewModelFactory = StakingStateViewModelFactory( primitiveFactory: primitiveFactory, analyticsRewardsViewModelFactoryBuilder: analyticsRewardsViewModelFactoryBuilder, logger: nil ) let networkViewModelFactory = NetworkInfoViewModelFactory(primitiveFactory: primitiveFactory) let dataValidatingFactory = StakingDataValidatingFactory(presentable: wireframe) let presenter = StakingMainPresenter( stateViewModelFactory: stateViewModelFactory, networkInfoViewModelFactory: networkViewModelFactory, viewModelFacade: viewModelFacade, dataValidatingFactory: dataValidatingFactory, logger: nil ) presenter.wireframe = wireframe presenter.interactor = interactor presenter.didReceive(newChain: .westend) presenter.didReceive(stashItem: StashItem(stash: WestendStub.address, controller: WestendStub.address)) presenter.didReceive(ledgerInfo: WestendStub.ledgerInfo.item) presenter.didReceive(nomination: WestendStub.nomination.item) return presenter } }
42.076087
114
0.620598
799e257924dc8a321599042cdc73acb6f920055e
17,365
// // UserAPI.swift // // Generated by openapi-generator // https://openapi-generator.tech // import Foundation #if canImport(AnyCodable) import AnyCodable #endif open class UserAPI { /** Create user - parameter body: (body) Created user object - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ @discardableResult open class func createUser(body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result<Void, ErrorResponse>) -> Void)) -> URLSessionTask? { return createUserWithRequestBuilder(body: body).execute(apiResponseQueue) { result in switch result { case .success: completion(.success(())) case let .failure(error): completion(.failure(error)) } } } /** Create user - POST /user - This can only be done by the logged in user. - parameter body: (body) Created user object - returns: RequestBuilder<Void> */ open class func createUserWithRequestBuilder(body: User) -> RequestBuilder<Void> { let localVariablePath = "/user" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ : ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) let localVariableRequestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** Creates list of users with given input array - parameter body: (body) List of user object - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ @discardableResult open class func createUsersWithArrayInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result<Void, ErrorResponse>) -> Void)) -> URLSessionTask? { return createUsersWithArrayInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result in switch result { case .success: completion(.success(())) case let .failure(error): completion(.failure(error)) } } } /** Creates list of users with given input array - POST /user/createWithArray - parameter body: (body) List of user object - returns: RequestBuilder<Void> */ open class func createUsersWithArrayInputWithRequestBuilder(body: [User]) -> RequestBuilder<Void> { let localVariablePath = "/user/createWithArray" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ : ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) let localVariableRequestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** Creates list of users with given input array - parameter body: (body) List of user object - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ @discardableResult open class func createUsersWithListInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result<Void, ErrorResponse>) -> Void)) -> URLSessionTask? { return createUsersWithListInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result in switch result { case .success: completion(.success(())) case let .failure(error): completion(.failure(error)) } } } /** Creates list of users with given input array - POST /user/createWithList - parameter body: (body) List of user object - returns: RequestBuilder<Void> */ open class func createUsersWithListInputWithRequestBuilder(body: [User]) -> RequestBuilder<Void> { let localVariablePath = "/user/createWithList" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ : ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) let localVariableRequestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** Delete user - parameter username: (path) The name that needs to be deleted - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ @discardableResult open class func deleteUser(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result<Void, ErrorResponse>) -> Void)) -> URLSessionTask? { return deleteUserWithRequestBuilder(username: username).execute(apiResponseQueue) { result in switch result { case .success: completion(.success(())) case let .failure(error): completion(.failure(error)) } } } /** Delete user - DELETE /user/{username} - This can only be done by the logged in user. - parameter username: (path) The name that needs to be deleted - returns: RequestBuilder<Void> */ open class func deleteUserWithRequestBuilder(username: String) -> RequestBuilder<Void> { var localVariablePath = "/user/{username}" let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableParameters: [String: Any]? = nil let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ : ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) let localVariableRequestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** Get user by user name - parameter username: (path) The name that needs to be fetched. Use user1 for testing. - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ @discardableResult open class func getUserByName(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result<User, ErrorResponse>) -> Void)) -> URLSessionTask? { return getUserByNameWithRequestBuilder(username: username).execute(apiResponseQueue) { result in switch result { case let .success(response): completion(.success(response.body!)) case let .failure(error): completion(.failure(error)) } } } /** Get user by user name - GET /user/{username} - parameter username: (path) The name that needs to be fetched. Use user1 for testing. - returns: RequestBuilder<User> */ open class func getUserByNameWithRequestBuilder(username: String) -> RequestBuilder<User> { var localVariablePath = "/user/{username}" let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableParameters: [String: Any]? = nil let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ : ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) let localVariableRequestBuilder: RequestBuilder<User>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** Logs user into the system - parameter username: (query) The user name for login - parameter password: (query) The password for login in clear text - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ @discardableResult open class func loginUser(username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result<String, ErrorResponse>) -> Void)) -> URLSessionTask? { return loginUserWithRequestBuilder(username: username, password: password).execute(apiResponseQueue) { result in switch result { case let .success(response): completion(.success(response.body!)) case let .failure(error): completion(.failure(error)) } } } /** Logs user into the system - GET /user/login - responseHeaders: [X-Rate-Limit(Int), X-Expires-After(Date)] - parameter username: (query) The user name for login - parameter password: (query) The password for login in clear text - returns: RequestBuilder<String> */ open class func loginUserWithRequestBuilder(username: String, password: String) -> RequestBuilder<String> { let localVariablePath = "/user/login" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableParameters: [String: Any]? = nil var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "username": username.encodeToJSON(), "password": password.encodeToJSON(), ]) let localVariableNillableHeaders: [String: Any?] = [ : ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) let localVariableRequestBuilder: RequestBuilder<String>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** Logs out current logged in user session - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ @discardableResult open class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result<Void, ErrorResponse>) -> Void)) -> URLSessionTask? { return logoutUserWithRequestBuilder().execute(apiResponseQueue) { result in switch result { case .success: completion(.success(())) case let .failure(error): completion(.failure(error)) } } } /** Logs out current logged in user session - GET /user/logout - returns: RequestBuilder<Void> */ open class func logoutUserWithRequestBuilder() -> RequestBuilder<Void> { let localVariablePath = "/user/logout" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableParameters: [String: Any]? = nil let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ : ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) let localVariableRequestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** Updated user - parameter username: (path) name that need to be deleted - parameter body: (body) Updated user object - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ @discardableResult open class func updateUser(username: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result<Void, ErrorResponse>) -> Void)) -> URLSessionTask? { return updateUserWithRequestBuilder(username: username, body: body).execute(apiResponseQueue) { result in switch result { case .success: completion(.success(())) case let .failure(error): completion(.failure(error)) } } } /** Updated user - PUT /user/{username} - This can only be done by the logged in user. - parameter username: (path) name that need to be deleted - parameter body: (body) Updated user object - returns: RequestBuilder<Void> */ open class func updateUserWithRequestBuilder(username: String, body: User) -> RequestBuilder<Void> { var localVariablePath = "/user/{username}" let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ : ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) let localVariableRequestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } }
45.939153
237
0.702044
164b6d7ece32527c4cbc7ca8bc75c40c43a0be9d
1,150
// // EPUBManifestParser.swift // EPUBKit // // Created by Witek Bobrowski on 30/06/2018. // Copyright © 2018 Witek Bobrowski. All rights reserved. // import AEXML import Foundation protocol EPUBManifestParser { func parse(_ xmlElement: AEXMLElement) -> EPUBManifest } class EPUBManifestParserImplementation: EPUBManifestParser { func parse(_ xmlElement: AEXMLElement) -> EPUBManifest { var items: [String: EPUBManifestItem] = [:] xmlElement["item"].all? .compactMap { item in guard let id = item.attributes["id"], let path = item.attributes["href"] else { return nil } let mediaType = item.attributes["media-type"] .map { EPUBMediaType(rawValue: $0) } ?? nil let properties = item.attributes["properties"] return EPUBManifestItem( id: id, path: path, mediaType: mediaType ?? .unknown, property: properties ) }.forEach { items[$0.id] = $0 } return EPUBManifest(id: xmlElement["id"].value, items: items) } }
32.857143
94
0.582609
72e8c88ed051ceee8e2c17850d7c4044d3c1ea85
2,069
// // TestedProtocol.swift // Cuckoo // // Created by Tadeas Kriz on 18/01/16. // Copyright © 2016 Brightify. All rights reserved. // protocol TestedProtocol { var readOnlyProperty: String { get } var readWriteProperty: Int { get set } var optionalProperty: Int? { get set } func noReturn() func count(characters: String) -> Int func withThrows() throws -> Int func withNoReturnThrows() throws func withClosure(_ closure: (String) -> Int) -> Int func withClosureAndParam(_ a: String, closure:(String) -> Int) -> Int func withEscape(_ a: String, action closure: @escaping (String) -> Void) func withOptionalClosure(_ a: String, closure: ((String) -> Void)?) func withOptionalClosureAndReturn(_ a: String, closure: ((String) -> Void)?) -> Int func withLabelAndUnderscore(labelA a: String, _ b: String) func withNamedTuple(tuple: (a: String, b: String)) -> Int func withImplicitlyUnwrappedOptional(i: Int!) -> String init() init(labelA a: String, _ b: String) func protocolMethod() -> String func methodWithParameter(_ param: String) -> String // Don't fix the whitespace in the return type. // It makes sure that inconsistent whitespace doesn't generate duplicate mock methods. func genericReturn() -> Dictionary<Int,Void> } extension TestedProtocol { func protocolMethod() -> String { return "a" } } protocol EmptyLabelProtocol { associatedtype T func empty(_: String) func empty(_: String) -> Int func empty(_: T) -> T } protocol OnlyLabelProtocol { func empty(_: String) func some(some: Int) func double(here there: Bool) } class OnlyLabelClass: OnlyLabelProtocol { func empty(_ mine: String) { } func some(some none: Int) { } func double(here notInHere: Bool) { } } public protocol PublicoProtocolo { associatedtype InternaloTypo var stringoStar: String { get set } init(hola: String) func internalMethod() }
20.69
90
0.647173
b9dcaaab68844601ef618c69f8a1075ecfeb1f44
13,557
// Copyright 2019 Algorand, Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // AccountsDataSource.swift import UIKit class AccountsDataSource: NSObject, UICollectionViewDataSource { weak var delegate: AccountsDataSourceDelegate? private let layout = Layout<LayoutConstants>() private let layoutBuilder = AssetListLayoutBuilder() var accounts: [Account] = UIApplication.shared.appConfiguration?.session.accounts ?? [] private var addedAssetDetails: [Account: Set<AssetDetail>] = [:] private var removedAssetDetails: [Account: Set<AssetDetail>] = [:] var hasPendingAssetAction: Bool { return !addedAssetDetails.isEmpty || !removedAssetDetails.isEmpty } func reload() { guard let session = UIApplication.shared.appConfiguration?.session else { return } accounts = session.accounts configureAddedAssetDetails() configureRemovedAssetDetails() } func refresh() { accounts.removeAll() reload() } func add(assetDetail: AssetDetail, to account: Account) { guard let accountIndex = accounts.firstIndex(of: account) else { return } accounts[accountIndex].assetDetails.append(assetDetail) if addedAssetDetails[account] == nil { addedAssetDetails[account] = [assetDetail] } else { addedAssetDetails[account]?.insert(assetDetail) } } func remove(assetDetail: AssetDetail, from account: Account) { guard let accountIndex = accounts.firstIndex(of: account), let idx = account.assetDetails.firstIndex(where: { $0.id == assetDetail.id }) else { return } account.assetDetails[idx] = assetDetail accounts[accountIndex] = account if removedAssetDetails[account] == nil { removedAssetDetails[account] = [assetDetail] } else { removedAssetDetails[account]?.insert(assetDetail) } } func section(for account: Account) -> Int? { return accounts.firstIndex(of: account) } func item(for assetDetail: AssetDetail, in account: Account) -> Int? { return account.assetDetails.firstIndex(of: assetDetail) } } extension AccountsDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return accounts.count } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let account = accounts[section] if account.assetDetails.isEmpty { return 1 } return account.assetDetails.count + 1 } } extension AccountsDataSource { func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if indexPath.item == 0 { return dequeueAlgoAssetCell(in: collectionView, cellForItemAt: indexPath) } return dequeueAssetCells(in: collectionView, cellForItemAt: indexPath) } private func dequeueAlgoAssetCell(in collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let cell = collectionView.dequeueReusableCell( withReuseIdentifier: AlgoAssetCell.reusableIdentifier, for: indexPath) as? AlgoAssetCell else { fatalError("Index path is out of bounds") } if indexPath.section < accounts.count { let account = accounts[indexPath.section] cell.bind(AlgoAssetViewModel(account: account)) } return cell } private func dequeueAssetCells(in collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if indexPath.section < accounts.count { let account = accounts[indexPath.section] let assetDetail = account.assetDetails[indexPath.item - 1] if assetDetail.isRemoved || assetDetail.isRecentlyAdded { let cell = layoutBuilder.dequeuePendingAssetCells( in: collectionView, cellForItemAt: indexPath, for: assetDetail ) cell.bind(PendingAssetViewModel(assetDetail: assetDetail)) return cell } else { guard let assets = accounts[indexPath.section].assets, let asset = assets.first(where: { $0.id == assetDetail.id }) else { fatalError("Unexpected Element") } let cell = layoutBuilder.dequeueAssetCells( in: collectionView, cellForItemAt: indexPath, for: assetDetail ) cell.bind(AssetViewModel(assetDetail: assetDetail, asset: asset)) return cell } } fatalError("Index path is out of bounds") } } extension AccountsDataSource { func collectionView( _ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath ) -> UICollectionReusableView { if kind == UICollectionView.elementKindSectionHeader { guard let headerView = collectionView.dequeueReusableSupplementaryView( ofKind: kind, withReuseIdentifier: AccountHeaderSupplementaryView.reusableIdentifier, for: indexPath ) as? AccountHeaderSupplementaryView else { fatalError("Unexpected element kind") } let account = accounts[indexPath.section] headerView.bind(AccountHeaderSupplementaryViewModel(account: account, isActionEnabled: true)) headerView.delegate = self headerView.tag = indexPath.section return headerView } else { guard let account = accounts[safe: indexPath.section] else { fatalError("Unexpected element kind") } if account.isWatchAccount() { guard let footerView = collectionView.dequeueReusableSupplementaryView( ofKind: kind, withReuseIdentifier: EmptyFooterSupplementaryView.reusableIdentifier, for: indexPath ) as? EmptyFooterSupplementaryView else { fatalError("Unexpected element kind") } return footerView } guard let footerView = collectionView.dequeueReusableSupplementaryView( ofKind: kind, withReuseIdentifier: AccountFooterSupplementaryView.reusableIdentifier, for: indexPath ) as? AccountFooterSupplementaryView else { fatalError("Unexpected element kind") } footerView.delegate = self footerView.tag = indexPath.section return footerView } } } extension AccountsDataSource: AccountHeaderSupplementaryViewDelegate { func accountHeaderSupplementaryViewDidTapQRButton(_ accountHeaderSupplementaryView: AccountHeaderSupplementaryView) { if accountHeaderSupplementaryView.tag < accounts.count { let account = accounts[accountHeaderSupplementaryView.tag] delegate?.accountsDataSource(self, didTapQRButtonFor: account) } } func accountHeaderSupplementaryViewDidTapOptionsButton(_ accountHeaderSupplementaryView: AccountHeaderSupplementaryView) { if accountHeaderSupplementaryView.tag < accounts.count { let account = accounts[accountHeaderSupplementaryView.tag] delegate?.accountsDataSource(self, didTapOptionsButtonFor: account) } } } extension AccountsDataSource: AccountFooterSupplementaryViewDelegate { func accountFooterSupplementaryViewDidTapAddAssetButton(_ accountFooterSupplementaryView: AccountFooterSupplementaryView) { if accountFooterSupplementaryView.tag < accounts.count { let account = accounts[accountFooterSupplementaryView.tag] delegate?.accountsDataSource(self, didTapAddAssetButtonFor: account) } } } extension AccountsDataSource { private func configureAddedAssetDetails() { // Check whether the asset is added to account in block. // If it's added, remove from the pending list. If it's not, add to current list again. for (account, addedAssets) in addedAssetDetails { if let index = section(for: account) { filterAddedAssets(at: index, for: account, in: addedAssets) addedAssetDetails.clearValuesIfEmpty(for: account) } } } private func filterAddedAssets(at index: Int, for account: Account, in addedAssets: Set<AssetDetail>) { addedAssetDetails[account] = addedAssets.filter { assetDetail -> Bool in let containsAssetDetailInUpdatedAccount = accounts[index].assetDetails.contains(assetDetail) if !containsAssetDetailInUpdatedAccount { accounts[index].assetDetails.append(assetDetail) } return !containsAssetDetailInUpdatedAccount } } private func configureRemovedAssetDetails() { // Check whether the asset is removed from account in block. If it's removed, remove from the pending list as well. for (account, removedAssets) in removedAssetDetails { if let index = section(for: account) { removedAssetDetails[account] = removedAssets.filter { !accounts[index].assetDetails.contains($0) } removedAssetDetails.clearValuesIfEmpty(for: account) } } } } extension AccountsDataSource: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { delegate?.accountsDataSource(self, didSelectAt: indexPath) } func collectionView( _ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath ) -> CGSize { let width = UIScreen.main.bounds.width - layout.current.defaultSectionInsets.left - layout.current.defaultSectionInsets.right if indexPath.item == 0 { return CGSize(width: width, height: layout.current.itemHeight) } else { let account = accounts[indexPath.section] let assetDetail = account.assetDetails[indexPath.item - 1] if assetDetail.hasBothDisplayName() { return CGSize(width: width, height: layout.current.multiItemHeight) } else { return CGSize(width: width, height: layout.current.itemHeight) } } } func collectionView( _ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int ) -> CGSize { return CGSize( width: UIScreen.main.bounds.width - layout.current.defaultSectionInsets.left - layout.current.defaultSectionInsets.right, height: layout.current.itemHeight ) } func collectionView( _ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int ) -> CGSize { if let account = accounts[safe: section], account.isWatchAccount() { return CGSize( width: UIScreen.main.bounds.width - layout.current.defaultSectionInsets.left - layout.current.defaultSectionInsets.right, height: layout.current.emptyFooterHeight ) } return CGSize( width: UIScreen.main.bounds.width - layout.current.defaultSectionInsets.left - layout.current.defaultSectionInsets.right, height: layout.current.multiItemHeight ) } } extension AccountsDataSource { private struct LayoutConstants: AdaptiveLayoutConstants { let defaultSectionInsets = UIEdgeInsets(top: 0.0, left: 20.0, bottom: 0.0, right: 20.0) let itemHeight: CGFloat = 52.0 let emptyFooterHeight: CGFloat = 44.0 let multiItemHeight: CGFloat = 72.0 } } protocol AccountsDataSourceDelegate: class { func accountsDataSource(_ accountsDataSource: AccountsDataSource, didTapOptionsButtonFor account: Account) func accountsDataSource(_ accountsDataSource: AccountsDataSource, didTapAddAssetButtonFor account: Account) func accountsDataSource(_ accountsDataSource: AccountsDataSource, didTapQRButtonFor account: Account) func accountsDataSource(_ accountsDataSource: AccountsDataSource, didSelectAt indexPath: IndexPath) }
39.069164
137
0.651177
62e4924193ca22af55efa0c0eafcae0d61546156
3,997
// // RouterHelper.swift // Services // // Created by chenminjie on 2021/3/11. // import Foundation import MJRouter public class RouterHelper { /// 注册服务 /// - Parameters: /// - routableService: 服务协议 /// - serviceClass: 服务协议实现类 public static func register<Protocol,T: NSObject>(_ routableService: RoutableService<Protocol>, forMakingService serviceClass: T.Type) where T: RouterProtocol { Router.register(routableService, forMakingService: serviceClass) } /// 创建服务 /// - Parameter routableService: 服务的协议 /// - Returns: 服务 public static func makeDestination<Protocol>(to routableService: RoutableService<Protocol>) -> Protocol? { return Router.makeDestination(to: routableService) } /// map contorller /// /// - Parameters: /// - string: url /// - page: controller public static func registerController<T: UIViewController>(url string: URLConvertiable, page: T.Type) where T: RouterProtocol { Router.registerController(url: string, page: page) } public static func registerCustomController<T: UIViewController>(url string: URLConvertiable, page: T.Type, action: @escaping ((RouterConfig?) -> Void)) where T: RouterProtocol { Router.registerCustomController(url: string, page: page, action: action) } /// 打开本地路由 /// - Parameters: /// - helperUrl: 路由枚举 /// - vc: 导航栏 public static func open(router helperUrl: RouterHelperUrl, completion: (([String: Any]?) -> Void)? = nil, from vc: UIViewController?) { if let _vc = vc { if helperUrl.isLogin { let service = Router.makeDestination(to: RoutableService<LoginModuleService>()) service?.doActionIfLogined(formVc: _vc, execute: { (isLogin) in if isLogin { Router.open(url: helperUrl.pattern, extened: helperUrl.params, completion: completion, jumpWay: helperUrl.jumpWay, from: vc, animated: true) } }) } else { Router.open(url: helperUrl.pattern, extened: helperUrl.params, completion: completion, jumpWay: helperUrl.jumpWay, from: vc, animated: true) } } } /// 直接通过url打开 /// - Parameters: /// - linkUrl: 链接地址 /// - params: 参数 /// - vc: 来源控制器 public static func open(router linkUrl: String?,params: [String: Any]? = nil, from vc: UIViewController?) { guard let _linkUrl = linkUrl else { return } Router.open(url: _linkUrl, extened: params, completion: nil, jumpWay: .push, from: vc, animated: true) } public enum RouterHelperUrl { case user case goodsDetail(goodsId: String) case shopCart var pattern: String { switch self { case .user: return RegisteredUrl.user.rawValue case .goodsDetail(_): return RegisteredUrl.goodsDetail.rawValue case .shopCart: return RegisteredUrl.shopCart.rawValue } } /// 参数 var params: [String: Any]? { switch self { case .goodsDetail(let goodsId): return ["goodsId": goodsId] default: return nil } } var jumpWay: Router.JumpWay { switch self { default: return .push } } var isLogin: Bool { switch self { case .user: return true case .shopCart: return true default: return false } } } /// 注册 public enum RegisteredUrl: String { case user = "mj://user/center" case goodsDetail = "mj://goods/detail" case shopCart = "mj://shopCart/index" } }
31.722222
182
0.556417
1ac7666bcbfd10d07afcd0fcc1e02be64211b669
6,891
// // Bridge.swift // CollectionKit // // Created by Luke Zhao on 2018-06-12. // Copyright © 2018 lkzhao. All rights reserved. // import UIKit // MARK: protocols @available(*, deprecated, message: "v2.0 deprecated naming") public typealias AnyCollectionProvider = Provider @available(*, deprecated, message: "v2.0 deprecated naming") public typealias CollectionDataProvider = DataSource @available(*, deprecated, message: "v2.0 deprecated naming") public typealias CollectionViewProvider = ViewSource @available(*, deprecated, message: "v2.0 deprecated naming") public typealias CollectionSizeProvider = SizeSource @available(*, deprecated, message: "v2.0 deprecated naming") public typealias CollectionLayout = Layout @available(*, deprecated, message: "v2.0 deprecated naming") public typealias CollectionPresenter = Animator // MARK: providers @available(*, deprecated, message: "v2.0 deprecated naming") public typealias CollectionProvider = BasicProvider @available(*, deprecated, message: "v2.0 deprecated naming") public typealias CollectionComposer = ComposedProvider @available(*, deprecated, message: "v2.0 deprecated naming") public typealias ViewCollectionProvider = SimpleViewProvider @available(*, deprecated, message: "v2.0 deprecated naming") public typealias EmptyStateCollectionProvider = EmptyStateProvider @available(*, deprecated, message: "v2.0 deprecated naming") public typealias SpaceCollectionProvider = SpaceProvider // MARK: others @available(*, deprecated, message: "v2.0 deprecated naming") public typealias ClosureDataProvider = ClosureDataSource @available(*, deprecated, message: "v2.0 deprecated naming") public typealias ClosureViewProvider = ClosureViewSource @available(*, deprecated, message: "v2.0 deprecated naming") public typealias ArrayDataProvider = ArrayDataSource extension CollectionView { @available(*, deprecated, message: "v2.0 deprecated naming") public var loading: Bool { return isLoadingCell } @available(*, deprecated, message: "v2.0 deprecated naming") public var reloading: Bool { return isReloading } } extension BasicProvider { public typealias OldTapHandler = (View, Int, DataSource<Data>) -> Void private static func convertTapHandler(_ tapHandler: OldTapHandler?) -> TapHandler? { if let tapHandler = tapHandler { return { context in tapHandler(context.view, context.index, context.dataSource) } } return nil } @available(*, deprecated, message: "please use designated init instead") public convenience init(identifier: String? = nil, dataProvider: DataSource<Data>, viewProvider: ViewSource<Data, View>, layout: Layout = FlowLayout(), sizeProvider: SizeSource<Data> = SizeSource<Data>(), presenter: Animator? = nil, willReloadHandler: (() -> Void)? = nil, didReloadHandler: (() -> Void)? = nil, tapHandler: OldTapHandler? = nil) { self.init(identifier: identifier, dataSource: dataProvider, viewSource: viewProvider, sizeSource: sizeProvider, layout: layout, animator: presenter, tapHandler: BasicProvider.convertTapHandler(tapHandler)) } @available(*, deprecated, message: "please use designated init instead") public convenience init(identifier: String? = nil, dataProvider: DataSource<Data>, viewGenerator: ((Data, Int) -> View)? = nil, viewUpdater: @escaping (View, Data, Int) -> Void, layout: Layout = FlowLayout(), sizeProvider: SizeSource<Data> = SizeSource<Data>(), presenter: Animator? = nil, willReloadHandler: (() -> Void)? = nil, didReloadHandler: (() -> Void)? = nil, tapHandler: OldTapHandler? = nil) { self.init(identifier: identifier, dataSource: dataProvider, viewSource: ClosureViewProvider(viewGenerator: viewGenerator, viewUpdater: viewUpdater), sizeSource: sizeProvider, layout: layout, animator: presenter, tapHandler: BasicProvider.convertTapHandler(tapHandler)) } @available(*, deprecated, message: "please use designated init instead") public convenience init(identifier: String? = nil, data: [Data], viewGenerator: ((Data, Int) -> View)? = nil, viewUpdater: @escaping (View, Data, Int) -> Void, layout: Layout = FlowLayout(), sizeProvider: SizeSource<Data> = SizeSource<Data>(), presenter: Animator? = nil, willReloadHandler: (() -> Void)? = nil, didReloadHandler: (() -> Void)? = nil, tapHandler: OldTapHandler? = nil) { self.init(identifier: identifier, dataSource: ArrayDataProvider(data: data), viewSource: ClosureViewProvider(viewGenerator: viewGenerator, viewUpdater: viewUpdater), sizeSource: sizeProvider, layout: layout, animator: presenter, tapHandler: BasicProvider.convertTapHandler(tapHandler)) } } @available(*, deprecated, message: "will be removed soon") open class LabelCollectionProvider: SimpleViewProvider { public var label: UILabel { return view(at: 0) as! UILabel } public init(identifier: String? = nil, insets: UIEdgeInsets = .zero) { let label = UILabel() label.numberOfLines = 0 super.init(identifier: identifier, views: [label], sizeStrategy: (.fill, .fit), layout: insets == .zero ? FlowLayout() : FlowLayout().inset(by: insets)) } public init(identifier: String? = nil, text: String, font: UIFont, color: UIColor = .black, insets: UIEdgeInsets = .zero) { let label = UILabel() label.font = font label.textColor = color label.text = text label.numberOfLines = 0 super.init(identifier: identifier, views: [label], sizeStrategy: (.fill, .fit), layout: insets == .zero ? FlowLayout() : FlowLayout().inset(by: insets)) } public init(identifier: String? = nil, attributedString: NSAttributedString, insets: UIEdgeInsets = .zero) { let label = UILabel() label.attributedText = attributedString label.numberOfLines = 0 super.init(identifier: identifier, views: [label], sizeStrategy: (.fill, .fit), layout: insets == .zero ? FlowLayout() : FlowLayout().inset(by: insets)) } }
41.017857
110
0.630097
e254bcf897e21fe26bb210922a305165e1c48d52
14,440
import Quick import Nimble import PactConsumerSwift class PactSwiftSpec: QuickSpec { override func spec() { var animalMockService: MockService? var animalServiceClient: AnimalServiceClient? describe("tests fulfilling all expected interactions") { beforeEach { animalMockService = MockService(provider: "Animal Service", consumer: "Animal Consumer Swift") animalServiceClient = AnimalServiceClient(baseUrl: animalMockService!.baseUrl) } it("gets an alligator") { animalMockService!.given("an alligator exists") .uponReceiving("a request for all alligators") .withRequest(method:.GET, path: "/alligators") .willRespondWith(status: 200, headers: ["Content-Type": "application/json"], body: [ ["name": "Mary", "type": "alligator"] ]) //Run the tests animalMockService!.run(timeout: 10000) { (testComplete) -> Void in animalServiceClient!.getAlligators( { (alligators) in expect(alligators[0].name).to(equal("Mary")) testComplete() }, failure: { (error) in testComplete() }) } } it("gets an alligator with path matcher") { let pathMatcher = Matcher.term(matcher: "^\\/alligators\\/[0-9]{4}", generate: "/alligators/1234") animalMockService!.given("an alligator exists") .uponReceiving("a request for an alligator with path matcher") .withRequest(method:.GET, path: pathMatcher) .willRespondWith(status: 200, headers: ["Content-Type": "application/json"], body: ["name": "Mary", "type": "alligator"]) //Run the tests animalMockService!.run { (testComplete) -> Void in animalServiceClient!.getAlligator(1234, success: { (alligator) in expect(alligator.name).to(equal("Mary")) testComplete() }, failure: { (error) in testComplete() }) } } describe("With query params") { it("should return animals living in water") { animalMockService!.given("an alligator exists") .uponReceiving("a request for animals living in water") .withRequest(method:.GET, path: "/animals", query: ["live": "water"]) .willRespondWith(status: 200, headers: ["Content-Type": "application/json"], body: [ ["name": "Mary", "type": "alligator"] ] ) //Run the tests animalMockService!.run { (testComplete) -> Void in animalServiceClient!.findAnimals(live: "water", response: { (response) in expect(response.count).to(equal(1)) let name = response[0].name expect(name).to(equal("Mary")) testComplete() }) } } it("should return animals living in water using dictionary matcher") { animalMockService!.given("an alligator exists") .uponReceiving("a request for animals living in water with dictionary matcher") .withRequest(method:.GET, path: "/animals", query: ["live": Matcher.somethingLike("water")]) .willRespondWith(status: 200, headers: ["Content-Type": "application/json"], body: [ ["name": "Mary", "type": "alligator"] ] ) //Run the tests animalMockService!.run { (testComplete) -> Void in animalServiceClient!.findAnimals(live: "water", response: { (response) in expect(response.count).to(equal(1)) let name = response[0].name expect(name).to(equal("Mary")) testComplete() }) } } it("should return animals living in water using matcher") { let queryMatcher = Matcher.term(matcher: "live=*", generate: "live=water") animalMockService!.given("an alligator exists") .uponReceiving("a request for animals living in water with matcher") .withRequest(method:.GET, path: "/animals", query: queryMatcher) .willRespondWith(status: 200, headers: ["Content-Type": "application/json"], body: [ ["name": "Mary", "type": "alligator"] ] ) //Run the tests animalMockService!.run { (testComplete) -> Void in animalServiceClient!.findAnimals(live: "water", response: { (response) in expect(response.count).to(equal(1)) let name = response[0].name expect(name).to(equal("Mary")) testComplete() }) } } } describe("With Header matches") { it("gets a secure alligator with auth header matcher") { animalMockService!.given("an alligator exists") .uponReceiving("a request for an alligator with header matcher") .withRequest(method: .GET, path: "/alligators", headers: ["Authorization": Matcher.somethingLike("OIOIUOIU")]) .willRespondWith(status: 200, headers: ["Content-Type": "application/json", "Etag": Matcher.somethingLike("x234")], body: ["name": "Mary", "type": "alligator"]) //Run the tests animalMockService!.run { (testComplete) -> Void in animalServiceClient!.getSecureAlligators(authToken: "OIOIUOIU", success: { (alligators) in expect(alligators[0].name).to(equal("Mary")) testComplete() }, failure: { (error) in testComplete() } ) } } } describe("PATCH request") { it("should unfriend me") { animalMockService!.given("Alligators and pidgeons exist") .uponReceiving("a request eat a pidgeon") .withRequest(method:.PATCH, path: "/alligator/eat", body: [ "type": "pidgeon" ]) .willRespondWith(status: 204, headers: ["Content-Type": "application/json"]) //Run the tests animalMockService!.run{ (testComplete) -> Void in animalServiceClient!.eat(animal: "pidgeon", success: { () in testComplete() }, error: { (error) in expect(true).to(equal(false)) testComplete() }) } } } describe("Expecting an error response") { it("returns an error") { animalMockService!.given("Alligators don't eat pidgeons") .uponReceiving("a request to no longer eat pidgeons") .withRequest(method:.DELETE, path: "/alligator/eat", body: [ "type": "pidgeon" ]) .willRespondWith(status:404, body: "No relationship") //Run the tests animalMockService!.run { (testComplete) -> Void in animalServiceClient!.wontEat(animal: "pidgeon", success: { () in // We are expecting this test to fail - the error handler should be called expect(true).to(equal(false)) testComplete() }, error: { (error) in testComplete() }) } } } describe("multiple interactions") { it("should allow multiple interactions in test setup") { animalMockService!.given("alligators don't each pidgeons") .uponReceiving("a request to eat") .withRequest(method:.PATCH, path: "/alligator/eat", body: ["type": "pidgeon"]) .willRespondWith(status: 204, headers: ["Content-Type": "application/json"]) animalMockService!.uponReceiving("what alligators eat") .withRequest(method:.GET, path: "/alligator/eat") .willRespondWith(status:200, headers: ["Content-Type": "application/json"], body: [ ["name": "Joseph", "type": Matcher.somethingLike("pidgeon")]]) //Run the tests animalMockService!.run { (testComplete) -> Void in animalServiceClient!.eat(animal: "pidgeon", success: { () in animalServiceClient!.eats { (response) in expect(response.count).to(equal(1)) let name = response[0].name let type = response[0].type expect(name).to(equal("Joseph")) expect(type).to(equal("pidgeon")) testComplete() } }, error: { (error) in expect(true).to(equal(false)) testComplete() }) } } } describe("Matchers") { it("Can match date based on regex") { animalMockService!.given("an alligator exists with a birthdate") .uponReceiving("a request for alligator with birthdate") .withRequest(method:.GET, path: "/alligators/123") .willRespondWith( status: 200, headers: ["Content-Type": "application/json"], body: [ "name": "Mary", "type": "alligator", "dateOfBirth": Matcher.term( matcher: "\\d{2}\\/\\d{2}\\/\\d{4}", generate: "02/02/1999" ) ]) //Run the tests animalMockService!.run { (testComplete) -> Void in animalServiceClient!.getAlligator(123, success: { (alligator) in expect(alligator.name).to(equal("Mary")) expect(alligator.dob).to(equal("02/02/1999")) testComplete() }, failure: { (error) in expect(true).to(equal(false)) testComplete() }) } } it("Can match legs based on type") { animalMockService!.given("an alligator exists with legs") .uponReceiving("a request for alligator with legs") .withRequest(method:.GET, path: "/alligators/1") .willRespondWith( status: 200, headers: ["Content-Type": "application/json"], body: [ "name": "Mary", "type": "alligator", "legs": Matcher.somethingLike(4) ]) //Run the tests animalMockService!.run { (testComplete) -> Void in animalServiceClient!.getAlligator(1, success: { (alligator) in expect(alligator.legs).to(equal(4)) testComplete() }, failure: { (error) in expect(true).to(equal(false)) testComplete() }) } } it("Can match based on flexible length array") { animalMockService!.given("multiple land based animals exist") .uponReceiving("a request for animals living on land") .withRequest( method:.GET, path: "/animals", query: ["live": "land"]) .willRespondWith( status: 200, headers: ["Content-Type": "application/json"], body: Matcher.eachLike(["name": "Bruce", "type": "wombat"])) //Run the tests animalMockService!.run { (testComplete) -> Void in animalServiceClient!.findAnimals(live: "land", response: { (response) in expect(response.count).to(equal(1)) expect(response[0].name).to(equal("Bruce")) testComplete() }) } } } } context("when defined interactions are not received") { let errorCapturer = ErrorCapture() beforeEach { animalMockService = MockService( provider: "Animal Service", consumer: "Animal Consumer Swift", pactVerificationService: PactVerificationService(), errorReporter: errorCapturer ) } describe("but specified HTTP request was not received by mock service") { it("returns error message from mock service") { animalMockService?.given("an alligator exists") .uponReceiving("a request for all alligators") .withRequest(method:.GET, path: "/alligators") .willRespondWith(status: 200, headers: ["Content-Type": "application/json"], body: [ ["name": "Mary", "type": "alligator"] ]) animalMockService?.run() { (testComplete) -> Void in testComplete() } expect(errorCapturer.message?.message).to(contain("Actual interactions do not match expected interactions for mock")) } it("specifies origin of test error to line where .run() method is called") { animalMockService?.given("an alligator exists") .uponReceiving("a request for all alligators") .withRequest(method:.GET, path: "/alligators") .willRespondWith(status: 200, headers: ["Content-Type": "application/json"], body: [ ["name": "Mary", "type": "alligator"] ]) let thisFile: String = #file let thisLine: UInt = #line animalMockService?.run() { (testComplete) -> Void in testComplete() } expect(errorCapturer.message?.file?.description) == thisFile expect(errorCapturer.message?.line) == thisLine + 1 } } } } }
42.346041
170
0.505055
0852b1a3b49fea77ebddadf7e77220358ca55817
10,914
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. import UIKit class MSAnalyticsViewController: UITableViewController, AppCenterProtocol { enum Priority: String { case Default = "Default" case Normal = "Normal" case Critical = "Critical" case Invalid = "Invalid" var flags: Flags { switch self { case .Normal: return [.normal] case .Critical: return [.critical] case .Invalid: return Flags.init(rawValue: 42) default: return [] } } static let allValues = [Default, Normal, Critical, Invalid] } enum Latency: String { case Default = "Default" case Min_10 = "10 Minutes" case Hour_1 = "1 Hour" case Hour_8 = "8 Hour" case Day_1 = "1 Day" static let allValues = [Default, Min_10, Hour_1, Hour_8, Day_1] static let allTimeValues = [3, 10*60, 1*60*60, 8*60*60, 24*60*60] } @IBOutlet weak var startSessionButton: UIButton! @IBOutlet weak var enableManualSession: UISwitch! @IBOutlet weak var enabled: UISwitch! @IBOutlet weak var eventName: UITextField! @IBOutlet weak var pageName: UITextField! @IBOutlet weak var pause: UIButton! @IBOutlet weak var resume: UIButton! @IBOutlet weak var priorityField: UITextField! @IBOutlet weak var countLabel: UILabel! @IBOutlet weak var countSlider: UISlider! @IBOutlet weak var transmissionIntervalLabel: UILabel! var appCenter: AppCenterDelegate! var eventPropertiesSection: EventPropertiesTableSection! @objc(analyticsResult) var analyticsResult: MSAnalyticsResult? = nil private var latencyPicker: MSEnumPicker<Latency>? private var priorityPicker: MSEnumPicker<Priority>? private var priority = Priority.Default private var latency = Latency.Default private var kEventPropertiesSectionIndex: Int = 2 private var kResultsPageIndex: Int = 2 override func viewDidLoad() { eventPropertiesSection = EventPropertiesTableSection(tableSection: kEventPropertiesSectionIndex, tableView: tableView) super.viewDidLoad() tableView.estimatedRowHeight = tableView.rowHeight tableView.rowHeight = UITableView.automaticDimension tableView.setEditing(true, animated: false) self.priorityPicker = MSEnumPicker<Priority>( textField: self.priorityField, allValues: Priority.allValues, onChange: {(index) in self.priority = Priority.allValues[index] }) self.priorityField.delegate = self.priorityPicker self.priorityField.text = self.priority.rawValue self.priorityField.tintColor = UIColor.clear self.countLabel.text = "Count: \(Int(countSlider.value))" initTransmissionIntervalLabel() // Disable results page. #if !ACTIVE_COMPILATION_CONDITION_PUPPET let cell = tableView.cellForRow(at: IndexPath(row: kResultsPageIndex, section: 0)) cell?.isUserInteractionEnabled = false cell?.contentView.alpha = 0.5 #endif } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.enabled.isOn = appCenter.isAnalyticsEnabled() self.enableManualSession.isOn = UserDefaults.standard.bool(forKey: kMSManualSessionTracker) // Make sure the UITabBarController does not cut off the last cell. self.edgesForExtendedLayout = [] } @IBAction func trackEvent() { guard let name = eventName.text else { return } let eventProperties = eventPropertiesSection.eventProperties() for _ in 0..<Int(countSlider.value) { if let properties = eventProperties as? EventProperties { // The AppCenterDelegate uses the argument label "withTypedProperties", but the underlying swift API simply uses "withProperties". if priority != .Default { appCenter.trackEvent(name, withTypedProperties: properties, flags: priority.flags) } else { appCenter.trackEvent(name, withTypedProperties: properties) } } else if let dictionary = eventProperties as? [String: String] { if priority != .Default { appCenter.trackEvent(name, withProperties: dictionary, flags: priority.flags) } else { appCenter.trackEvent(name, withProperties: dictionary) } } else { if priority != .Default { appCenter.trackEvent(name, withTypedProperties: nil, flags: priority.flags) } else { appCenter.trackEvent(name) } } for targetToken in MSTransmissionTargets.shared.transmissionTargets.keys { if MSTransmissionTargets.shared.targetShouldSendAnalyticsEvents(targetToken: targetToken) { let target = MSTransmissionTargets.shared.transmissionTargets[targetToken]! if let properties = eventProperties as? EventProperties { if priority != .Default { target.trackEvent(name, withProperties: properties, flags: priority.flags) } else { target.trackEvent(name, withProperties: properties) } } else if let dictionary = eventProperties as? [String: String] { if priority != .Default { target.trackEvent(name, withProperties: dictionary, flags: priority.flags) } else { target.trackEvent(name, withProperties: dictionary) } } else { if priority != .Default { target.trackEvent(name, withProperties: [:], flags: priority.flags) } else { target.trackEvent(name) } } } } } } @IBAction func startSession(_ sender: Any) { appCenter.startSession() } @IBAction func switchManualSessionTracker(_ sender: UISwitch) { UserDefaults.standard.set(sender.isOn, forKey: kMSManualSessionTracker) print("Restart the app for the changes to take effect.") } @IBAction func trackPage() { guard let name = eventName.text else { return } appCenter.trackPage(name) } @IBAction func enabledSwitchUpdated(_ sender: UISwitch) { appCenter.setAnalyticsEnabled(sender.isOn) sender.isOn = appCenter.isAnalyticsEnabled() } @IBAction func pause(_ sender: UIButton) { appCenter.pause() } @IBAction func resume(_ sender: UIButton) { appCenter.resume() } @IBAction func countChanged(_ sender: Any) { self.countLabel.text = "Count: \(Int(countSlider.value))" } @IBAction func dismissKeyboard(_ sender: UITextField!) { sender.resignFirstResponder() } func enablePauseResume(enable: Bool) { pause.isEnabled = enable resume.isEnabled = enable } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let destination = segue.destination as? MSAnalyticsResultViewController { destination.analyticsResult = analyticsResult } } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { eventPropertiesSection.tableView(tableView, commit: editingStyle, forRowAt: indexPath) } override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle { if indexPath.section == kEventPropertiesSectionIndex { return eventPropertiesSection.tableView(tableView, editingStyleForRowAt: indexPath) } return .delete } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) if indexPath.section == kEventPropertiesSectionIndex && eventPropertiesSection.isInsertRow(indexPath) { self.tableView(tableView, commit: .insert, forRowAt: indexPath) } else if indexPath.section == 0 && indexPath.row == 3 { present(initTransmissionAlert(tableView), animated: true) } } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == kEventPropertiesSectionIndex { return eventPropertiesSection.tableView(tableView, numberOfRowsInSection: section) } return super.tableView(tableView, numberOfRowsInSection: section) } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableView.automaticDimension } /** * Without this override, the default implementation will try to get a table cell that is out of bounds * (since they are inserted/removed at a slightly different time than the actual data source is updated). */ override func tableView(_ tableView: UITableView, indentationLevelForRowAt indexPath: IndexPath) -> Int { return 0 } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { if indexPath.section == kEventPropertiesSectionIndex { return eventPropertiesSection.tableView(tableView, canEditRowAt:indexPath) } return false } override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { return false } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.section == kEventPropertiesSectionIndex { return eventPropertiesSection.tableView(tableView, cellForRowAt:indexPath) } return super.tableView(tableView, cellForRowAt: indexPath) } func initTransmissionIntervalLabel() { let interval = UserDefaults.standard.integer(forKey: kMSTransmissionIterval) updateIntervalLabel(transmissionInterval: interval) } func updateIntervalLabel(transmissionInterval: Int) { let formattedInterval = TimeInterval(transmissionInterval) let formatter = DateComponentsFormatter() formatter.unitsStyle = .positional formatter.allowedUnits = [ .hour, .minute, .second] formatter.zeroFormattingBehavior = [ .pad] transmissionIntervalLabel.text = formatter.string(from: formattedInterval) } func initTransmissionAlert(_ tableView: UITableView) -> UIAlertController { let alert = UIAlertController(title: "Transmission Interval", message: nil, preferredStyle: .alert) let confirmAction = UIAlertAction(title: "OK", style: .default, handler: {(_ action:UIAlertAction) -> Void in let result = alert.textFields?[0].text let timeResult: Int = Int(result!) ?? 0 UserDefaults.standard.setValue(timeResult, forKey: kMSTransmissionIterval) self.updateIntervalLabel(transmissionInterval: timeResult) tableView.reloadData() }) let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) alert.addAction(confirmAction) alert.addAction(cancelAction) alert.addTextField(configurationHandler: {(_ textField: UITextField) -> Void in textField.text = String(UserDefaults.standard.integer(forKey: kMSTransmissionIterval)) textField.keyboardType = UIKeyboardType.numberPad }) return alert } }
37.634483
138
0.71138
48a4caa40aa0a183507d0fb1a943c3e1195d3da5
738
// // ViewController.swift // exercicio0501 // // Created by Jackson on 25/05/2018. // Copyright © 2018 Targettrust. All rights reserved. // import UIKit class ViewController: UIViewController { // MARK: - Hoisting let _debug: Bool = true let _logtag: String = "ViewController" override func viewDidLoad() { super.viewDidLoad() if self._debug { print("\(self._logtag) - viewDidLoad") } addBehaviors(behaviors: [HideNavigationBarBehavior()]) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() if self._debug { print("\(self._logtag) - didReceiveMemoryWarning") } // Dispose of any resources that can be recreated. } }
23.0625
77
0.651762
0360fa7cde7bee8271baecf85bf4266fd4b71cfc
677
// // ClassScheduleViewCellTableViewCell.swift // ZippyMaps // // Created by Kay,Maxwell on 12/1/16. // Copyright © 2016 Kay,Maxwell. All rights reserved. // import UIKit class ClassScheduleViewCellTableViewCell: UITableViewCell { @IBOutlet weak var classNameLabel: UILabel! //@IBOutlet weak var startTimeLabel: UILabel! //@IBOutlet weak var endTimeLabel: UILabel! 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 } }
22.566667
65
0.689808
f968e86975cd914ac0d5cbef8af670b5fe63b94b
4,528
// // DynamicBlurView.swift // DynamicBlurView // // Created by Kyohei Ito on 2015/04/08. // Copyright (c) 2015年 kyohei_ito. All rights reserved. // import UIKit open class DynamicBlurView: UIView { open override class var layerClass: AnyClass { BlurLayer.self } private var blurLayer: BlurLayer { layer as! BlurLayer } private var staticImage: UIImage? private var displayLink: CADisplayLink? { didSet { oldValue?.invalidate() } } private var renderingTarget: UIView? { window != nil ? (isDeepRendering ? window : superview) : nil } private var relativeLayerRect: CGRect { blurLayer.current.convertRect(to: renderingTarget?.layer) } /// Radius of blur. open var blurRadius: CGFloat { get { blurLayer.blurRadius } set { blurLayer.blurRadius = newValue } } /// Default is none. open var trackingMode: TrackingMode = .none { didSet { if trackingMode != oldValue { linkForDisplay() } } } /// Blend color. open var blendColor: UIColor? /// Blend mode. open var blendMode: CGBlendMode = .plusLighter /// Default is 3. open var iterations = 3 /// If the view want to render beyond the layer, should be true. open var isDeepRendering = false /// When none of tracking mode, it can change the radius of blur with the ratio. Should set from 0 to 1. open var blurRatio: CGFloat = 1 { didSet { if oldValue != blurRatio, let blurredImage = staticImage.flatMap(imageBlurred) { blurLayer.draw(blurredImage) } } } /// Quality of captured image. open var quality: CaptureQuality { get { blurLayer.quality } set { blurLayer.quality = newValue } } public override init(frame: CGRect) { super.init(frame: frame) isUserInteractionEnabled = false } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) isUserInteractionEnabled = false } open override func didMoveToWindow() { super.didMoveToWindow() if trackingMode == .none { renderingTarget?.layoutIfNeeded() staticImage = currentImage() } } open override func didMoveToSuperview() { super.didMoveToSuperview() if superview == nil { displayLink = nil } else { linkForDisplay() } } func imageBlurred(_ image: UIImage) -> UIImage? { image.blurred( radius: blurLayer.currentBlurRadius, iterations: iterations, ratio: blurRatio, blendColor: blendColor, blendMode: blendMode ) } func currentImage() -> UIImage? { renderingTarget.flatMap { view in blurLayer.snapshotImageBelowLayer(view.layer, in: isDeepRendering ? view.bounds : relativeLayerRect) } } } extension DynamicBlurView { open override func display(_ layer: CALayer) { if let blurredImage = (staticImage ?? currentImage()).flatMap(imageBlurred) { let usedImage = (layer.cornerRadius > 0 ? blurredImage.withRoundedCorners(radius: layer.cornerRadius) : blurredImage) ?? UIImage() blurLayer.draw(usedImage) if isDeepRendering { blurLayer.contentsRect = relativeLayerRect.rectangle(usedImage.size) } } } } extension DynamicBlurView { private func linkForDisplay() { displayLink = UIScreen.main.displayLink(withTarget: self, selector: #selector(DynamicBlurView.displayDidRefresh(_:))) displayLink?.add(to: .main, forMode: RunLoop.Mode(rawValue: trackingMode.description)) } @objc private func displayDidRefresh(_ displayLink: CADisplayLink) { display(layer) } } extension DynamicBlurView { /// Remove cache of blur image then get it again. open func refresh() { blurLayer.refresh() staticImage = nil blurRatio = 1 display(layer) } /// Remove cache of blur image. open func remove() { blurLayer.refresh() staticImage = nil blurRatio = 1 layer.contents = nil } /// Should use when needs to change layout with animation when is set none of tracking mode. public func animate() { blurLayer.animate() } }
26.325581
142
0.605345
566bd71445a09b738ec3a2a154e2c71d92e71e08
14,358
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/ #if !os(tvOS) import os.log import AVFoundation private let sizeOfMIDIPacketList = MemoryLayout<MIDIPacketList>.size private let sizeOfMIDIPacket = MemoryLayout<MIDIPacket>.size /// The `MIDIPacketList` struct consists of two fields, numPackets(`UInt32`) and /// packet(an Array of 1 instance of `MIDIPacket`). The packet is supposed to be a "An open-ended /// array of variable-length MIDIPackets." but for convenience it is instaciated with /// one instance of a `MIDIPacket`. To figure out the size of the header portion of this struct, /// we can get the size of a UInt32, or subtract the size of a single packet from the size of a /// packet list. I opted for the latter. private let sizeOfMIDIPacketListHeader = sizeOfMIDIPacketList - sizeOfMIDIPacket /// The MIDIPacket struct consists of a timestamp (`MIDITimeStamp`), a length (`UInt16`) and /// data (an Array of 256 instances of `Byte`). The data field is supposed to be a "A variable-length /// stream of MIDI messages." but for convenience it is instaciated as 256 bytes. To figure out the /// size of the header portion of this struct, we can add the size of the `timestamp` and `length` /// fields, or subtract the size of the 256 `Byte`s from the size of the whole packet. I opted for /// the former. private let sizeOfMIDIPacketHeader = MemoryLayout<MIDITimeStamp>.size + MemoryLayout<UInt16>.size private let sizeOfMIDICombinedHeaders = sizeOfMIDIPacketListHeader + sizeOfMIDIPacketHeader func MIDIOutputPort(client: MIDIClientRef, name: CFString) -> MIDIPortRef? { var port: MIDIPortRef = 0 guard MIDIOutputPortCreate(client, name, &port) == noErr else { return nil } return port } internal extension Collection where Index == Int { var startIndex: Index { return 0 } func index(after index: Index) -> Index { return index + 1 } } internal struct MIDIDestinations: Collection { typealias Index = Int typealias Element = MIDIEndpointRef init() { } var endIndex: Index { return MIDIGetNumberOfDestinations() } subscript (index: Index) -> Element { return MIDIGetDestination(index) } } extension Collection where Iterator.Element == MIDIEndpointRef { var names: [String] { return map { getMIDIObjectStringProperty(ref: $0, property: kMIDIPropertyName) } } var uniqueIds: [MIDIUniqueID] { return map { getMIDIObjectIntegerProperty(ref: $0, property: kMIDIPropertyUniqueID) } } } internal func getMIDIObjectStringProperty(ref: MIDIObjectRef, property: CFString) -> String { var string: Unmanaged<CFString>? MIDIObjectGetStringProperty(ref, property, &string) if let returnString = string?.takeRetainedValue() { return returnString as String } else { return "" } } internal func getMIDIObjectIntegerProperty(ref: MIDIObjectRef, property: CFString) -> Int32 { var result: Int32 = 0 MIDIObjectGetIntegerProperty(ref, property, &result) return result } extension AKMIDI { /// Array of destination unique ids public var destinationUIDs: [MIDIUniqueID] { return MIDIDestinations().uniqueIds } /// Array of destination names public var destinationNames: [String] { return MIDIDestinations().names } /// Lookup a destination name from its unique id /// /// - Parameter forUid: unique id for a destination /// - Returns: name of destination or "Unknown" /// public func destinationName(for destUid: MIDIUniqueID) -> String { let name: String = zip(destinationNames, destinationUIDs).first { (arg: (String, MIDIUniqueID)) -> Bool in let (_, uid) = arg return destUid == uid }.map { (arg) -> String in let (name, _) = arg return name } ?? "Unknown" return name } /// Look up the unique id for a destination index /// /// - Parameter outputIndex: index of destination /// - Returns: unique identifier for the port /// public func uidForDestinationAtIndex(_ outputIndex: Int = 0) -> MIDIUniqueID { let endpoint: MIDIEndpointRef = MIDIDestinations()[outputIndex] let uid = getMIDIObjectIntegerProperty(ref: endpoint, property: kMIDIPropertyUniqueID) return uid } /// Open a MIDI Output Port by name /// /// - Parameter name: String containing the name of the MIDI Output /// @available(*, deprecated, message: "Try to not use names any more because they are not unique across devices") public func openOutput(name: String) { guard let index = destinationNames.firstIndex(of: name) else { openOutput(uid: 0) return } let uid = uidForDestinationAtIndex(index) openOutput(uid: uid) } /// Handle the acceptable default case of no parameter without causing a /// deprecation warning public func openOutput() { openOutput(uid: 0) } /// Open a MIDI Output Port by index /// /// - Parameter outputIndex: Index of destination endpoint /// public func openOutput(index outputIndex: Int) { guard outputIndex < destinationNames.count else { return } let uid = uidForDestinationAtIndex(outputIndex) openOutput(uid: uid) } /// /// Open a MIDI Output Port /// /// - parameter outputUid: Unique id of the MIDI Output /// public func openOutput(uid outputUid: MIDIUniqueID) { if outputPort == 0 { guard let tempPort = MIDIOutputPort(client: client, name: outputPortName) else { AKLog("Unable to create MIDIOutputPort", log: OSLog.midi, type: .error) return } outputPort = tempPort } let destinations = MIDIDestinations() // To get all endpoints; and set in endpoints array (mapping without condition) if outputUid == 0 { _ = zip(destinationUIDs, destinations).map { endpoints[$0] = $1 } } else { // To get only [the FIRST] endpoint with name provided in output (conditional mapping) _ = zip(destinationUIDs, destinations).first { (arg: (MIDIUniqueID, MIDIDestinations.Element)) -> Bool in let (uid, _) = arg return outputUid == uid }.map { endpoints[$0] = $1 } } } /// Close a MIDI Output port by name /// /// - Parameter name: Name of port to close. /// public func closeOutput(name: String = "") { guard let index = destinationNames.firstIndex(of: name) else { return } let uid = uidForDestinationAtIndex(index) closeOutput(uid: uid) } /// Close a MIDI Output port by index /// /// - Parameter index: Index of destination port name /// public func closeOutput(index outputIndex: Int) { guard outputIndex < destinationNames.count else { return } let uid = uidForDestinationAtIndex(outputIndex) closeOutput(uid: uid) } /// Close a MIDI Output port /// /// - parameter inputName: Unique id of the MIDI Output /// public func closeOutput(uid outputUid: MIDIUniqueID) { let name = destinationName(for: outputUid) AKLog("Closing MIDI Output '\(String(describing: name))'", log: OSLog.midi) var result = noErr if endpoints[outputUid] != nil { endpoints.removeValue(forKey: outputUid) AKLog("Disconnected \(name) and removed it from endpoints", log: OSLog.midi) if endpoints.isEmpty { // if there are no more endpoints, dispose of midi output port result = MIDIPortDispose(outputPort) if result == noErr { AKLog("Disposed MIDI Output port", log: OSLog.midi) } else { AKLog("Error disposing MIDI Output port: \(result)", log: OSLog.midi, type: .error) } outputPort = 0 } } } /// Send Message with data public func sendMessage(_ data: [MIDIByte], offset: MIDITimeStamp = 0) { // Create a buffer that is big enough to hold the data to be sent and // all the necessary headers. let bufferSize = data.count + sizeOfMIDICombinedHeaders // the discussion section of MIDIPacketListAdd states that "The maximum // size of a packet list is 65536 bytes." Checking for that limit here. if bufferSize > 65_536 { AKLog("error sending midi : data array is too large, requires a buffer larger than 65536", log: OSLog.midi, type: .error) return } var buffer = Data(count: bufferSize) // Use Data (a.k.a NSData) to create a block where we have access to a // pointer where we can create the packetlist and send it. No need for // explicit alloc and dealloc. buffer.withUnsafeMutableBytes { (ptr: UnsafeMutableRawBufferPointer) -> Void in if let packetListPointer = ptr.bindMemory(to: MIDIPacketList.self).baseAddress { let packet = MIDIPacketListInit(packetListPointer) let nextPacket: UnsafeMutablePointer<MIDIPacket>? = MIDIPacketListAdd(packetListPointer, bufferSize, packet, offset, data.count, data) // I would prefer stronger error handling here, perhaps throwing // to force the app developer to handle the error. if nextPacket == nil { AKLog("error sending midi: Failed to add packet to packet list.", log: OSLog.midi, type: .error) return } for endpoint in endpoints.values { let result = MIDISend(outputPort, endpoint, packetListPointer) if result != noErr { AKLog("error sending midi: \(result)", log: OSLog.midi, type: .error) } } if virtualOutput != 0 { MIDIReceived(virtualOutput, packetListPointer) } } } } /// Clear MIDI destinations public func clearEndpoints() { endpoints.removeAll() } /// Send Messsage from MIDI event data public func sendEvent(_ event: AKMIDIEvent) { sendMessage(event.data) } /// Send a Note On Message public func sendNoteOnMessage(noteNumber: MIDINoteNumber, velocity: MIDIVelocity, channel: MIDIChannel = 0) { let noteCommand: MIDIByte = MIDIByte(0x90) + channel let message: [MIDIByte] = [noteCommand, noteNumber, velocity] self.sendMessage(message) } /// Send a Note Off Message public func sendNoteOffMessage(noteNumber: MIDINoteNumber, velocity: MIDIVelocity, channel: MIDIChannel = 0) { let noteCommand: MIDIByte = MIDIByte(0x80) + channel let message: [MIDIByte] = [noteCommand, noteNumber, velocity] self.sendMessage(message) } /// Send a Continuous Controller message public func sendControllerMessage(_ control: MIDIByte, value: MIDIByte, channel: MIDIChannel = 0) { let controlCommand: MIDIByte = MIDIByte(0xB0) + channel let message: [MIDIByte] = [controlCommand, control, value] self.sendMessage(message) } /// Send a pitch bend message. /// /// - Parameters: /// - value: Value of pitch shifting between 0 and 16383. Send 8192 for no pitch bending. /// - channel: Channel you want to send pitch bend message. Defaults 0. public func sendPitchBendMessage(value: UInt16, channel: MIDIChannel = 0) { let pitchCommand = MIDIByte(0xE0) + channel let mask: UInt16 = 0x007F let byte1 = MIDIByte(value & mask) // MSB, bit shift right 7 let byte2 = MIDIByte((value & (mask << 7)) >> 7) // LSB, mask of 127 let message: [MIDIByte] = [pitchCommand, byte1, byte2] self.sendMessage(message) } // MARK: - Expand api to include MIDITimeStamp // MARK: - Send a message with MIDITimeStamp public func sendNoteOnMessageWithTime(noteNumber: MIDINoteNumber, velocity: MIDIVelocity, channel: MIDIChannel = 0, time: MIDITimeStamp = 0) { let noteCommand: UInt8 = UInt8(0x90) + UInt8(channel) let message: [UInt8] = [noteCommand, UInt8(noteNumber), UInt8(velocity)] self.sendMessageWithTime(message, time: time) } /// Send a Note Off Message public func sendNoteOffMessageWithTime(noteNumber: MIDINoteNumber, velocity: MIDIVelocity, channel: MIDIChannel = 0, time: MIDITimeStamp = 0) { let noteCommand: UInt8 = UInt8(0x80) + UInt8(channel) let message: [UInt8] = [noteCommand, UInt8(noteNumber), UInt8(velocity)] self.sendMessageWithTime(message, time: time) } /// Send Message with data public func sendMessageWithTime(_ data: [UInt8], time: MIDITimeStamp) { let packetListPointer: UnsafeMutablePointer<MIDIPacketList> = UnsafeMutablePointer.allocate(capacity: 1) var packet: UnsafeMutablePointer<MIDIPacket> = MIDIPacketListInit(packetListPointer) packet = MIDIPacketListAdd(packetListPointer, 1_024, packet, time, data.count, data) for endpoint in endpoints.values { let result = MIDISend(outputPort, endpoint, packetListPointer) if result != noErr { AKLog("error sending midi: \(result)", log: OSLog.midi, type: .error) } } if virtualOutput != 0 { MIDIReceived(virtualOutput, packetListPointer) } } } #endif
37.390625
117
0.613804
ccf525e72bfa56cd2dd881968d84602eb34eb03c
1,943
// // ServicesManager.swift // KocomojoKit // // Created by Antonio Bello on 1/27/15. // Copyright (c) 2015 Elapsus. All rights reserved. // import Foundation public class ServicesManager { private struct Static { static var instance: ServicesManager = ServicesManager() } public class var instance: ServicesManager { return Static.instance } private lazy var api: RestAPI = RestAPI.instance private init() {} } /// MARK: - Public interface extension ServicesManager { public func getCountries(completion: Result<[Country]> -> ()) { self.api.getCountries { apiResult in var result: Result<[Country]> switch apiResult { case .HttpError(let status): let error = NSError(domain: "kocomojo.kit", code: -4, userInfo: [NSLocalizedDescriptionKey: "Server error: \(status)"]) result = Result.Error(error) case .InvocationError(let error): result = Result.Error(error) case .Value(let value): let countries = value().countries result = Result.Value(countries) } completion(result) } } public func getPlans(completion: Result<[Plan]> -> ()) { self.api.getPlans { apiResult in var result: Result<[Plan]> switch apiResult { case .HttpError(let status): let error = NSError(domain: "kocomojo.kit", code: -4, userInfo: [NSLocalizedDescriptionKey: "Server error: \(status)"]) result = Result.Error(error) case .InvocationError(let error): result = Result.Error(error) case .Value(let value): let plans = value().plans result = Result.Value(plans) } completion(result) } }}
30.359375
135
0.557385
fc27cc4915fb26f1eaaf3c4b1a1ef649fcb3d6ee
6,637
// DO NOT EDIT. // swift-format-ignore-file // // Generated by the Swift generator plugin for the protocol buffer compiler. // Source: proto/clarifai/api/utils/extensions.proto // // For information on using the generated types, please see the documentation: // https://github.com/apple/swift-protobuf/ import Foundation import SwiftProtobuf // If the compiler emits an error on this type, it is because this file // was generated by a version of the `protoc` Swift plug-in that is // incompatible with the version of SwiftProtobuf to which you are linking. // Please ensure that you are building against the same version of the API // that was used to generate this file. fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck { struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {} typealias Version = _2 } // MARK: - Extension support defined in extensions.proto. // MARK: - Extension Properties // Swift Extensions on the exteneded Messages to add easy access to the declared // extension fields. The names are based on the extension field name from the proto // declaration. To avoid naming collisions, the names are prefixed with the name of // the scope where the extend directive occurs. extension SwiftProtobuf.Google_Protobuf_FieldOptions { /// If True then we will return this field with it's zero value even if not set. /// This means in json responses empty lists will appear instead of not being returned (which is /// the default convention for proto3). For int's we will show 0, for floats 0.0, etc. public var Clarifai_Api_Utils_clShowIfEmpty: Bool { get {return getExtensionValue(ext: Clarifai_Api_Utils_Extensions_cl_show_if_empty) ?? false} set {setExtensionValue(ext: Clarifai_Api_Utils_Extensions_cl_show_if_empty, value: newValue)} } /// Returns true if extension `Clarifai_Api_Utils_Extensions_cl_show_if_empty` /// has been explicitly set. public var hasClarifai_Api_Utils_clShowIfEmpty: Bool { return hasExtensionValue(ext: Clarifai_Api_Utils_Extensions_cl_show_if_empty) } /// Clears the value of extension `Clarifai_Api_Utils_Extensions_cl_show_if_empty`. /// Subsequent reads from it will return its default value. public mutating func clearClarifai_Api_Utils_clShowIfEmpty() { clearExtensionValue(ext: Clarifai_Api_Utils_Extensions_cl_show_if_empty) } public var Clarifai_Api_Utils_clMoretags: String { get {return getExtensionValue(ext: Clarifai_Api_Utils_Extensions_cl_moretags) ?? String()} set {setExtensionValue(ext: Clarifai_Api_Utils_Extensions_cl_moretags, value: newValue)} } /// Returns true if extension `Clarifai_Api_Utils_Extensions_cl_moretags` /// has been explicitly set. public var hasClarifai_Api_Utils_clMoretags: Bool { return hasExtensionValue(ext: Clarifai_Api_Utils_Extensions_cl_moretags) } /// Clears the value of extension `Clarifai_Api_Utils_Extensions_cl_moretags`. /// Subsequent reads from it will return its default value. public mutating func clearClarifai_Api_Utils_clMoretags() { clearExtensionValue(ext: Clarifai_Api_Utils_Extensions_cl_moretags) } /// For float fields where this is set, this value will be used by the server when parsing the /// request and the field is not present in the request. If the field is present in the request, /// then the value of the field will be used instead. This is ONLY used for json requests as binary /// proto requests are expected to always set the field. public var Clarifai_Api_Utils_clDefaultFloat: Float { get {return getExtensionValue(ext: Clarifai_Api_Utils_Extensions_cl_default_float) ?? 0} set {setExtensionValue(ext: Clarifai_Api_Utils_Extensions_cl_default_float, value: newValue)} } /// Returns true if extension `Clarifai_Api_Utils_Extensions_cl_default_float` /// has been explicitly set. public var hasClarifai_Api_Utils_clDefaultFloat: Bool { return hasExtensionValue(ext: Clarifai_Api_Utils_Extensions_cl_default_float) } /// Clears the value of extension `Clarifai_Api_Utils_Extensions_cl_default_float`. /// Subsequent reads from it will return its default value. public mutating func clearClarifai_Api_Utils_clDefaultFloat() { clearExtensionValue(ext: Clarifai_Api_Utils_Extensions_cl_default_float) } } // MARK: - File's ExtensionMap: Clarifai_Api_Utils_Extensions_Extensions /// A `SwiftProtobuf.SimpleExtensionMap` that includes all of the extensions defined by /// this .proto file. It can be used any place an `SwiftProtobuf.ExtensionMap` is needed /// in parsing, or it can be combined with other `SwiftProtobuf.SimpleExtensionMap`s to create /// a larger `SwiftProtobuf.SimpleExtensionMap`. public let Clarifai_Api_Utils_Extensions_Extensions: SwiftProtobuf.SimpleExtensionMap = [ Clarifai_Api_Utils_Extensions_cl_show_if_empty, Clarifai_Api_Utils_Extensions_cl_moretags, Clarifai_Api_Utils_Extensions_cl_default_float ] // Extension Objects - The only reason these might be needed is when manually // constructing a `SimpleExtensionMap`, otherwise, use the above _Extension Properties_ // accessors for the extension fields on the messages directly. /// If True then we will return this field with it's zero value even if not set. /// This means in json responses empty lists will appear instead of not being returned (which is /// the default convention for proto3). For int's we will show 0, for floats 0.0, etc. public let Clarifai_Api_Utils_Extensions_cl_show_if_empty = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufBool>, SwiftProtobuf.Google_Protobuf_FieldOptions>( _protobuf_fieldNumber: 50000, fieldName: "clarifai.api.utils.cl_show_if_empty" ) public let Clarifai_Api_Utils_Extensions_cl_moretags = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufString>, SwiftProtobuf.Google_Protobuf_FieldOptions>( _protobuf_fieldNumber: 50001, fieldName: "clarifai.api.utils.cl_moretags" ) /// For float fields where this is set, this value will be used by the server when parsing the /// request and the field is not present in the request. If the field is present in the request, /// then the value of the field will be used instead. This is ONLY used for json requests as binary /// proto requests are expected to always set the field. public let Clarifai_Api_Utils_Extensions_cl_default_float = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufFloat>, SwiftProtobuf.Google_Protobuf_FieldOptions>( _protobuf_fieldNumber: 50010, fieldName: "clarifai.api.utils.cl_default_float" )
53.096
202
0.801868
2878a0250d147f99546d544dca420f08b40e8200
4,643
// // APIClient.swift // MovieLister // // Created by Ben Scheirman on 10/29/19. // Copyright © 2019 Fickle Bits. All rights reserved. // import Foundation import SimpleNetworking struct MovieDB { static let baseURL = URL(string: "https://api.themoviedb.org/3/")! static var api: APIClient = { let configuration = URLSessionConfiguration.default configuration.httpAdditionalHeaders = [ "Authorization" : "Bearer \(apiKey)" ] return APIClient( configuration: configuration, adapters: [ SessionAdapter(), LoggingAdapter(logLevel: .debug) ]) }() struct SessionAdapter : RequestAdapter { func adapt(_ request: inout URLRequest) { guard let sessionId = Current.sessionManager.currentSessionId else { return } guard let requestURL = request.url else { return } guard var components = URLComponents(url: requestURL, resolvingAgainstBaseURL: false) else { return } var queryItems = components.queryItems ?? [] queryItems.append(URLQueryItem(name: "session_id", value: sessionId)) components.queryItems = queryItems request.url = components.url } } struct AuthorizationAdapter : RequestAdapter { func adapt(_ request: URLRequest) -> URLRequest { guard let requestURL = request.url else { return request } guard var components = URLComponents(url: requestURL, resolvingAgainstBaseURL: false) else { return request } let apiKey = "asdf" var queryItems = components.queryItems ?? [] queryItems.append(URLQueryItem(name: "apiKey", value: apiKey)) components.queryItems = queryItems var req = request req.url = components.url return req } } } extension Request { static func popularMovies(_ completion: @escaping (Result<PagedResults<Movie>, APIError>) -> Void) -> Request { Request.basic(baseURL: MovieDB.baseURL, path: "discover/movie", params: [ URLQueryItem(name: "sort_by", value: "popularity.desc") ]) { result in result.decoding(PagedResults<Movie>.self, completion: completion) } } static func configuration(_ completion: @escaping (Result<MovieDBConfiguration, APIError>) -> Void) -> Request { Request.basic(baseURL: MovieDB.baseURL, path: "configuration") { result in result.decoding(MovieDBConfiguration.self, completion: completion) } } static func createRequestToken(_ completion: @escaping (Result<AuthenticationTokenResponse, APIError>) -> Void) -> Request { Request.basic(baseURL: MovieDB.baseURL, path: "authentication/token/new") { result in result.decoding(AuthenticationTokenResponse.self, completion: completion) } } static func createSession(requestToken: String, _ completion: @escaping (Result<CreateSessionResponse, APIError>) -> Void) -> Request { struct Body : Model { let requestToken: String } return Request.post(baseURL: MovieDB.baseURL, path: "authentication/session/new", body: Body(requestToken: requestToken)) { result in result.decoding(CreateSessionResponse.self, completion: completion) } } static func account(_ completion: @escaping (Result<Account, APIError>) -> Void) -> Request { Request.basic(baseURL: MovieDB.baseURL, path: "account") { result in result.decoding(Account.self, completion: completion) } } static func favoriteMovies(accountID: Int, _ completion: @escaping (Result<PagedResults<Movie>, APIError>) -> Void) -> Request { Request.basic(baseURL: MovieDB.baseURL, path: "account/\(accountID)/favorite/movies") { result in result.decoding(PagedResults<Movie>.self, completion: completion) } } static func markFavorite(accountID: Int, mediaType: String, mediaID: Int, favorite: Bool, _ completion: @escaping (Result<GenericResponse, APIError>) -> Void) -> Request { struct Body : Model { let mediaType: String let mediaID: Int let favorite: Bool } let body = Body(mediaType: mediaType, mediaID: mediaID, favorite: favorite) return Request.post(baseURL: MovieDB.baseURL, path: "account/\(accountID)/favorite", body: body) { result in result.decoding(GenericResponse.self, completion: completion) } } }
40.373913
175
0.636657
d54a9a372041e55f87b091f6deb93a75fc1162c8
371
public class Item { var name: String var sellIn: Int var quality: Int public init(name: String, sellIn: Int, quality: Int) { self.name = name self.sellIn = sellIn self.quality = quality } } extension Item: CustomStringConvertible { public var description: String { return "\(name), \(sellIn), \(quality)" } }
20.611111
58
0.601078
89039dbfee672cc0aaae55e18c511f6c7dd024e1
7,253
// // PaymentModesVCViewController.swift // SafexPay // // Created by Sandeep on 8/13/20. // Copyright © 2020 Antino Labs. All rights reserved. // import UIKit import KRProgressHUD class PaymentModesVC: UIViewController { // MARK:- Outlets @IBOutlet weak var navBarTopView: UIView! @IBOutlet weak var navBarBottomView: UIView! @IBOutlet weak var amountLbl: UILabel! @IBOutlet weak var orderLbl: UILabel! @IBOutlet weak var logoImg: UIImageView! @IBOutlet weak var tableView: UITableView! // MARK:- Properties var BrandDetails: BrandingDetail? var mechantId = String.empty var price = String.empty var orderId = String.empty var custName = String.empty var custEmail = String.empty var custNumber = String.empty var externalKey = String.empty // private var paymodes: [PaymentMode]? private var paymentmodes: [paymentModeNew]? // MARK:- Lifecycle public init() { super.init(nibName: "PaymentModesVC", bundle: safexBundle) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.getPaymodes(merchantId: self.mechantId) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // self.getSavedCards(merchantId: self.mechantId) setupView() setuptableView() } // MARK:- Helpers func setupView(){ if let details = self.BrandDetails{ self.logoImg.setKfImage(with: details.logo) } // self.navBarBottomView.backgroundColor = headerColor // self.navBarTopView.backgroundColor = headerColor self.navBarBottomView.addShadow(color: UIColor.lightGray, offSet: CGSize(width: 0, height: 3)) self.amountLbl.text = "AED \(price)" self.orderLbl.text = "Order no:" + "" + "\(orderId)" } func setuptableView(){ self.tableView.delegate = self self.tableView.dataSource = self self.tableView.register(UINib(nibName: "PaymentModeCell", bundle: safexBundle), forCellReuseIdentifier: "PaymentModeCell") } func removeSubview(tag: Int){ guard let viewWithTag = self.view.viewWithTag(tag) else {return} viewWithTag.removeFromSuperview() } func setupDetailView(for type: paymentModeNew){ let vc = PaymentDetailVC() vc.modalPresentationStyle = .fullScreen vc.price = self.price vc.orderId = self.orderId vc.viewType = type vc.mechantId = self.mechantId vc.custName = self.custName vc.custEmail = self.custEmail vc.custNumber = self.custNumber vc.externalKey = self.externalKey vc.BrandDetails = self.BrandDetails present(vc, animated: false, completion: nil) } @IBAction func closePaymentGateway(_ sender: UIButton) { self.dismiss(animated: true, completion: nil) } } extension PaymentModesVC: UITableViewDelegate, UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.paymentmodes?.count ?? 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "PaymentModeCell") as! PaymentModeCell if let mode = self.paymentmodes?[indexPath.row]{ cell.setData(mode: mode) } cell.selectionStyle = .none return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 60.0 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let mode = self.paymentmodes?[indexPath.row]{ print(mode.paymentName) self.setupDetailView(for: mode) } } } extension PaymentModesVC{ private func getPaymodes(merchantId: String){ KRProgressHUD.show() DataClient.getPaymodes(merchantId: merchantId) { (status, data) in if status{ if let details = data{ self.decryptBrandingDetail(encData: details) } }else{ KRProgressHUD.dismiss() Console.log(ErrorMessages.somethingWentWrong) } } } private func decryptBrandingDetail(encData: String){ let payloadResponse = AESClient.AESDecrypt(dataToDecrypt: encData, decryptionKey: self.externalKey) let dataDict = convertToArrayDictionary(text: payloadResponse) // print(dataDict) KRProgressHUD.dismiss() do{ let data2 = try JSONSerialization.data(withJSONObject: dataDict as Any , options: .prettyPrinted) let decoder = JSONDecoder() do { var paymodes = [PaymentMode]() paymodes = try decoder.decode([PaymentMode].self, from: data2) sortPaymentMethods(data: paymodes) } catch let DecodingError.dataCorrupted(context) { print(context) KRProgressHUD.dismiss() } catch let DecodingError.keyNotFound(key, context) { print("Key '\(key)' not found:", context.debugDescription) print("codingPath:", context.codingPath) KRProgressHUD.dismiss() } catch let DecodingError.valueNotFound(value, context) { print("Value '\(value)' not found:", context.debugDescription) print("codingPath:", context.codingPath) KRProgressHUD.dismiss() } catch let DecodingError.typeMismatch(type, context) { print("Type '\(type)' mismatch:", context.debugDescription) print("codingPath:", context.codingPath) KRProgressHUD.dismiss() } catch { print("error: ", error) KRProgressHUD.dismiss() } } catch { Console.log(error.localizedDescription) KRProgressHUD.dismiss() } } func sortPaymentMethods(data: [PaymentMode]){ var paymodesSet = [paymentModeNew]() data.forEach({ (mode) in switch mode.payModeID { case "CC","DC" : paymodesSet.append(paymentModeNew(paymentName: "Pay by card", payModeID: "DC", modeDetailList: mode.paymentModeDetailsList)) case "CE" : paymodesSet.append(paymentModeNew(paymentName: "Pay by instalments (credit card)", payModeID: mode.payModeID, modeDetailList: mode.paymentModeDetailsList)) case "TB" : paymodesSet.append(paymentModeNew(paymentName: "Buy now pay later", payModeID: mode.payModeID, modeDetailList: mode.paymentModeDetailsList)) default: return } }) paymentmodes = paymodesSet.removingDuplicates() KRProgressHUD.dismiss() self.tableView.reloadData() } }
36.265
171
0.623466
4bd816d64c47bd1681d865e83336f2a6435bdb51
118
//: [Previous](@previous) enum List<Element> { case end indirect case node(value: Element, next: List<Element>) }
14.75
56
0.686441
e43ba081565df36108cb11734a9d15be4acec6cb
624
import ComposableArchitecture import SwiftUI public struct SettingsView: View { let store: Store<SettingsState, SettingsAction> public init(store: Store<SettingsState, SettingsAction>) { self.store = store } public var body: some View { Text("Hello, runitz!") .padding() } } struct SettingsView_Previews: PreviewProvider { static var previews: some View { SettingsView( store: .init( initialState: .init(), reducer: settingsReducer, environment: SettingsEnvironment() ) ) } }
22.285714
62
0.591346
cc91e4b472cd7bd53ff657cf6941ac92b4b467ea
2,144
// // ItlyMixpanelPlugin.swift // ItlyMixpanelPlugin // // Copyright © 2020 Iteratively. All rights reserved. // import Foundation import Mixpanel import ItlySdk @objc(ITLMixpanelPlugin) public class ItlyMixpanelPlugin: Plugin { private var mixpanelClient: MixpanelInstance! private weak var logger: Logger? private var token: String @objc public init(_ token: String) { self.token = token super.init(id: "ItlyMixpanelPlugin") } public override func load(_ options: Options) { super.load(options) self.logger = options.logger logger?.debug("\(self.id) load") self.mixpanelClient = Mixpanel.initialize(token: token) } public override func reset() { super.reset() logger?.debug("\(self.id) reset") mixpanelClient?.reset() } public override func alias(_ userId: String, previousId: String?) { super.alias(userId, previousId: previousId) logger?.debug("\(self.id) alias(userId=\(userId) previousId=\(previousId ?? ""))") mixpanelClient?.createAlias(userId, distinctId: previousId ?? mixpanelClient.distinctId) } public override func identify(_ userId: String?, properties: ItlySdk.Properties?) { super.identify(userId, properties: properties) logger?.debug("\(self.id) identify(userId=\(userId ?? ""), properties=\(properties?.properties ?? [:]))") guard let userId = userId else { return } mixpanelClient?.identify(distinctId: userId) mixpanelClient?.identify(distinctId: userId, usePeople: true) if let properties = properties?.properties { mixpanelClient?.people.set(properties: properties.compactMapValues{ $0 as? MixpanelType }) } } public override func track(_ userId: String?, event: Event) { super.track(userId, event: event) logger?.debug("\(self.id) track(userId = \(userId ?? ""), event=\(event.name) properties=\(event.properties))") mixpanelClient?.track(event: event.name, properties: event.properties.compactMapValues{ $0 as? MixpanelType }) } }
32
119
0.655317
336d9afeccc0abadada6de48ecc88099132089fa
4,048
// // AcronymsController.swift // App // // Created by Rebouh Aymen on 18/05/2018. // import Foundation import Vapor import Fluent struct AcronymsController: RouteCollection { func boot(router: Router) throws { let acronymsInitialRoute = router.grouped("api", "acronyms") acronymsInitialRoute.post(Acronym.self, use: create) acronymsInitialRoute.get(use: getAll) // Acronym.parameter autodetect the type of Acronym id. It also helps for type safery. acronymsInitialRoute.get(Acronym.parameter, use: get) acronymsInitialRoute.get(Acronym.parameter, "user", use: getUser) acronymsInitialRoute.put(Acronym.parameter, use: update) acronymsInitialRoute.delete(Acronym.parameter, use: delete) acronymsInitialRoute.get("first", use: getFirstAcronym) // http://localhost:8080/api/acronyms/search?q=ONU acronymsInitialRoute.get("search", use: search) // http://localhost:8080/api/acronyms/search?q=ONU acronymsInitialRoute.get("searchMultiple", use: searchMultiple) } func getAll(_ req: Request) throws -> Future<[Acronym]> { if let sort = req.query[String.self, at: "sort"], sort == "asc" || sort == "desc" { return try Acronym.query(on: req).sort(\.short, sort == "asc" ? .ascending : .descending).all() } else { return Acronym.query(on: req).all() } } func create(_ req: Request, acronym: Acronym) throws -> Future<Acronym> { return acronym.save(on: req) } func get(_ req: Request) throws -> Future<Acronym> { // This function performs all the work necessary to get the acronym from the database return try req.parameters.next(Acronym.self) } func getUser(_ req: Request) throws -> Future<User> { // This function performs all the work necessary to get the acronym from the database return try req.parameters.next(Acronym.self) .flatMap(to: User.self) { acronym in return try acronym.user.get(on: req) } } func update(_ req: Request) throws -> Future<Acronym> { // dual future form of flatMap, to wait for both the parameter extraction and content decoding to complete. return try flatMap(to: Acronym.self, req.parameters.next(Acronym.self), req.content.decode(Acronym.self)) { acronym, newAcronym -> Future<Acronym> in acronym.short = newAcronym.short acronym.long = newAcronym.long acronym.userId = newAcronym.userId return acronym.save(on: req) } } func delete(_ req: Request) throws -> Future<HTTPStatus> { return try req.parameters.next(Acronym.self) .delete(on: req) .transform(to: HTTPStatus.noContent) } func search(_ req: Request) throws -> Future<[Acronym]> { guard let searchTerm = req.query[String.self, at: "q"] else { throw Abort(.badRequest) } return try Acronym.query(on: req) // This line below is not type safe .filter(\.short, .equals, .data(searchTerm)) // This line below is type safe //.filter(\.short == searchTerm) .all() } func searchMultiple(_ req: Request) throws -> Future<[Acronym]> { guard let searchTerm = req.query[String.self, at: "q"] else { throw Abort(.badRequest) } return try Acronym.query(on: req).group(.or) { or in try or.filter(\.short, .equals, .data(searchTerm)) try or.filter(\.long, .equals, .data(searchTerm)) }.all() } func getFirstAcronym(_ req: Request) throws -> Future<Acronym> { return Acronym.query(on: req).first().map(to: Acronym.self) { acronym in guard let acronym = acronym else { throw Abort(.notFound) } return acronym } } }
39.686275
115
0.603014
f5278175513bdfc0534035dd5fbe5d84805ab818
1,006
import Foundation func printPersonName(_ person: Person, _ path: KeyPath<Person, String>) { print("Person name = \(person[keyPath: path])") } class Person { var firstName: String var lastName: String var age: Int init(_ firstName: String, _ lastName: String, _ age: Int) { self.firstName = firstName self.lastName = lastName self.age = age } } class Student: Person { var className: String init(_ firstName: String, _ lastName: String, _ age: Int, _ className: String) { self.className = className super.init(firstName, lastName, age) } } var firstPerson = Person("Nhat", "Hoang", 10) var firstStudent = Student("Rio", "Vincente", 20, "Mẫu giáo lớn") var nameKeyPath = \Person.lastName var agekeyPath = \Person.age var studentNameKeyPath = \Student.lastName printPersonName(firstPerson, nameKeyPath) //printPersonName(firstPerson, agekeyPath) //printPersonName(firstStudent, studentNameKeyPath) print(firstStudent)
26.473684
84
0.690855
f9cba0f7f7b074919440d572856115b0f4c89d79
3,666
import XCTest import RBBJSON @available(iOS 10.0, *) final class NumbersTests: XCTestCase { func testNumberConversion() { do { XCTAssertEqual(Int("foo" as RBBJSON), nil) XCTAssertEqual(Int("" as RBBJSON), nil) XCTAssertEqual(Int("123.4" as RBBJSON), nil) XCTAssertEqual(Int(123.4 as RBBJSON), 123) XCTAssertEqual(Int(0 as RBBJSON), 0) XCTAssertEqual(Int("foo" as RBBJSON, lenient: true), nil) XCTAssertEqual(Int("" as RBBJSON, lenient: true), nil) XCTAssertEqual(Int("123" as RBBJSON, lenient: true), 123) XCTAssertEqual(Int("123.4" as RBBJSON, lenient: true), 123) XCTAssertEqual(Int(123.4 as RBBJSON, lenient: true), 123) XCTAssertEqual(Int(0 as RBBJSON, lenient: true), 0) } do { XCTAssertEqual(UInt32("foo" as RBBJSON), nil) XCTAssertEqual(UInt32("" as RBBJSON), nil) XCTAssertEqual(UInt32("123.4" as RBBJSON), nil) XCTAssertEqual(UInt32(123.4 as RBBJSON), 123) XCTAssertEqual(UInt32(0 as RBBJSON), 0) XCTAssertEqual(UInt32("foo" as RBBJSON, lenient: true), nil) XCTAssertEqual(UInt32("" as RBBJSON, lenient: true), nil) XCTAssertEqual(UInt32("123" as RBBJSON, lenient: true), 123) XCTAssertEqual(UInt32("123.4" as RBBJSON, lenient: true), 123) XCTAssertEqual(UInt32(123.4 as RBBJSON, lenient: true), 123) XCTAssertEqual(UInt32(0 as RBBJSON, lenient: true), 0) } do { XCTAssertEqual(CGFloat("foo" as RBBJSON), nil) XCTAssertEqual(CGFloat("" as RBBJSON), nil) XCTAssertEqual(CGFloat("123.4" as RBBJSON), nil) XCTAssertEqual(CGFloat(123.4 as RBBJSON), 123.4) XCTAssertEqual(CGFloat(0 as RBBJSON), 0) XCTAssertEqual(CGFloat("foo" as RBBJSON, lenient: true), nil) XCTAssertEqual(CGFloat("" as RBBJSON, lenient: true), nil) XCTAssertEqual(CGFloat("123.4" as RBBJSON, lenient: true), 123.4) XCTAssertEqual(CGFloat(123.4 as RBBJSON, lenient: true), 123.4) XCTAssertEqual(CGFloat(0 as RBBJSON, lenient: true), 0) } do { XCTAssertEqual(Double("foo" as RBBJSON), nil) XCTAssertEqual(Double("" as RBBJSON), nil) XCTAssertEqual(Double("123.4" as RBBJSON), nil) XCTAssertEqual(Double(123.4 as RBBJSON), 123.4) XCTAssertEqual(Double(0 as RBBJSON), 0) XCTAssertEqual(Double("foo" as RBBJSON, lenient: true), nil) XCTAssertEqual(Double("" as RBBJSON, lenient: true), nil) XCTAssertEqual(Double("123.4" as RBBJSON, lenient: true), 123.4) XCTAssertEqual(Double(123.4 as RBBJSON, lenient: true), 123.4) XCTAssertEqual(Double(0 as RBBJSON, lenient: true), 0) } do { XCTAssertEqual(Float("foo" as RBBJSON), nil) XCTAssertEqual(Float("" as RBBJSON), nil) XCTAssertEqual(Float("123.4" as RBBJSON), nil) XCTAssertEqual(Float(123.4 as RBBJSON), 123.4) XCTAssertEqual(Float(0 as RBBJSON), 0) XCTAssertEqual(Float("foo" as RBBJSON, lenient: true), nil) XCTAssertEqual(Float("" as RBBJSON, lenient: true), nil) XCTAssertEqual(Float("123.4" as RBBJSON, lenient: true), 123.4) XCTAssertEqual(Float(123.4 as RBBJSON, lenient: true), 123.4) XCTAssertEqual(Float(0 as RBBJSON, lenient: true), 0) } } }
45.259259
77
0.586197
e6bc6422ead71f3bd19a7ed07f84f2eefc73a857
390
// // UploadNetworkAPI.swift // AnyNetworkService // // Created by 刘栋 on 2020/1/4. // Copyright © 2020-2021 anotheren.com. All rights reserved. // import Foundation import Alamofire public protocol UploadNetworkAPI: NetworkAPI { associatedtype ResultType func handle(formData: Alamofire.MultipartFormData) func handle(response data: Data) throws -> ResultType }
20.526316
61
0.728205
165c6c7ca134ac46507f41c9c922ef85607120cb
5,086
// // OnboardingView.swift // RP // // Created by Salih Çakmak on 9.01.2022. // import SwiftUI struct OnboardingView: View { @AppStorage("onboarding") var isOnboardingViewActive : Bool = true @State private var buttonWidth : Double = UIScreen.main.bounds.width - 80 @State private var buttonOffset: CGFloat = 0 @State private var isAnimating : Bool = false @State private var imageOffset : CGSize = .zero var body: some View { ZStack { Color.white .ignoresSafeArea() VStack (spacing: 20){ Spacer() VStack { Text("Spider") .font(.system(size: 80)) .fontWeight(.thin) .foregroundColor(.black) } .opacity(isAnimating ? 1 : 0) .offset(y: isAnimating ? 0 : -40) .animation(.easeOut(duration: 1), value: isAnimating) ZStack{ CircleGroupView(ShapeColor: .black, ShapeOpacity: 0.2) Image("Spider") .resizable() .scaledToFit() .offset(y: isAnimating ? 35 : -35) .animation( Animation .easeInOut(duration: 1) .repeatForever() ,value: isAnimating ) } Spacer() ZStack{ Capsule() .fill(Color.white.opacity(0.2)) Capsule() .fill(Color.white.opacity(0.2)) .padding(8) Text("Kaydır") .font(.system(.title3 ,design: .rounded)) .fontWeight(.thin) .foregroundColor(.black) .offset(x: 20) HStack{ Capsule() .fill(Color.black.opacity(0.2)) .frame(width: buttonOffset + 80) Spacer() } HStack{ ZStack{ Circle() .fill(Color.black.opacity(0.3)) Circle() .fill(.black.opacity(0.3)) .padding(8) Image(systemName: "chevron.right.2") .font(.system(size: 24, weight: .bold)) } .foregroundColor(.white) .frame(width: 80, height: 80, alignment: .center) .offset(x: buttonOffset) .gesture( DragGesture() .onChanged { gesture in if gesture.translation.width > 0 && buttonOffset <= buttonWidth - 80 { buttonOffset = gesture.translation.width } } .onEnded { _ in withAnimation(Animation.easeOut(duration: 1)) { if buttonOffset > buttonWidth / 2 { buttonOffset = buttonWidth - 80 isOnboardingViewActive = false buttonOffset = 0 } else { buttonOffset = 0 } } } ) Spacer() } } .frame(width: buttonWidth ,height: 80, alignment: .center) .padding() .opacity(isAnimating ? 1 : 0) .offset(y: isAnimating ? 0 : 40) .animation(.easeOut(duration: 1), value: isAnimating) } } .onAppear(perform: { isAnimating = true }) } } struct OnboardingView_Previews: PreviewProvider { static var previews: some View { OnboardingView() } }
35.816901
110
0.323437
1de5907cd16b5e17582e22eef93126cd19e0e328
18,403
// // Copyright 2020 Adobe. All rights reserved. // This file is licensed to you under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. You may obtain a copy // of the License at http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under // the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS // OF ANY KIND, either express or implied. See the License for the specific language // governing permissions and limitations under the License. // @testable import AEPCore @testable import AEPExperiencePlatform import AEPServices import Foundation import XCTest /// Struct defining the event specifications - contains the event type and source struct EventSpec { let type: String let source: String } /// Hashable `EventSpec`, to be used as key in Dictionaries extension EventSpec: Hashable & Equatable { static func == (lhs: EventSpec, rhs: EventSpec) -> Bool { return lhs.source.lowercased() == rhs.source.lowercased() && lhs.type.lowercased() == rhs.type.lowercased() } func hash(into hasher: inout Hasher) { hasher.combine(type) hasher.combine(source) } } class FunctionalTestBase: XCTestCase { /// Use this property to execute code logic in the first run in this test class; this value changes to False after the parent tearDown is executed private(set) static var isFirstRun: Bool = true private static var networkService: FunctionalTestNetworkService = FunctionalTestNetworkService() /// Use this setting to enable debug mode logging in the `FunctionalTestBase` static var debugEnabled = false public class override func setUp() { super.setUp() UserDefaults.clearAll() MobileCore.setLogLevel(level: LogLevel.trace) networkService = FunctionalTestNetworkService() ServiceProvider.shared.networkService = networkService } public override func setUp() { super.setUp() continueAfterFailure = false MobileCore.registerExtensions([InstrumentedExtension.self]) } public override func tearDown() { super.tearDown() // to revisit when AMSDK-10169 is available // wait .2 seconds in case there are unexpected events that were in the dispatch process during cleanup usleep(200000) resetTestExpectations() FunctionalTestBase.isFirstRun = false EventHub.reset() UserDefaults.clearAll() } /// Reset event and network request expectations and drop the items received until this point func resetTestExpectations() { log("Resetting functional test expectations for events and network requests") InstrumentedExtension.reset() FunctionalTestBase.networkService.reset() } /// Unregisters the `InstrumentedExtension` from the Event Hub. This method executes asynchronous. func unregisterInstrumentedExtension() { let event = Event(name: "Unregister Instrumented Extension", type: FunctionalTestConst.EventType.INSTRUMENTED_EXTENSION, source: FunctionalTestConst.EventSource.UNREGISTER_EXTENSION, data: nil) MobileCore.dispatch(event: event) } // MARK: Expected/Unexpected events assertions /// Sets an expectation for a specific event type and source and how many times the event should be dispatched /// - Parameters: /// - type: the event type as a `String`, should not be empty /// - source: the event source as a `String`, should not be empty /// - count: the number of times this event should be dispatched, but default it is set to 1 /// - See also: /// - assertExpectedEvents(ignoreUnexpectedEvents:) func setExpectationEvent(type: String, source: String, expectedCount: Int32 = 1) { guard expectedCount > 0 else { assertionFailure("Expected event count should be greater than 0") return } guard !type.isEmpty, !source.isEmpty else { assertionFailure("Expected event type and source should be non-empty trings") return } InstrumentedExtension.expectedEvents[EventSpec(type: type, source: source)] = CountDownLatch(expectedCount) } /// Asserts if all the expected events were received and fails if an unexpected event was seen /// - Parameters: /// - ignoreUnexpectedEvents: if set on false, an assertion is made on unexpected events, otherwise the unexpected events are ignored /// - See also: /// - setExpectationEvent(type: source: count:) /// - assertUnexpectedEvents() func assertExpectedEvents(ignoreUnexpectedEvents: Bool = false, file: StaticString = #file, line: UInt = #line) { guard InstrumentedExtension.expectedEvents.count > 0 else { // swiftlint:disable:this empty_count assertionFailure("There are no event expectations set, use this API after calling setExpectationEvent", file: file, line: line) return } let currentExpectedEvents = InstrumentedExtension.expectedEvents.shallowCopy for expectedEvent in currentExpectedEvents { let waitResult = expectedEvent.value.await(timeout: FunctionalTestConst.Defaults.WAIT_EVENT_TIMEOUT) let expectedCount: Int32 = expectedEvent.value.getInitialCount() let receivedCount: Int32 = expectedEvent.value.getInitialCount() - expectedEvent.value.getCurrentCount() XCTAssertFalse(waitResult == DispatchTimeoutResult.timedOut, "Timed out waiting for event type \(expectedEvent.key.type) and source \(expectedEvent.key.source), expected \(expectedCount), but received \(receivedCount)", file: (file), line: line) XCTAssertEqual(expectedCount, receivedCount, "Expected \(expectedCount) event(s) of type \(expectedEvent.key.type) and source \(expectedEvent.key.source), but received \(receivedCount)", file: (file), line: line) } guard ignoreUnexpectedEvents == false else { return } assertUnexpectedEvents(file: file, line: line) } /// Asserts if any unexpected event was received. Use this method to verify the received events are correct when setting event expectations. /// - See also: setExpectationEvent(type: source: count:) func assertUnexpectedEvents(file: StaticString = #file, line: UInt = #line) { wait() var unexpectedEventsReceivedCount = 0 var unexpectedEventsAsString = "" let currentReceivedEvents = InstrumentedExtension.receivedEvents.shallowCopy for receivedEvent in currentReceivedEvents { // check if event is expected and it is over the expected count if let expectedEvent = InstrumentedExtension.expectedEvents[EventSpec(type: receivedEvent.key.type, source: receivedEvent.key.source)] { _ = expectedEvent.await(timeout: FunctionalTestConst.Defaults.WAIT_EVENT_TIMEOUT) let expectedCount: Int32 = expectedEvent.getInitialCount() let receivedCount: Int32 = expectedEvent.getInitialCount() - expectedEvent.getCurrentCount() XCTAssertEqual(expectedCount, receivedCount, "Expected \(expectedCount) events of type \(receivedEvent.key.type) and source \(receivedEvent.key.source), but received \(receivedCount)", file: (file), line: line) } // check for events that don't have expectations set else { unexpectedEventsReceivedCount += receivedEvent.value.count unexpectedEventsAsString.append("(\(receivedEvent.key.type), \(receivedEvent.key.source), \(receivedEvent.value.count)),") log("Received unexpected event with type: \(receivedEvent.key.type) source: \(receivedEvent.key.source)") } } XCTAssertEqual(0, unexpectedEventsReceivedCount, "Received \(unexpectedEventsReceivedCount) unexpected event(s): \(unexpectedEventsAsString)", file: (file), line: line) } /// To be revisited once AMSDK-10169 is implemented /// - Parameters: /// - timeout:how long should this method wait, in seconds; by default it waits up to 1 second func wait(_ timeout: UInt32? = FunctionalTestConst.Defaults.WAIT_TIMEOUT) { if let timeout = timeout { sleep(timeout) } } /// Returns the `ACPExtensionEvent`(s) dispatched through the Event Hub, or empty if none was found. /// Use this API after calling `setExpectationEvent(type:source:count:)` to wait for the right amount of time /// - Parameters: /// - type: the event type as in the exectation /// - source: the event source as in the expectation /// - timeout: how long should this method wait for the expected event, in seconds; by default it waits up to 1 second /// - Returns: list of events with the provided `type` and `source`, or empty if none was dispatched func getDispatchedEventsWith(type: String, source: String, timeout: TimeInterval = FunctionalTestConst.Defaults.WAIT_EVENT_TIMEOUT, file: StaticString = #file, line: UInt = #line) -> [Event] { if InstrumentedExtension.expectedEvents[EventSpec(type: type, source: source)] != nil { let waitResult = InstrumentedExtension.expectedEvents[EventSpec(type: type, source: source)]?.await(timeout: timeout) XCTAssertFalse(waitResult == DispatchTimeoutResult.timedOut, "Timed out waiting for event type \(type) and source \(source)", file: file, line: line) } else { wait(FunctionalTestConst.Defaults.WAIT_TIMEOUT) } return InstrumentedExtension.receivedEvents[EventSpec(type: type, source: source)] ?? [] } /// Synchronous call to get the shared state for the specified `stateOwner`. This API throws an assertion failure in case of timeout. /// - Parameter ownerExtension: the owner extension of the shared state (typically the name of the extension) /// - Parameter timeout: how long should this method wait for the requested shared state, in seconds; by default it waits up to 3 second /// - Returns: latest shared state of the given `stateOwner` or nil if no shared state was found func getSharedStateFor(_ ownerExtension: String, timeout: TimeInterval = FunctionalTestConst.Defaults.WAIT_SHARED_STATE_TIMEOUT) -> [AnyHashable: Any]? { log("GetSharedState for \(ownerExtension)") let event = Event(name: "Get Shared State", type: FunctionalTestConst.EventType.INSTRUMENTED_EXTENSION, source: FunctionalTestConst.EventSource.SHARED_STATE_REQUEST, data: ["stateowner": ownerExtension]) var returnedState: [AnyHashable: Any]? let expectation = XCTestExpectation(description: "Shared state data returned") MobileCore.dispatch(event: event, responseCallback: { event in if let eventData = event?.data { returnedState = eventData["state"] as? [AnyHashable: Any] } expectation.fulfill() }) wait(for: [expectation], timeout: timeout) return returnedState } // MARK: Network Service helpers /// Set a custom network response to a network request /// - Parameters: /// - url: The URL for which to return the response /// - httpMethod: The `HttpMethod` for which to return the response, along with the `url` /// - responseHttpConnection: `HttpConnection` to be returned when a `NetworkRequest` with the specified `url` and `httpMethod` is seen; when nil is provided the default /// `HttpConnection` is returned func setNetworkResponseFor(url: String, httpMethod: HttpMethod, responseHttpConnection: HttpConnection?) { guard let requestUrl = URL(string: url) else { assertionFailure("Unable to convert the provided string \(url) to URL") return } _ = FunctionalTestBase.networkService.setResponseConnectionFor(networkRequest: NetworkRequest(url: requestUrl, httpMethod: httpMethod), responseConnection: responseHttpConnection) } /// Set a network request expectation. /// /// - Parameters: /// - url: The URL for which to set the expectation /// - httpMethod: the `HttpMethod` for which to set the expectation, along with the `url` /// - count: how many times a request with this url and httpMethod is expected to be sent, by default it is set to 1 /// - See also: /// - assertNetworkRequestsCount() /// - getNetworkRequestsWith(url:httpMethod:) func setExpectationNetworkRequest(url: String, httpMethod: HttpMethod, expectedCount: Int32 = 1, file: StaticString = #file, line: UInt = #line) { guard expectedCount > 0 else { assertionFailure("Expected event count should be greater than 0") return } guard let requestUrl = URL(string: url) else { assertionFailure("Unable to convert the provided string \(url) to URL") return } FunctionalTestBase.networkService.setExpectedNetworkRequest(networkRequest: NetworkRequest(url: requestUrl, httpMethod: httpMethod), count: expectedCount) } /// Asserts that the correct number of network requests were being sent, based on the previously set expectations. /// - See also: /// - setExpectationNetworkRequest(url:httpMethod:) func assertNetworkRequestsCount(file: StaticString = #file, line: UInt = #line) { let expectedNetworkRequests = FunctionalTestBase.networkService.getExpectedNetworkRequests() guard !expectedNetworkRequests.isEmpty else { assertionFailure("There are no network request expectations set, use this API after calling setExpectationNetworkRequest") return } for expectedRequest in expectedNetworkRequests { let waitResult = expectedRequest.value.await(timeout: 2) let expectedCount: Int32 = expectedRequest.value.getInitialCount() let receivedCount: Int32 = expectedRequest.value.getInitialCount() - expectedRequest.value.getCurrentCount() XCTAssertFalse(waitResult == DispatchTimeoutResult.timedOut, "Timed out waiting for network request(s) with URL \(expectedRequest.key.url.absoluteString) and HTTPMethod \(expectedRequest.key.httpMethod.toString()), expected \(expectedCount) but received \(receivedCount)", file: file, line: line) XCTAssertEqual(expectedCount, receivedCount, "Expected \(expectedCount) network request(s) for URL \(expectedRequest.key.url.absoluteString) and HTTPMethod \(expectedRequest.key.httpMethod.toString()), but received \(receivedCount)", file: file, line: line) } } /// Returns the `NetworkRequest`(s) sent through the Core NetworkService, or empty if none was found. /// Use this API after calling `setExpectationNetworkRequest(url:httpMethod:count:)` to wait for the right amount of time /// - Parameters: /// - url: The URL for which to retrieved the network requests sent, should be a valid URL /// - httpMethod: the `HttpMethod` for which to retrieve the network requests, along with the `url` /// - timeout: how long should this method wait for the expected network requests, in seconds; by default it waits up to 1 second /// - Returns: list of network requests with the provided `url` and `httpMethod`, or empty if none was dispatched /// - See also: /// - setExpectationNetworkRequest(url:httpMethod:) func getNetworkRequestsWith(url: String, httpMethod: HttpMethod, timeout: TimeInterval = FunctionalTestConst.Defaults.WAIT_NETWORK_REQUEST_TIMEOUT, file: StaticString = #file, line: UInt = #line) -> [NetworkRequest] { guard let requestUrl = URL(string: url) else { assertionFailure("Unable to convert the provided string \(url) to URL") return [] } let networkRequest = NetworkRequest(url: requestUrl, httpMethod: httpMethod) if let waitResult = FunctionalTestBase.networkService.awaitFor(networkRequest: networkRequest, timeout: timeout) { XCTAssertFalse(waitResult == DispatchTimeoutResult.timedOut, "Timed out waiting for network request(s) with URL \(url) and HTTPMethod \(httpMethod.toString())", file: file, line: line) } else { wait(FunctionalTestConst.Defaults.WAIT_TIMEOUT) } return FunctionalTestBase.networkService.getReceivedNetworkRequestsMatching(networkRequest: networkRequest) } /// Use this API for JSON formatted `NetworkRequest` body in order to retrieve a flattened dictionary containing its data. /// This API fails the assertion if the request body cannot be parsed as JSON. /// - Parameters: /// - networkRequest: the NetworkRequest to parse /// - Returns: The JSON request body represented as a flatten dictionary func getFlattenNetworkRequestBody(_ networkRequest: NetworkRequest, file: StaticString = #file, line: UInt = #line) -> [String: Any] { if !networkRequest.connectPayload.isEmpty { let data = Data(networkRequest.connectPayload.utf8) if let payloadAsDictionary = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] { return flattenDictionary(dict: payloadAsDictionary) } else { XCTFail("Failed to parse networkRequest.connectionPayload to JSON", file: file, line: line) } } log("Connection payload is empty for network request with URL \(networkRequest.url.absoluteString), HTTPMethod \(networkRequest.httpMethod.toString())") return [:] } /// Print message to console if `FunctionalTestBase.debug` is true /// - Parameter message: message to log to console func log(_ message: String) { FunctionalTestBase.log(message) } /// Print message to console if `FunctionalTestBase.debug` is true /// - Parameter message: message to log to console static func log(_ message: String) { guard !message.isEmpty && FunctionalTestBase.debugEnabled else { return } print("FunctionalTestBase - \(message)") } }
55.098802
308
0.693094
76afd6dde396d44b0d5b370df157283a30e70799
544
// // URLSessionProtocol.swift // TestingNSURLSession // // Created by Joe Masilotti on 1/8/16. // Copyright © 2016 Masilotti.com. All rights reserved. // // UPDATED by Jarrod Parkes on 08/17/17. // import Foundation // MARK: - URLSession: URLSessionProtocol extension URLSession: URLSessionProtocol { public func dataTaskWithURL(_ url: URL, completionHandler: @escaping DataTaskResult) -> URLSessionDataTaskProtocol { return (dataTask(with: url, completionHandler: completionHandler)) as URLSessionDataTaskProtocol } }
27.2
120
0.744485
48ab2044e839a3f6ee671fcb2ef9b476829dc835
2,102
// // Model.swift // ContentsSwitch // // Created by cookie on 20/02/2018. // Copyright © 2018 cookie. All rights reserved. // import Foundation import UIKit public struct LabelSwitchConfig { struct GradientBack { var colors: [CGColor] var startPoint: CGPoint var endPoint: CGPoint } var text: String var textColor: UIColor var font: UIFont var backgroundColor: UIColor var backGradient: GradientBack? var backImage: UIImage? public init(text: String, textColor: UIColor, font: UIFont, backgroundColor: UIColor) { self.text = text self.textColor = textColor self.font = font self.backgroundColor = backgroundColor } public init(text: String, textColor: UIColor, font: UIFont, gradientColors: [CGColor], startPoint: CGPoint, endPoint: CGPoint) { self.init(text: text, textColor: textColor, font: font, backgroundColor: .white) self.backGradient = GradientBack(colors: gradientColors, startPoint: startPoint, endPoint: endPoint) } public init(text: String, textColor: UIColor, font: UIFont, image: UIImage?) { self.init(text: text, textColor: textColor, font: font, backgroundColor: .white) self.backImage = image } public static let defaultLeft = LabelSwitchConfig(text: "Left", textColor: .white, font: .boldSystemFont(ofSize: 20), backgroundColor: UIColor.red) public static let defaultRight = LabelSwitchConfig(text: "Right", textColor: .white, font: .boldSystemFont(ofSize: 20), backgroundColor: UIColor.blue) } public enum LabelSwitchState { case L case R mutating func flip() { switch self { case .L: self = .R case .R: self = .L } } }
29.605634
132
0.559943
5b9b5412def4ed1fd4617a93cd253fb6661130a9
63
// // File.swift // SmartconfigExample // import Foundation
9
22
0.68254
91a0066b84765d44abf3bf1959680d89c4f1a25e
1,106
// // WechatAuth.swift // Pay_Example // // Created by Tank on 2018/9/14. // Copyright © 2018年 CocoaPods. All rights reserved. // import UIKit import Pay extension PaySDK { public func sendAuthRequest() -> Void { let req = SendAuthReq() req.scope = "snsapi_userinfo" req.state = state WXApi.send(req) } } extension PaySDK: WXApiDelegate { public func onResp(_ resp: BaseResp!) { if type(of: resp) == SendAuthReq.self { let authResp = resp as! SendAuthResp if 0 == authResp.errCode && state == authResp.state { self.authDelegate?.authRequestSuccess(code: authResp.code) } else { self.authDelegate?.authRequestError(error: authResp.errStr) } } else if (type(of: resp) == PayResp.self) { let payResp = resp as! PayResp if 0 == payResp.errCode { payDelegate?.payRequestSuccess(data: payResp.returnKey) } else { payDelegate?.payRequestError(error: payResp.errStr) } } } }
27.65
75
0.573237
87f9e1af7c70d176bce0dd539647ba7a0b9e9a52
4,995
// // SpeedtestTests.swift // RMBT // // Created by Benjamin Pucher on 24.08.15. // Copyright © 2015 Specure GmbH. All rights reserved. // import XCTest class SpeedtestTests: XCTestCase { override func setUp() { super.setUp() // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // tap allow on location permission popup addUIInterruptionMonitorWithDescription("Location Dialog") { (alert) -> Bool in if alert.label == "Location Prompt" { alert.buttons["Allow"].tap() return true } return false } } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func test01RunTest() { let app = XCUIApplication() app.buttons["START"].tap() /// let testPredicate = NSPredicate(format: "exists == 1") let object = app.navigationBars.elementMatchingType(.Any, identifier: "Test Result") expectationForPredicate(testPredicate, evaluatedWithObject: object, handler: nil) waitForExpectationsWithTimeout(60, handler: nil) /// app.navigationBars["Test Result"].childrenMatchingType(.Button).matchingIdentifier("Back").elementBoundByIndex(0).tap() } func test02AbortRunningTest() { let app = XCUIApplication() app.buttons["START"].tap() sleep(10) // not perfect but working... app.childrenMatchingType(.Window).elementBoundByIndex(0).childrenMatchingType(.Other).element.childrenMatchingType(.Other).element.tap() app.alerts["NetTest"].collectionViews.buttons["Abort Test"].tap() // TODO: test for start screen visible again! } func test03AbortRunningTestMultipleTimes() { let app = XCUIApplication() app.buttons["START"].tap() sleep(10) // not perfect but working... app.childrenMatchingType(.Window).elementBoundByIndex(0).childrenMatchingType(.Other).element.childrenMatchingType(.Other).element.tap() app.alerts["NetTest"].collectionViews.buttons["Continue"].tap() // continue sleep(10) // not perfect but working... app.childrenMatchingType(.Window).elementBoundByIndex(0).childrenMatchingType(.Other).element.childrenMatchingType(.Other).element.tap() app.alerts["NetTest"].collectionViews.buttons["Abort Test"].tap() // abort // TODO: test for start screen visible again! } func test04DontAbortRunningTest() { let app = XCUIApplication() app.buttons["START"].tap() sleep(10) // not perfect but working... app.childrenMatchingType(.Window).elementBoundByIndex(0).childrenMatchingType(.Other).element.childrenMatchingType(.Other).element.tap() app.alerts["NetTest"].collectionViews.buttons["Continue"].tap() /// let testPredicate = NSPredicate(format: "exists == 1") let object = app.navigationBars.elementMatchingType(.Any, identifier: "Test Result") expectationForPredicate(testPredicate, evaluatedWithObject: object, handler: nil) waitForExpectationsWithTimeout(60, handler: nil) /// app.navigationBars["Test Result"].childrenMatchingType(.Button).matchingIdentifier("Back").elementBoundByIndex(0).tap() } func test05DontAbortRunningTestMultipleTimes() { let app = XCUIApplication() app.buttons["START"].tap() sleep(10) // not perfect but working... app.childrenMatchingType(.Window).elementBoundByIndex(0).childrenMatchingType(.Other).element.childrenMatchingType(.Other).element.tap() app.alerts["NetTest"].collectionViews.buttons["Continue"].tap() sleep(10) // not perfect but working... app.childrenMatchingType(.Window).elementBoundByIndex(0).childrenMatchingType(.Other).element.childrenMatchingType(.Other).element.tap() app.alerts["NetTest"].collectionViews.buttons["Continue"].tap() /// let testPredicate = NSPredicate(format: "exists == 1") let object = app.navigationBars.elementMatchingType(.Any, identifier: "Test Result") expectationForPredicate(testPredicate, evaluatedWithObject: object, handler: nil) waitForExpectationsWithTimeout(60, handler: nil) /// app.navigationBars["Test Result"].childrenMatchingType(.Button).matchingIdentifier("Back").elementBoundByIndex(0).tap() } /* func test06HomeButtonPressDuringSpeedtest() { let app = XCUIApplication() app.buttons["START"].tap() sleep(10) // not perfect but working... XCUIDevice.sharedDevice().pressButton(XCUIDeviceButton.Home) } */ }
34.93007
144
0.669469
efb3234de329218413846efd0d9df8cbc897275b
4,027
// // MainView.swift // Emotion // // Created by User on 19.11.2021. // import SwiftUI struct MainView: View { //@Environment(\.managedObjectContext) var moc @FetchRequest(sortDescriptors: []) var notes: FetchedResults<Notes> @EnvironmentObject var coordinator: EmotionCoordinator @Environment(\.colorScheme) var colorScheme var body: some View { ZStack { List { ForEach(coordinator.items, id: \.self.task) { item in RowItem(item: item) } } .lineSpacing(5) .overlay(ZStack { Button(action: coordinator.showAddTask) { Image("AddTaskImage") .resizable() .scaledToFit() .background(Circle().fill(Color("mainColor"))) .frame(width: 48, height: 48, alignment: .center) } PulseButton() } .padding(.bottom, 15) .padding(.trailing, 15), alignment: .bottomTrailing ) } } } struct MainView_Previews: PreviewProvider { static var previews: some View { MainView() } } struct PulseButton: View { @State var animate = false var body: some View { ZStack { Circle() .strokeBorder(Color("mainColor"), lineWidth: 1) .background(Circle().foregroundColor(Color("mainColor"))) .opacity(0.25) .frame(width: 80, height: 80) .scaleEffect(self.animate ? 1 : 0) Circle() .strokeBorder(Color("mainColor"), lineWidth: 1) .background(Circle().foregroundColor(Color("mainColor"))) .opacity(0.35) .frame(width: 70, height: 70) .scaleEffect(self.animate ? 1 : 0) Circle() .strokeBorder(Color("mainColor"), lineWidth: 1) .background(Circle().foregroundColor(Color("mainColor"))) .opacity(0.45) .frame(width: 60, height: 60) .scaleEffect(self.animate ? 1 : 0) Circle() .strokeBorder(Color("mainColor"), lineWidth: 1) .background(Circle().foregroundColor(Color("mainColor"))) .opacity(0.55) .frame(width: 50, height: 50) .scaleEffect(self.animate ? 1 : 0) }.onAppear { self.animate.toggle() } .animation(Animation.linear(duration: 1.5).repeatForever(autoreverses: false)) } } struct RowItem: View { let item: Notes var body: some View { HStack { Circle() .background(.white) Image(Emotion.Smile.getEmotionFor(id: Int(item.emotion)).image) .cornerRadius(15) .foregroundColor(.white) .frame(width: 40, height: 40) .padding(5) Text(item.task ?? "Empty") .font(.footnote) .fontWeight(.light) .multilineTextAlignment(.leading) .lineLimit(4) .padding(.trailing, 10) HStack { Divider() .foregroundColor(.white) } VStack { Text("13") .font(.title) .fontWeight(.semibold) .foregroundColor(.white) Text("SEP") .font(.title) .fontWeight(.semibold) .foregroundColor(.white) } .padding(5) } .background(Color("mainColor")) .cornerRadius(15) .padding() } }
28.971223
86
0.454184
14d5018fad76e06cfa953a646440089b33ee9c59
115
import XCTest import FilesTests var tests = [XCTestCaseEntry]() tests += FilesTests.__allTests() XCTMain(tests)
12.777778
32
0.765217
ed98a6b51274c27fa83f4910a808bda1533f6845
2,027
// // MainTabBarController.swift // Habits // // Created by shunnamiki on 2021/06/01. // import UIKit class MainTabBarController: UITabBarController { let homeVC: UINavigationController = { let vc: UICollectionViewController = { let vc = HomeCollectionViewController() let image = UIImage(systemName: "house.fill") vc.tabBarItem = UITabBarItem(title: "Home", image: image, tag: 0) return vc }() let nav = UINavigationController(rootViewController: vc) return nav }() let habitVC: UINavigationController = { let vc: UICollectionViewController = { let vc = HabitCollectionViewController() let image = UIImage(systemName: "star.fill") vc.tabBarItem = UITabBarItem(title: "Habits", image: image, tag: 1) return vc }() let nav = UINavigationController(rootViewController: vc) return nav }() let userVC: UINavigationController = { let vc: UICollectionViewController = { let vc = UserCollectionViewController() let image = UIImage(systemName: "person.2.fill") vc.tabBarItem = UITabBarItem(title: "People", image: image, tag: 2) return vc }() let nav = UINavigationController(rootViewController: vc) return nav }() let logHabbitVC: UINavigationController = { let vc: UICollectionViewController = { let vc = LogHabitCollectionViewController() let image = UIImage(systemName: "checkmark.square.fill") vc.tabBarItem = UITabBarItem(title: "Log Habits", image: image, tag: 1) return vc }() let nav = UINavigationController(rootViewController: vc) return nav }() override func viewDidLoad() { super.viewDidLoad() viewControllers = [ homeVC, habitVC, userVC, logHabbitVC, ] } }
29.808824
83
0.588555
1471656cd624eef93fb2aa541b768ee6348b22b5
3,484
// // Created by entaoyang on 2018-12-29. // Copyright (c) 2018 yet.net. All rights reserved. // import Foundation import UIKit public extension UILabel { static var makePrimary: UILabel { return UILabel.Primary } static var makeMinor: UILabel { return UILabel.Minor } static var Primary: UILabel { let a = UILabel(frame: .zero) a.stylePrimary() return a } static var Minor: UILabel { let a = UILabel(frame: .zero) a.styleMinor() return a } @discardableResult func styleMinor() -> Self { self.textColor = Theme.Text.minorColor self.font = Theme.Text.minorFont return self } @discardableResult func stylePrimary() -> Self { self.textColor = Theme.Text.primaryColor self.font = Theme.Text.primaryFont return self } var heightThatFit: CGFloat { let sz = self.sizeThatFits(.zero) return sz.height } var widthThatFit: CGFloat { let sz = self.sizeThatFits(.zero) return sz.width } @discardableResult func align(_ a: NSTextAlignment) -> Self { self.textAlignment = a return self } @discardableResult func lines(_ n: Int) -> Self { self.numberOfLines = n self.superview?.setNeedsLayout() return self } @discardableResult func text(_ s: String?) -> Self { self.text = s self.superview?.setNeedsLayout() return self } @discardableResult func font(_ f: UIFont) -> Self { self.font = f self.superview?.setNeedsLayout() return self } @discardableResult func textColor(_ c: UIColor) -> Self { self.textColor = c return self } @discardableResult func shadowColor(_ c: UIColor?) -> Self { self.shadowColor = c return self } @discardableResult func shadowOffset(_ s: CGSize) -> Self { self.shadowOffset = s return self } @discardableResult func lineBreakMode(_ m: NSLineBreakMode) -> Self { self.lineBreakMode = m return self } @discardableResult func attributedText(_ s: NSAttributedString?) -> Self { self.attributedText = s return self } @discardableResult func highlightedTextColor(_ c: UIColor?) -> Self { self.highlightedTextColor = c return self } @discardableResult func highlighted(_ b: Bool) -> Self { self.isHighlighted = b return self } @discardableResult func userInteractionEnabled(_ b: Bool) -> Self { self.isUserInteractionEnabled = b return self } @discardableResult func enabled(_ b: Bool) -> Self { self.isEnabled = b return self } @discardableResult func adjustsFontSizeToFitWidth(_ b: Bool) -> Self { self.adjustsFontSizeToFitWidth = b return self } @discardableResult func minimumScaleFactor(_ f: CGFloat) -> Self { self.minimumScaleFactor = f return self } @discardableResult func allowsDefaultTighteningForTruncation(_ b: Bool) -> Self { self.allowsDefaultTighteningForTruncation = b return self } @discardableResult func lineBreakStrategy(_ s: NSParagraphStyle.LineBreakStrategy) -> Self { self.lineBreakStrategy = s return self } }
21.775
77
0.600746
38a7ebb2b6093a08e880ad52d0ab470da40cce83
858
// // SimpleProtocols.swift // Mocky_Example // // Created by Andrzej Michnia on 16.11.2017. // Copyright © 2017 CocoaPods. All rights reserved. // import Foundation //sourcery: AutoMockable protocol SimpleProtocolWithMethods { func simpleMethod() func simpleMehtodThatReturns() -> Int func simpleMehtodThatReturns(param: String) -> String func simpleMehtodThatReturns(optionalParam: String?) -> String? } //sourcery: AutoMockable protocol SimpleProtocolWithProperties { var property: String { get set } weak var weakProperty: AnyObject! { get set } var propertyGetOnly: String { get } var propertyOptional: Int? { get set } var propertyImplicit: Int! { get set } } //sourcery: AutoMockable protocol SimpleProtocolWithBothMethodsAndProperties { var property: String { get } func simpleMethod() -> String }
26
67
0.727273
1a04a708a2f8ada1c9b12051f8cc4e47141e2cb1
162
// // Copyright © 2020 Paris Android User Group. All rights reserved. // import FirebaseFirestore import CodableFirebase extension Timestamp: TimestampType {}
18
67
0.777778
383122313c10f0c810df885b6036f511558f9439
331
import Foundation class AboutConfigurator { func configure(view: AboutViewController) { let router = AboutRouter() router.transitionHandler = view let presenter = AboutPresenter() presenter.view = view presenter.router = router view.output = presenter } }
22.066667
47
0.616314
ddc9e04a47bc174089337d5830ee892c1ecc57f0
3,775
import Prelude import Prelude_UIKit import UIKit public let updateDraftCloseBarButtonItemStyle = closeBarButtonItemStyle <> UIBarButtonItem.lens.accessibilityHint %~ { _ in "Closes update draft." } public let updateDraftPreviewBarButtonItemStyle = doneBarButtonItemStyle <> UIBarButtonItem.lens.title %~ { _ in Strings.general_navigation_buttons_preview() } public let updateTitleTextFieldStyle = formFieldStyle <> UITextField.lens.font %~ { _ in .ksr_title1(size: 22) } <> UITextField.lens.placeholder %~ { _ in Strings.dashboard_post_update_compose_placeholder_title() } <> UITextField.lens.returnKeyType .~ .next <> UITextField.lens.textColor .~ .ksr_support_400 public let updateBodyTextViewStyle = UITextView.lens.backgroundColor .~ .clear <> UITextView.lens.font %~ { _ in .ksr_callout() } <> UITextView.lens.textColor .~ .ksr_support_400 <> UITextView.lens.textContainerInset .~ .init(top: 34, left: 12, bottom: 12, right: 12) <> UITextView.lens.textContainer.lineFragmentPadding .~ 0 <> UITextView.lens.tintColor .~ .ksr_create_700 public let updateBodyPlaceholderTextViewStyle = updateBodyTextViewStyle <> UITextView.lens.text %~ { _ in Strings.Share_an_update_about_your_project() } <> UITextView.lens.textColor .~ .ksr_support_400 <> UITextView.lens.isUserInteractionEnabled .~ false public let updateBackersOnlyButtonStyle = UIButton.lens.contentEdgeInsets .~ .init(top: 0, left: 7, bottom: 0, right: 0) <> UIButton.lens.image(for: .normal) %~ { _ in image(named: "update-draft-visibility-public-icon") } <> UIButton.lens.image(for: .selected) %~ { _ in image(named: "update-draft-visibility-backers-only-icon") } <> UIButton.lens.tintColor .~ .ksr_support_400 <> UIButton.lens.title(for: .normal) %~ { _ in Strings.dashboard_post_update_compose_public_label() } <> UIButton.lens.title(for: .selected) %~ { _ in Strings.dashboard_post_update_compose_private_label() } <> UIButton.lens.titleColor(for: .normal) .~ .ksr_support_400 <> UIButton.lens.titleEdgeInsets .~ .init(top: 0, left: 7, bottom: 0, right: 0) <> UIButton.lens.titleLabel.font %~ { _ in .ksr_caption1() } public let updateAddAttachmentButtonStyle = UIButton.lens.backgroundColor .~ .ksr_support_100 <> UIButton.lens.contentCompressionResistancePriority(for: .vertical) .~ .required <> UIButton.lens.contentEdgeInsets .~ .init(top: 11, left: 9, bottom: 12, right: 9) <> UIButton.lens.contentHuggingPriority(for: .vertical) .~ .required <> UIButton.lens.image(for: .normal) %~ { _ in image(named: "update-draft-add-attachment-icon") } <> UIButton.lens.layer.borderColor .~ UIColor.ksr_support_300.cgColor <> UIButton.lens.layer.borderWidth .~ 1 <> UIButton.lens.layer.cornerRadius .~ 8 <> UIButton.lens.tintColor .~ .ksr_support_400 <> UIButton.lens.title(for: .normal) .~ nil public let updateAddAttachmentExpandedButtonStyle = UIButton.lens.tintColor .~ .ksr_support_400 <> UIButton.lens.title(for: .normal) %~ { _ in Strings.dashboard_post_update_compose_attachment_buttons_add_attachment() } <> UIButton.lens.titleLabel.font %~ { _ in .ksr_caption1() } public let updateAttachmentsScrollViewStyle = UIScrollView.lens.showsHorizontalScrollIndicator .~ false public let updateAttachmentsStackViewStyle = UIStackView.lens.spacing .~ 8 public let updateAttachmentsThumbStyle = UIImageView.lens.contentMode .~ .scaleAspectFill <> UIImageView.lens.clipsToBounds .~ true <> UIImageView.lens.layer.cornerRadius .~ 4 <> UIImageView.lens.isUserInteractionEnabled .~ true public let updatePreviewBarButtonItemStyle = doneBarButtonItemStyle <> UIBarButtonItem.lens.title %~ { _ in Strings.general_navigation_buttons_publish() }
46.604938
105
0.742781
4a6e85b8552eb3aeb208a74fcd2f8f85a20ae1f7
8,779
/** * 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. **/ #if os(Linux) import Foundation public let LclErrorDomain = "Lcl.Error.Domain" public class LclJSONSerialization { private static let JSON_WRITE_ERROR = "JSON Write failure." private static let FALSE = "false" private static let TRUE = "true" private static let NULL = "null" public class func isValidJSONObject(_ obj: Any) -> Bool { // TODO: - revisit this once bridging story gets fully figured out func isValidJSONObjectInternal(_ obj: Any) -> Bool { // object is Swift.String or NSNull if obj is String || obj is Int || obj is Bool || obj is NSNull || obj is UInt { return true } // object is a Double and is not NaN or infinity if let number = obj as? Double { let invalid = number.isInfinite || number.isNaN return !invalid } // object is a Float and is not NaN or infinity if let number = obj as? Float { let invalid = number.isInfinite || number.isNaN return !invalid } // object is NSNumber and is not NaN or infinity if let number = obj as? NSNumber { let invalid = number.doubleValue.isInfinite || number.doubleValue.isNaN return !invalid } let mirror = Mirror(reflecting: obj) if mirror.displayStyle == .collection { // object is Swift.Array for element in mirror.children { guard isValidJSONObjectInternal(element.value) else { return false } } return true } else if mirror.displayStyle == .dictionary { // object is Swift.Dictionary for pair in mirror.children { let pairMirror = Mirror(reflecting: pair.value) if pairMirror.displayStyle == .tuple && pairMirror.children.count == 2 { let generator = pairMirror.children.makeIterator() if generator.next()!.value is String { guard isValidJSONObjectInternal(generator.next()!.value) else { return false } } else { // Invalid JSON Object, Key not a String return false } } else { // Invalid Dictionary return false } } return true } else { // invalid object return false } } // top level object must be an Swift.Array or Swift.Dictionary let mirror = Mirror(reflecting: obj) guard mirror.displayStyle == .collection || mirror.displayStyle == .dictionary else { return false } return isValidJSONObjectInternal(obj) } public class func dataWithJSONObject(_ obj: Any, options: JSONSerialization.WritingOptions) throws -> Data { var result = Data() try writeJson(obj, options: options) { (str: String?) in if let str = str { result.append(str.data(using: String.Encoding.utf8) ?? Data()) } } return result } /* Helper function to enable writing to NSData as well as NSStream */ private static func writeJson(_ obj: Any, options opt: JSONSerialization.WritingOptions, writer: (String?) -> Void) throws { let prettyPrint = opt.rawValue & JSONSerialization.WritingOptions.prettyPrinted.rawValue != 0 let padding: String? = prettyPrint ? "" : nil try writeJsonValue(obj, padding: padding, writer: writer) } /* Write out a JSON value (simple value, object, or array) */ private static func writeJsonValue(_ obj: Any, padding: String?, writer: (String?) -> Void) throws { if obj is String { writer("\"") writer((obj as! String).replacingOccurrences(of: "\n", with: "\\n")) writer("\"") } else if obj is Bool { writer(obj as! Bool ? TRUE : FALSE) } else if obj is Int || obj is Float || obj is Double || obj is UInt { writer(String(describing: obj)) } else if obj is NSNumber { writer(JSON.stringFromNumber(obj as! NSNumber)) } else if obj is NSNull { writer(NULL) } else { let mirror = Mirror(reflecting: obj) if mirror.displayStyle == .collection { try writeJsonArray(mirror.children.map { $0.value as Any }, padding: padding, writer: writer) } else if mirror.displayStyle == .dictionary { try writeJsonObject(mirror.children.map { $0.value }, padding: padding, writer: writer) } else { print("writeJsonValue: Unsupported type \(type(of: obj))") throw createWriteError("Unsupported data type to be written out as JSON") } } } /* Write out a dictionary as a JSON object */ private static func writeJsonObject(_ pairs: Array<Any>, padding: String?, writer: (String?) -> Void) throws { let (nestedPadding, startOfLine, endOfLine) = setupPadding(padding) let nameValueSeparator = padding != nil ? ": " : ":" writer("{") var comma = "" let realComma = "," for pair in pairs { let pairMirror = Mirror(reflecting: pair) if pairMirror.displayStyle == .tuple && pairMirror.children.count == 2 { let generator = pairMirror.children.makeIterator() if let key = generator.next()!.value as? String { let value = generator.next()!.value writer(comma) comma = realComma writer(endOfLine) writer(nestedPadding) writer("\"") writer(key) writer("\"") writer(nameValueSeparator) try writeJsonValue(value, padding: nestedPadding, writer: writer) } } } writer(endOfLine) writer(startOfLine) writer("}") } /* Write out an array as a JSON Array */ private static func writeJsonArray(_ obj: Array<Any>, padding: String?, writer: (String?) -> Void) throws { let (nestedPadding, startOfLine, endOfLine) = setupPadding(padding) writer("[") var comma = "" let realComma = "," for value in obj { writer(comma) comma = realComma writer(endOfLine) writer(nestedPadding) try writeJsonValue(value, padding: nestedPadding, writer: writer) } writer(endOfLine) writer(startOfLine) writer("]") } /* Setup "padding" to be used in objects and arrays. Note: if padding is nil, then all padding, newlines etc., are suppressed */ private static func setupPadding(_ padding: String?) -> (String?, String?, String?) { var nestedPadding: String? var startOfLine: String? var endOfLine: String? if let padding = padding { nestedPadding = padding + " " startOfLine = padding endOfLine = "\n" } else { nestedPadding = nil startOfLine = nil endOfLine = nil } return (nestedPadding, startOfLine, endOfLine) } private static func createWriteError(_ reason: String) -> NSError { let userInfo: [String: Any] = [NSLocalizedDescriptionKey: JSON_WRITE_ERROR, NSLocalizedFailureReasonErrorKey: reason] return NSError(domain: LclErrorDomain, code: 1, userInfo: userInfo) } } #endif
36.27686
128
0.544937
d6344d4de4a233700a393f1398aae1283309c3b8
1,247
// // count.swift // RxSwiftExt-iOS // // Created by Fred on 06/11/2018. // Copyright © 2018 RxSwiftCommunity. All rights reserved. // import Foundation import RxSwift extension Observable { /** Count the number of items emitted by an Observable - seealso: [count operator on reactivex.io](http://reactivex.io/documentation/operators/count.html) - returns: An Observable sequence containing a value that represents how many elements in the specified observable sequence satisfy a condition if provided, else the count of items. */ public func count() -> Observable<Int> { return reduce(0) { count, _ in count + 1 } } /** Count the number of items emitted by an Observable - seealso: [count operator on reactivex.io](http://reactivex.io/documentation/operators/count.html) - parameter predicate: predicate determines what elements to be counted. - returns: An Observable sequence containing a value that represents how many elements in the specified observable sequence satisfy a condition if provided, else the count of items. */ public func count(_ predicate: @escaping (Element) throws -> Bool) -> Observable<Int> { return filter(predicate).count() } }
38.96875
186
0.710505
560c56f6b22794e51c06856abeb98500a33fd8cf
19,598
// // TheDaleksMasterPlan.swift // DW Episode Guide // // Created by Mark Howard on 09/11/2021. // import SwiftUI import UniformTypeIdentifiers struct TheDaleksMasterPlan: View { @Environment(\.managedObjectContext) private var viewContext @FetchRequest(entity: TheDaleksMasterPlanClass.entity(), sortDescriptors: [], animation: .default) private var items: FetchedResults<TheDaleksMasterPlanClass> @State var showingShare = false @AppStorage("TheDaleksMasterPlanNotes") var notes = "" #if os(iOS) @Environment(\.horizontalSizeClass) var horizontalSizeClass @FocusState private var isFocused: Bool #endif var body: some View { #if os(macOS) ForEach(items) { item in ScrollView { HStack { Spacer() Image("TheDaleksMasterPlan") .resizable() .scaledToFill() .cornerRadius(25) .frame(width: 150, height: 150) .contextMenu { Button(action: {let pasteboard = NSPasteboard.general pasteboard.clearContents() pasteboard.writeObjects([NSImage(named: "TheDaleksMasterPlan")!]) }) { Text("Copy") } } .onDrag { let data = NSImage(named: "TheDaleksMasterPlan")?.tiffRepresentation let provider = NSItemProvider(item: data as NSSecureCoding?, typeIdentifier: UTType.tiff.identifier as String) provider.previewImageHandler = { (handler, _, _) -> Void in handler?(data as NSSecureCoding?, nil) } return provider } Spacer() VStack { Text("\(item.title!)") .bold() .font(.title) .padding() Text("Story No. 21") .font(.title3) Text("Written By - Terry Nation\nAnd Dennis Spooner") .font(.title3) .multilineTextAlignment(.center) } Spacer() } .padding() Divider() HStack { Spacer() GroupBox(label: Label("Broadcast", systemImage: "dot.radiowaves.left.and.right")) { VStack { Spacer() HStack { Spacer() Text("\(item.broadcast!)") Spacer() } Spacer() } } Spacer() GroupBox(label: Label("Companions", systemImage: "person.2.fill")) { VStack { Spacer() HStack { Spacer() Text("\(item.companions!)") Spacer() } Spacer() } } Spacer() } .padding() Divider() HStack { Spacer() GroupBox(label: Label("Director", systemImage: "camera.fill")) { VStack { Spacer() HStack { Spacer() Text("\(item.director!)") Spacer() } Spacer() } } Spacer() GroupBox(label: Label("Producer", systemImage: "person.text.rectangle")) { VStack { Spacer() HStack { Spacer() Text("\(item.producer!)") Spacer() } Spacer() } } Spacer() } .padding() Divider() HStack { Spacer() GroupBox(label: Label("Doctor", systemImage: "person.crop.square.filled.and.at.rectangle")) { VStack { Spacer() HStack { Spacer() Text("\(item.doctor!)") Spacer() } Spacer() } } Spacer() GroupBox(label: Label("Length", systemImage: "clock.arrow.circlepath")) { VStack { Spacer() HStack { Spacer() Text("\(item.length!)") Spacer() } Spacer() } } Spacer() } .padding() Divider() HStack { Spacer() GroupBox(label: Label("Notes", systemImage: "note.text")) { TextEditor(text: $notes) .frame(height: 200) } Spacer() } .padding() } .toolbar { ToolbarItem(placement: .primaryAction) { Button(action: {self.showingShare = true}) { Image(systemName: "square.and.arrow.up") } .background(SharingsPicker(isPresented: $showingShare, sharingItems: [URL(string: "https://en.wikipedia.org/wiki/The_Daleks%27_Master_Plan")!])) } } .textSelection(.enabled) .navigationTitle("\(item.title!)") } #elseif os(iOS) if horizontalSizeClass == .compact { ForEach(items) { item in Form { HStack { Spacer() Image("TheDaleksMasterPlan") .resizable() .scaledToFill() .frame(width: 150, height: 150) .contextMenu { Button(action: {let pasteboard = UIPasteboard.general pasteboard.image = UIImage(named: "TheDaleksMasterPlan") }) { Label("Copy", systemImage: "doc.on.doc") } } .onDrag { return NSItemProvider(object: UIImage(named: "TheDaleksMasterPlan")! as UIImage) } preview: {Image("TheDaleksMasterPlan")} Spacer() } Text("Story No. 21") .onDrag { return NSItemProvider(object: String("Story No. 21") as NSString) } Text("Written By - Terry Nation\nAnd Dennis Spooner") .onDrag { return NSItemProvider(object: String("Written By - Terry Nation\nAnd Dennis Spooner") as NSString) } Section(header: Label("Broadcast", systemImage: "dot.radiowaves.left.and.right")) { Text("\(item.broadcast!)") .onDrag { return NSItemProvider(object: String("\(item.broadcast!)") as NSString) } } Section(header: Label("Companions", systemImage: "person.2.fill")) { Text("\(item.companions!)") .onDrag { return NSItemProvider(object: String("\(item.companions!)") as NSString) } } Section(header: Label("Director", systemImage: "camera.fill")) { Text("\(item.director!)") .onDrag { return NSItemProvider(object: String("\(item.director!)") as NSString) } } Section(header: Label("Producer", systemImage: "person.text.rectangle")) { Text("\(item.producer!)") .onDrag { return NSItemProvider(object: String("\(item.producer!)") as NSString) } } Section(header: Label("Doctor", systemImage: "person.crop.square.filled.and.at.rectangle")) { Text("\(item.doctor!)") .onDrag { return NSItemProvider(object: String("\(item.doctor!)") as NSString) } } Section(header: Label("Length", systemImage: "clock.arrow.circlepath")) { Text("\(item.length!)") .onDrag { return NSItemProvider(object: String("\(item.length!)") as NSString) } } Section(header: Label("Notes", systemImage: "note.text")) { TextEditor(text: $notes) .frame(height: 200) .focused($isFocused) } } .textSelection(.enabled) .navigationTitle("\(item.title!)") .navigationBarTitleDisplayMode(.inline) .toolbar { ToolbarItem(placement: .navigationBarTrailing) { Button(action: {self.showingShare = true}) { Image(systemName: "square.and.arrow.up") } .sheet(isPresented: $showingShare) { ActivityView(activityItems: [URL(string: "https://en.wikipedia.org/wiki/The_Daleks%27_Master_Plan")!], applicationActivities: nil) } } ToolbarItemGroup(placement: .keyboard) { Spacer() Button("Done") { isFocused = false } } } } } else { ForEach(items) { item in ScrollView { HStack { Spacer() Image("TheDaleksMasterPlan") .resizable() .scaledToFill() .cornerRadius(25) .frame(width: 150, height: 150) .contextMenu { Button(action: {let pasteboard = UIPasteboard.general pasteboard.image = UIImage(named: "TheDaleksMasterPlan") }) { Label("Copy", systemImage: "doc.on.doc") } } .onDrag { return NSItemProvider(object: UIImage(named: "TheDaleksMasterPlan")! as UIImage) } preview: {Image("TheDaleksMasterPlan")} Spacer() VStack { Text("\(item.title!)") .bold() .font(.title) .padding() Text("Story No. 21") .font(.title3) .onDrag { return NSItemProvider(object: String("Story No. 21") as NSString) } Text("Written By - Terry Nation\nAnd Dennis Spooner") .font(.title3) .multilineTextAlignment(.center) .onDrag { return NSItemProvider(object: String("Written By - Terry Nation\nAnd Dennis Spooner") as NSString) } } Spacer() } .padding() Divider() HStack { Spacer() GroupBox(label: Label("Broadcast", systemImage: "dot.radiowaves.left.and.right")) { VStack { Spacer() HStack { Spacer() Text("\(item.broadcast!)") Spacer() } Spacer() } } .onDrag { return NSItemProvider(object: String("\(item.broadcast!)") as NSString) } Spacer() GroupBox(label: Label("Companions", systemImage: "person.2.fill")) { VStack { Spacer() HStack { Spacer() Text("\(item.companions!)") Spacer() } Spacer() } } .onDrag { return NSItemProvider(object: String("\(item.companions!)") as NSString) } Spacer() } .padding() Divider() HStack { Spacer() GroupBox(label: Label("Director", systemImage: "camera.fill")) { VStack { Spacer() HStack { Spacer() Text("\(item.director!)") Spacer() } Spacer() } } .onDrag { return NSItemProvider(object: String("\(item.director!)") as NSString) } Spacer() GroupBox(label: Label("Producer", systemImage: "person.text.rectangle")) { VStack { Spacer() HStack { Spacer() Text("\(item.producer!)") Spacer() } Spacer() } } .onDrag { return NSItemProvider(object: String("\(item.producer!)") as NSString) } Spacer() } .padding() Divider() HStack { Spacer() GroupBox(label: Label("Doctor", systemImage: "person.crop.square.filled.and.at.rectangle")) { VStack { Spacer() HStack { Spacer() Text("\(item.doctor!)") Spacer() } Spacer() } } .onDrag { return NSItemProvider(object: String("\(item.doctor!)") as NSString) } Spacer() GroupBox(label: Label("Length", systemImage: "clock.arrow.circlepath")) { VStack { Spacer() HStack { Spacer() Text("\(item.length!)") Spacer() } Spacer() } } .onDrag { return NSItemProvider(object: String("\(item.length!)") as NSString) } Spacer() } .padding() Divider() HStack { Spacer() GroupBox(label: Label("Notes", systemImage: "note.text")) { TextEditor(text: $notes) .frame(height: 200) .focused($isFocused) } Spacer() } .padding() } .toolbar { ToolbarItem(placement: .primaryAction) { Button(action: {self.showingShare = true}) { Image(systemName: "square.and.arrow.up") } .sheet(isPresented: $showingShare) { ActivityView(activityItems: [URL(string: "https://en.wikipedia.org/wiki/The_Daleks%27_Master_Plan")!], applicationActivities: nil) } } ToolbarItemGroup(placement: .keyboard) { Spacer() Button("Done") { isFocused = false } } } .textSelection(.enabled) .navigationTitle("\(item.title!)") .navigationBarTitleDisplayMode(.inline) } } #endif } } struct TheDaleksMasterPlan_Previews: PreviewProvider { static var previews: some View { TheDaleksMasterPlan() } }
43.072527
164
0.333452
7256242b3ed447b648d95812a3645d2fb546e12b
150
// Copyright © 2021 Andreas Link. All rights reserved. enum SettingsViewAction { case didUpdateCheckBox(Bool) case didUpdateToken(String) }
21.428571
55
0.746667
755dbedf6d8817176ad6ef3531dfee617f5ef570
1,018
import Foundation let calendar = Calendar.current extension Date { // 根据当前时间计算下一天,以 Date 格式返回 public func nextDate() -> Date { let components = calendar.dateComponents([.hour, .minute, .second, .nanosecond], from: self) let nextDate = calendar.nextDate(after: self, matching: components, matchingPolicy: .nextTime) ?? Date() return nextDate } // 根据日期获取对应年、月、日 public func getYearMonthDay() -> (String, String, String) { let components = calendar.dateComponents([.year, .month, .day], from: self) let yearStr = String(format: "%d", components.year ?? 2020) let monthStr = String(format: "%d", components.month ?? 06) let dayStr = String(format: "%d", components.day ?? 18) return (yearStr, monthStr, dayStr) } // 日期转字符串 public func getDateStr() -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" return dateFormatter.string(from: self) } }
32.83871
112
0.628684
bbff1549c5bd8a17a82b85450058abfa07006b38
241
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing enum e { var d = { ( [ { { } } let { func d { protocol b { class case ,
15.0625
87
0.688797
3a5e2a8255a8652184d7dec792b96b98cf92b898
15,841
// // ViewController.swift // PoseEstimation-CoreML // // Created by GwakDoyoung on 05/07/2018. // Copyright © 2018 tucan9389. All rights reserved. // import UIKit import Vision import CoreMedia import Accelerate import MobileCoreServices import CoreGraphics import CoreVideo import AVFoundation class JointViewController: UIViewController { public typealias DetectObjectsCompletion = ([PredictedPoint?]?, Error?) -> Void//関数の別名をつけて,引数をすっきりさせる. // MARK: - UI Properties @IBOutlet weak var videoPreview: UIView! @IBOutlet weak var jointView: DrawingJointView! @IBOutlet weak var labelsTableView: UITableView! @IBOutlet weak var inferenceLabel: UILabel! @IBOutlet weak var etimeLabel: UILabel! @IBOutlet weak var fpsLabel: UILabel! @IBOutlet weak var COG: UILabel! /// //ここにも深度のいれます. /// private let depthDataOutput = AVCaptureDepthDataOutput() // MARK: - Performance Measurement Property private let 👨‍🔧 = 📏()//クラスのインスタンス化.📏()クラスの関数が使えるようになる. // MARK: - AV Property var videoCapture: VideoCapture!//VideoCaptureクラスのプロパティ. // MARK: - ML Properties // Core ML model typealias EstimationModel = model_cpm//クラス名変更. // Preprocess and Inference var request: VNCoreMLRequest?//VNCoreMLRequestクラスのプロパティ. var visionModel: VNCoreMLModel?//VNCoreMLModelクラスのプロパティ. // Postprocess var postProcessor: HeatmapPostProcessor = HeatmapPostProcessor()//インスタンス化. var mvfilters: [MovingAverageFilter] = []//箱の用意 // Inference Result Data private var tableData: [PredictedPoint?] = []//箱の用意 // MARK: - View Controller Life Cycle override func viewDidLoad() { super.viewDidLoad() // setup the model setUpModel()//下の方で定義してる. // print("一回通過") // setup camera setUpCamera() // print("一回通過") // setup tableview datasource on bottom labelsTableView.dataSource = self//dataSourceは一種のデリゲート.labelsTableViewによって動かされますよってこと. // print("一回通過") // setup delegate for performance measurement 👨‍🔧.delegate = self//これもデリゲート.👨‍🔧によって動かされますよってこと. // print("一回通過") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // print("一回通過") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.videoCapture.start()//videoCapture動け! // print("一回通過") } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.videoCapture.stop()//videoCapture止まれ! // print("最後の最後に多分通過") } // MARK: - Setup Core ML func setUpModel() { if let visionModel = try? VNCoreMLModel(for: EstimationModel().model) {//try?で関数の例外を無視できる.戻り値がnilになる.学習データの読み取り? self.visionModel = visionModel request = VNCoreMLRequest(model: visionModel, completionHandler: visionRequestDidComplete) request?.imageCropAndScaleOption = .scaleFill // print("ここは最初の一回通過") } else { fatalError() } } // MARK: - SetUp Video func setUpCamera() { videoCapture = VideoCapture()//videoCaptureのインスタンス化 videoCapture.delegate = self//videocaptureクラスがデリゲートします. videoCapture.fps = 30 videoCapture.setUp(sessionPreset: .vga640x480) { success in//ここから別のキューに向かいます. if success { // add preview view on the layer if let previewLayer = self.videoCapture.previewLayer { self.videoPreview.layer.addSublayer(previewLayer) self.resizePreviewLayer() } // start video preview when setup is done self.videoCapture.start() } } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() resizePreviewLayer() // print("ここ回る") } func resizePreviewLayer() { videoCapture.previewLayer?.frame = videoPreview.bounds } } // MARK: - VideoCaptureDelegate extension JointViewController: VideoCaptureDelegate {//ここは別のqueueです. func videoCapture(_ capture: VideoCapture, didCaptureVideoFrame pixelBuffer: CVPixelBuffer?, timestamp: CMTime) { // the captured image from camera is contained on pixelBuffer if let pixelBuffer = pixelBuffer { // start of measure self.👨‍🔧.🎬👏() print("よーいアクション!by太郎") // predict! self.predictUsingVision(pixelBuffer: pixelBuffer) } } } extension JointViewController { // MARK: - Inferencing func predictUsingVision(pixelBuffer: CVPixelBuffer) {//上で呼ばれる関数.ここで姿勢推定. guard let request = request else { fatalError() } // vision framework configures the input size of image following our model's input configuration automatically let handler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer)//引数ありのクラスのインスタンス化.だからinitでかいてあるよ. try? handler.perform([request])//いざ,推定! print("推定します") } // MARK: - Postprocessing func visionRequestDidComplete(request: VNRequest, error: Error?) {//setupModelで呼ばれる関数.何故か繰り返される.ここがわからない部分です. self.👨‍🔧.🏷(with: "endInference")//endInference(推論終了)の行に時間を代入.直前30個分保存. print("推測完了!") if let observations = request.results as? [VNCoreMLFeatureValueObservation], let heatmaps = observations.first?.featureValue.multiArrayValue {//多分結果を取得. /* =================================================================== */ /* ========================= post-processing ========================= */ /* ------------------ convert heatmap to point array ----------------- */ var predictedPoints = postProcessor.convertToPredictedPoints(from: heatmaps) /* --------------------- moving average filter ----------------------- */ if predictedPoints.count != mvfilters.count { mvfilters = predictedPoints.map { _ in MovingAverageFilter(limit: 3) } // print("ここは3") } // var l = 0 for (predictedPoint, filter) in zip(predictedPoints, mvfilters) { filter.add(element: predictedPoint) // filter.add(element: predictedPoint(maxPoint: (1 - x , y), maxConfidence: confidence)) // print("ここは4")//14回繰り返す...体の部位の数だけ繰り返してる! // l = l + 1 // print(l) // print(predictedPoint) // guard let hey = predictedPoint?.maxPoint.x else {fatalError()}///以下4行でpredictedPoint?.maxPointには0~1の数値が入ることがわかった. // if hey > CGFloat(0.8){ // fatalError() // }else{} } // print(predictedPoints) predictedPoints = mvfilters.map { $0.averagedValue() }//多分フィルター.このフィルターでmaxconfidenceが補正されるみたい. //print(predictedPoints) for i in 0...13{//画面をフロントカメラにしたので,x方向の座標も反転させます. if predictedPoints[i]?.maxPoint.x != nil{ predictedPoints[i]!.maxPoint.x = 1 - predictedPoints[i]!.maxPoint.x } } /////////////////////////////////////////////////////////////////////////// //この段階で一回分の14点の測定データが出力される.ということで,ここで重心の計算します./// /////////////////////////////////////////////////////////////////////////// /////////ここにも深度情報とるやついれときます////////////////////////////// // let depthData = syncedDepthData.depthData // let depthPixelBuffer = depthData.depthDataMap ///////////////////////////////////////////////////////////////////// let COGkeisan = COGcalculate() if let R_shoulder_zisin = predictedPoints[2]?.maxConfidence, let L_shoulder_zisin = predictedPoints[5]?.maxConfidence, let R_knee_zisin = predictedPoints[9]?.maxConfidence, let L_knee_zisin = predictedPoints[12]?.maxConfidence{ if (R_shoulder_zisin > 1.0 && L_shoulder_zisin > 1.0 && R_knee_zisin > 1.0 && L_knee_zisin > 1.0){ var COG_ue_x = COGkeisan.show_COG_ue(R_shoulder: (predictedPoints[2]?.maxPoint.x),L_shoulder: (predictedPoints[5]?.maxPoint.x),R_hip: (predictedPoints[8]?.maxPoint.x),L_hip: (predictedPoints[11]?.maxPoint.x)) var R_COG_sita_x = COGkeisan.show_R_COG_sita(R_hip: (predictedPoints[8]?.maxPoint.x),R_knee: (predictedPoints[9]?.maxPoint.x)) var L_COG_sita_x = COGkeisan.show_L_COG_sita(L_hip: (predictedPoints[11]?.maxPoint.x),L_knee: (predictedPoints[12]?.maxPoint.x)) var COG_sita_x = COGkeisan.show_COG_sita(R_COG_sita: R_COG_sita_x , L_COG_sita: L_COG_sita_x) var COG_x = COGkeisan.show_COG(COG_ue: COG_ue_x , COG_sita: COG_sita_x) var COG_ue_y = COGkeisan.show_COG_ue(R_shoulder: (predictedPoints[2]?.maxPoint.y),L_shoulder: (predictedPoints[5]?.maxPoint.y),R_hip: (predictedPoints[8]?.maxPoint.y),L_hip: (predictedPoints[11]?.maxPoint.y)) var R_COG_sita_y = COGkeisan.show_R_COG_sita(R_hip: (predictedPoints[8]?.maxPoint.y),R_knee: (predictedPoints[9]?.maxPoint.y)) var L_COG_sita_y = COGkeisan.show_L_COG_sita(L_hip: (predictedPoints[11]?.maxPoint.y),L_knee: (predictedPoints[12]?.maxPoint.y)) var COG_sita_y = COGkeisan.show_COG_sita(R_COG_sita: R_COG_sita_y , L_COG_sita: L_COG_sita_y) var COG_y = COGkeisan.show_COG(COG_ue: COG_ue_y , COG_sita: COG_sita_y) ////////////////////////////////////////////////////////////////////////////////// /////////////////////////ここにも深度よみとるやついれていきます.////////////////////////// ///////////////////////////////////////////////////////////////////////////////// // let depthPoint = CGPoint(x: 640 * (1 - COG_y), y: 480 * (1 - COG_x)) // let COG_z = updateDepthLabel(depthFrame: depthPixelBuffer, depthPoint: depthPoint) DispatchQueue.main.async { self.COG.text = "(x,y,z) = (\(String(format: "%.2f", COG_x)) , \(String(format: "%.2f", COG_y)))" } }else{ DispatchQueue.main.async { self.COG.text = "N/A" } } }else { DispatchQueue.main.async { self.COG.text = "N/A" } } // print("ここは5")// /* =================================================================== */ /* =================================================================== */ /* ======================= display the results ======================= */ DispatchQueue.main.sync { // draw line self.jointView.bodyPoints = predictedPoints // show key points description self.showKeypointsDescription(with: predictedPoints)//下で定義してる // print(predictedPoints) // end of measure self.👨‍🔧.🎬🤚() print("カーーーーーーッッットby太郎") // print("ここは6") } /* =================================================================== */ } else { // end of measure self.👨‍🔧.🎬🤚() } } func showKeypointsDescription(with n_kpoints: [PredictedPoint?]) {//上で呼ばれる.予想点を代入. self.tableData = n_kpoints // print(self.tableData) self.labelsTableView.reloadData()//座標のテーブルをリセット. } ///ここにも深度読み取る関数いれます. func updateDepthLabel(depthFrame: CVPixelBuffer, depthPoint: CGPoint) -> (String) { assert(kCVPixelFormatType_DepthFloat16 == CVPixelBufferGetPixelFormatType(depthFrame)) CVPixelBufferLockBaseAddress(depthFrame, .readOnly) let rowData = CVPixelBufferGetBaseAddress(depthFrame)! + Int(depthPoint.y) * CVPixelBufferGetBytesPerRow(depthFrame) // swift does not have an Float16 data type. Use UInt16 instead, and then translate var f16Pixel = rowData.assumingMemoryBound(to: UInt16.self)[Int(depthPoint.x)] CVPixelBufferUnlockBaseAddress(depthFrame, .readOnly) var f32Pixel = Float(0.0) var src = vImage_Buffer(data: &f16Pixel, height: 1, width: 1, rowBytes: 2) var dst = vImage_Buffer(data: &f32Pixel, height: 1, width: 1, rowBytes: 4) vImageConvert_Planar16FtoPlanarF(&src, &dst, 0) // Convert the depth frame format to cm let COG_z = String(format: "%.2f cm", f32Pixel * 100) return COG_z } } // MARK: - UITableView Data Source extension JointViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (tableData.count )// > 0 ? 1 : 0 //13個のデータがあると伝える. } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath) // print("答えた行の回数回ります.(画面に映っている行の数)") cell.textLabel?.text = Constant.pointLabels[indexPath.row]//13個の体の部位の名前表示.でも,常に実行されてるわけじゃなくて,デリゲートだから, // ビューが画面に映っている時にそのデータが表示される.ビューテーブルによって引き起こされる部分だから. // // R elbow // if indexPath.row == 2 { // // print(Constant.pointLabels[indexPath.row]) // // if let body_point = tableData[indexPath.row] { // let pointText: String = "\(String(format: "%.3f", body_point.maxPoint.x)), \(String(format: "%.3f", body_point.maxPoint.y))" // print("\(String(format: "%.3f", body_point.maxPoint.x)), \(String(format: "%.3f", body_point.maxPoint.y))") // } else { // cell.detailTextLabel?.text = "N/A" // } // // } // if indexPath.row == 1{//デリゲートだから,こーゆー書き方だとその行をみる時しか実行されない.ビューテーブルによって引き起こされる部分だから. // // if tableData[8] != nil && tableData[9] != nil{ // let p = (tableData[8]!.maxPoint.x * 56/100) // let q = (tableData[9]!.maxPoint.x * 44/100) // print(p+q) // } else { // print("N/A") // } // } if let body_point = tableData[indexPath.row] { let pointText: String = "\(String(format: "%.3f", body_point.maxPoint.x)), \(String(format: "%.3f", body_point.maxPoint.y))" cell.detailTextLabel?.text = "(\(pointText)), [\(String(format: "%.3f", body_point.maxConfidence))]" // print("onusi") // print(tableData) } else { cell.detailTextLabel?.text = "N/A" } return cell } } // MARK: - 📏(Performance Measurement) Delegate extension JointViewController: 📏Delegate { func updateMeasure(inferenceTime: Double, executionTime: Double, fps: Int) { // print("ここも回る1") self.inferenceLabel.text = "inference: \(Int(inferenceTime*1000.0)) mm" self.etimeLabel.text = "execution: \(Int(executionTime*1000.0)) mm" self.fpsLabel.text = "fps: \(fps)" } }
41.907407
239
0.550281
1ea3c38f6daeafd4c24786de3250f5d6a42ee048
792
// // MainTabBarController.swift // LivingApplication // // Created by ioser on 17/5/14. // Copyright © 2017年 ioser. All rights reserved. // import UIKit class MainTabBarController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() UITabBar.appearance().tintColor = UIColor.orangeColor() createViewControllers("Home") createViewControllers("live") createViewControllers("follow") createViewControllers("Profile") } func createViewControllers(storyboardName : String) -> Void { // 通过storeboard加载控制器 let viewController = UIStoryboard(name: storyboardName,bundle: nil).instantiateInitialViewController() addChildViewController(viewController!) } }
24.75
110
0.671717
efd3e1c7838a05b704f892d798d0fba5c5e9b867
2,501
// // ScanNDEFCommand.swift // TCMP // // Created by David Shalaby on 2018-03-08. // Copyright © 2018 Papyrus Electronics Inc d/b/a TapTrack. All rights reserved. // /* * Copyright (c) 2018. Papyrus Electronics, Inc d/b/a TapTrack. * * 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 @objc public class ScanNDEFCommand : NSObject, TCMPMessage { @objc public let commandFamily : [UInt8] = CommandFamily.basicNFC @objc public let commandCode: UInt8 = BasicNFCCommandCode.scanNDEFMessage.rawValue @objc public var payload: [UInt8] { get { if(pollingMode == PollingMode.pollForType1){ return [timeout,0x01] }else if(pollingMode == PollingMode.pollForGeneral){ return [timeout,0x02] }else{ return [] } } } @objc public private(set) var timeout : UInt8 = 0x00 @objc public private(set) var pollingMode : PollingMode = PollingMode.pollForGeneral @objc public override init() {} @objc public init(timeout : UInt8, pollingMode : PollingMode){ self.timeout = timeout self.pollingMode = pollingMode } @objc public init(payload: [UInt8]) throws { super.init() try parsePayload(payload: payload) } @objc public func parsePayload(payload: [UInt8]) throws { if(payload.count >= 2){ timeout = payload[0] switch (payload[1]){ case 0x01: pollingMode = PollingMode.pollForType1 case 0x02: pollingMode = PollingMode.pollForGeneral default: throw TCMPParsingError.invalidPollingMode } }else{ throw TCMPParsingError.payloadTooShort } } // Deprecated after version 0.1.12. Left here for legacy reasons. @objc public static func getCommandCode() -> UInt8 { return 0x04 } }
30.876543
88
0.627349