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
33b3e822d8bf5ed4e2adca8c2ee5c2f14840d398
4,813
// // BodyTests.swift // SwiftLinkPreview // // Created by Leonardo Cardoso on 05/07/2016. // Copyright © 2016 leocardz.com. All rights reserved. // import XCTest @testable import SwiftLinkPreview // This class tests body texts class BodyTests: XCTestCase { // MARK: - Vars var spanTemplate = "" var pTemplate = "" var divTemplate = "" let slp = SwiftLinkPreview() // MARK: - SetUps // Those setup functions get that template, and fulfil determinated areas with rand texts, images and tags override func setUp() { super.setUp() self.spanTemplate = File.toString(Constants.bodyTextSpan) self.divTemplate = File.toString(Constants.bodyTextDiv) self.pTemplate = File.toString(Constants.bodyTextP) } // MARK: - Span func setUpSpan() { var metaData = [ Constants.random1: String.randomText(), Constants.random2: String.randomText() ] var template = self.spanTemplate template = template.replace(Constants.headRandom, with: String.randomText()) template = template.replace(Constants.random1, with: metaData[Constants.random1]!) template = template.replace(Constants.random2, with: metaData[Constants.random2]!) template = template.replace(Constants.tag1, with: String.randomText()) template = template.replace(Constants.tag2, with: String.randomText()) template = template.replace(Constants.bodyRandomPre, with: String.randomText()) template = template.replace(Constants.bodyRandomMiddle, with: String.randomText()) template = template.replace(Constants.bodyRandomPos, with: String.randomText()).extendedTrim let response = self.slp.crawlDescription(template, result: SwiftLinkPreview.Response()) let comparable = (response.result[.description] as! String) XCTAssert(comparable == metaData[Constants.random1]!.decoded || comparable == metaData[Constants.random2]!.decoded) } func testSpan() { for _ in 0 ..< 100 { self.setUpSpan() } } // MARK: - Div func setUpDiv() { let metaData = [ Constants.random1: String.randomText(), Constants.random2: String.randomText() ] var template = self.divTemplate template = template.replace(Constants.headRandom, with: String.randomText()) template = template.replace(Constants.random1, with: metaData[Constants.random1]!) template = template.replace(Constants.random2, with: metaData[Constants.random2]!) template = template.replace(Constants.tag1, with: String.randomText()) template = template.replace(Constants.tag2, with: String.randomText()) template = template.replace(Constants.bodyRandomPre, with: String.randomText()) template = template.replace(Constants.bodyRandomMiddle, with: String.randomText()) template = template.replace(Constants.bodyRandomPos, with: String.randomText()).extendedTrim let response = self.slp.crawlDescription(template, result: SwiftLinkPreview.Response()) let comparable = (response.result[.description] as! String) XCTAssert(comparable == metaData[Constants.random1]!.decoded || comparable == metaData[Constants.random2]!.decoded) } func testDiv() { for _ in 0 ..< 100 { self.setUpDiv() } } // MARK: - P func setUpP() { let metaData = [ Constants.random1: String.randomText(), Constants.random2: String.randomText() ] var template = self.pTemplate template = template.replace(Constants.headRandom, with: String.randomText()) template = template.replace(Constants.random1, with: metaData[Constants.random1]!) template = template.replace(Constants.random2, with: metaData[Constants.random2]!) template = template.replace(Constants.tag1, with: String.randomText()) template = template.replace(Constants.tag2, with: String.randomText()) template = template.replace(Constants.bodyRandomPre, with: String.randomText()) template = template.replace(Constants.bodyRandomMiddle, with: String.randomText()) template = template.replace(Constants.bodyRandomPos, with: String.randomText()).extendedTrim let response = self.slp.crawlDescription(template, result: SwiftLinkPreview.Response()) let comparable = (response.result[.description] as! String) XCTAssert(comparable == metaData[Constants.random1]!.decoded || comparable == metaData[Constants.random2]!.decoded) } func testP() { for _ in 0 ..< 100 { self.setUpP() } } }
31.457516
123
0.656971
d7e4891d273786fdd537b10809134a27dd95421d
1,911
// // Custom.swift // VK_app // // Created by Aleksandr Fetisov on 18/07/2019. // Copyright © 2019 Aleksandr Fetisov. All rights reserved. // import UIKit @IBDesignable class LikeImageView: UIControl { override func awakeFromNib() { super.awakeFromNib() } public var isHeartFilled = false { didSet { self.setNeedsDisplay() } } public var heartColor:UIColor = .red override func draw(_ rect: CGRect) { super.draw(rect) guard let context = UIGraphicsGetCurrentContext() else { return } context.setStrokeColor(UIColor.lightGray.cgColor) context.setFillColor(UIColor.red.cgColor) context.saveGState() heart.stroke() if isHeartFilled { context.setStrokeColor(UIColor.red.cgColor) heart.stroke() heart.fill() } } let heart: UIBezierPath = { let heart = UIBezierPath() let rect = CGRect(x: 0, y: 0, width: 30, height: 30) let sideOne = rect.width * 0.4 let sideTwo = rect.height * 0.3 let arcRadius = sqrt(sideOne*sideOne + sideTwo*sideTwo)/2 heart.addArc(withCenter: CGPoint(x: rect.width * 0.3, y: rect.height * 0.35), radius: CGFloat(arcRadius), startAngle: 135.degreesToRadians, endAngle: 315.degreesToRadians, clockwise: true) heart.addLine(to: CGPoint(x: rect.width/2, y: rect.height * 0.2)) heart.addArc(withCenter: CGPoint(x: rect.width * 0.7, y: rect.height * 0.35), radius: CGFloat(arcRadius), startAngle: 225.degreesToRadians, endAngle: 45.degreesToRadians, clockwise: true) heart.addLine(to: CGPoint(x: rect.width * 0.5, y: rect.height * 0.95)) heart.close() return heart }() } extension Int { var degreesToRadians: CGFloat { return CGFloat(self) * .pi / 180 } }
29.4
196
0.609628
1a87656a4b44e344c3d3c67b49f63c22d9554ad4
1,404
// swift-tools-version:5.0 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "Web3swift", platforms: [ .macOS(.v10_12), .iOS(.v11), ], products: [ // Products define the executables and libraries produced by a package, and make them visible to other packages. .library(name: "web3swift", targets: ["web3swift"]), ], dependencies: [ .package(url: "https://github.com/attaswift/BigInt.git", from: "5.3.0"), .package(url: "https://github.com/mxcl/PromiseKit.git", from: "6.15.4"), .package(url: "https://github.com/daltoniam/Starscream.git", from: "4.0.4"), .package(url: "https://github.com/krzyzanowskim/CryptoSwift.git", from: "1.4.2"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages which this package depends on. .target(name: "secp256k1"), .target( name: "web3swift", dependencies: ["BigInt", "secp256k1", "PromiseKit", "Starscream", "CryptoSwift"], exclude: [ ]), .testTarget( name: "web3swiftTests", dependencies: ["web3swift"]), ] )
39
122
0.612536
11c7c378bae9ab0155186f7f9dd6ba027317bd52
795
// // UIView+LoadFromNib.swift // ShopApp // // Created by Mykola Voronin on 2/11/18. // Copyright © 2018 RubyGarage. All rights reserved. // import UIKit extension UIView { func loadFromNib(with nibName: String? = nil) { let view = Bundle.main.loadNibNamed(nibName ?? nameOfClass, owner: self)?.last as! UIView addSubview(view) view.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 0).isActive = true view.trailingAnchor.constraint(equalTo: trailingAnchor, constant: 0).isActive = true view.topAnchor.constraint(equalTo: topAnchor, constant: 0).isActive = true view.bottomAnchor.constraint(equalTo: bottomAnchor, constant: 0).isActive = true view.translatesAutoresizingMaskIntoConstraints = false } }
34.565217
97
0.698113
1e088752ae9426ccd8c180068c1e9513edf8c652
888
// // ListPresenterViewMock.swift // DirectoryTests // // Created by daniele on 19/10/2020. // Copyright © 2020 DeeplyMadStudio. All rights reserved. // import Foundation @testable import Directory @testable import Common class ListPresenterViewMock: ListPresenterViewProtocol { var _mainViewData: ((ListViewData.MainViewData) -> Void)? func updateMain(viewData: ListViewData.MainViewData) { self._mainViewData?(viewData) } var _updateCells: ((ListViewData.ListDataUpdate) -> Void)? func updateCells(viewData: ListViewData.ListDataUpdate) { self._updateCells?(viewData) } var _updateActivityStart: (() -> Void)? func updateActivityStart() { self._updateActivityStart?() } var _updateActivityStop: (() -> Void)? func updateActivityStop() { self._updateActivityStop?() } }
22.769231
62
0.67455
9c9c5e0a79d24d8db50a9fdb96bcc49454a55015
605
// // SampleRow.swift // ListWithTextFieldSample // // Created by Yusuke Hasegawa on 2021/07/09. // import SwiftUI struct SampleRow: View { @Binding var model: SampleModel var onCommit: () -> Void var body: some View { TextField.init("tap to edit text", text: self.$model.text, onEditingChanged: { _ in //nop }, onCommit: { self.onCommit() }) } } struct SampleRow_Previews: PreviewProvider { static var previews: some View { SampleRow(model: .constant(.init(text: "sample text")), onCommit: { }) } }
20.166667
91
0.586777
8a0a59598badc382cfa6cbe58ac62a35e797b4fa
508
// // Composable+Styleable.swift // ViewComposer // // Created by Alexander Cyon on 2017-06-06. // // import Foundation /// Makes it possible to instantiate and style `Composable` from array literal like this: `let myComposableView: MyComposableView = [.text("foo")]` public extension Styleable where Self: Composable, Self.StyleType.Attribute == Element { init(arrayLiteral elements: Self.Element...) { self.init(StyleType(Self.StyleType.removeDuplicatesIfNeededAndAble(elements))) } }
29.882353
147
0.732283
e4e9be2c785db4314bf3a08f23ca3cc767e2e490
36,023
// RUN: %target-typecheck-verify-swift func markUsed<T>(_ t: T) {} struct X { } var _x: X class SomeClass {} func takeTrailingClosure(_ fn: () -> ()) -> Int {} func takeIntTrailingClosure(_ fn: () -> Int) -> Int {} //===--- // Stored properties //===--- var stored_prop_1: Int = 0 var stored_prop_2: Int = takeTrailingClosure {} //===--- // Computed properties -- basic parsing //===--- var a1: X { get { return _x } } var a2: X { get { return _x } set { _x = newValue } } var a3: X { get { return _x } set(newValue) { _x = newValue } } var a4: X { set { _x = newValue } get { return _x } } var a5: X { set(newValue) { _x = newValue } get { return _x } } // Reading/writing properties func accept_x(_ x: X) { } func accept_x_inout(_ x: inout X) { } func test_global_properties(_ x: X) { accept_x(a1) accept_x(a2) accept_x(a3) accept_x(a4) accept_x(a5) a1 = x // expected-error {{cannot assign to value: 'a1' is a get-only property}} a2 = x a3 = x a4 = x a5 = x accept_x_inout(&a1) // expected-error {{cannot pass immutable value as inout argument: 'a1' is a get-only property}} accept_x_inout(&a2) accept_x_inout(&a3) accept_x_inout(&a4) accept_x_inout(&a5) } //===--- Implicit 'get'. var implicitGet1: X { return _x } var implicitGet2: Int { var zzz = 0 // expected-warning@-1 {{initialization of variable 'zzz' was never used; consider replacing with assignment to '_' or removing it}} // For the purpose of this test, any other function attribute work as well. @inline(__always) func foo() {} return 0 } var implicitGet3: Int { @inline(__always) func foo() {} return 0 } // Here we used apply weak to the getter itself, not to the variable. var x15: Int { // For the purpose of this test we need to use an attribute that cannot be // applied to the getter. weak var foo: SomeClass? = SomeClass() // expected-warning {{variable 'foo' was written to, but never read}} // expected-warning@-1 {{instance will be immediately deallocated because variable 'foo' is 'weak'}} // expected-note@-2 {{a strong reference is required to prevent the instance from being deallocated}} // expected-note@-3 {{'foo' declared here}} return 0 } // Disambiguated as stored property with a trailing closure in the initializer. // var disambiguateGetSet1a: Int = 0 { // expected-error {{variable with getter/setter cannot have an initial value}} get {} } var disambiguateGetSet1b: Int = 0 { // expected-error {{variable with getter/setter cannot have an initial value}} get { return 42 } } var disambiguateGetSet1c: Int = 0 { // expected-error {{variable with getter/setter cannot have an initial value}} set {} // expected-error {{variable with a setter must also have a getter}} } var disambiguateGetSet1d: Int = 0 { // expected-error {{variable with getter/setter cannot have an initial value}} set(newValue) {} // expected-error {{variable with a setter must also have a getter}} } // Disambiguated as stored property with a trailing closure in the initializer. func disambiguateGetSet2() { func get(_ fn: () -> ()) {} var a: Int = takeTrailingClosure { get {} } // Check that the property is read-write. a = a + 42 } func disambiguateGetSet2Attr() { func get(_ fn: () -> ()) {} var a: Int = takeTrailingClosure { @inline(__always) func foo() {} get {} } // Check that the property is read-write. a = a + 42 } // Disambiguated as stored property with a trailing closure in the initializer. func disambiguateGetSet3() { func set(_ fn: () -> ()) {} var a: Int = takeTrailingClosure { set {} } // Check that the property is read-write. a = a + 42 } func disambiguateGetSet3Attr() { func set(_ fn: () -> ()) {} var a: Int = takeTrailingClosure { @inline(__always) func foo() {} set {} } // Check that the property is read-write. a = a + 42 } // Disambiguated as stored property with a trailing closure in the initializer. func disambiguateGetSet4() { func set(_ x: Int, fn: () -> ()) {} let newValue: Int = 0 var a: Int = takeTrailingClosure { set(newValue) {} } // Check that the property is read-write. a = a + 42 } func disambiguateGetSet4Attr() { func set(_ x: Int, fn: () -> ()) {} var newValue: Int = 0 // expected-warning@-1 {{variable 'newValue' was never mutated; consider changing to 'let' constant}} var a: Int = takeTrailingClosure { @inline(__always) func foo() {} set(newValue) {} } // Check that the property is read-write. a = a + 42 } // Disambiguated as stored property with a trailing closure in the initializer. var disambiguateImplicitGet1: Int = 0 { // expected-error {{variable with getter/setter cannot have an initial value}} return 42 } var disambiguateImplicitGet2: Int = takeIntTrailingClosure { return 42 } //===--- // Observed properties //===--- class C { var prop1 = 42 { didSet { } } var prop2 = false { willSet { } } var prop3: Int? = nil { didSet { } } var prop4: Bool? = nil { willSet { } } } protocol TrivialInit { init() } class CT<T : TrivialInit> { var prop1 = 42 { didSet { } } var prop2 = false { willSet { } } var prop3: Int? = nil { didSet { } } var prop4: Bool? = nil { willSet { } } var prop5: T? = nil { didSet { } } var prop6: T? = nil { willSet { } } var prop7 = T() { didSet { } } var prop8 = T() { willSet { } } } //===--- // Parsing problems //===--- var computed_prop_with_init_1: X { get {} } = X() // expected-error {{expected expression}} expected-error {{consecutive statements on a line must be separated by ';'}} {{2-2=;}} var x2 { // expected-error{{computed property must have an explicit type}} {{7-7=: <# Type #>}} expected-error{{type annotation missing in pattern}} get { return _x } } var (x3): X { // expected-error{{getter/setter can only be defined for a single variable}} get { return _x } } var duplicateAccessors1: X { get { // expected-note {{previous definition of getter here}} return _x } set { // expected-note {{previous definition of setter here}} _x = newValue } get { // expected-error {{variable already has a getter}} return _x } set(v) { // expected-error {{variable already has a setter}} _x = v } } var duplicateAccessors2: Int = 0 { willSet { // expected-note {{previous definition of 'willSet' here}} } didSet { // expected-note {{previous definition of 'didSet' here}} } willSet { // expected-error {{variable already has 'willSet'}} } didSet { // expected-error {{variable already has 'didSet'}} } } var extraTokensInAccessorBlock1: X { get {} a // expected-error {{expected 'get', 'set', 'willSet', or 'didSet' keyword to start an accessor definition}} } var extraTokensInAccessorBlock2: X { get {} weak // expected-error {{expected 'get', 'set', 'willSet', or 'didSet' keyword to start an accessor definition}} a } var extraTokensInAccessorBlock3: X { get {} a = b // expected-error {{expected 'get', 'set', 'willSet', or 'didSet' keyword to start an accessor definition}} set {} get {} } var extraTokensInAccessorBlock4: X { get blah wibble // expected-error{{expected '{' to start getter definition}} } var extraTokensInAccessorBlock5: X { set blah wibble // expected-error{{expected '{' to start setter definition}} } var extraTokensInAccessorBlock6: X { // expected-error{{non-member observing properties require an initializer}} willSet blah wibble // expected-error{{expected '{' to start 'willSet' definition}} } var extraTokensInAccessorBlock7: X { // expected-error{{non-member observing properties require an initializer}} didSet blah wibble // expected-error{{expected '{' to start 'didSet' definition}} } var extraTokensInAccessorBlock8: X { foo // expected-error {{use of unresolved identifier 'foo'}} get {} // expected-error{{use of unresolved identifier 'get'}} set {} // expected-error{{use of unresolved identifier 'set'}} } var extraTokensInAccessorBlock9: Int { get // expected-error {{expected '{' to start getter definition}} var a = b } struct extraTokensInAccessorBlock10 { var x: Int { get // expected-error {{expected '{' to start getter definition}} var a = b } init() {} } var x9: X { get ( ) { // expected-error{{expected '{' to start getter definition}} } } var x10: X { set ( : ) { // expected-error{{expected setter parameter name}} } get {} } var x11 : X { set { // expected-error{{variable with a setter must also have a getter}} } } var x12: X { set(newValue %) { // expected-error {{expected ')' after setter parameter name}} expected-note {{to match this opening '('}} // expected-error@-1 {{expected '{' to start setter definition}} } } var x13: X {} // expected-error {{computed property must have accessors specified}} // Type checking problems struct Y { } var y: Y var x20: X { get { return y // expected-error{{cannot convert return expression of type 'Y' to return type 'X'}} } set { y = newValue // expected-error{{cannot assign value of type 'X' to type 'Y'}} } } var x21: X { get { return y // expected-error{{cannot convert return expression of type 'Y' to return type 'X'}} } set(v) { y = v // expected-error{{cannot assign value of type 'X' to type 'Y'}} } } var x23: Int, x24: Int { // expected-error{{'var' declarations with multiple variables cannot have explicit getters/setters}} return 42 } var x25: Int { // expected-error{{'var' declarations with multiple variables cannot have explicit getters/setters}} return 42 }, x26: Int // expected-warning{{variable 'x26' was never used; consider replacing with '_' or removing it}} // Properties of struct/enum/extensions struct S { var _backed_x: X, _backed_x2: X var x: X { get { return _backed_x } mutating set(v) { _backed_x = v } } } extension S { var x2: X { get { return self._backed_x2 } mutating set { _backed_x2 = newValue } } var x3: X { get { return self._backed_x2 } } } struct StructWithExtension1 { var foo: Int static var fooStatic = 4 } extension StructWithExtension1 { var fooExt: Int // expected-error {{extensions must not contain stored properties}} static var fooExtStatic = 4 } class ClassWithExtension1 { var foo: Int = 0 class var fooStatic = 4 // expected-error {{class stored properties not supported in classes; did you mean 'static'?}} } extension ClassWithExtension1 { var fooExt: Int // expected-error {{extensions must not contain stored properties}} class var fooExtStatic = 4 // expected-error {{class stored properties not supported in classes; did you mean 'static'?}} } enum EnumWithExtension1 { var foo: Int // expected-error {{enums must not contain stored properties}} static var fooStatic = 4 } extension EnumWithExtension1 { var fooExt: Int // expected-error {{extensions must not contain stored properties}} static var fooExtStatic = 4 } protocol ProtocolWithExtension1 { var foo: Int { get } static var fooStatic : Int { get } } extension ProtocolWithExtension1 { var fooExt: Int // expected-error{{extensions must not contain stored properties}} static var fooExtStatic = 4 // expected-error{{static stored properties not supported in protocol extensions}} } protocol ProtocolWithExtension2 { var bar: String { get } } struct StructureImplementingProtocolWithExtension2: ProtocolWithExtension2 { let bar: String } extension ProtocolWithExtension2 { static let baz: ProtocolWithExtension2 = StructureImplementingProtocolWithExtension2(bar: "baz") // expected-error{{static stored properties not supported in protocol extensions}} } func getS() -> S { let s: S return s } func test_extension_properties(_ s: inout S, x: inout X) { accept_x(s.x) accept_x(s.x2) accept_x(s.x3) accept_x(getS().x) accept_x(getS().x2) accept_x(getS().x3) s.x = x s.x2 = x s.x3 = x // expected-error{{cannot assign to property: 'x3' is a get-only property}} getS().x = x // expected-error{{cannot assign to property: 'getS' returns immutable value}} getS().x2 = x // expected-error{{cannot assign to property: 'getS' returns immutable value}} getS().x3 = x // expected-error{{cannot assign to property: 'x3' is a get-only property}} accept_x_inout(&getS().x) // expected-error{{cannot pass immutable value as inout argument: 'getS' returns immutable value}} accept_x_inout(&getS().x2) // expected-error{{cannot pass immutable value as inout argument: 'getS' returns immutable value}} accept_x_inout(&getS().x3) // expected-error{{cannot pass immutable value as inout argument: 'x3' is a get-only property}} x = getS().x x = getS().x2 x = getS().x3 accept_x_inout(&s.x) accept_x_inout(&s.x2) accept_x_inout(&s.x3) // expected-error{{cannot pass immutable value as inout argument: 'x3' is a get-only property}} } extension S { mutating func test(other_x: inout X) { x = other_x x2 = other_x x3 = other_x // expected-error{{cannot assign to property: 'x3' is a get-only property}} other_x = x other_x = x2 other_x = x3 } } // Accessor on non-settable type struct Aleph { var b: Beth { get { return Beth(c: 1) } } } struct Beth { var c: Int } func accept_int_inout(_ c: inout Int) { } func accept_int(_ c: Int) { } func test_settable_of_nonsettable(_ a: Aleph) { a.b.c = 1 // expected-error{{cannot assign}} let x:Int = a.b.c _ = x accept_int(a.b.c) accept_int_inout(&a.b.c) // expected-error {{cannot pass immutable value as inout argument: 'b' is a get-only property}} } // TODO: Static properties are only implemented for nongeneric structs yet. struct MonoStruct { static var foo: Int = 0 static var (bar, bas): (String, UnicodeScalar) = ("zero", "0") static var zim: UInt8 { return 0 } static var zang = UnicodeScalar("\0") static var zung: UInt16 { get { return 0 } set {} } var a: Double var b: Double } struct MonoStructOneProperty { static var foo: Int = 22 } enum MonoEnum { static var foo: Int = 0 static var zim: UInt8 { return 0 } } struct GenStruct<T> { static var foo: Int = 0 // expected-error{{static stored properties not supported in generic types}} } class MonoClass { class var foo: Int = 0 // expected-error{{class stored properties not supported in classes; did you mean 'static'?}} } protocol Proto { static var foo: Int { get } } func staticPropRefs() -> (Int, Int, String, UnicodeScalar, UInt8) { return (MonoStruct.foo, MonoEnum.foo, MonoStruct.bar, MonoStruct.bas, MonoStruct.zim) } func staticPropRefThroughInstance(_ foo: MonoStruct) -> Int { return foo.foo //expected-error{{static member 'foo' cannot be used on instance of type 'MonoStruct'}} } func memberwiseInitOnlyTakesInstanceVars() -> MonoStruct { return MonoStruct(a: 1.2, b: 3.4) } func getSetStaticProperties() -> (UInt8, UInt16) { MonoStruct.zim = 12 // expected-error{{cannot assign}} MonoStruct.zung = 34 return (MonoStruct.zim, MonoStruct.zung) } var selfRefTopLevel: Int { return selfRefTopLevel // expected-warning {{attempting to access 'selfRefTopLevel' within its own getter}} } var selfRefTopLevelSetter: Int { get { return 42 } set { markUsed(selfRefTopLevelSetter) // no-warning selfRefTopLevelSetter = newValue // expected-warning {{attempting to modify 'selfRefTopLevelSetter' within its own setter}} } } var selfRefTopLevelSilenced: Int { get { return properties.selfRefTopLevelSilenced // no-warning } set { properties.selfRefTopLevelSilenced = newValue // no-warning } } class SelfRefProperties { var getter: Int { return getter // expected-warning {{attempting to access 'getter' within its own getter}} // expected-note@-1 {{access 'self' explicitly to silence this warning}} {{12-12=self.}} } var setter: Int { get { return 42 } set { markUsed(setter) // no-warning var unused = setter + setter // expected-warning {{initialization of variable 'unused' was never used; consider replacing with assignment to '_' or removing it}} {{7-17=_}} setter = newValue // expected-warning {{attempting to modify 'setter' within its own setter}} // expected-note@-1 {{access 'self' explicitly to silence this warning}} {{7-7=self.}} } } var silenced: Int { get { return self.silenced // no-warning } set { self.silenced = newValue // no-warning } } var someOtherInstance: SelfRefProperties = SelfRefProperties() var delegatingVar: Int { // This particular example causes infinite access, but it's easily possible // for the delegating instance to do something else. return someOtherInstance.delegatingVar // no-warning } } func selfRefLocal() { var getter: Int { return getter // expected-warning {{attempting to access 'getter' within its own getter}} } var setter: Int { get { return 42 } set { markUsed(setter) // no-warning setter = newValue // expected-warning {{attempting to modify 'setter' within its own setter}} } } } struct WillSetDidSetProperties { var a: Int { willSet { markUsed("almost") } didSet { markUsed("here") } } var b: Int { willSet { markUsed(b) markUsed(newValue) } } var c: Int { willSet(newC) { markUsed(c) markUsed(newC) } } var d: Int { didSet { // expected-error {{'didSet' cannot be provided together with a getter}} markUsed("woot") } get { return 4 } } var e: Int { willSet { // expected-error {{'willSet' cannot be provided together with a setter}} markUsed("woot") } set { // expected-error {{variable with a setter must also have a getter}} return 4 // expected-error {{unexpected non-void return value in void function}} } } var f: Int { willSet(5) {} // expected-error {{expected willSet parameter name}} didSet(^) {} // expected-error {{expected didSet parameter name}} } var g: Int { willSet(newValue 5) {} // expected-error {{expected ')' after willSet parameter name}} expected-note {{to match this opening '('}} // expected-error@-1 {{expected '{' to start 'willSet' definition}} } var h: Int { didSet(oldValue ^) {} // expected-error {{expected ')' after didSet parameter name}} expected-note {{to match this opening '('}} // expected-error@-1 {{expected '{' to start 'didSet' definition}} } // didSet/willSet with initializers. // Disambiguate trailing closures. var disambiguate1: Int = 42 { // simple initializer, simple label didSet { markUsed("eek") } } var disambiguate2: Int = 42 { // simple initializer, complex label willSet(v) { markUsed("eek") } } var disambiguate3: Int = takeTrailingClosure {} { // Trailing closure case. willSet(v) { markUsed("eek") } } var disambiguate4: Int = 42 { willSet {} } var disambiguate5: Int = 42 { didSet {} } var disambiguate6: Int = takeTrailingClosure { @inline(__always) func f() {} return () } var inferred1 = 42 { willSet { markUsed("almost") } didSet { markUsed("here") } } var inferred2 = 40 { willSet { markUsed(b) markUsed(newValue) } } var inferred3 = 50 { willSet(newC) { markUsed(c) markUsed(newC) } } } // Disambiguated as accessor. struct WillSetDidSetDisambiguate1 { var willSet: Int var x: (() -> ()) -> Int = takeTrailingClosure { willSet = 42 // expected-error {{expected '{' to start 'willSet' definition}} } } struct WillSetDidSetDisambiguate1Attr { var willSet: Int var x: (() -> ()) -> Int = takeTrailingClosure { willSet = 42 // expected-error {{expected '{' to start 'willSet' definition}} } } // Disambiguated as accessor. struct WillSetDidSetDisambiguate2 { func willSet(_: () -> Int) {} var x: (() -> ()) -> Int = takeTrailingClosure { willSet {} } } struct WillSetDidSetDisambiguate2Attr { func willSet(_: () -> Int) {} var x: (() -> ()) -> Int = takeTrailingClosure { willSet {} } } // No need to disambiguate -- this is clearly a function call. func willSet(_: () -> Int) {} struct WillSetDidSetDisambiguate3 { var x: Int = takeTrailingClosure({ willSet { 42 } }) } protocol ProtocolGetSet1 { var a: Int // expected-error {{property in protocol must have explicit { get } or { get set } specifier}} {{13-13= { get <#set#> \}}} } protocol ProtocolGetSet2 { var a: Int {} // expected-error {{property in protocol must have explicit { get } or { get set } specifier}} {{14-16={ get <#set#> \}}} } protocol ProtocolGetSet3 { var a: Int { get } } protocol ProtocolGetSet4 { var a: Int { set } // expected-error {{variable with a setter must also have a getter}} } protocol ProtocolGetSet5 { var a: Int { get set } } protocol ProtocolGetSet6 { var a: Int { set get } } protocol ProtocolWillSetDidSet1 { var a: Int { willSet } // expected-error {{property in protocol must have explicit { get } or { get set } specifier}} {{14-25={ get <#set#> \}}} expected-error {{expected get or set in a protocol property}} } protocol ProtocolWillSetDidSet2 { var a: Int { didSet } // expected-error {{property in protocol must have explicit { get } or { get set } specifier}} {{14-24={ get <#set#> \}}} expected-error {{expected get or set in a protocol property}} } protocol ProtocolWillSetDidSet3 { var a: Int { willSet didSet } // expected-error {{property in protocol must have explicit { get } or { get set } specifier}} {{14-32={ get <#set#> \}}} expected-error 2 {{expected get or set in a protocol property}} } protocol ProtocolWillSetDidSet4 { var a: Int { didSet willSet } // expected-error {{property in protocol must have explicit { get } or { get set } specifier}} {{14-32={ get <#set#> \}}} expected-error 2 {{expected get or set in a protocol property}} } protocol ProtocolWillSetDidSet5 { let a: Int { didSet willSet } // expected-error {{immutable property requirement must be declared as 'var' with a '{ get }' specifier}} {{3-6=var}} {{13-13= { get \}}} {{none}} expected-error 2 {{expected get or set in a protocol property}} expected-error {{'let' declarations cannot be computed properties}} {{3-6=var}} } var globalDidsetWillSet: Int { // expected-error {{non-member observing properties require an initializer}} didSet {} } var globalDidsetWillSet2 : Int = 42 { didSet {} } class Box { var num: Int init(num: Int) { self.num = num } } func double(_ val: inout Int) { val *= 2 } class ObservingPropertiesNotMutableInWillSet { var anotherObj : ObservingPropertiesNotMutableInWillSet init() {} var property: Int = 42 { willSet { // <rdar://problem/16826319> willSet immutability behavior is incorrect anotherObj.property = 19 // ok property = 19 // expected-warning {{attempting to store to property 'property' within its own willSet}} double(&property) // expected-warning {{attempting to store to property 'property' within its own willSet}} double(&self.property) // no-warning } } // <rdar://problem/21392221> - call to getter through BindOptionalExpr was not viewed as a load var _oldBox : Int weak var weakProperty: Box? { willSet { _oldBox = weakProperty?.num ?? -1 } } func localCase() { var localProperty: Int = 42 { willSet { localProperty = 19 // expected-warning {{attempting to store to property 'localProperty' within its own willSet}} } } } } func doLater(_ fn : () -> ()) {} // rdar://<rdar://problem/16264989> property not mutable in closure inside of its willSet class MutableInWillSetInClosureClass { var bounds: Int = 0 { willSet { let oldBounds = bounds doLater { self.bounds = oldBounds } } } } // <rdar://problem/16191398> add an 'oldValue' to didSet so you can implement "didChange" properties var didSetPropertyTakingOldValue : Int = 0 { didSet(oldValue) { markUsed(oldValue) markUsed(didSetPropertyTakingOldValue) } } // rdar://16280138 - synthesized getter is defined in terms of archetypes, not interface types protocol AbstractPropertyProtocol { associatedtype Index var a : Index { get } } struct AbstractPropertyStruct<T> : AbstractPropertyProtocol { typealias Index = T var a : T } // Allow _silgen_name accessors without bodies. var _silgen_nameGet1: Int { @_silgen_name("get1") get set { } } var _silgen_nameGet2: Int { set { } @_silgen_name("get2") get } var _silgen_nameGet3: Int { @_silgen_name("get3") get } var _silgen_nameGetSet: Int { @_silgen_name("get4") get @_silgen_name("set4") set } // <rdar://problem/16375910> reject observing properties overriding readonly properties class Base16375910 { var x : Int { // expected-note {{attempt to override property here}} return 42 } var y : Int { // expected-note {{attempt to override property here}} get { return 4 } set {} } } class Derived16375910 : Base16375910 { override init() {} override var x : Int { // expected-error {{cannot observe read-only property 'x'; it can't change}} willSet { markUsed(newValue) } } } // <rdar://problem/16382967> Observing properties have no storage, so shouldn't prevent initializer synth class Derived16382967 : Base16375910 { override var y : Int { willSet { markUsed(newValue) } } } // <rdar://problem/16659058> Read-write properties can be made read-only in a property override class Derived16659058 : Base16375910 { override var y : Int { // expected-error {{cannot override mutable property with read-only property 'y'}} get { return 42 } } } // <rdar://problem/16406886> Observing properties don't work with ownership types struct PropertiesWithOwnershipTypes { unowned var p1 : SomeClass { didSet { } } init(res: SomeClass) { p1 = res } } // <rdar://problem/16608609> Assert (and incorrect error message) when defining a constant stored property with observers class Test16608609 { let constantStored: Int = 0 { // expected-error {{'let' declarations cannot be observing properties}} {{4-7=var}} willSet { } didSet { } } } // <rdar://problem/16941124> Overriding property observers warn about using the property value "within its own getter" class rdar16941124Base { var x = 0 } class rdar16941124Derived : rdar16941124Base { var y = 0 override var x: Int { didSet { y = x + 1 // no warning. } } } // Overrides of properties with custom ownership. class OwnershipBase { class var defaultObject: AnyObject { fatalError("") } var strongVar: AnyObject? // expected-note{{overridden declaration is here}} weak var weakVar: AnyObject? // expected-note{{overridden declaration is here}} // FIXME: These should be optional to properly test overriding. unowned var unownedVar: AnyObject = defaultObject unowned var optUnownedVar: AnyObject? = defaultObject unowned(unsafe) var unownedUnsafeVar: AnyObject = defaultObject // expected-note{{overridden declaration is here}} unowned(unsafe) var optUnownedUnsafeVar: AnyObject? = defaultObject } class OwnershipExplicitSub : OwnershipBase { override var strongVar: AnyObject? { didSet {} } override weak var weakVar: AnyObject? { didSet {} } override unowned var unownedVar: AnyObject { didSet {} } override unowned var optUnownedVar: AnyObject? { didSet {} } override unowned(unsafe) var unownedUnsafeVar: AnyObject { didSet {} } override unowned(unsafe) var optUnownedUnsafeVar: AnyObject? { didSet {} } } class OwnershipImplicitSub : OwnershipBase { override var strongVar: AnyObject? { didSet {} } override weak var weakVar: AnyObject? { didSet {} } override unowned var unownedVar: AnyObject { didSet {} } override unowned var optUnownedVar: AnyObject? { didSet {} } override unowned(unsafe) var unownedUnsafeVar: AnyObject { didSet {} } override unowned(unsafe) var optUnownedUnsafeVar: AnyObject? { didSet {} } } class OwnershipBadSub : OwnershipBase { override weak var strongVar: AnyObject? { // expected-error {{cannot override 'strong' property with 'weak' property}} didSet {} } override unowned var weakVar: AnyObject? { // expected-error {{cannot override 'weak' property with 'unowned' property}} didSet {} } override weak var unownedVar: AnyObject { // expected-error {{'weak' variable should have optional type 'AnyObject?'}} didSet {} } override unowned var unownedUnsafeVar: AnyObject { // expected-error {{cannot override 'unowned(unsafe)' property with 'unowned' property}} didSet {} } } // <rdar://problem/17391625> Swift Compiler Crashes when Declaring a Variable and didSet in an Extension class rdar17391625 { var prop = 42 // expected-note {{overri}} } extension rdar17391625 { var someStoredVar: Int // expected-error {{extensions must not contain stored properties}} var someObservedVar: Int { // expected-error {{extensions must not contain stored properties}} didSet { } } } class rdar17391625derived : rdar17391625 { } extension rdar17391625derived { // Not a stored property, computed because it is an override. override var prop: Int { // expected-error {{overri}} didSet { } } } // <rdar://problem/27671033> Crash when defining property inside an invalid extension // (This extension is no longer invalid.) public protocol rdar27671033P {} struct rdar27671033S<Key, Value> {} extension rdar27671033S : rdar27671033P where Key == String { let d = rdar27671033S<Int, Int>() // expected-error {{extensions must not contain stored properties}} } // <rdar://problem/19874152> struct memberwise initializer violates new sanctity of previously set `let` property struct r19874152S1 { let number : Int = 42 } _ = r19874152S1(number:64) // expected-error {{argument passed to call that takes no arguments}} _ = r19874152S1() // Ok struct r19874152S2 { var number : Int = 42 } _ = r19874152S2(number:64) // Ok, property is a var. _ = r19874152S2() // Ok struct r19874152S3 { // expected-note {{'init(flavor:)' declared here}} let number : Int = 42 let flavor : Int } _ = r19874152S3(number:64) // expected-error {{incorrect argument label in call (have 'number:', expected 'flavor:')}} {{17-23=flavor}} _ = r19874152S3(number:64, flavor: 17) // expected-error {{extra argument 'number' in call}} _ = r19874152S3(flavor: 17) // ok _ = r19874152S3() // expected-error {{missing argument for parameter 'flavor' in call}} struct r19874152S4 { let number : Int? = nil } _ = r19874152S4(number:64) // expected-error {{argument passed to call that takes no arguments}} _ = r19874152S4() // Ok struct r19874152S5 { } _ = r19874152S5() // ok struct r19874152S6 { let (a,b) = (1,2) // Cannot handle implicit synth of this yet. } _ = r19874152S5() // ok // <rdar://problem/24314506> QoI: Fix-it for dictionary initializer on required class var suggests [] instead of [:] class r24314506 { // expected-error {{class 'r24314506' has no initializers}} var myDict: [String: AnyObject] // expected-note {{stored property 'myDict' without initial value prevents synthesized initializers}} {{34-34= = [:]}} } // https://bugs.swift.org/browse/SR-3893 // Generic type is not inferenced from its initial value for properties with // will/didSet struct SR3893Box<Foo> { let value: Foo } struct SR3893 { // Each of these "bad" properties used to produce errors. var bad: SR3893Box = SR3893Box(value: 0) { willSet { print(newValue.value) } } var bad2: SR3893Box = SR3893Box(value: 0) { willSet(new) { print(new.value) } } var bad3: SR3893Box = SR3893Box(value: 0) { didSet { print(oldValue.value) } } var good: SR3893Box<Int> = SR3893Box(value: 0) { didSet { print(oldValue.value) } } var plain: SR3893Box = SR3893Box(value: 0) } protocol WFI_P1 : class {} protocol WFI_P2 : class {} class WeakFixItTest { init() {} // expected-error @+1 {{'weak' variable should have optional type 'WeakFixItTest?'}} {{31-31=?}} weak var foo : WeakFixItTest // expected-error @+1 {{'weak' variable should have optional type '(WFI_P1 & WFI_P2)?'}} {{18-18=(}} {{33-33=)?}} weak var bar : WFI_P1 & WFI_P2 } // SR-8811 (Warning) let sr8811a = fatalError() // expected-warning {{constant 'sr8811a' inferred to have type 'Never', which is an enum with no cases}} expected-note {{add an explicit type annotation to silence this warning}} let sr8811b: Never = fatalError() // Ok let sr8811c = (16, fatalError()) // expected-warning {{constant 'sr8811c' inferred to have type '(Int, Never)', which contains an enum with no cases}} expected-note {{add an explicit type annotation to silence this warning}} let sr8811d: (Int, Never) = (16, fatalError()) // Ok // SR-10995 class SR_10995 { func makeDoubleOptionalNever() -> Never?? { return nil } func makeSingleOptionalNever() -> Never? { return nil } func sr_10995_foo() { let doubleOptionalNever = makeDoubleOptionalNever() // expected-warning {{constant 'doubleOptionalNever' inferred to have type 'Never??', which may be unexpected}} // expected-note@-1 {{add an explicit type annotation to silence this warning}} // expected-warning@-2 {{initialization of immutable value 'doubleOptionalNever' was never used; consider replacing with assignment to '_' or removing it}} let singleOptionalNever = makeSingleOptionalNever() // expected-warning {{constant 'singleOptionalNever' inferred to have type 'Never?', which may be unexpected}} // expected-note@-1 {{add an explicit type annotation to silence this warning}} // expected-warning@-2 {{initialization of immutable value 'singleOptionalNever' was never used; consider replacing with assignment to '_' or removing it}} } } // SR-9267 class SR_9267 {} extension SR_9267 { var foo: String = { // expected-error {{extensions must not contain stored properties}} // expected-error {{function produces expected type 'String'; did you mean to call it with '()'?}} // expected-note {{Remove '=' to make 'foo' a computed property}}{{19-21=}} return "Hello" } } enum SR_9267_E { var SR_9267_prop: String = { // expected-error {{enums must not contain stored properties}} // expected-error {{function produces expected type 'String'; did you mean to call it with '()'?}} // expected-note {{Remove '=' to make 'SR_9267_prop' a computed property}}{{28-30=}} return "Hello" } } var SR_9267_prop_1: Int = { // expected-error {{function produces expected type 'Int'; did you mean to call it with '()'?}} // expected-note {{Remove '=' to make 'SR_9267_prop_1' a computed property}}{{25-27=}} return 0 } class SR_9267_C { var SR_9267_prop_2: String = { // expected-error {{function produces expected type 'String'; did you mean to call it with '()'?}} // expected-note {{Remove '=' to make 'SR_9267_prop_2' a computed property}}{{30-32=}} return "Hello" } } class SR_9267_C2 { let SR_9267_prop_3: Int = { return 0 } // expected-error {{function produces expected type 'Int'; did you mean to call it with '()'?}} // expected-note {{Remove '=' to make 'SR_9267_prop_3' a computed property}}{{3-6=var}}{{27-29=}} } class LazyPropInClass { lazy var foo: Int = { return 0 } // expected-error {{function produces expected type 'Int'; did you mean to call it with '()'?}} // expected-note@-1 {{Remove '=' to make 'foo' a computed property}}{{21-23=}}{{3-8=}} }
26.943156
323
0.666408
79b82c943bde3a2f3ff5c9b5a60ae0b399a9fba5
30,194
// The MIT License (MIT) // // Copyright (c) 2016-2019 Alexander Grebenyuk (github.com/kean). import XCTest import Future // Tests migrated from JS https://github.com/promises-aplus/promises-tests class APlusTests: XCTestCase { func test_2_1_2() { describe("2.1.2.1: When fulfilled, a promise: must not transition to any other state.") { expect("trying to fulfill then immediately fulfill with a different value") { finish in let future = Future<Int, MyError> { promise in promise.succeed(value: 0) promise.succeed(value: 1) } future.on(success: { XCTAssertEqual($0, 0) finish() }) } expect("trying to fulfill then immediately reject") { finish in let future = Future<Int, MyError> { promise in promise.succeed(value: 0) promise.fail(error: MyError.e1) } future.on(success: { XCTAssertEqual($0, 0) finish() }) } expect("trying to fulfill then reject, delayed") { finish in let future = Future<Int, MyError> { promise in after(ticks: 5) { promise.succeed(value: 0) promise.fail(error: .e1) } } future.on(success: { XCTAssertEqual($0, 0) finish() }) } expect("trying to fulfill immediately then reject delayed") { finish in let future = Future<Int, MyError> { promise in promise.succeed(value: 0) after(ticks: 5) { promise.fail(error: MyError.e1) } } future.on(success: { XCTAssertEqual($0, 0) finish() }) } } } func test_2_1_3() { describe("2.1.3.1: When rejected, a promise: must not transition to any other state.") { expect("reject then reject with different error") { finish in let future = Future<Int, MyError> { promise in promise.fail(error: MyError.e1) promise.fail(error: MyError.e2) } future.on(failure: { XCTAssertEqual($0, MyError.e1) finish() }) } expect("trying to reject then immediately fulfill") { finish in let future = Future<Int, MyError> { promise in promise.fail(error: MyError.e1) promise.succeed(value: 1) } future.on(failure: { XCTAssertEqual($0, MyError.e1) finish() }) } expect("trying to reject then fulfill, delayed") { finish in let future = Future<Int, MyError> { promise in after(ticks: 5) { promise.fail(error: MyError.e1) promise.succeed(value: 1) } } future.on(failure: { XCTAssertEqual($0, MyError.e1) finish() }) } expect("trying to reject immediately then fulfill delayed") { finish in let future = Future<Int, MyError> { promise in promise.fail(error: MyError.e1) after(ticks: 5) { promise.succeed(value: 1) } } future.on(failure: { XCTAssertEqual($0, MyError.e1) finish() }) } } } func test_2_2_1() { describe("2.2.1: Both `onFulfilled` and `onRejected` are optional arguments.") // Doesn't make sense in Swift } func test_2_2_2() { describe("2.2.2: If `onFulfilled` is a function") { describe("2.2.2.1: it must be called after `promise` is fulfilled, with `promise`’s fulfillment value as its first argument.") { expect("fulfill delayed") { finish in Future<Int, MyError>.eventuallySuccessfull().on(success: { XCTAssertEqual($0, sentinel) finish() }) } expect("fulfill immediately") { finish in Future<Int, MyError>(value: sentinel).on(success: { XCTAssertEqual($0, sentinel) finish() }) } } describe("2.2.2.2: it must not be called before `promise` is fulfilled") { expect("fulfilled after a delay") { finish in let promise = Promise<Int, MyError>() let future = promise.future var called = false future.on(success: { _ in called = true finish() }) future.on(failure: { _ in XCTFail() }) after(ticks: 5) { XCTAssertFalse(called) promise.succeed(value: 1) } } expect("never fulfilled") { finish in let future = Promise<Int, MyError>() future.future.on(success: { _ in XCTFail() }) after(ticks: 5) { finish() } } } describe("2.2.2.3: it must not be called more than once.") { expect("already-fulfilled") { finish in let future = Future<Int, MyError>(value: sentinel) var timesCalled = 0 future.on(success: { _ in timesCalled += 1 XCTAssertEqual(timesCalled, 1) }) after(ticks: 20) { finish() XCTAssertEqual(timesCalled, 1) } } expect("trying to fulfill a pending promise more than once, immediately") { finish in let promise = Promise<Int, MyError>() let future = promise.future var timesCalled = 0 future.on(success: { _ in timesCalled += 1 XCTAssertEqual(timesCalled, 1) }) promise.succeed(value: 1) promise.succeed(value: 2) promise.succeed(value: 1) after(ticks: 20) { finish() XCTAssertEqual(timesCalled, 1) } } expect("trying to fulfill a pending promise more than once, delayed") { finish in let promise = Promise<Int, MyError>() let future = promise.future var timesCalled = 0 future.on(success: { _ in timesCalled += 1 XCTAssertEqual(timesCalled, 1) }) after(ticks: 5) { promise.succeed(value: 1) promise.succeed(value: 2) promise.succeed(value: 1) } after(ticks: 25) { finish() XCTAssertEqual(timesCalled, 1) } } expect("trying to fulfill a pending promise more than once, immediately then delayed") { finish in let promise = Promise<Int, MyError>() let future = promise.future var timesCalled = 0 future.on(success: { XCTAssertEqual($0, sentinel) timesCalled += 1 XCTAssertEqual(timesCalled, 1) }) promise.succeed(value: sentinel) after(ticks: 5) { promise.succeed(value: sentinel) } after(ticks: 25) { finish() XCTAssertEqual(timesCalled, 1) } } expect("when multiple `then` calls are made, spaced apart in time") { finish in let promise = Promise<Int, MyError>() let future = promise.future var timesCalled = 0 after(ticks: 5) { future.on(success: { XCTAssertEqual($0, sentinel) timesCalled += 1 XCTAssertEqual(timesCalled, 1) }) } after(ticks: 10) { future.on(success: { XCTAssertEqual($0, sentinel) timesCalled += 1 XCTAssertEqual(timesCalled, 2) }) } after(ticks: 15) { future.on(success: { XCTAssertEqual($0, sentinel) timesCalled += 1 XCTAssertEqual(timesCalled, 3) finish() }) } after(ticks: 20) { promise.succeed(value: sentinel) } } expect("when `then` is interleaved with fulfillment") { finish in let promise = Promise<Int, MyError>() let future = promise.future var timesCalled = 0 future.on(success: { XCTAssertEqual($0, sentinel) timesCalled += 1 XCTAssertEqual(timesCalled, 1) }) promise.succeed(value: sentinel) future.on(success: { XCTAssertEqual($0, sentinel) timesCalled += 1 XCTAssertEqual(timesCalled, 2) finish() }) } } } } func test_2_2_3() { describe("2.2.3: If `onRejected` is a function,") { describe("2.2.3.1: it must be called after `promise` is rejected, with `promise`’s rejection reason as its first argument.") { expect("rejected after delay") { finish in Future<Int, MyError>.eventuallyFailed().on(failure: { XCTAssertEqual($0, MyError.e1) finish() }) } expect("already-rejected") { finish in Future<Int, MyError>(error: MyError.e1).on(failure: { XCTAssertEqual($0, MyError.e1) finish() }) } } describe("2.2.3.2: it must not be called before `promise` is rejected") { expect("rejected after a delay") { finish in let promise = Promise<Int, MyError>() let future = promise.future var called = false future.on(failure: { _ in called = true finish() }) future.on(success: { _ in XCTFail() }) after(ticks: 5) { XCTAssertFalse(called) promise.fail(error: MyError.e1) } } expect("never rejected") { finish in let promise = Promise<Int, MyError>() let future = promise.future future.on(failure: { _ in XCTFail() }) after(ticks: 5) { finish() } } } describe("2.2.3.3: it must not be called more than once.") { expect("already-rejected") { finish in let future = Future<Int, MyError>(error: MyError.e1) var timesCalled = 0 future.on(failure: { XCTAssertEqual($0, MyError.e1) timesCalled += 1 XCTAssertEqual(timesCalled, 1) }) after(ticks: 25) { finish() XCTAssertEqual(timesCalled, 1) } } expect("trying to reject a pending promise more than once, immediately") { finish in let promise = Promise<Int, MyError>() let future = promise.future var timesCalled = 0 future.on(failure: { XCTAssertEqual($0, .e1) timesCalled += 1 XCTAssertEqual(timesCalled, 1) }) promise.fail(error: MyError.e1) promise.fail(error: MyError.e1) after(ticks: 25) { finish() XCTAssertEqual(timesCalled, 1) } } expect("trying to reject a pending promise more than once, delayed") { finish in let promise = Promise<Int, MyError>() let future = promise.future var timesCalled = 0 future.on(failure: { XCTAssertEqual($0, MyError.e1) timesCalled += 1 XCTAssertEqual(timesCalled, 1) }) after(ticks: 5) { promise.fail(error: MyError.e1) promise.fail(error: MyError.e1) } after(ticks: 25) { finish() XCTAssertEqual(timesCalled, 1) } } expect("trying to reject a pending promise more than once, immediately then delayed") { finish in let promise = Promise<Int, MyError>() let future = promise.future var timesCalled = 0 future.on(failure: { XCTAssertEqual($0, MyError.e1) timesCalled += 1 XCTAssertEqual(timesCalled, 1) }) promise.fail(error: MyError.e1) after(ticks: 5) { promise.fail(error: MyError.e1) } after(ticks: 25) { finish() XCTAssertEqual(timesCalled, 1) } } expect("when multiple `then` calls are made, spaced apart in time") { finish in let promise = Promise<Int, MyError>() let future = promise.future var timesCalled = 0 future.on(failure: { XCTAssertEqual($0, MyError.e1) timesCalled += 1 XCTAssertEqual(timesCalled, 1) }) after(ticks: 5) { future.on(failure: { XCTAssertEqual($0, MyError.e1) timesCalled += 1 XCTAssertEqual(timesCalled, 2) }) } after(ticks: 10) { future.on(failure: { XCTAssertEqual($0, MyError.e1) timesCalled += 1 XCTAssertEqual(timesCalled, 3) finish() }) } after(ticks: 15) { promise.fail(error: MyError.e1) } } expect("when `then` is interleaved with rejection") { finish in let promise = Promise<Int, MyError>() let future = promise.future var timesCalled = 0 future.on(failure: { XCTAssertEqual($0, MyError.e1) timesCalled += 1 XCTAssertEqual(timesCalled, 1) }) promise.fail(error: MyError.e1) future.on(failure: { XCTAssertEqual($0, MyError.e1) timesCalled += 1 XCTAssertEqual(timesCalled, 2) finish() }) } } } } func test_2_2_5() { describe("2.2.5 `onFulfilled` and `onRejected` must be called as functions (i.e. with no `this` value).") // Doesn't make sense in Swift } func test_2_2_6() { describe("2.2.6: `then` may be called multiple times on the same promise.") { describe("2.2.6.1: If/when `promise` is fulfilled, all respective `onFulfilled` callbacks must execute in the order of their originating calls to `then`.") { expect("multiple boring fulfillment handlers", count: 3) { finish in let future = Future<Int, MyError>.eventuallySuccessfull() future.on(success: { XCTAssertEqual($0, sentinel) finish() }) future.on(success: { XCTAssertEqual($0, sentinel) finish() }) future.on(success: { XCTAssertEqual($0, sentinel) finish() }) } describe("multiple fulfillment handlers, one of which throws") { // Doesn't make sense in Future, cause it doesn't allow throws (yet?) } expect("results in multiple branching chains with their own fulfillment values", count: 3) { finish in let future = Future<Int, MyError>.eventuallySuccessfull() future.map { val -> Int in XCTAssertEqual(val, sentinel) return 2 }.on(success: { XCTAssertEqual($0, 2) finish() }) future.map { val -> Int in XCTAssertEqual(val, sentinel) return 3 }.on(success: { XCTAssertEqual($0, 3) finish() }) future.map { val -> Int in XCTAssertEqual(val, sentinel) return 4 }.on(success: { XCTAssertEqual($0, 4) finish() }) } // expect("`onFulfilled` handlers are called in the original order") { finish in // let future = Future<Int, MyError>.eventuallySuccessfull() // var callCount = 0 // // future.on(success: { // XCTAssertEqual($0, sentinel) // callCount += 1 // XCTAssertEqual(callCount, 1) // }) // // // future.on(success: { // XCTAssertEqual($0, sentinel) // callCount += 1 // XCTAssertEqual(callCount, 2) // }) // // future.on(success: { // XCTAssertEqual($0, sentinel) // callCount += 1 // XCTAssertEqual(callCount, 3) // finish() // }) // // future.on(failure: { _ in XCTFail() }) // } expect("even when one handler is added inside another handle") { finish in let future = Future<Int, MyError>.eventuallySuccessfull() var callCount = 0 future.on(success: { XCTAssertEqual($0, sentinel) callCount += 1 XCTAssertEqual(callCount, 1) future.on(success: { XCTAssertEqual($0, sentinel) callCount += 1 XCTAssertEqual(callCount, 2) future.on(success: { XCTAssertEqual($0, sentinel) callCount += 1 XCTAssertEqual(callCount, 3) finish() }) }) }) } } describe("2.2.6.2: If/when `promise` is rejected, all respective `onRejected` callbacks must execute in the order of their originating calls to `then`.") { expect("multiple boring rejection handlers", count: 3) { finish in let future = Future<Int, MyError>.eventuallyFailed() future.on(failure: { XCTAssertEqual($0, MyError.e1) finish() }) future.on(failure: { XCTAssertEqual($0, MyError.e1) finish() }) future.on(failure: { XCTAssertEqual($0, MyError.e1) finish() }) } describe("multiple rejection handlers, one of which throws") { // Doesn't make sense in Future, cause it doesn't allow throws (yet?) } // expect("`onRejected` handlers are called in the original order") { finish in // let future = Future<Int, MyError>.eventuallyFailed() // var callCount = 0 // // future.on(failure: { // XCTAssertEqual($0, MyError.e1) // callCount += 1 // XCTAssertEqual(callCount, 1) // }) // // future.on(failure: { // XCTAssertEqual($0, MyError.e1) // callCount += 1 // XCTAssertEqual(callCount, 2) // }) // // future.on(failure: { // XCTAssertEqual($0, MyError.e1) // callCount += 1 // XCTAssertEqual(callCount, 3) // finish() // }) // // future.on(success: { _ in XCTFail() }) // } expect("even when one handler is added inside another handle") { finish in let future = Future<Int, MyError>.eventuallyFailed() var callCount = 0 future.on(failure: { XCTAssertEqual($0, MyError.e1) callCount += 1 XCTAssertEqual(callCount, 1) future.on(failure: { XCTAssertEqual($0, MyError.e1) callCount += 1 XCTAssertEqual(callCount, 2) future.on(failure: { XCTAssertEqual($0, MyError.e1) callCount += 1 XCTAssertEqual(callCount, 3) finish() }) }) }) } } } func test_2_2_7() { describe("2.2.7: `then` must return a promise: `promise2 = promise1.then(onFulfilled, onRejected)") { describe("is a promise") { // Doesn't make sense in Swift } describe("2.2.7.1: If either `onFulfilled` or `onRejected` returns a value `x`, run the Promise Resolution procedure `[[Resolve]](promise2, x)`") { // See separate 3.3 tests } describe("2.2.7.2: If either `onFulfilled` or `onRejected` throws an exception `e`, `promise2` must be rejected with `e` as the reason.") { // We don't test that since we don't allow then/catch to throw } describe("2.2.7.3: If `onFulfilled` is not a function and `promise1` is fulfilled, `promise2` must be fulfilled with the same value.") { // Doesn't make sense in Swift } describe("2.2.7.4: If `onRejected` is not a function and `promise1` is rejected, `promise2` must be rejected with the same reason.") { // Doesn't make sense in Swift } } } func test_2_3_1() { describe("2.3.1: If `promise` and `x` refer to the same object, reject `promise` with a `TypeError' as the reason.") { // First of, this is really a fatal error which is a result of // a programmatic error - it's not 'just an error'. // Second of, Future doesn't (yet) support this since it seems // like an overkill at this point. } } func test_2_3_2() { describe("2.3.2: If `x` is a promise, adopt its state") { describe("2.3.2.1: If `x` is pending, `promise` must remain pending until `x` is fulfilled or rejected.") { expect("via return from a fulfilled promise") { finish in let future = Future(value: 1).flatMap { _ in return Future<Int, MyError> { _ in } // pending } future.on(completion: { XCTFail() }) after(ticks: 20) { finish() } } expect("via return from a rejected promise") { finish in let future = Future<Int, MyError>(error: MyError.e1).flatMapError { _ in return Future<Int, MyError> { _ in } // pending } future.on(completion: { XCTFail() }) after(ticks: 20) { finish() } } } describe("2.3.2.2: If/when `x` is fulfilled, fulfill `promise` with the same value.") { expect("`x` is already-fulfilled") { finish in let future = Future<Int, MyError>(value: sentinel).map { return $0 } future.on(success: { XCTAssertEqual($0, sentinel) finish() }) } expect("`x` is eventually-fulfilled") { finish in let future = Future<Int, MyError>.eventuallySuccessfull().map { return $0 } future.on(success: { XCTAssertEqual($0, sentinel) finish() }) } } describe("2.3.2.3: If/when `x` is rejected, reject `promise` with the same reason.") { expect("`x` is already-rejected") { finish in let future = Future<Int, MyError>(error: MyError.e1).map { _ in } future.on(failure: { XCTAssertEqual($0, MyError.e1) finish() }) } expect("`x` is eventually-rejected") { finish in let future = Future<Int, MyError>.eventuallyFailed().map { _ in } future.on(failure: { XCTAssertEqual($0, MyError.e1) finish() }) } } } } func test_2_3_3() { describe("2.3.3: Otherwise, if `x` is an object or function,") { // Most of those tests doesn't make sense in Swift // FIXME: Get back to it later, there might be some usefull tests } } func test_2_3_4() { describe("2.3.4: If `x` is not an object or function, fulfill `promise` with `x`") { // Doesn't make sense in Swift } } } }
37.415118
169
0.400046
2fc7b04e09b1dca57785e86d43ad9a151fa7cba1
220
// // SBTableView.swift // SBExtensions // // Created by Admin on 04.03.18. // Copyright © 2018 Stepan Boichenko. All rights reserved. // import Foundation import UIKit open class SBTableView: UITableView { }
14.666667
59
0.695455
b92b047b049a45bc4d70017cfc7e4695705a2224
1,958
// // String-Extension.swift // DNLocalMusicPlayer // // Created by 许一宁 on 2020/8/7. // Copyright © 2020 大宁. All rights reserved. // import Cocoa class String_Extension: NSString { } extension String { //MARK: 查找string的首个NSRange func rangeOfString(_ string:String, ignoreCase:Bool? = false) -> NSRange? { // 判断是否忽略大小写 let options:CompareOptions = ignoreCase! ? [.regularExpression, .caseInsensitive] : [.regularExpression] if let range:Range = self.range(of: string, options: options, range: self.range(of: self), locale: nil){ let location = self.distance(from: self.startIndex, to: range.lowerBound) let nsRange = NSRange(location: location, length: string.count) return nsRange } return nil } //MARK: 查找String的所有NSRange数组(可设置是否忽略大小写) func rangesOfString(_ string:String, ignoreCase:Bool? = false) -> [NSRange] { // 判断是否忽略大小写 let options:CompareOptions = ignoreCase! ? [.regularExpression, .caseInsensitive] : [.regularExpression] // 返回的NSRange数组 var rangeArray:[NSRange] = [] // 搜索到的Range var range:Range? = self.range(of: string, options: options, range: self.range(of: self), locale: nil) // 启动shile,添加并重新计算查询,如果range在while循环中最终为nil则终止 while let searchRange = range { // 搜索到的location let location = self.distance(from: self.startIndex, to: searchRange.lowerBound) // 根据location和length创建NSRange let nsRange = NSRange(location: location, length: string.count) // 添加进数组 rangeArray.append(nsRange) // 重新计算Range(前闭后开的区域 searchRange.upperBound..<self.endIndex) let searchedRange = Range(uncheckedBounds: (searchRange.upperBound, self.endIndex)) range = self.range(of: string, options: options, range: searchedRange, locale: nil) } return rangeArray } }
37.653846
112
0.643003
f719cf72795d36c1195043de980ebc79d3690393
1,125
// // AboutView.swift // DarkMode Switcher // // Created by Mohamed Arradi on 6/11/18. // Copyright © 2018 Mohamed ARRADI. All rights reserved. // import Foundation import Cocoa class AboutWindow: NSWindowController { @IBOutlet weak var appIconImageView: NSImageView! @IBOutlet weak var appNameLabel: NSTextField! @IBOutlet weak var appBuildVersionLabel: NSTextField! override var windowNibName: NSNib.Name? { return "AboutWindow" } override func windowDidLoad() { super.windowDidLoad() self.window?.titlebarAppearsTransparent = true self.window?.center() self.window?.makeKeyAndOrderFront(nil) NSApp.activate(ignoringOtherApps: true) appNameLabel.stringValue = "Darky" guard let releaseVersionNumber = Bundle.main.releaseVersionNumber, let buildNumber = Bundle.main.buildVersionNumber else { return } appBuildVersionLabel.stringValue = "Version ".appending(releaseVersionNumber).appending(String(format: ".%@", buildNumber)) } }
27.439024
131
0.659556
f71fdd3e9a508806990710faf127ad3289c21578
7,774
import UIKit class TodoListViewController: UIViewController { @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var inputViewBottom: NSLayoutConstraint! @IBOutlet weak var inputTextField: UITextField! @IBOutlet weak var isTodayButton: UIButton! @IBOutlet weak var addButton: UIButton! // [X] TODO: TodoViewModel 만들기 let todoListViewModel = TodoViewModel() override func viewDidLoad() { super.viewDidLoad() // [X] TODO: 키보드 디텍션 NotificationCenter.default.addObserver(self, selector: #selector(adjustInputView), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(adjustInputView), name: UIResponder.keyboardWillHideNotification, object: nil) // [X] TODO: 데이터 불러오기 todoListViewModel.loadTasks() // let todo = TodoManager.shared.createTodo(detail: "👍 🚀 Corona 난리", isToday: true) // Storage.saveTodo(todo, fileName: "test.json") } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // let todo = Storage.restoreTodo("test.json") // print("---> restore from disk: \(todo)") } @IBAction func isTodayButtonTapped(_ sender: Any) { // [X] TODO: 투데이 버튼 토글 작업 isTodayButton.isSelected = !isTodayButton.isSelected } @IBAction func addTaskButtonTapped(_ sender: Any) { // [X] TODO: Todo 태스크 추가 // add task to view model // and tableview reload or update guard let detail = inputTextField.text, detail.isEmpty == false else { return } let todo = TodoManager.shared.createTodo(detail: detail, isToday: isTodayButton.isSelected) todoListViewModel.addTodo(todo) collectionView.reloadData() inputTextField.text = "" isTodayButton.isSelected = false } // [X] TODO: BG 탭했을때, 키보드 내려오게 하기 @IBAction func tapBG(_ sender: Any) { inputTextField.resignFirstResponder() } } extension TodoListViewController { @objc private func adjustInputView(noti: Notification) { guard let userInfo = noti.userInfo else { return } // TODO: [X] 키보드 높이에 따른 인풋뷰 위치 변경 guard let keyboardFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return } if noti.name == UIResponder.keyboardWillShowNotification { let adjustmentHeight = keyboardFrame.height - view.safeAreaInsets.bottom inputViewBottom.constant = adjustmentHeight } else { inputViewBottom.constant = 0 } print("Keyboard ENd Frame: \(keyboardFrame)") } } extension TodoListViewController: UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { // [X] TODO: 섹션 몇개 return todoListViewModel.numOfSection } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // [X] TODO: 섹션별 아이템 몇개 if section == 0 { return todoListViewModel.todayTodos.count } else { return todoListViewModel.upcompingTodos.count } } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TodoListCell", for: indexPath) as? TodoListCell else { return UICollectionViewCell() } var todo: Todo if indexPath.section == 0 { todo = todoListViewModel.todayTodos[indexPath.item] } else { todo = todoListViewModel.upcompingTodos[indexPath.item] } cell.updateUI(todo: todo) // [X] TODO: 커스텀 셀 // [X] TODO: todo 를 이용해서 updateUI // [X] TODO: doneButtonHandler 작성 // [X] TODO: deleteButtonHandler 작성 cell.doneButtonTapHandler = { isDone in todo.isDone = isDone self.todoListViewModel.updateTodo(todo) self.collectionView.reloadData() } cell.deleteButtonTapHandler = { self.todoListViewModel.deleteTodo(todo) self.collectionView.reloadData() } return cell } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { switch kind { case UICollectionView.elementKindSectionHeader: guard let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "TodoListHeaderView", for: indexPath) as? TodoListHeaderView else { return UICollectionReusableView() } guard let section = TodoViewModel.Section(rawValue: indexPath.section) else { return UICollectionReusableView() } header.sectionTitleLabel.text = section.title return header default: return UICollectionReusableView() } } } extension TodoListViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { // [X] TODO: 사이즈 계산하기 let width = collectionView.bounds.width let heigh: CGFloat = 50 return CGSize(width: width, height: heigh) } } class TodoListCell: UICollectionViewCell { @IBOutlet weak var checkButton: UIButton! @IBOutlet weak var descriptionLabel: UILabel! @IBOutlet weak var deleteButton: UIButton! @IBOutlet weak var strikeThroughView: UIView! @IBOutlet weak var strikeThroughWidth: NSLayoutConstraint! var doneButtonTapHandler: ((Bool) -> Void)? var deleteButtonTapHandler: (() -> Void)? override func awakeFromNib() { super.awakeFromNib() reset() } override func prepareForReuse() { super.prepareForReuse() reset() } func updateUI(todo: Todo) { // [X] TODO: 셀 업데이트 하기 checkButton.isSelected = todo.isDone descriptionLabel.text = todo.detail descriptionLabel.alpha = todo.isDone ? 0.2 : 1 deleteButton.isHidden = todo.isDone == false showStrikeThrough(todo.isDone) } private func showStrikeThrough(_ show: Bool) { if show { strikeThroughWidth.constant = descriptionLabel.bounds.width } else { strikeThroughWidth.constant = 0 } } func reset() { // [X] TODO: reset로직 구현 descriptionLabel.alpha = 1 deleteButton.isHidden = true showStrikeThrough(false) } @IBAction func checkButtonTapped(_ sender: Any) { // [X]TODO: checkButton 처리 checkButton.isSelected = !checkButton.isSelected let isDone = checkButton.isSelected showStrikeThrough(isDone) descriptionLabel.alpha = isDone ? 0.2 : 1 deleteButton.isHidden = !isDone doneButtonTapHandler?(isDone) } @IBAction func deleteButtonTapped(_ sender: Any) { // [X] TODO: deleteButton 처리 deleteButtonTapHandler?() } } class TodoListHeaderView: UICollectionReusableView { @IBOutlet weak var sectionTitleLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() } }
33.080851
181
0.631721
469c53bbe24943d9512c85e55e5f36b68ad10c42
1,475
import Foundation import Models public final class TestStoppedEvent: Equatable, CustomStringConvertible { public enum Result: String, Equatable { case success case failure case lost } public let testName: TestName public let result: Result public let testDuration: TimeInterval public let testExceptions: [TestException] public let testStartTimestamp: TimeInterval public init( testName: TestName, result: Result, testDuration: TimeInterval, testExceptions: [TestException], testStartTimestamp: TimeInterval ) { self.testName = testName self.result = result self.testDuration = testDuration self.testExceptions = testExceptions self.testStartTimestamp = testStartTimestamp } public var succeeded: Bool { return result == .success } public var description: String { return "<\(type(of: self)) \(testName) result: \(result), duration: \(testDuration) sec, started at: \(testStartTimestamp)>" } public static func == (left: TestStoppedEvent, right: TestStoppedEvent) -> Bool { return left.testName == right.testName && left.result == right.result && (left.testDuration - right.testDuration) < 0.01 && left.testExceptions == right.testExceptions && (left.testStartTimestamp - right.testStartTimestamp) < 0.01 } }
31.382979
132
0.64339
8963cd591acc3df8a0d48281bb21b526093e85e0
231
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func < { extension g { enum b { protocol c { { } class case ,
17.769231
87
0.727273
1d9c73946f4441f8d460db5f79397847e9dbe663
3,322
// // JJPreviewView.swift // JJImagePicker // // Created by 李骏 on 2018/4/3. // Copyright © 2018年 李骏. All rights reserved. // import UIKit class JJPreviewView: UIView,UIScrollViewDelegate { lazy var scrollView:UIScrollView = { let tempScroll = UIScrollView.init() tempScroll.frame = self.bounds tempScroll.maximumZoomScale = 3.0 tempScroll.minimumZoomScale = 1.0 tempScroll.isMultipleTouchEnabled = true tempScroll.delegate = self tempScroll.scrollsToTop = false tempScroll.showsHorizontalScrollIndicator = false tempScroll.showsVerticalScrollIndicator = false tempScroll.delaysContentTouches = false return tempScroll }() lazy var imageView:UIImageView = { let tempIV = UIImageView.init(frame: self.bounds) tempIV.contentMode = UIViewContentMode.scaleAspectFit return tempIV }() lazy var containerView:UIView = { let tempContainer = UIView.init(frame: self.bounds) return tempContainer }() func resetScale() { self.scrollView.zoomScale = 1 } override init(frame: CGRect) { super.init(frame: frame) self.initUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() self.scrollView.frame = self.bounds self.resetScale() } func initUI() { self.addSubview(self.scrollView) self.scrollView.addSubview(self.containerView) self.containerView.addSubview(self.imageView) let doubleTap = UITapGestureRecognizer.init(target: self, action: #selector(doubleTapAction(recognizer:))) doubleTap.numberOfTapsRequired = 2 self.addGestureRecognizer(doubleTap) } @objc func doubleTapAction(recognizer:UITapGestureRecognizer) { let scrollView = self.scrollView var scale :CGFloat = 1 if scrollView.zoomScale != 3.0 { scale = 3 }else{ scale = 1 } let zoomRect = self.zoomRectForScale(scale: scale, center: recognizer.location(in: recognizer.view)) scrollView.zoom(to: zoomRect, animated: true) } func zoomRectForScale(scale:CGFloat,center:CGPoint) -> CGRect { var zoomRect:CGRect = CGRect.init() zoomRect.size.height = self.scrollView.frame.size.height/scale zoomRect.size.width = self.scrollView.frame.size.width/scale zoomRect.origin.x = center.x - (zoomRect.size.width / 2) zoomRect.origin.y = center.y - zoomRect.size.height/2 return zoomRect } func viewForZooming(in scrollView: UIScrollView) -> UIView? { return scrollView.subviews[0] } func scrollViewDidZoom(_ scrollView: UIScrollView) { let offsetX = scrollView.frame.size.width > scrollView.contentSize.width ?(scrollView.frame.size.width-scrollView.contentSize.width)*0.5:0 let offsetY = scrollView.frame.size.height>scrollView.contentSize.height ?(scrollView.frame.size.height-scrollView.contentSize.height)*0.5:0 self.containerView.center = CGPoint.init(x: scrollView.contentSize.width * 0.5 + offsetX, y: scrollView.contentSize.height*0.5 + offsetY) } }
37.325843
148
0.666767
20cf97f706d3aa047c32491b6030885107015c22
2,693
import Basic import Foundation import SPMUtility import TuistCore protocol VersionsControlling: AnyObject { typealias Installation = (AbsolutePath) throws -> Void func install(version: String, installation: Installation) throws func uninstall(version: String) throws func path(version: String) -> AbsolutePath func versions() -> [InstalledVersion] func semverVersions() -> [Version] } enum InstalledVersion: CustomStringConvertible, Equatable { case semver(Version) case reference(String) var description: String { switch self { case let .reference(value): return value case let .semver(value): return value.description } } static func == (lhs: InstalledVersion, rhs: InstalledVersion) -> Bool { switch (lhs, rhs) { case let (.semver(lhsVersion), .semver(rhsVersion)): return lhsVersion == rhsVersion case let (.reference(lhsRef), .reference(rhsRef)): return lhsRef == rhsRef default: return false } } } class VersionsController: VersionsControlling { // MARK: - VersionsControlling func install(version: String, installation: Installation) throws { let tmpDir = try TemporaryDirectory(removeTreeOnDeinit: true) try installation(tmpDir.path) // Copy only if there's file in the folder if !tmpDir.path.glob("*").isEmpty { let dstPath = path(version: version) if FileHandler.shared.exists(dstPath) { try FileHandler.shared.delete(dstPath) } try FileHandler.shared.copy(from: tmpDir.path, to: dstPath) } } func uninstall(version: String) throws { let path = self.path(version: version) if FileHandler.shared.exists(path) { try FileHandler.shared.delete(path) } } func path(version: String) -> AbsolutePath { return Environment.shared.versionsDirectory.appending(component: version) } func versions() -> [InstalledVersion] { return Environment.shared.versionsDirectory.glob("*").map { path in let versionStringValue = path.components.last! if let version = Version(string: versionStringValue) { return InstalledVersion.semver(version) } else { return InstalledVersion.reference(versionStringValue) } } } func semverVersions() -> [Version] { return versions().compactMap { version in if case let InstalledVersion.semver(semver) = version { return semver } return nil } } }
30.602273
81
0.624954
f41a7fc4f2ca2060b6b683111dd4adabdbd2b65a
1,118
// // WXFriendHeaderView.swift // swiftTaste // // Created by Liu on 16/7/26. // Copyright © 2016年 Dajie. All rights reserved. // import UIKit class WXFriendHeaderView: UITableViewHeaderFooterView { var title : String?{ didSet{ titleLabel.text = title } } override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) let bgView = UIView.init() bgView.backgroundColor = DEFAULT_BACKGROUND_COLOR() self.backgroundView = bgView addSubview(titleLabel) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() titleLabel.frame = CGRect(x: 10, y: 0, width: self.frameWidth - 15, height: self.frameHeight) } // MARK: - lazy var fileprivate lazy var titleLabel : UILabel = { let label = UILabel() label.font = UIFont.systemFont(ofSize: 14) label.textColor = UIColor.gray return label }() }
24.304348
101
0.610912
ff68e422c16cd7de6aa55c8678a823331b02df1c
3,857
// // EventManager.swift // Heart Calendar // // Created by Andrew Finke on 2/7/18. // Copyright © 2018 Andrew Finke. All rights reserved. // import UIKit import EventKit class EventManager { // MARK: - Types struct Event: Comparable { private let event: EKEvent var title: String { return event.title } var startDate: Date { return event.startDate } var endDate: Date { return event.endDate } var calendarColor: UIColor { return UIColor(cgColor: event.calendar.cgColor) } var calendarName: String { return event.calendar.title } init(_ event: EKEvent) { self.event = event } //swiftlint:disable:next operator_whitespace static func <(lhs: EventManager.Event, rhs: EventManager.Event) -> Bool { // 1. Check event title (e.g. 1. A_Event, 2. B_Event) // 2. Check event start date (e.g. 1. A_Event (starts 1/1), 2. A_Event (starts 1/2)) // 3. Check event calendar title (e.g. 1. A_Event (A_Cal), 2. A_Event (B_Cal)) // 4. Check event calendar identifier if lhs.event.title == rhs.event.title { if lhs.event.startDate == rhs.event.startDate { if lhs.event.calendar.title == rhs.event.calendar.title { return lhs.event.calendar.calendarIdentifier > rhs.event.calendar.calendarIdentifier } else { return lhs.event.calendar.title > rhs.event.calendar.title } } else { return lhs.event.startDate > rhs.event.startDate } } else { return lhs.event.title > rhs.event.title } } //swiftlint:disable:next operator_whitespace static func ==(lhs: EventManager.Event, rhs: EventManager.Event) -> Bool { return lhs.event == rhs.event } } struct Calendar { fileprivate let calendar: EKCalendar var title: String { return calendar.title } var identifier: String { return calendar.calendarIdentifier } var color: UIColor { return UIColor(cgColor: calendar.cgColor) } init(_ calendar: EKCalendar) { self.calendar = calendar } } // MARK: - Properties private let eventStore = EKEventStore() // MARK: - Methods func authorize(completion: @escaping (Bool, Error?) -> Void) { eventStore.requestAccess(to: .event) { (success, error) in completion(success, error) } } func allStoreCalendars() -> [Calendar] { return eventStore.calendars(for: .event).map { Calendar($0) } } func events(between startDate: Date, and endDate: Date) -> [Event] { let storeCalendars = allStoreCalendars() var calendarIdentifiers = PreferencesManager.shared.calendarIdentifiers if calendarIdentifiers == nil { calendarIdentifiers = storeCalendars.map { $0.calendar.calendarIdentifier } PreferencesManager.shared.calendarIdentifiers = calendarIdentifiers } guard let calendarIDs = calendarIdentifiers, !calendarIDs.isEmpty else { return [] } let selectedCalendars = storeCalendars .map { $0.calendar } .filter { calendarIDs.contains($0.calendarIdentifier) } let predicate = eventStore.predicateForEvents(withStart: startDate, end: endDate, calendars: selectedCalendars) return eventStore.events(matching: predicate).map { Event($0) } } }
31.357724
108
0.564688
14ea876f87a579234fdf4afc486a641adeb7c479
266
// // Help.swift // Barliman iOS Prototype // // Created by Ben J on 8/7/18. // Copyright © 2018 Ben Jenkins. All rights reserved. // import Foundation extension Notification.Name { static let helpRequested = NSNotification.Name("helpRequested") }
17.733333
54
0.684211
8fa9b605371c3f37f74e1370b2faa65d53c201b2
191
// // Note.swift // MyNotesList // // Created by Francis Low on 10/3/21. // import Foundation struct Note: Identifiable { var id: String var title: String var desc: String }
12.733333
38
0.638743
c15b4aeba277eb4db74eef882a9ccf055387a48b
4,751
import Foundation import TSCBasic import TuistCore import TuistCoreTesting import TuistGraph import TuistGraphTesting import TuistSupport import XcodeProj import XCTest @testable import TuistGenerator @testable import TuistSupportTesting final class WorkspaceDescriptorGeneratorTests: TuistUnitTestCase { var subject: WorkspaceDescriptorGenerator! override func setUp() { super.setUp() system.swiftVersionStub = { "5.2" } subject = WorkspaceDescriptorGenerator(config: .init(projectGenerationContext: .serial)) } override func tearDown() { subject = nil super.tearDown() } // MARK: - Tests func test_generate_workspaceStructure() throws { // Given let temporaryPath = try self.temporaryPath() try createFiles([ "README.md", "Documentation/README.md", "Website/index.html", "Website/about.html", ]) let additionalFiles: [FileElement] = [ .file(path: temporaryPath.appending(RelativePath("README.md"))), .file(path: temporaryPath.appending(RelativePath("Documentation/README.md"))), .folderReference(path: temporaryPath.appending(RelativePath("Website"))), ] let workspace = Workspace.test( xcWorkspacePath: temporaryPath.appending(component: "Test.xcworkspace"), additionalFiles: additionalFiles ) let graph = Graph.test(entryPath: temporaryPath, workspace: workspace) // When let valueGraph = ValueGraph(graph: graph) let graphTraverser = ValueGraphTraverser(graph: valueGraph) let result = try subject.generate(graphTraverser: graphTraverser) // Then let xcworkspace = result.xcworkspace XCTAssertEqual(xcworkspace.data.children, [ .group(.init(location: .group("Documentation"), name: "Documentation", children: [ .file(.init(location: .group("README.md"))), ])), .file(.init(location: .group("README.md"))), .file(.init(location: .group("Website"))), ]) } func test_generate_workspaceStructure_noWorkspaceData() throws { // Given let name = "test" let temporaryPath = try self.temporaryPath() try FileHandler.shared.createFolder(temporaryPath.appending(component: "\(name).xcworkspace")) let workspace = Workspace.test(name: name) let graph = Graph.test(entryPath: temporaryPath, workspace: workspace) let valueGraph = ValueGraph(graph: graph) let graphTraverser = ValueGraphTraverser(graph: valueGraph) // When XCTAssertNoThrow( try subject.generate(graphTraverser: graphTraverser) ) } func test_generate_workspaceStructureWithProjects() throws { // Given let temporaryPath = try self.temporaryPath() let target = anyTarget() let project = Project.test(path: temporaryPath, sourceRootPath: temporaryPath, xcodeProjPath: temporaryPath.appending(component: "Test.xcodeproj"), name: "Test", settings: .default, targets: [target]) let workspace = Workspace.test( xcWorkspacePath: temporaryPath.appending(component: "Test.xcworkspace"), projects: [project.path] ) let graph = Graph.create(project: project, dependencies: [(target, [])]) let valueGraph = ValueGraph(graph: graph.with(workspace: workspace)) let graphTraverser = ValueGraphTraverser(graph: valueGraph) // When let result = try subject.generate(graphTraverser: graphTraverser) // Then let xcworkspace = result.xcworkspace XCTAssertEqual(xcworkspace.data.children, [ .file(.init(location: .group("Test.xcodeproj"))), ]) } // MARK: - Helpers func anyTarget(dependencies: [Dependency] = []) -> Target { Target.test(infoPlist: nil, entitlements: nil, settings: nil, dependencies: dependencies) } } extension XCWorkspaceDataElement: CustomDebugStringConvertible { public var debugDescription: String { switch self { case let .file(file): return file.location.path case let .group(group): return group.debugDescription } } } extension XCWorkspaceDataGroup: CustomDebugStringConvertible { public var debugDescription: String { children.debugDescription } }
34.179856
103
0.61566
e8a61c90be231ca20b3e93b879a0da095b4d1959
567
// // Other.swift // Tiv Bible // // Created by Isaac Iniongun on 20/05/2020. // Copyright © 2020 Iniongun Group. All rights reserved. // import Foundation @objcMembers class Other: Base { dynamic var title = "" dynamic var subTitle = "" dynamic var text = "" var shareableContent: String { "\(title)\n\n\(subTitle)\n\n\(text)" } convenience required init(title: String, subTitle: String, text: String) { self.init() self.title = title self.subTitle = subTitle self.text = text } }
20.25
78
0.597884
3ad39c99d2667a6a06dd8eaedc09ecfe960fbb54
4,166
//===----------------------------------------------------------------------===// // // 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-codegenerator. // DO NOT EDIT. #if compiler(>=5.5) && canImport(_Concurrency) import SotoCore // MARK: Paginators @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *) extension Honeycode { /// The ListTableColumns API allows you to retrieve a list of all the columns in a table in a workbook. /// Return PaginatorSequence for operation. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on public func listTableColumnsPaginator( _ input: ListTableColumnsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil ) -> AWSClient.PaginatorSequence<ListTableColumnsRequest, ListTableColumnsResult> { return .init( input: input, command: listTableColumns, inputKey: \ListTableColumnsRequest.nextToken, outputKey: \ListTableColumnsResult.nextToken, logger: logger, on: eventLoop ) } /// The ListTableRows API allows you to retrieve a list of all the rows in a table in a workbook. /// Return PaginatorSequence for operation. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on public func listTableRowsPaginator( _ input: ListTableRowsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil ) -> AWSClient.PaginatorSequence<ListTableRowsRequest, ListTableRowsResult> { return .init( input: input, command: listTableRows, inputKey: \ListTableRowsRequest.nextToken, outputKey: \ListTableRowsResult.nextToken, logger: logger, on: eventLoop ) } /// The ListTables API allows you to retrieve a list of all the tables in a workbook. /// Return PaginatorSequence for operation. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on public func listTablesPaginator( _ input: ListTablesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil ) -> AWSClient.PaginatorSequence<ListTablesRequest, ListTablesResult> { return .init( input: input, command: listTables, inputKey: \ListTablesRequest.nextToken, outputKey: \ListTablesResult.nextToken, logger: logger, on: eventLoop ) } /// The QueryTableRows API allows you to use a filter formula to query for specific rows in a table. /// Return PaginatorSequence for operation. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on public func queryTableRowsPaginator( _ input: QueryTableRowsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil ) -> AWSClient.PaginatorSequence<QueryTableRowsRequest, QueryTableRowsResult> { return .init( input: input, command: queryTableRows, inputKey: \QueryTableRowsRequest.nextToken, outputKey: \QueryTableRowsResult.nextToken, logger: logger, on: eventLoop ) } } #endif // compiler(>=5.5) && canImport(_Concurrency)
35.913793
109
0.614978
56370693af1d3f7c42355e90ea95c4dc501edd79
1,560
// // MarketTableViewCell.swift // Cryptomarket // // Created by Alex on 05.01.18. // Copyright © 2018 Alexander Dobrynin. All rights reserved. // import UIKit import CryptomarketKit // TODO this might be an indicator for bad design class MarketTableViewCell: UITableViewCell { static let Identifier = "MarketTableViewCell" @IBOutlet private weak var marketImageView: UIImageView! @IBOutlet private weak var marketLabel: UILabel! @IBOutlet private weak var countLabel: UILabel! func configure(withImageUrl url: URL?, text: String, count: Int? = nil) { marketLabel?.text = text countLabel.text = count.map(String.init) if let url = url { fetchImage(url) } } private var dedicatedUrl: URL? private func fetchImage(_ url: URL) { dedicatedUrl = url ImageLoader.shared.imageBy(url: url) { [weak self] (img, reqUrl) in guard let strongSelf = self else { return } guard reqUrl == strongSelf.dedicatedUrl else { return } strongSelf.marketImageView.image = img strongSelf.marketImageView.alpha = 0.0 UIView.animate(withDuration: 0.3, animations: { strongSelf.marketImageView.alpha = 1.0 }) } } override func prepareForReuse() { super.prepareForReuse() marketImageView.image = nil marketLabel.text = nil countLabel.text = nil dedicatedUrl = nil } }
27.857143
77
0.609615
1404412a7309f977b75e9639afcce8a29cfde9d3
499
// // CollectionPrettyCell.swift // DYZB // // Created by 1 on 16/9/18. // Copyright © 2016年 superBee. All rights reserved. // import UIKit import Kingfisher class CollectionPrettyCell: CollectionBaseCell { //mark - 控件属性 @IBOutlet weak var cityBtn: UIButton! //mark - 定义模型属性 override var anchor : AnchorModel? { didSet{ super.anchor = anchor // 3、所在城市 cityBtn.setTitle(anchor?.anchor_city, forState: .Normal) } } }
19.192308
68
0.611222
72a2417d563b47cb3d88e6e7d1ea825d8845f89d
2,881
// // JSONSerialization+Dekoter.swift // Dekoter // // Created by Artem Stepanenko on 14/04/17. // Copyright (c) 2016 Artem Stepanenko <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /// An `JSONSerialization` extension to deserialize objects which implement the `Koting` protocol from JSON. extension JSONSerialization { /// Creates an object which implements the `Koting` protocol from JSON data. /// /// - Parameters: /// - data: JSON data. /// - opt: Options. /// - Returns: A deserialized object. class func de_jsonObject<T: Dekoting>(with data: Data, options opt: JSONSerialization.ReadingOptions = []) -> T? { guard let object = try? jsonObject(with: data, options: opt), let dict = object as? [AnyHashable: Any] else { return nil } return de_serializedObject(from: dict) } /// Creates an array of objects which implement the `Koting` protocol from JSON data. /// /// - Parameters: /// - data: JSON data. /// - opt: Options. /// - Returns: A deserialized array. class func de_jsonObject<T: Dekoting>(with data: Data, options opt: JSONSerialization.ReadingOptions = []) -> [T]? { guard let object = try? jsonObject(with: data, options: opt), let dicts = object as? [[AnyHashable: Any]] else { return nil } return dicts.flatMap { de_serializedObject(from: $0) } } } // MARK: - Private fileprivate extension JSONSerialization { class func de_serializedObject<T: Dekoting>(from dict: [AnyHashable: Any]) -> T? { let koter = Koter(objects: dict) guard let object = T(koter: koter) else { return nil } return object } }
38.932432
120
0.665741
1cb83826b6c266847b3c17fd2f39784babcb1e70
1,150
// RUN: %target-swift-frontend -typecheck %s -I %S/Inputs -enable-source-import -parse-as-library -verify // Name lookup is global in a library. var x : x_ty = 4 typealias x_ty = Int // Name lookup is global in a library. // This case requires doing semantic analysis (conversion checking) after // parsing. var y : y_ty = 4 typealias y_ty = (Int) // Verify that never-defined types are caught. var z : z_ty = 42 // expected-error {{use of undeclared type 'z_ty'}} // Make sure we type-check all declarations before any initializers var a : Int = b var b : Int = 1 var c = 1 var d = 2 var e = 3 // Name-binding with imports import imported_module func over1(_ x: UInt64) {} // expected-note{{found this candidate}} func over2(_ x: UInt32) {} func over3(_ x: UInt32) {} typealias over4 = UInt32 func testover() { // FIXME: Very weird diagnostic here. over1(0) // expected-error{{ambiguous use of 'over1'}} over2(0) over3(0) // FIXME: Should we produce an ambiguity error here? var x : over4 = 10 } // Referring to name within a module. var d2 : Swift.Int = 5 var y2 : library.y_ty = 5 func increment_y2() { y2 = library.y2 + 1 }
25
105
0.687826
bb236862a3a8ea7a512b13ab480a80ac89a96bbd
10,914
// // HippoActionMessage.swift // Fugu // // Created by Vishal on 04/02/19. // Copyright © 2019 Socomo Technologies Private Limited. All rights reserved. // import Foundation class HippoActionMessage: HippoMessage { var selectedBtnId: String = "" var isUserInteractionEnbled: Bool = false var buttons: [HippoActionButton]? var responseMessage: HippoMessage? var repliedBy: String? var repliedById: Int? override init?(dict: [String : Any]) { super.init(dict: dict) isActive = Bool.parse(key: "is_active", json: dict) selectedBtnId = dict["selected_btn_id"] as? String ?? "" repliedBy = dict["replied_by"] as? String repliedById = Int.parse(values: dict, key: "replied_by_id") if let content_value = dict["content_value"] as? [[String: Any]] { self.contentValues = content_value let selectedId = selectedBtnId.isEmpty ? nil : selectedBtnId let (buttons, selectedButton) = HippoActionButton.getArray(array: contentValues, selectedId: selectedId) if type == .dateTime || type == .address { tryToSetResponseMessage() }else if type == .botAttachment { tryToSetResponseMessageForAttachment() }else { tryToSetResponseMessage(selectedButton: selectedButton) } self.buttons = buttons } setHeight() isUserInteractionEnbled = isActive } func tryToSetResponseMessageForAttachment() { if let dic = self.contentValues.first { responseMessage = HippoMessage(message: "", type: .normal, senderName: repliedBy, senderId: repliedById, chatType: chatType) if let rawFileType = dic["file_type"] as? String { responseMessage?.documentType = FileType(mimeType: rawFileType) } responseMessage?.thumbnailUrl = dic["thumbnail_url"] as? String responseMessage?.fileUrl = dic["url"] as? String ?? dic["attachment_url"] as? String responseMessage?.fileName = dic["file_name"] as? String responseMessage?.imageUrl = dic["attachment_url"] as? String if responseMessage?.documentType == .document || responseMessage?.documentType == .video { responseMessage?.type = .attachment }else { responseMessage?.type = .imageFile } responseMessage?.userType = .customer responseMessage?.creationDateTime = self.creationDateTime responseMessage?.status = status cellDetail?.actionHeight = nil } } func tryToSetResponseMessage(selectedButton: HippoActionButton?) { guard let parsedSelectedButton = selectedButton else { return } responseMessage = HippoMessage(message: parsedSelectedButton.title, type: .normal, senderName: repliedBy, senderId: repliedById, chatType: chatType) responseMessage?.userType = .customer responseMessage?.creationDateTime = self.creationDateTime responseMessage?.status = status cellDetail?.actionHeight = nil } func tryToSetResponseMessage() { if let dic = self.contentValues.first { if type == .dateTime { responseMessage = HippoMessage(message: dic["date_time_message"] as? String ?? "", type: .normal, senderName: repliedBy, senderId: repliedById, chatType: chatType) }else { responseMessage = HippoMessage(message: dic["address"] as? String ?? "", type: .normal, senderName: repliedBy, senderId: repliedById, chatType: chatType) } responseMessage?.userType = .customer responseMessage?.creationDateTime = self.creationDateTime responseMessage?.status = status cellDetail?.actionHeight = nil } } func setHeight() { cellDetail = HippoCellDetail() cellDetail?.headerHeight = attributtedMessage.messageHeight + attributtedMessage.nameHeight + attributtedMessage.timeHeight cellDetail?.showSenderName = false if let attributtedMessage = responseMessage?.attributtedMessage { if responseMessage?.type == .imageFile { cellDetail?.responseHeight = 250 }else if responseMessage?.type == .attachment { switch responseMessage?.concreteFileType { case .video: cellDetail?.responseHeight = 234 default: cellDetail?.responseHeight = 80 } }else { let nameHeight: CGFloat = HippoConfig.shared.appUserType == .agent ? attributtedMessage.nameHeight : 0 cellDetail?.responseHeight = attributtedMessage.messageHeight + attributtedMessage.timeHeight + nameHeight + 10 } cellDetail?.actionHeight = nil } else { let buttonHeight = buttonsHeight() //(buttons?.count ?? 0) * 50 cellDetail?.actionHeight = CGFloat(buttonHeight) + 15 + 10 + 10 //Button Height + (timeLabelHeight + time gap from top) + padding } cellDetail?.padding = 1 } func buttonsHeight() -> CGFloat { guard let buttons = buttons, !buttons.isEmpty else { return 0 } let maxWidth = windowScreenWidth - 27 var buttonCount: Int = 0 var remaningWidth: CGFloat = maxWidth for each in buttons { let w: CGFloat = findButtonWidth(each.title) + 40 let widthRemaningAfterInsertion = remaningWidth - w - 5 if remaningWidth == maxWidth { buttonCount += 1 remaningWidth = widthRemaningAfterInsertion } else if widthRemaningAfterInsertion <= -5 { buttonCount += 1 remaningWidth = maxWidth - w - 5 } else { remaningWidth = widthRemaningAfterInsertion } // let message = "===\(each.title)--w=\(w)--widthRemaningAfterInsertion=\(widthRemaningAfterInsertion)--b=\(buttonCount)--remaning=\(remaningWidth) \n" // HippoConfig.shared.log.debug(message, level: .custom) } return CGFloat(buttonCount * 35) + CGFloat(5 * (buttonCount - 1)) } private func findButtonWidth(_ text: String) -> CGFloat { let attributedText = NSMutableAttributedString(string: text) let range = (text as NSString).range(of: text) attributedText.addAttribute(.font, value: HippoConfig.shared.theme.incomingMsgFont, range: range) let boxSize: CGSize = CGSize(width: windowScreenWidth - 30, height: CGFloat.greatestFiniteMagnitude) return sizeOf(attributedString: attributedText, availableBoxSize: boxSize).width } private func sizeOf(attributedString: NSMutableAttributedString, availableBoxSize: CGSize) -> CGSize { return attributedString.boundingRect(with: availableBoxSize, options: .usesLineFragmentOrigin, context: nil).size } override func getJsonToSendToFaye() -> [String : Any] { var json = super.getJsonToSendToFaye() if type != .dateTime && type != .address && type != .botAttachment{ json["selected_btn_id"] = selectedBtnId json["is_active"] = isActive.intValue() } json["content_value"] = contentValues json["user_id"] = currentUserId() json["replied_by"] = currentUserName() json["replied_by_id"] = currentUserId() return json } func selectBtnWith(btnId: String) { selectedBtnId = btnId isActive = false isUserInteractionEnbled = false repliedById = currentUserId() repliedBy = currentUserName() let selectedId = selectedBtnId.isEmpty ? nil : selectedBtnId if type == .dateTime || type == .address { tryToSetResponseMessage() } else if type == .botAttachment { tryToSetResponseMessageForAttachment() }else{ if !contentValues.isEmpty { contentValues.append(contentsOf: customButtons) let list = contentValues let (buttons, selectedButton) = HippoActionButton.getArray(array: list, selectedId: selectedId) self.tryToSetResponseMessage(selectedButton: selectedButton) self.buttons = buttons } } setHeight() } func updateObject(with newObject: HippoActionMessage) { super.updateObject(with: newObject) self.selectedBtnId = newObject.selectedBtnId self.isActive = newObject.isActive self.isUserInteractionEnbled = newObject.isUserInteractionEnbled self.repliedById = newObject.repliedById self.repliedBy = newObject.repliedBy let selectedId = selectedBtnId.isEmpty ? nil : selectedBtnId if type == .dateTime || type == .address { tryToSetResponseMessage() }else if type == .botAttachment { tryToSetResponseMessageForAttachment() }else { if !contentValues.isEmpty { let (buttons, selectedButton) = HippoActionButton.getArray(array: contentValues, selectedId: selectedId) self.tryToSetResponseMessage(selectedButton: selectedButton) self.buttons = buttons } } setHeight() self.status = .sent messageRefresed?() } func getButtonWithId(id: String) -> HippoActionButton? { guard let buttons = self.buttons else { return nil } let button = buttons.first { (b) -> Bool in return b.id == id } return button } } let customButtons: [[String: Any]] = [ [ "btn_id": "451", "btn_color": "#FFFFFF", "btn_title": "Agent List", "btn_title_color": "#000000", "btn_selected_color": "#1E7EFF", "action": "AGENTS", "btn_title_selected_color": "#FFFFFF" ], [ "btn_id": "454", "btn_color": "#FFFFFF", "btn_title": "audio call", "btn_title_color": "#000000", "btn_selected_color": "#1E7EFF", "action": "AUDIO_CALL", "btn_title_selected_color": "#FFFFFF" ], [ "btn_id": "455", "btn_color": "#FFFFFF", "btn_title": "video call", "btn_title_color": "#000000", "btn_selected_color": "#1E7EFF", "action": "VIDEO_CALL", "btn_title_selected_color": "#FFFFFF" ], [ "btn_id": "455", "btn_color": "#FFFFFF", "btn_title": "Continue chat", "btn_title_color": "#000000", "btn_selected_color": "#1E7EFF", "action": "CONTINUE_CHAT", "btn_title_selected_color": "#FFFFFF" ] ]
38.978571
179
0.608118
0ac5b0a9eaa033e8ab4f75becfab22e373e37e51
18,769
// // Staff.swift // MusicNotationCore // // Created by Kyle Sherman on 6/15/15. // Copyright © 2015 Kyle Sherman. All rights reserved. // public struct Staff: RandomAccessCollection { // MARK: - Collection Conformance public typealias Index = Int public var startIndex: Int { notesHolders.startIndex } public var endIndex: Int { notesHolders.endIndex } public subscript(position: Index) -> Iterator.Element { notesHolders[position] } public func index(after i: Int) -> Int { notesHolders.index(after: i) } public func index(before i: Int) -> Int { notesHolders.index(before: i) } public typealias Iterator = IndexingIterator<[NotesHolder]> public func makeIterator() -> Iterator { notesHolders.makeIterator() } // MARK: - Main Properties public let clef: Clef public let instrument: Instrument public private(set) var measureCount: Int = 0 internal private(set) var notesHolders: [NotesHolder] = [] { didSet { recomputeMeasureIndexes() } } private var measureIndexes: [(notesHolderIndex: Int, repeatMeasureIndex: Int?)] = [] public init(clef: Clef, instrument: Instrument) { self.clef = clef self.instrument = instrument } public mutating func appendMeasure(_ measure: Measure) { let measureBefore = try? self.measure(at: lastIndex) let clefChange = measureBefore?.lastClef ?? clef var measure = measure _ = measure.changeFirstClefIfNeeded(to: clefChange) notesHolders.append(measure) measureCount += measure.measureCount } public mutating func appendRepeat(_ measureRepeat: MeasureRepeat) { var measureRepeat = measureRepeat let measureBefore = try? measure(at: lastIndex) for index in measureRepeat.measures.indices { _ = measureRepeat.measures[index].changeFirstClefIfNeeded(to: measureBefore?.lastClef ?? clef) } notesHolders.append(measureRepeat) measureCount += measureRepeat.measureCount } /// /// Changes the Clef at the given location. /// /// - parameter clef: The new `Clef` to change to /// - parameter measureIndex: The index of the measure to change the clef /// - parameter noteIndex: The index of the note at which you want the clef to change /// - parameter setIndex: The index of the note set in which the note resides where you want to change the clef /// - throws: /// - `StaffError.measureIndexOutOfRange` /// - `StaffError.repeatedMeasureCannotBeModified` if the measure is a repeated measure. /// - `StaffError.internalError` if the function has an internal implementation error. /// public mutating func changeClef(_ clef: Clef, in measureIndex: Int, atNote noteIndex: Int, inSet setIndex: Int = 0) throws { guard var measure = try measure(at: measureIndex) as? Measure else { throw StaffError.repeatedMeasureCannotBeModified } try measure.changeClef(clef, at: noteIndex, inSet: setIndex) try replaceMeasure(at: measureIndex, with: measure) // If there is already another clef specified after the new clef, then // there is no need to propagate to the following measures. guard !measure.hasClefAfterNote(at: noteIndex, inSet: setIndex) else { return } try propagateClefChange(clef, fromMeasureIndex: measureIndex) } /// /// Inserts a measure at the given index. /// /// If the given index falls on a `MeasureRepeat`, there are 3 things that can happen: /// /// 1. If the index is the beginning of a repeat, see the `beforeRepeat` parameter. /// 2. If the index is within the original measure(s) to be repeated, the `newMeasure` /// will be inserted into the repeat. The new measure is therefore repeated /// `MeasureRepeat.repeatCount` times. /// 3. If the index is within the repeated portion, the insert will fail, because /// the repeated measures are immutable. See `MeasureRepeat`. /// /// - parameter measure: The measure to be inserted. /// - parameter index: The index where the measure should be inserted. /// - parameter beforeRepeat: Default value is true. This parameter is only used if the given index is /// the beginning of a repeat. True if you want the measure to be inserted before the repeat. False /// when you want the measure to be inserted into the repeat at the given index. /// - throws: /// - `StaffError.measureIndexOutOfRange` /// - `StaffError.noRepeatToInsertInto` /// - `StaffError.hasToInsertIntoRepeatIfIndexIsNotFirstMeasureOfRepeat` /// - `StaffError.internalError` /// - `MeasureRepeatError.indexOutOfRange` /// - `MeasureRepeatError.cannotModifyRepeatedMeasures` /// public mutating func insertMeasure(_ measure: Measure, at index: Int, beforeRepeat: Bool = true) throws { var measure = measure let measureBefore = try? self.measure(at: index - 1) let clefChange = measureBefore?.lastClef ?? clef let didChangeClef = measure.changeFirstClefIfNeeded(to: clefChange) // Need to propagate lastClef if there are clef changes already in the measure if let newClef = measure.lastClef, !didChangeClef { try propagateClefChange(newClef, fromMeasureIndex: index) } let notesHolderIndex = try notesHolderIndexFromMeasureIndex(index) // Not a repeat, just insert if notesHolderIndex.repeatMeasureIndex == nil { notesHolders.insert(measure, at: notesHolderIndex.notesHolderIndex) measureCount += measure.measureCount } else { if beforeRepeat, notesHolderIndex.repeatMeasureIndex == 0 { notesHolders.insert(measure, at: notesHolderIndex.notesHolderIndex) measureCount += measure.measureCount return } // Is a repeat, so insert if it is one of the measures to be repeated guard var measureRepeat = notesHolders[notesHolderIndex.notesHolderIndex] as? MeasureRepeat, let repeatMeasureIndex = notesHolderIndex.repeatMeasureIndex else { assertionFailure("Index translation showed should be a repeat, but it's not") throw StaffError.internalError } try measureRepeat.insertMeasure(measure, at: repeatMeasureIndex) notesHolders[notesHolderIndex.notesHolderIndex] = measureRepeat } } /// /// Inserts a `MeasureRepeat` at the given index. If there is already a repeat at the given index, /// this will fail. /// /// - parameter measureRepeat: The repeat to insert. /// - parameter index: The index where the repeat should be inserted. /// - throws: /// - `StaffError.measureIndexOutOfRange` /// - `StaffError.cannotInsertRepeatWhereOneAlreadyExists` /// public mutating func insertRepeat(_ measureRepeat: MeasureRepeat, at index: Int) throws { var measureRepeat = measureRepeat let measureBefore = try? measure(at: index - 1) var didChangeClef: Bool = true for index in measureRepeat.measures.indices { didChangeClef = measureRepeat.measures[index].changeFirstClefIfNeeded(to: measureBefore?.lastClef ?? clef) } if let newClef = measureRepeat.measures.last?.lastClef, !didChangeClef { try propagateClefChange(newClef, fromMeasureIndex: index + measureRepeat.measureCount) } let notesHolderIndex = try notesHolderIndexFromMeasureIndex(index) guard notesHolderIndex.repeatMeasureIndex == nil || notesHolderIndex.repeatMeasureIndex == 0 else { throw StaffError.cannotInsertRepeatWhereOneAlreadyExists } notesHolders.insert(measureRepeat, at: notesHolderIndex.notesHolderIndex) measureCount += measureRepeat.measureCount } /// /// Replaces the measure at the given index with a new measure. The measure index takes into consideration /// repeats. Therefore, the index is the actual index of the measure as it were played. /// /// - parameter measureIndex: The index of the measure to replace. /// - parameter newMeasure: The new measure to replace the old one. /// - throws: /// - `StaffError.repeatedMeasureCannotBeModified` if the measure is a repeated measure. /// - `StaffError.internalError` if index translation doesn't work properly. /// public mutating func replaceMeasure(at measureIndex: Int, with newMeasure: Measure) throws { try replaceMeasure(at: measureIndex, with: newMeasure, shouldChangeClef: true) } /// /// Ties a note to the next note. /// /// - parameter noteIndex: The index of the note in the specified measure to begin the tie. /// - parameter measureIndex: The index of the measure that contains the note at which the tie should begin. /// - parameter setIndex: The index of the set of notes you want to modify. There can be multiple sets of notes /// that make up a full measure on their own. i.e. bass drum notes and hi-hat notes. See `Measure` for more info. /// - throws: /// - `StaffError.noteIndexoutOfRange` /// - `StaffError.noNextNoteToTie` if the note specified is the last note in the staff. /// - `StaffError.measureIndexOutOfRange` /// - `StaffError.repeatedMeasureCannotHaveTie` if the index for the measure specified refers to a measure that is /// a repeat of another measure. /// - `StaffError.internalError`, `MeasureError.internalError` if the function has an internal implementation error. /// - `MeasureError.noteIndexOutOfRange` /// public mutating func startTieFromNote(at noteIndex: Int, inMeasureAt measureIndex: Int, inSet setIndex: Int = 0) throws { try modifyTieForNote(at: noteIndex, inMeasureAt: measureIndex, removeTie: false, inSet: setIndex) } /// /// Removes the tie beginning at the note at the specified index. /// /// - parameter noteIndex: The index of the note in the specified measure where the tie begins. /// - parameter measureIndex: The index of the measure that contains the note at which the tie begins. /// - parameter setIndex: The index of the set of notes you want to modify. There can be multiple sets of notes /// that make up a full measure on their own. i.e. bass drum notes and hi-hat notes. See `Measure` for more info. /// - throws: /// - `StaffError.noteIndexoutOfRange` /// - `StaffError.noNextNoteToTie` if the note specified is the last note in the staff. /// - `StaffError.measureIndexOutOfRange` /// - `StaffError.repeatedMeasureCannotHaveTie` if the index for the measure specified refers to a measure that is /// a repeat of another measure. /// - `MeasureError.noteIndexOutOfRange` /// - `StaffError.internalError`, `MeasureError.internalError` if the function has an internal implementation error. /// public mutating func removeTieFromNote(at noteIndex: Int, inMeasureAt measureIndex: Int, inSet setIndex: Int = 0) throws { try modifyTieForNote(at: noteIndex, inMeasureAt: measureIndex, removeTie: true, inSet: setIndex) } /// /// - parameter measureIndex: The index of the measure to return. /// - returns An `ImmutableMeasure` at the given index within the staff. /// - throws: /// - `StaffError.measureIndexOutOfRange` /// - `StaffError.internalError` if the function has an internal implementation error. /// public func measure(at measureIndex: Int) throws -> ImmutableMeasure { let (notesHolderIndex, repeatMeasureIndex) = try notesHolderIndexFromMeasureIndex(measureIndex) if let measureRepeat = notesHolders[notesHolderIndex] as? MeasureRepeat, let repeatMeasureIndex = repeatMeasureIndex { return measureRepeat.expand()[repeatMeasureIndex] } else if let measure = notesHolders[notesHolderIndex] as? ImmutableMeasure { return measure } throw StaffError.internalError } /// /// - parameters measureIndex: The index of a measure that is either repeated or is one of the repeated measures. /// - returns A `MeasureRepeat` that contains the measure(s) that are repeated as well as the repeat count. Returns nil /// if the measure at the specified index is not part of repeat. /// - throws: /// - `StaffError.measureIndexOutOfRange` /// - `StaffError.internalError` if the function has an internal implementation error. /// public func measureRepeat(at measureIndex: Int) throws -> MeasureRepeat? { let (notesHolderIndex, _) = try notesHolderIndexFromMeasureIndex(measureIndex) return notesHolders[notesHolderIndex] as? MeasureRepeat } internal func notesHolderAtMeasureIndex(_ measureIndex: Int) throws -> NotesHolder { let (notesHolderIndex, _) = try notesHolderIndexFromMeasureIndex(measureIndex) return notesHolders[notesHolderIndex] } private mutating func modifyTieForNote(at noteIndex: Int, inMeasureAt measureIndex: Int, removeTie: Bool, inSet setIndex: Int) throws { let notesHolderIndex = try notesHolderIndexFromMeasureIndex(measureIndex) // Ensure first measure information provided is valid for tie var firstMeasure = try mutableMeasureFromNotesHolderIndex(notesHolderIndex.notesHolderIndex, repeatMeasureIndex: notesHolderIndex.repeatMeasureIndex) guard noteIndex < firstMeasure.noteCount[setIndex] else { throw StaffError.noteIndexOutOfRange } if noteIndex == firstMeasure.noteCount[setIndex] - 1 { let secondNotesHolderIndex: (notesHolderIndex: Int, repeatMeasureIndex: Int?) do { secondNotesHolderIndex = try notesHolderIndexFromMeasureIndex(measureIndex + 1) } catch { throw StaffError.noNextNoteToTie } var secondMeasure = try mutableMeasureFromNotesHolderIndex( secondNotesHolderIndex.notesHolderIndex, repeatMeasureIndex: secondNotesHolderIndex.repeatMeasureIndex ) guard secondMeasure.noteCount[setIndex] > 0 else { throw StaffError.noNextNoteToTie } if !removeTie { let firstNote = try firstMeasure.note(at: noteIndex, inSet: setIndex) let secondNote = try secondMeasure.note(at: 0, inSet: setIndex) if firstNote.pitches != secondNote.pitches { throw StaffError.notesMustHaveSamePitchesToTie } } // Modify tie and update second Measure. The first Measure update is done later. try firstMeasure.modifyTie(at: noteIndex, requestedTieState: removeTie ? nil : .begin, inSet: setIndex) try secondMeasure.modifyTie(at: 0, requestedTieState: removeTie ? nil : .end, inSet: setIndex) try replaceMeasure(at: measureIndex + 1, with: secondMeasure) } else { if removeTie { try firstMeasure.removeTie(at: noteIndex, inSet: setIndex) } else { try firstMeasure.startTie(at: noteIndex, inSet: setIndex) } } try replaceMeasure(at: measureIndex, with: firstMeasure) } internal func notesHolderIndexFromMeasureIndex(_ index: Int) throws -> (notesHolderIndex: Int, repeatMeasureIndex: Int?) { guard index >= 0, index < measureCount else { throw StaffError.measureIndexOutOfRange } return measureIndexes[index] } internal mutating func replaceMeasure(at measureIndex: Index, with newMeasure: Measure, shouldChangeClef: Bool) throws { var newMeasure = newMeasure let oldMeasure = try? measure(at: measureIndex) if shouldChangeClef { let didChangeClef = newMeasure.changeFirstClefIfNeeded(to: oldMeasure?.originalClef ?? clef) if let newClef = newMeasure.lastClef, !didChangeClef { try propagateClefChange(newClef, fromMeasureIndex: measureIndex) } } let (notesHolderIndex, repeatMeasureIndex) = try notesHolderIndexFromMeasureIndex(measureIndex) let newNotesHolder: NotesHolder if let repeatMeasureIndex = repeatMeasureIndex { guard (try? mutableMeasureFromNotesHolderIndex(notesHolderIndex, repeatMeasureIndex: repeatMeasureIndex)) != nil else { throw StaffError.repeatedMeasureCannotBeModified } guard var measureRepeat = notesHolders[notesHolderIndex] as? MeasureRepeat else { assertionFailure("Index translation showed should be a repeat, but it's not") throw StaffError.internalError } measureRepeat.measures[repeatMeasureIndex] = newMeasure newNotesHolder = measureRepeat } else { newNotesHolder = newMeasure } notesHolders[notesHolderIndex] = newNotesHolder } private mutating func recomputeMeasureIndexes() { measureIndexes = [] for (i, notesHolder) in notesHolders.enumerated() { switch notesHolder { case is Measure: measureIndexes.append((notesHolderIndex: i, repeatMeasureIndex: nil)) case let measureRepeat as MeasureRepeat: for j in 0 ..< measureRepeat.measureCount { measureIndexes.append((notesHolderIndex: i, repeatMeasureIndex: j)) } default: assertionFailure("NotesHolders should only be Measure or MeasureRepeat") continue } } } private func mutableMeasureFromNotesHolderIndex(_ notesHolderIndex: Int, repeatMeasureIndex: Int?) throws -> Measure { let notesHolder = notesHolders[notesHolderIndex] // Ensure first measure information provided is valid for tie if let repeatMeasureIndex = repeatMeasureIndex { // If repeatMeasureIndex is not nil, check if measure is not a repeated one // If it's not, check if noteIndex is less than count of measure guard let measureRepeat = notesHolder as? MeasureRepeat else { assertionFailure("Index translation showed should be a repeat, but it's not") throw StaffError.internalError } guard let mutableMeasure = measureRepeat.expand()[repeatMeasureIndex] as? Measure else { throw StaffError.repeatedMeasureCannotHaveTie } return mutableMeasure } else { // If repeatMeasureIndex is nil, check if the noteIndex is less than note count of measure assert(notesHolder.measureCount == 1, "Index translation showed should be a single measure, but it's not") guard let immutableMeasure = notesHolder as? ImmutableMeasure else { throw StaffError.internalError } if let mutableMeasure = immutableMeasure as? Measure { return mutableMeasure } else { assertionFailure("If not a repeated measure, should be a mutable measure") throw StaffError.internalError } } } private mutating func propagateClefChange(_ clef: Clef, fromMeasureIndex measureIndex: Int) throws { // Modify every `originalClef` and `lastClef` that follows the measure until not needed for index in (measureIndex + 1) ..< measureCount { do { guard var measure = try self.measure(at: index) as? Measure else { continue } let didChangeClef = measure.changeFirstClefIfNeeded(to: clef) if !didChangeClef { break } try replaceMeasure(at: index, with: measure, shouldChangeClef: false) } catch { continue } } } } public enum StaffError: Error { case noteIndexOutOfRange case measureIndexOutOfRange case noNextNoteToTie case noNextNote case notBeginningOfTie case repeatedMeasureCannotHaveTie case notesMustHaveSamePitchesToTie case measureNotPartOfRepeat case repeatedMeasureCannotBeModified case cannotInsertRepeatWhereOneAlreadyExists case noRepeatToInsertInto case hasToInsertIntoRepeatIfIndexIsNotFirstMeasureOfRepeat case internalError } extension Staff: CustomDebugStringConvertible { public var debugDescription: String { let notesDescription = notesHolders.map { $0.debugDescription }.joined(separator: ", ") return "staff(\(clef) \(instrument) \(notesDescription))" } }
42.367946
151
0.747296
03159761f08f7b89b04d28cf0a0bb131dd05302b
793
// // StatusBarStyleModifier.swift // SwiftUI-WeChat // // Created by Gesen on 2019/12/29. // Copyright © 2019 Gesen. All rights reserved. // import SwiftUI extension View { /// 控制状态栏样式 func statusBar(style: UIStatusBarStyle) -> ModifiedContent<Self, StatusBarStyleModifier> { modifier(StatusBarStyleModifier(style: style)) } } struct StatusBarStyleModifier: ViewModifier { let style: UIStatusBarStyle func body(content: Content) -> some View { if self.style != self.appState.preferredStatusBarStyle { self.appState.preferredStatusBarStyle = self.style } return content .onDisappear { self.appState.preferredStatusBarStyle = .default } } @EnvironmentObject var appState: AppState }
24.030303
94
0.672131
ef05692102ffa95ae83832129e0d6852d08bab69
3,861
// // SourceShader.swift // Pods // // Created by Reza Ali on 2/10/22. // import Foundation import Metal open class SourceShader: Shader { public var pipelineURL: URL { didSet { if oldValue != pipelineURL { sourceNeedsUpdate = true } } } public private(set) var source: String? public private(set) var shaderSource: String? var sourceNeedsUpdate: Bool = true { didSet { if sourceNeedsUpdate { libraryNeedsUpdate = true } } } public required init(_ label: String, _ pipelineURL: URL, _ vertexFunctionName: String? = nil, _ fragmentFunctionName: String? = nil) { self.pipelineURL = pipelineURL super.init(label, vertexFunctionName, fragmentFunctionName, nil) } public required init() { fatalError("init() has not been implemented") } override func setup() { setupSource() super.setup() } override func update() { updateSource() super.update() } func updateSource() { if sourceNeedsUpdate { setupSource() } } deinit { source = nil } override func setupParameters() { if let shaderSource = shaderSource, let params = parseParameters(source: shaderSource, key: label + "Uniforms") { params.label = label.titleCase parameters = params } parametersNeedsUpdate = false } override func setupLibrary() { guard let context = context, let source = source else { return } do { library = try context.device.makeLibrary(source: source, options: nil) libraryNeedsUpdate = false } catch { print("\(label) Shader: \(error.localizedDescription)") } } func setupShaderSource() -> String? { do { return try MetalFileCompiler().parse(pipelineURL) } catch { print("\(label) Shader: \(error.localizedDescription)") } return nil } func setupSource() { guard let satinURL = getPipelinesSatinUrl(), let shaderSource = setupShaderSource() else { return } let includesURL = satinURL.appendingPathComponent("Includes.metal") do { let compiler = MetalFileCompiler() var source = try compiler.parse(includesURL) injectConstants(source: &source) injectVertex(source: &source, vertexDescriptor: vertexDescriptor) injectVertexData(source: &source) injectVertexUniforms(source: &source) source += shaderSource injectPassThroughVertex(label: label, source: &source) self.shaderSource = shaderSource self.source = source sourceNeedsUpdate = false } catch { print("\(label) Shader: \(error.localizedDescription)") } } override public func clone() -> Shader { let clone: SourceShader = type(of: self).init(label, pipelineURL, vertexFunctionName, fragmentFunctionName) clone.label = label clone.pipelineURL = pipelineURL clone.library = library clone.pipeline = pipeline clone.source = source clone.delegate = delegate clone.parameters = parameters.clone() clone.blending = blending clone.sourceRGBBlendFactor = sourceRGBBlendFactor clone.sourceAlphaBlendFactor = sourceAlphaBlendFactor clone.destinationRGBBlendFactor = destinationRGBBlendFactor clone.destinationAlphaBlendFactor = destinationAlphaBlendFactor clone.rgbBlendOperation = rgbBlendOperation clone.alphaBlendOperation = alphaBlendOperation clone.context = context return clone } }
27.978261
139
0.605025
76f2d84b52db16d3ccd764da14891ca6c5d5f30f
5,431
import Cocoa final class PushOpController: PasswordOpController { let remoteOption: RemoteOperationOption? init(remoteOption: RemoteOperationOption, windowController: XTWindowController) { self.remoteOption = remoteOption super.init(windowController: windowController) } required init(windowController: XTWindowController) { self.remoteOption = nil super.init(windowController: windowController) } func progressCallback(progress: PushTransferProgress) -> Bool { guard !canceled, let repository = repository else { return true } let note = Notification.progressNotification(repository: repository, progress: Float(progress.current), total: Float(progress.total)) NotificationCenter.default.post(note) return !canceled } override func start() throws { guard let repository = repository else { throw RepoError.unexpected } let remote: Remote let branches: [LocalBranch] switch remoteOption { case .all: throw RepoError.unexpected case .new: try pushNewBranch() return case .currentBranch, nil: guard let branchName = repository.currentBranch, let currentBranch = repository.localBranch(named: branchName) else { NSLog("Can't get current branch") throw RepoError.detachedHead } guard let remoteBranch = currentBranch.trackingBranch, let remoteName = remoteBranch.remoteName, let trackedRemote = repository.remote(named: remoteName) else { try pushNewBranch() return } remote = trackedRemote branches = [currentBranch] case .named(let remoteName): guard let namedRemote = repository.remote(named: remoteName) else { throw RepoError.notFound } let localTrackingBranches = repository.localBranches.filter { $0.trackingBranch?.remoteName == remoteName } guard !localTrackingBranches.isEmpty else { let alert = NSAlert() alert.messageString = .noRemoteBranches(remoteName) alert.beginSheetModal(for: windowController!.window!, completionHandler: nil) return } remote = namedRemote branches = localTrackingBranches } let alert = NSAlert() let remoteName = remote.name ?? "origin" let message: UIString = branches.count == 1 ? .confirmPush(localBranch: branches.first!.name, remote: remoteName) : .confirmPushAll(remote: remoteName) alert.messageString = message alert.addButton(withString: .push) alert.addButton(withString: .cancel) alert.beginSheetModal(for: windowController!.window!) { (response) in if response == .alertFirstButtonReturn { self.push(branches: branches, remote: remote) } else { self.ended(result: .canceled) } } } func pushNewBranch() throws { guard let repository = self.repository, let window = windowController?.window, let branchName = repository.currentBranch, let currentBranch = repository.localBranch(named: branchName) else { throw RepoError.unexpected } let sheetController = PushNewPanelController.controller() sheetController.alreadyTracking = currentBranch.trackingBranchName != nil sheetController.setRemotes(repository.remoteNames()) window.beginSheet(sheetController.window!) { (response) in guard response == .OK else { self.ended(result: .canceled) return } guard let remote = repository.remote(named: sheetController.selectedRemote) else { self.ended(result: .failure) return } self.push(branches: [currentBranch], remote: remote, then: { // This is now on the repo queue DispatchQueue.main.async { if sheetController.setTrackingBranch, let remoteName = remote.name { currentBranch.trackingBranchName = remoteName +/ currentBranch.strippedName } } }) } } override func shoudReport(error: NSError) -> Bool { return true } override func repoErrorMessage(for error: RepoError) -> UIString { if error.isGitError(GIT_EBAREREPO) { return .pushToBare } else { return super.repoErrorMessage(for: error) } } func push(branches: [LocalBranch], remote: Remote, then callback: (() -> Void)? = nil) { tryRepoOperation { guard let repository = self.repository else { return } let callbacks = RemoteCallbacks(passwordBlock: self.getPassword, downloadProgress: nil, uploadProgress: self.progressCallback) if let url = remote.pushURL ?? remote.url { self.setKeychainInfo(from: url) } try repository.push(branches: branches, remote: remote, callbacks: callbacks) callback?() self.windowController?.repoController.refsChanged() self.ended() } } }
28.73545
83
0.608728
388cde72475d0c589a7d1280c87728600b0c7bd3
1,370
/* * The MIT License (MIT) * * Copyright (c) 2016 NBCO Yandex.Money LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import Foundation // MARK: - Equatable extension Dictionary: Equatable { public static func == (lhs: Dictionary, rhs: Dictionary) -> Bool { return NSDictionary(dictionary: lhs).isEqual(to: rhs) } }
41.515152
80
0.744526
14bc98948a53a15df166cd153c180cff069ebce3
892
// // PlanetsViewController.swift // Planets // // Created by Valentin Kalchev (Zuant) on 25/01/21. // import UIKit import Planets public class PlanetsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet private var tableView: UITableView! var tableModel: [PlanetCellController] = [] { didSet { self.tableView.reloadData() } } var onViewDidLoad: (() -> Void)? public override func viewDidLoad() { super.viewDidLoad() onViewDidLoad?() } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return tableModel[indexPath.row].view(tableView: tableView) } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tableModel.count } }
25.485714
107
0.661435
28f62a4da90c3b821c238b973dcf18d6133426eb
204
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing A{a{}}var:{struct A{let e:A}enum A
34
87
0.75
ac1f6b571d9965aa55d3391ee377c58e9c90360c
2,098
// The MIT License (MIT) // Copyright © 2022 Ivan Vorobei ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. extension SFSymbol { public static var bookmark: Bookmark { .init(name: "bookmark") } open class Bookmark: SFSymbol { @available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) open var circle: SFSymbol { ext(.start.circle) } @available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) open var circleFill: SFSymbol { ext(.start.circle.fill) } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) open var fill: SFSymbol { ext(.start.fill) } @available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) open var slash: SFSymbol { ext(.start.slash) } @available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) open var slashFill: SFSymbol { ext(.start.slash.fill) } @available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *) open var square: SFSymbol { ext(.start.square) } @available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *) open var squareFill: SFSymbol { ext(.start.square.fill) } } }
45.608696
81
0.71878
7a9364bedbc60e920369b645d2841bcdf5b8e0a9
13,456
/** © Copyright 2019, The Great Rift Valley Software Company LICENSE: MIT License 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. The Great Rift Valley Software Company: https://riftvalleysoftware.com */ import Cocoa #if !DIRECT // We declare the DIRECT preprocessor macro in the target settings. import RVS_BTDriver_MacOS #endif /* ################################################################################################################################## */ // MARK: - The Base (Common) View Controller Class for Each Device /* ################################################################################################################################## */ /** This controls a screen that allows a direct command/response with each device, and also allows a "details" screen to appear, listing the device state. */ class RVS_BTDriver_OBD_MacOS_Test_Harness_Device_ViewController: RVS_BTDriver_OBD_MacOS_Test_Harness_Base_Device_ViewController { /* ############################################################################################################################## */ // MARK: - Static Properties /* ############################################################################################################################## */ /* ################################################################## */ /** This is the storyboard instantiation ID. */ static let storyboardID = "device-view-controller" /* ################################################################## */ /** The label for the enter text field. */ @IBOutlet weak var enterTextLabel: NSTextField! /* ################################################################## */ /** The text entry field, where the user types in the command. */ @IBOutlet weak var enterTextField: NSTextField! /* ################################################################## */ /** the button the user presses to send the command. */ @IBOutlet weak var sendTextButton: NSButton! /* ################################################################## */ /** The label for the response display. */ @IBOutlet weak var responseDisplayLabel: NSTextField! /* ################################################################## */ /** The text view portion of the scrollable area for the response. */ @IBOutlet var responseTextView: NSTextView! /* ################################################################## */ /** This is the button that calls out the details modal sheet. */ @IBOutlet weak var detailsCalloutButton: NSButton! /* ################################################################## */ /** This is the button that calls out the commands modal sheet. */ @IBOutlet weak var commandsButton: NSButton! /* ############################################################################################################################## */ // MARK: - RVS_BTDriver_OBD_DeviceDelegate Handlers /* ############################################################################################################################## */ /* ################################################################## */ /** This is called when an OBD device updates its transaction. - parameter inTransaction: The transaction that was updated. It may be nil. */ override func deviceUpdatedTransaction(_ inTransaction: RVS_BTDriver_OBD_Device_TransactionStruct) { if let data = inTransaction.responseData, var stringValue = String(data: data, encoding: .ascii) { #if DEBUG print("Device Returned This Data: \(stringValue)") #endif DispatchQueue.main.async { // First time through, we add the command, and give it a carat. if self.responseTextView?.string.isEmpty ?? true, let initialString = self.enterTextField?.stringValue { stringValue = ">" + initialString + "\r\n" + stringValue } self.responseTextView?.string += stringValue if let cleanedValue = inTransaction.responseDataAsString, !cleanedValue.isEmpty { self.responseTextView?.string += "\r\n\r\n" + "SLUG-CleanedValue".localizedVariant self.responseTextView?.string += cleanedValue self.responseTextView?.string += "\r\n\r\n>" } self.responseTextView?.scrollToEndOfDocument(nil) self.setUpUI() self.enterTextField?.stringValue = "" self.enterTextField?.becomeFirstResponder() } } } /* ############################################################################################################################## */ // MARK: - RVS_BTDriver_DeviceSubscriberProtocol Handlers /* ############################################################################################################################## */ /* ################################################################## */ /** Error reporting method. Since the driver will handle displaying the error, all we do, is clean up the UX. - parameter inDevice: The `RVS_BTDriver_OBD_DeviceProtocol` instance that encountered the error. - parameter encounteredThisError: The error that was encountered. */ override func subscribedDevice(_ device: RVS_BTDriver_DeviceProtocol, encounteredThisError inError: RVS_BTDriver.Errors) { #if DEBUG print("ERROR! \(String(describing: inError))") #endif DispatchQueue.main.async { self.enterTextField?.stringValue = "" self.setUpUI() self.enterTextField?.becomeFirstResponder() } } } /* ################################################################################################################################## */ // MARK: - NSTextFieldDelegate Methods /* ################################################################################################################################## */ extension RVS_BTDriver_OBD_MacOS_Test_Harness_Device_ViewController: NSTextFieldDelegate { /* ################################################################## */ /** Called when text changes in the send text box. - parameter inNotification: The notification object for the text field. */ func controlTextDidChange(_ inNotification: Notification) { if let textField = inNotification.object as? NSTextField, textField == enterTextField { #if DEBUG print("New Text Entered for \(textField.stringValue)") #endif setUpUI() } } } /* ################################################################################################################################## */ // MARK: - IBAction Methods /* ################################################################################################################################## */ extension RVS_BTDriver_OBD_MacOS_Test_Harness_Device_ViewController { /* ################################################################## */ /** This will initiate a data send to the device, using whatever is in the command text field. - parameter: ignored. */ @IBAction func sendButtonHit(_: Any) { if let sendString = enterTextField?.stringValue, !sendString.isEmpty { #if DEBUG print("Sending: \(sendString).") #endif sendTextButton?.isEnabled = false enterTextField?.isEnabled = false deviceInstance.sendCommand(sendString + "\r\n", rawCommand: sendString) } } } /* ################################################################################################################################## */ // MARK: - Instance Methods /* ################################################################################################################################## */ extension RVS_BTDriver_OBD_MacOS_Test_Harness_Device_ViewController { /* ################################################################## */ /** Sets up the UI elements. */ func setUpUI() { if var modelTitle = deviceInstance?.deviceName { if let device = deviceInstance as? RVS_BTDriver_OBD_ELM327_DeviceProtocol { modelTitle += " (ELM327 v\(device.elm327Version))" } title = modelTitle } enterTextField?.isEnabled = true sendTextButton?.isEnabled = !(enterTextField?.stringValue.isEmpty ?? true) } } /* ################################################################################################################################## */ // MARK: - Base Class Override Methods /* ################################################################################################################################## */ extension RVS_BTDriver_OBD_MacOS_Test_Harness_Device_ViewController { /* ################################################################## */ /** Called after the view has loaded and initialized from the storyboard. */ override func viewDidLoad() { super.viewDidLoad() enterTextLabel?.stringValue = (enterTextLabel?.stringValue ?? "ERROR").localizedVariant responseDisplayLabel?.stringValue = (responseDisplayLabel?.stringValue ?? "ERROR").localizedVariant sendTextButton?.title = (sendTextButton?.title ?? "ERROR").localizedVariant detailsCalloutButton?.title = (detailsCalloutButton?.title ?? "ERROR").localizedVariant commandsButton?.title = (commandsButton?.title ?? "ERROR").localizedVariant deviceInstance?.subscribe(self) deviceInstance?.delegate = self self.responseTextView?.string = "" setUpUI() } /* ################################################################## */ /** When we are about to appear, we register with the app delegate object. */ override func viewWillAppear() { super.viewWillAppear() if let uuid = deviceInstance?.uuid { appDelegateObject.openDeviceControllers[uuid] = self } deviceInstance?.subscribe(self) self.enterTextField?.becomeFirstResponder() } /* ################################################################## */ /** We remove ourselves when we are about to go away. */ override func viewWillDisappear() { super.viewWillDisappear() if let uuid = deviceInstance?.uuid { appDelegateObject.openDeviceControllers.removeValue(forKey: uuid) } deviceInstance?.unsubscribe(self) } /* ################################################################## */ /** Called just before we bring in a device details instance screen. - parameters: - for: The Segue instance - sender: Data being associated. In this case, it is the device to associate with the screen. */ override func prepare(for inSegue: NSStoryboardSegue, sender inDevice: Any?) { if let destination = inSegue.destinationController as? RVS_BTDriver_OBD_MacOS_Test_Harness_Base_Device_ViewController { destination.deviceInstance = deviceInstance } } } /* ################################################################################################################################## */ // MARK: - RVS_BTDriver_DeviceSubscriberProtocol Handlers /* ################################################################################################################################## */ extension RVS_BTDriver_OBD_MacOS_Test_Harness_Device_ViewController { /* ################################################################## */ /** Called if the device state changes, in some way. - parameter inDevice: The device instance that is calling this. */ func deviceStatusUpdate(_ inDevice: RVS_BTDriver_DeviceProtocol) { #if DEBUG print("Device Status Changed") #endif DispatchQueue.main.async { self.setUpUI() } } }
45.306397
151
0.472354
46b2a7d8554301748a4ae7265961fb6b118f8303
579
// // SmallIconProvider.swift // NetNewsWire // // Created by Brent Simmons on 12/16/17. // Copyright © 2017 Ranchero Software. All rights reserved. // import AppKit import Articles import Account protocol SmallIconProvider { var smallIcon: NSImage? { get } } extension Feed: SmallIconProvider { var smallIcon: NSImage? { if let image = appDelegate.faviconDownloader.favicon(for: self) { return image } return AppImages.genericFeedImage } } extension Folder: SmallIconProvider { var smallIcon: NSImage? { return NSImage(named: NSImage.Name.folder) } }
17.029412
67
0.73057
8a5997e9de654eb88534660c098ebc06b02de4fd
3,540
// // ProfileView.swift // Latest // // Created by Cédric Bahirwe on 14/04/2021. // import SwiftUI struct ProfileView: View { var body: some View { VStack(spacing: 0) { SheetHeaderView() ScrollView { VStack(alignment: .leading, spacing: 0) { Button(action: { }) { Text("Log In") .font(Font.body.weight(.semibold)) .padding(.horizontal, 50) .padding(.vertical, 10) .border(Color.systemWhite, width: 1.5) } .padding() .padding(.vertical) ProfileItem(label: "Manage Accounts") Section(header: Text("NOTIFICATIONS") .font(Font.callout.weight(.semibold)) .padding(.vertical) .padding(.horizontal, 12) ) { ProfileItem(label: "Enable Notifications") } Section(header: Text("CONTENT PREFERENCES") .font(Font.callout.weight(.semibold)) .padding(.vertical) .padding(.horizontal, 12) ) { ProfileItem(label: "Clear Cached Content") } Section(header: Text("SUPPORT") .font(Font.callout.weight(.semibold)) .padding(.vertical) .padding(.horizontal, 12) ) { ProfileItem(label: "Provide Feedback") ProfileItem(label: "Rate App") ProfileItem(label: "Share App") } Section(header: Text("SUPPORT") .font(Font.caption.weight(.semibold)) .padding(12) ) { ProfileItem(label: "Privacy Policy") ProfileItem(label: "Version 1.0") ProfileItem(label: "Credits") } } } .foregroundColor(.systemWhite) .frame(maxWidth:.infinity, alignment: .topLeading) .background( LinearGradient(gradient: Gradient(colors: [Color.mainColor, Color.blue]), startPoint: .topLeading, endPoint: .bottomTrailing) ) } } } struct ProfileView_Previews: PreviewProvider { static var previews: some View { ProfileView() } } extension ProfileView { private struct ProfileItem: View { let label: String let hasBg: Bool = true var body: some View { HStack { Text(label) .font(Font.callout.weight(.light)) Spacer() Image(systemName: "chevron.right") } .font(Font.callout.weight(.light)) .padding(12) .background(Color.primary.opacity(0.3)) } } }
34.038462
141
0.391808
0a2a172422f161b7592543ab8ef8766d4a9d4593
1,798
import XCTest @testable import Helpers class TimeTests: XCTestCase { func testAdd15Seconds() { let time = Time(hours: 5, minutes: 30, seconds: 15) let newTime = time.timeByAdding(seconds: 15) XCTAssertEqual(newTime, Time(hours: 5, minutes: 30, seconds: 30)) } func testAdd30SecondsAndChangeMinutes() { let time = Time(hours: 13, minutes: 20, seconds: 45) let newTime = time.timeByAdding(seconds: 30) XCTAssertEqual(newTime, Time(hours: 13, minutes: 21, seconds: 15)) } func testAdd90SecondsAndChangeMinutes() { let time = Time(hours: 13, minutes: 0, seconds: 0) let newTime = time.timeByAdding(seconds: 90) XCTAssertEqual(newTime, Time(hours: 13, minutes: 1, seconds: 30)) } func testAdd1SecondAndChangeHour() { let time = Time(hours: 13, minutes: 59, seconds: 59) let newTime = time.timeByAdding(seconds: 1) XCTAssertEqual(newTime, Time(hours: 14, minutes: 0, seconds: 0)) } func testAdd900SecondsAndChangeMinutesAndHours() { let time = Time(hours: 13, minutes: 50, seconds: 0) let newTime = time.timeByAdding(seconds: 900) XCTAssertEqual(newTime, Time(hours: 14, minutes: 5, seconds: 0)) } func testFormatTime() { let time = Time(hours: 13, minutes: 2, seconds: 6) let format = time.description XCTAssertEqual(format, "13:02:06") } func testTotalSeconds() { XCTAssertEqual(Time(hours: 0, minutes: 0, seconds: 10).totalSeconds, 10) XCTAssertEqual(Time(hours: 0, minutes: 30, seconds: 10).totalSeconds, 1810) XCTAssertEqual(Time(hours: 1, minutes: 0, seconds: 10).totalSeconds, 3610) } func testStrideBy315Times() { let start = Time(hours: 13, minutes: 10, seconds: 0) let end = Time(hours: 13, minutes: 15, seconds: 15) let times = stride(from: start, to: end, by: +1) XCTAssertEqual(times.sorted().count, 315) } }
32.690909
77
0.706897
f9078266df42aa937c9c6faf7dad6424b0c09d48
594
// swift-tools-version:5.0 import PackageDescription let package = Package( name: "swift-nio-redis-client", products: [ .library(name: "Redis", targets: [ "Redis" ]) ], dependencies: [ .package(url: "https://github.com/apple/swift-nio.git", from: "2.20.0"), .package(url: "https://github.com/SwiftNIOExtras/swift-nio-redis.git", from: "0.10.3") ], targets: [ .target (name: "Redis", dependencies: [ "NIORedis" ]), .testTarget(name: "RedisTests", dependencies: [ "Redis" ]) ] )
28.285714
79
0.545455
4a770eeba20ac38959fb4b6ba15312255d9ce137
1,490
// // NewsCardCell.swift // CoinCraft // // Created by Gilwan Ryu on 2020/02/12. // Copyright © 2020 Gilwan Ryu. All rights reserved. // import UIKit import Kingfisher import Domain class NewsCardCell: UITableViewCell { @IBOutlet weak var backView: UIViewCustom! @IBOutlet weak var thumbnailImageView: UIImageView! @IBOutlet weak var companyNameLabel: UILabel! @IBOutlet weak var tagsLabel: UILabel! @IBOutlet weak var bodyLabel: UILabel! @IBOutlet weak var indicator: UIActivityIndicatorView! 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 } func bind(news: NewsViewable) { self.indicator.startAnimating() if let imageUrl = URL(string: news.sourceImageUrl) { thumbnailImageView.kf.setImage(with: ImageResource(downloadURL: imageUrl, cacheKey: news.imageUrl), placeholder: nil, options: nil, progressBlock: nil) { result in self.indicator.stopAnimating() } } companyNameLabel.text = news.sourceName bodyLabel.text = news.title tagsLabel.text = news.tags } }
29.215686
111
0.602685
6aec425714ca6583f3c40b496f04ff347b9a466f
1,119
import FutureHTTP extension HTTPClientError { var tethys: TethysKit.NetworkError { switch self { case .unknown, .url: return .unknown case .network(let networkError): return networkError.tethys case .http, .security: return .badResponse(Data()) } } } extension FutureHTTP.NetworkError { fileprivate var tethys: TethysKit.NetworkError { switch self { case .cancelled: return .cancelled case .timedOut: return .timedOut case .cannotConnectTohost, .connectionLost: return .serverNotFound case .cannotFindHost, .dnsFailed: return .dns case .notConnectedToInternet: return .internetDown } } } extension HTTPResponse { var tethysError: TethysKit.NetworkError? { guard let status = self.status else { return .badResponse(self.body) } guard let httpError = TethysKit.HTTPError(rawValue: status.rawValue) else { return nil } return .http(httpError, self.body) } }
26.023256
83
0.60143
f938e746abd20ea23fb4e54a98f71bad38868d36
10,980
// // PaymentCardsTest.swift // VGSCollectSDK // // Created by Dima on 09.07.2020. // Copyright © 2020 VGS. All rights reserved. // import XCTest @testable import VGSCollectSDK @testable import VGSPaymentCards class PaymentCardsTest: VGSCollectBaseTestCase { var collector: VGSCollect! var cardTextField: VGSTextField! override func setUp() { super.setUp() collector = VGSCollect(id: "tnt") cardTextField = VGSTextField() let config = VGSConfiguration(collector: collector, fieldName: "cardNum") config.type = .cardNumber cardTextField.configuration = config resetCardBrands() } override func tearDown() { collector = nil cardTextField = nil resetCardBrands() } func testEditingDefaultBrands() { VGSPaymentCards.visa.name = "cutomized-visa" VGSPaymentCards.visa.regex = "^9\\d*$" VGSPaymentCards.visa.formatPattern = "####-####-####-###" VGSPaymentCards.visa.cardNumberLengths = [15] cardTextField.setText("911111111111111111111111") if let state = cardTextField.state as? CardState { XCTAssertTrue(state.cardBrand == VGSPaymentCards.CardBrand.visa) XCTAssertTrue(state.cardBrand.stringValue == "cutomized-visa") XCTAssertTrue(state.cardBrand.cardLengths == [15]) XCTAssertTrue(state.isValid) XCTAssertTrue(state.inputLength == 15) } else { XCTFail("Failt state card text files") } VGSPaymentCards.visa.checkSumAlgorithm = .none VGSPaymentCards.visa.cardNumberLengths = [12] cardTextField.setText("900000000012") if let state = cardTextField.state as? CardState { XCTAssertTrue(state.cardBrand == VGSPaymentCards.CardBrand.visa) XCTAssertTrue(state.cardBrand.stringValue == "cutomized-visa") XCTAssertTrue(state.cardBrand.cardLengths == [12]) XCTAssertTrue(state.isValid) XCTAssertTrue(state.inputLength == 12) XCTAssertTrue(state.last4 == "0012") XCTAssertTrue(state.bin == "900000") } else { XCTFail("Failt state card text files") } } func testCustomBrandPriority() { let customBrandName = "custom-brand-1" let customBrand = VGSCustomPaymentCardModel(name: customBrandName, regex: VGSPaymentCards.visa.regex, formatPattern: "#### #### #### ####", cardNumberLengths: [15, 19], cvcLengths: [5], checkSumAlgorithm: .luhn, brandIcon: nil) VGSPaymentCards.cutomPaymentCardModels = [customBrand] cardTextField.setText("4111111") if let state = cardTextField.state as? CardState { XCTAssertTrue(state.cardBrand == VGSPaymentCards.CardBrand.custom(brandName: customBrandName)) } else { XCTFail("Failt state card text files") } let regex = "^9\\d*$" let customBrandName2 = "custom-brand-2" let customBrand2 = VGSCustomPaymentCardModel(name: customBrandName2, regex: regex, formatPattern: "#### #### #### ####", cardNumberLengths: [15, 19], cvcLengths: [5], checkSumAlgorithm: .luhn, brandIcon: nil) VGSPaymentCards.cutomPaymentCardModels = [customBrand2] VGSPaymentCards.visa.regex = regex cardTextField.setText("911111") if let state = cardTextField.state as? CardState { XCTAssertTrue(state.cardBrand == VGSPaymentCards.CardBrand.custom(brandName: customBrandName2)) } else { XCTFail("Failt state card text files") } } func testCustomBrands() { let customBrand1 = VGSCustomPaymentCardModel(name: "custom-brand-1", regex: "^911\\d*$", formatPattern: "#### #### #### ####", cardNumberLengths: [15, 19], cvcLengths: [3], checkSumAlgorithm: .luhn, brandIcon: nil) let customBrand2 = VGSCustomPaymentCardModel(name: "custom-brand-2", regex: "^922\\d*$", formatPattern: "#### #### #### ####", cardNumberLengths: Array(12...16), cvcLengths: [3, 4], checkSumAlgorithm: .none, brandIcon: nil) let customBrands = [customBrand1, customBrand2] VGSPaymentCards.cutomPaymentCardModels = customBrands cardTextField.setText("9111 1111 1111 111") if let state = cardTextField.state as? CardState { XCTAssertTrue(state.cardBrand == .custom(brandName: "custom-brand-1")) XCTAssertTrue(state.cardBrand.stringValue == "custom-brand-1") XCTAssertTrue(state.cardBrand.cardLengths == [15, 19]) XCTAssertTrue(state.isValid) XCTAssertTrue(state.inputLength == 15) } else { XCTFail("Failt state card text files") } cardTextField.setText("92222222222222222222222222") if let state = cardTextField.state as? CardState { XCTAssertTrue(state.cardBrand == .custom(brandName: "custom-brand-2")) XCTAssertTrue(state.cardBrand.stringValue == "custom-brand-2") XCTAssertTrue(state.cardBrand.cardLengths == Array(12...16)) XCTAssertTrue(state.isValid) XCTAssertTrue(state.inputLength == 16) } else { XCTFail("Failt state card text files") } } func testUnknownBrands() { cardTextField.setText("9111 1111 1111 111") if let state = cardTextField.state as? CardState { XCTAssertTrue(state.cardBrand == .unknown) XCTAssertFalse(state.isValid) XCTAssertTrue(state.inputLength == 15) } else { XCTFail("Failt state card text files") } VGSPaymentCards.unknown.formatPattern = "#### #### #### #### #### ####" VGSPaymentCards.unknown.cardNumberLengths = [15] VGSPaymentCards.unknown.checkSumAlgorithm = .luhn cardTextField.setText("9111 1111 1111 111") if let state = cardTextField.state as? CardState { XCTAssertTrue(state.cardBrand == .unknown) XCTAssertFalse(state.isValid) XCTAssertTrue(state.inputLength == 15) } else { XCTFail("Failt state card text files") } cardTextField.validationRules = VGSValidationRuleSet(rules: [ VGSValidationRulePaymentCard.init(error: "some error", validateUnknownCardBrand: true) ]) cardTextField.setText("9111 1111 1111 111") if let state = cardTextField.state as? CardState { XCTAssertTrue(state.cardBrand == .unknown) XCTAssertTrue(state.isValid) XCTAssertTrue(state.inputLength == 15) } else { XCTFail("Failt state card text files") } VGSPaymentCards.unknown.cardNumberLengths = Array(12...19) VGSPaymentCards.unknown.checkSumAlgorithm = .none cardTextField.setText("123456789012") if let state = cardTextField.state as? CardState { XCTAssertTrue(state.cardBrand == .unknown) XCTAssertTrue(state.isValid) XCTAssertTrue(state.inputLength == 12) } else { XCTFail("Failt state card text files") } cardTextField.setText("0000 1111 0000 1111 000") if let state = cardTextField.state as? CardState { XCTAssertTrue(state.cardBrand == .unknown) XCTAssertTrue(state.isValid) XCTAssertTrue(state.inputLength == 19) } else { XCTFail("Failt state card text files") } cardTextField.setText("0000 1111 0000 1111 0009") if let state = cardTextField.state as? CardState { XCTAssertTrue(state.cardBrand == .unknown) XCTAssertFalse(state.isValid) XCTAssertTrue(state.inputLength == 20) } else { XCTFail("Failt state card text files") } } func testAvailableBrands() { XCTAssertTrue(VGSPaymentCards.availableCardBrands.count == VGSPaymentCards.defaultCardModels.count) let customBrand1 = VGSCustomPaymentCardModel(name: "custom-brand-1", regex: "^9\\d*$", formatPattern: "#### #### #### ####", cardNumberLengths: [15, 19], cvcLengths: [5], checkSumAlgorithm: .luhn, brandIcon: nil) let customBrand2 = VGSCustomPaymentCardModel(name: "custom-brand-2", regex: "^9\\d*$", formatPattern: "#### #### #### ####", cardNumberLengths: [15, 19], cvcLengths: [5], checkSumAlgorithm: .luhn, brandIcon: nil) let customBrands = [customBrand1, customBrand2] VGSPaymentCards.cutomPaymentCardModels = customBrands XCTAssertTrue(VGSPaymentCards.availableCardBrands.count == VGSPaymentCards.defaultCardModels.count + customBrands.count) } func resetCardBrands() { VGSPaymentCards.elo = VGSPaymentCardModel(brand: .elo) VGSPaymentCards.visaElectron = VGSPaymentCardModel(brand: .visaElectron) VGSPaymentCards.maestro = VGSPaymentCardModel(brand: .maestro) VGSPaymentCards.forbrugsforeningen = VGSPaymentCardModel(brand: .forbrugsforeningen) VGSPaymentCards.dankort = VGSPaymentCardModel(brand: .dankort) VGSPaymentCards.visa = VGSPaymentCardModel(brand: .visa) VGSPaymentCards.masterCard = VGSPaymentCardModel(brand: .mastercard) VGSPaymentCards.amex = VGSPaymentCardModel(brand: .amex) VGSPaymentCards.hipercard = VGSPaymentCardModel(brand: .hipercard) VGSPaymentCards.dinersClub = VGSPaymentCardModel(brand: .dinersClub) VGSPaymentCards.discover = VGSPaymentCardModel(brand: .discover) VGSPaymentCards.unionpay = VGSPaymentCardModel(brand: .unionpay) VGSPaymentCards.jcb = VGSPaymentCardModel(brand: .jcb) VGSPaymentCards.cutomPaymentCardModels = [] } }
42.393822
124
0.57204
c1cb5433f371d8b3c37780e8294d8c6648aa80c2
2,549
//Copyright © 2019 Stormbird PTE. LTD. import Foundation class RateLimiter { private let name: String? private let block: () -> Void private let limit: TimeInterval private var timer: Timer? private var shouldRunWhenWindowCloses = false private var isWindowActive: Bool { timer?.isValid ?? false } init(name: String? = nil, limit: TimeInterval, autoRun: Bool = false, block: @escaping () -> Void) { self.name = name self.limit = limit self.block = block if autoRun { run() } } func run() { if isWindowActive { shouldRunWhenWindowCloses = true } else { runWithNewWindow() } } @objc private func windowIsClosed() { if shouldRunWhenWindowCloses { runWithNewWindow() } } private func runWithNewWindow() { shouldRunWhenWindowCloses = false block() timer?.invalidate() //NOTE: avoid memory leak, remove capturing self timer = Timer.scheduledTimer(withTimeInterval: limit, repeats: false) { [weak self] _ in guard let strongSelf = self else { return } strongSelf.windowIsClosed() } } } public protocol SyncLimiter { @discardableResult func execute(_ block: () -> Void) -> Bool func reset() } extension SyncLimiter { public func execute<T>(_ block: () -> T) -> T? { var value: T? = nil execute { value = block() } return value } } public final class TimedLimiter: SyncLimiter { // MARK: - Properties public let limit: TimeInterval public private(set) var lastExecutedAt: Date? private let syncQueue = DispatchQueue(label: "com.alphaWallet.ratelimit", attributes: []) // MARK: - Initializers public init(limit: TimeInterval) { self.limit = limit } // MARK: - Limiter @discardableResult public func execute(_ block: () -> Void) -> Bool { let executed = syncQueue.sync { () -> Bool in let now = Date() let timeInterval = now.timeIntervalSince(lastExecutedAt ?? .distantPast) if timeInterval > limit { lastExecutedAt = now return true } else { return false } } if executed { block() } return executed } public func reset() { syncQueue.sync { lastExecutedAt = nil } } }
23.601852
104
0.561789
e8be44673821345b8c3b60d2546e49cc3d59ccbf
20,499
/* This source file is part of the Swift.org open source project Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import Foundation import TSCBasic /// The canonical identifier for a package, based on its source location. public struct PackageIdentity: CustomStringConvertible { /// A textual representation of this instance. public let description: String /// Creates a package identity from a string. /// - Parameter value: A string used to identify a package. init(_ value: String) { self.description = value } /// Creates a package identity from a URL. /// - Parameter url: The package's URL. public init(url: URL) { self.init(urlString: url.absoluteString) } /// Creates a package identity from a URL. /// - Parameter urlString: The package's URL. // FIXME: deprecate this public init(urlString: String) { self.description = PackageIdentityParser(urlString).description } /// Creates a package identity from a file path. /// - Parameter path: An absolute path to the package. public init(path: AbsolutePath) { self.description = PackageIdentityParser(path.pathString).description } /// Creates a plain package identity for a root package /// - Parameter value: A string used to identify a package, will be used unmodified public static func plain(_ value: String) -> PackageIdentity { PackageIdentity(value) } // TODO: formalize package registry identifier public var scopeAndName: (scope: Scope, name: Name)? { let components = description.split(separator: ".", maxSplits: 1, omittingEmptySubsequences: true) guard components.count == 2, let scope = Scope(components.first), let name = Name(components.last) else { return .none } return (scope: scope, name: name) } } extension PackageIdentity: Equatable, Comparable { private func compare(to other: PackageIdentity) -> ComparisonResult { return self.description.caseInsensitiveCompare(other.description) } public static func == (lhs: PackageIdentity, rhs: PackageIdentity) -> Bool { return lhs.compare(to: rhs) == .orderedSame } public static func < (lhs: PackageIdentity, rhs: PackageIdentity) -> Bool { return lhs.compare(to: rhs) == .orderedAscending } public static func > (lhs: PackageIdentity, rhs: PackageIdentity) -> Bool { return lhs.compare(to: rhs) == .orderedDescending } } extension PackageIdentity: Hashable { public func hash(into hasher: inout Hasher) { hasher.combine(description.lowercased()) } } extension PackageIdentity: Codable { public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() let description = try container.decode(String.self) self.init(description) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(self.description) } } // MARK: - extension PackageIdentity { /// Provides a namespace for related packages within a package registry. public struct Scope: LosslessStringConvertible, Hashable, Equatable, Comparable, ExpressibleByStringLiteral { public let description: String public init(validating description: String) throws { guard !description.isEmpty else { throw StringError("The minimum length of a package scope is 1 character.") } guard description.count <= 39 else { throw StringError("The maximum length of a package scope is 39 characters.") } for (index, character) in zip(description.indices, description) { guard character.isASCII, character.isLetter || character.isNumber || character == "-" else { throw StringError("A package scope consists of alphanumeric characters and hyphens.") } if character.isPunctuation { switch (index, description.index(after: index)) { case (description.startIndex, _): throw StringError("Hyphens may not occur at the beginning of a scope.") case (_, description.endIndex): throw StringError("Hyphens may not occur at the end of a scope.") case (_, let nextIndex) where description[nextIndex].isPunctuation: throw StringError("Hyphens may not occur consecutively within a scope.") default: continue } } } self.description = description } public init?(_ description: String) { guard let scope = try? Scope(validating: description) else { return nil } self = scope } fileprivate init?(_ substring: String.SubSequence?) { guard let substring = substring else { return nil } self.init(String(substring)) } // MARK: - Equatable & Comparable private func compare(to other: Scope) -> ComparisonResult { // Package scopes are case-insensitive (for example, `mona` ≍ `MONA`). return self.description.caseInsensitiveCompare(other.description) } public static func == (lhs: Scope, rhs: Scope) -> Bool { return lhs.compare(to: rhs) == .orderedSame } public static func < (lhs: Scope, rhs: Scope) -> Bool { return lhs.compare(to: rhs) == .orderedAscending } public static func > (lhs: Scope, rhs: Scope) -> Bool { return lhs.compare(to: rhs) == .orderedDescending } // MARK: - Hashable public func hash(into hasher: inout Hasher) { hasher.combine(description.lowercased()) } // MARK: - ExpressibleByStringLiteral public init(stringLiteral value: StringLiteralType) { try! self.init(validating: value) } } /// Uniquely identifies a package in a scope public struct Name: LosslessStringConvertible, Hashable, Equatable, Comparable, ExpressibleByStringLiteral { public let description: String public init(validating description: String) throws { guard !description.isEmpty else { throw StringError("The minimum length of a package name is 1 character.") } guard description.count <= 100 else { throw StringError("The maximum length of a package name is 100 characters.") } for (index, character) in zip(description.indices, description) { guard character.isASCII, character.isLetter || character.isNumber || character == "-" || character == "_" else { throw StringError("A package name consists of alphanumeric characters, underscores, and hyphens.") } if character.isPunctuation { switch (index, description.index(after: index)) { case (description.startIndex, _): throw StringError("Hyphens and underscores may not occur at the beginning of a name.") case (_, description.endIndex): throw StringError("Hyphens and underscores may not occur at the end of a name.") case (_, let nextIndex) where description[nextIndex].isPunctuation: throw StringError("Hyphens and underscores may not occur consecutively within a name.") default: continue } } } self.description = description } public init?(_ description: String) { guard let name = try? Name(validating: description) else { return nil } self = name } fileprivate init?(_ substring: String.SubSequence?) { guard let substring = substring else { return nil } self.init(String(substring)) } // MARK: - Equatable & Comparable private func compare(to other: Name) -> ComparisonResult { // Package scopes are case-insensitive (for example, `LinkedList` ≍ `LINKEDLIST`). return self.description.caseInsensitiveCompare(other.description) } public static func == (lhs: Name, rhs: Name) -> Bool { return lhs.compare(to: rhs) == .orderedSame } public static func < (lhs: Name, rhs: Name) -> Bool { return lhs.compare(to: rhs) == .orderedAscending } public static func > (lhs: Name, rhs: Name) -> Bool { return lhs.compare(to: rhs) == .orderedDescending } // MARK: - Hashable public func hash(into hasher: inout Hasher) { hasher.combine(description.lowercased()) } // MARK: - ExpressibleByStringLiteral public init(stringLiteral value: StringLiteralType) { try! self.init(validating: value) } } } // MARK: - struct PackageIdentityParser { /// A textual representation of this instance. public let description: String /// Instantiates an instance of the conforming type from a string representation. public init(_ string: String) { self.description = Self.computeDefaultName(fromLocation: string).lowercased() } /// Compute the default name of a package given its URL. public static func computeDefaultName(fromURL url: URL) -> String { Self.computeDefaultName(fromLocation: url.absoluteString) } /// Compute the default name of a package given its path. public static func computeDefaultName(fromPath path: AbsolutePath) -> String { Self.computeDefaultName(fromLocation: path.pathString) } /// Compute the default name of a package given its location. public static func computeDefaultName(fromLocation url: String) -> String { #if os(Windows) let isSeparator : (Character) -> Bool = { $0 == "/" || $0 == "\\" } #else let isSeparator : (Character) -> Bool = { $0 == "/" } #endif // Get the last path component of the URL. // Drop the last character in case it's a trailing slash. var endIndex = url.endIndex if let lastCharacter = url.last, isSeparator(lastCharacter) { endIndex = url.index(before: endIndex) } let separatorIndex = url[..<endIndex].lastIndex(where: isSeparator) let startIndex = separatorIndex.map { url.index(after: $0) } ?? url.startIndex var lastComponent = url[startIndex..<endIndex] // Strip `.git` suffix if present. if lastComponent.hasSuffix(".git") { lastComponent = lastComponent.dropLast(4) } return String(lastComponent) } } /// A canonicalized package location. /// /// A package may declare external packages as dependencies in its manifest. /// Each external package is uniquely identified by the location of its source code. /// /// An external package dependency may itself have one or more external package dependencies, /// known as _transitive dependencies_. /// When multiple packages have dependencies in common, /// Swift Package Manager determines which version of that package should be used /// (if any exist that satisfy all specified requirements) /// in a process called package resolution. /// /// External package dependencies are located by a URL /// (which may be an implicit `file://` URL in the form of a file path). /// For the purposes of package resolution, /// package URLs are case-insensitive (mona ≍ MONA) /// and normalization-insensitive (n + ◌̃ ≍ ñ). /// Swift Package Manager takes additional steps to canonicalize URLs /// to resolve insignificant differences between URLs. /// For example, /// the URLs `https://example.com/Mona/LinkedList` and `[email protected]:mona/linkedlist` /// are equivalent, in that they both resolve to the same source code repository, /// despite having different scheme, authority, and path components. /// /// The `PackageIdentity` type canonicalizes package locations by /// performing the following operations: /// /// * Removing the scheme component, if present /// ``` /// https://example.com/mona/LinkedList → example.com/mona/LinkedList /// ``` /// * Removing the userinfo component (preceded by `@`), if present: /// ``` /// [email protected]/mona/LinkedList → example.com/mona/LinkedList /// ``` /// * Removing the port subcomponent, if present: /// ``` /// example.com:443/mona/LinkedList → example.com/mona/LinkedList /// ``` /// * Replacing the colon (`:`) preceding the path component in "`scp`-style" URLs: /// ``` /// [email protected]:mona/LinkedList.git → example.com/mona/LinkedList /// ``` /// * Expanding the tilde (`~`) to the provided user, if applicable: /// ``` /// ssh://[email protected]/~/LinkedList.git → example.com/~mona/LinkedList /// ``` /// * Removing percent-encoding from the path component, if applicable: /// ``` /// example.com/mona/%F0%9F%94%97List → example.com/mona/🔗List /// ``` /// * Removing the `.git` file extension from the path component, if present: /// ``` /// example.com/mona/LinkedList.git → example.com/mona/LinkedList /// ``` /// * Removing the trailing slash (`/`) in the path component, if present: /// ``` /// example.com/mona/LinkedList/ → example.com/mona/LinkedList /// ``` /// * Removing the fragment component (preceded by `#`), if present: /// ``` /// example.com/mona/LinkedList#installation → example.com/mona/LinkedList /// ``` /// * Removing the query component (preceded by `?`), if present: /// ``` /// example.com/mona/LinkedList?utm_source=forums.swift.org → example.com/mona/LinkedList /// ``` /// * Adding a leading slash (`/`) for `file://` URLs and absolute file paths: /// ``` /// file:///Users/mona/LinkedList → /Users/mona/LinkedList /// ``` public struct CanonicalPackageLocation: Equatable, CustomStringConvertible { /// A textual representation of this instance. public let description: String /// Instantiates an instance of the conforming type from a string representation. public init(_ string: String) { var description = string.precomposedStringWithCanonicalMapping.lowercased() // Remove the scheme component, if present. let detectedScheme = description.dropSchemeComponentPrefixIfPresent() // Remove the userinfo subcomponent (user / password), if present. if case (let user, _)? = description.dropUserinfoSubcomponentPrefixIfPresent() { // If a user was provided, perform tilde expansion, if applicable. description.replaceFirstOccurenceIfPresent(of: "/~/", with: "/~\(user)/") } // Remove the port subcomponent, if present. description.removePortComponentIfPresent() // Remove the fragment component, if present. description.removeFragmentComponentIfPresent() // Remove the query component, if present. description.removeQueryComponentIfPresent() // Accomodate "`scp`-style" SSH URLs if detectedScheme == nil || detectedScheme == "ssh" { description.replaceFirstOccurenceIfPresent(of: ":", before: description.firstIndex(of: "/"), with: "/") } // Split the remaining string into path components, // filtering out empty path components and removing valid percent encodings. var components = description.split(omittingEmptySubsequences: true, whereSeparator: isSeparator) .compactMap { $0.removingPercentEncoding ?? String($0) } // Remove the `.git` suffix from the last path component. var lastPathComponent = components.popLast() ?? "" lastPathComponent.removeSuffixIfPresent(".git") components.append(lastPathComponent) description = components.joined(separator: "/") // Prepend a leading slash for file URLs and paths if detectedScheme == "file" || string.first.flatMap(isSeparator) ?? false { description.insert("/", at: description.startIndex) } self.description = description } } #if os(Windows) fileprivate let isSeparator: (Character) -> Bool = { $0 == "/" || $0 == "\\" } #else fileprivate let isSeparator: (Character) -> Bool = { $0 == "/" } #endif private extension Character { var isDigit: Bool { switch self { case "0", "1", "2", "3", "4", "5", "6", "7", "8", "9": return true default: return false } } var isAllowedInURLScheme: Bool { return isLetter || self.isDigit || self == "+" || self == "-" || self == "." } } private extension String { @discardableResult mutating func removePrefixIfPresent<T: StringProtocol>(_ prefix: T) -> Bool { guard hasPrefix(prefix) else { return false } removeFirst(prefix.count) return true } @discardableResult mutating func removeSuffixIfPresent<T: StringProtocol>(_ suffix: T) -> Bool { guard hasSuffix(suffix) else { return false } removeLast(suffix.count) return true } @discardableResult mutating func dropSchemeComponentPrefixIfPresent() -> String? { if let rangeOfDelimiter = range(of: "://"), self[startIndex].isLetter, self[..<rangeOfDelimiter.lowerBound].allSatisfy({ $0.isAllowedInURLScheme }) { defer { self.removeSubrange(..<rangeOfDelimiter.upperBound) } return String(self[..<rangeOfDelimiter.lowerBound]) } return nil } @discardableResult mutating func dropUserinfoSubcomponentPrefixIfPresent() -> (user: String, password: String?)? { if let indexOfAtSign = firstIndex(of: "@"), let indexOfFirstPathComponent = firstIndex(where: isSeparator), indexOfAtSign < indexOfFirstPathComponent { defer { self.removeSubrange(...indexOfAtSign) } let userinfo = self[..<indexOfAtSign] var components = userinfo.split(separator: ":", maxSplits: 2, omittingEmptySubsequences: false) guard components.count > 0 else { return nil } let user = String(components.removeFirst()) let password = components.last.map(String.init) return (user, password) } return nil } @discardableResult mutating func removePortComponentIfPresent() -> Bool { if let indexOfFirstPathComponent = firstIndex(where: isSeparator), let startIndexOfPort = firstIndex(of: ":"), startIndexOfPort < endIndex, let endIndexOfPort = self[index(after: startIndexOfPort)...].lastIndex(where: { $0.isDigit }), endIndexOfPort <= indexOfFirstPathComponent { self.removeSubrange(startIndexOfPort ... endIndexOfPort) return true } return false } @discardableResult mutating func removeFragmentComponentIfPresent() -> Bool { if let index = firstIndex(of: "#") { self.removeSubrange(index...) } return false } @discardableResult mutating func removeQueryComponentIfPresent() -> Bool { if let index = firstIndex(of: "?") { self.removeSubrange(index...) } return false } @discardableResult mutating func replaceFirstOccurenceIfPresent<T: StringProtocol, U: StringProtocol>( of string: T, before index: Index? = nil, with replacement: U ) -> Bool { guard let range = range(of: string) else { return false } if let index = index, range.lowerBound >= index { return false } self.replaceSubrange(range, with: replacement) return true } }
36.736559
118
0.623494
d74842d3476e77eb1e3d026369b335bdc47c51bf
644
import Foundation import FirebaseAnalytics final class EvtTracker { class func log(evtTitle:String,contentType:String){ FIRAnalytics.logEvent(withName: kFIREventSelectContent, parameters: [ kFIRParameterItemID: "id-\(evtTitle)" as NSObject, kFIRParameterItemName: evtTitle as NSObject, kFIRParameterContentType: "\(contentType)" as NSObject ]) } // custome evts // class func log(){ // FIRAnalytics.logEvent(withName: "share_image", parameters: [ // "name": name as NSObject, // "full_text": text as NSObject // ]) // // } }
25.76
77
0.618012
1a4762c4aa384ebcb792e6a23fd639ff53ed54bd
533
// // AppDelegate.swift // Joplin Clipper // // Created by Christopher Weirup on 2020-02-06. // Copyright © 2020 Christopher Weirup. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ aNotification: Notification) { // Insert code here to initialize your application } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } }
23.173913
71
0.709193
56070a093323f90a23baad554e4ef3a4eaa97d4e
1,872
// // EncodedAttributeTest.swift // JSONAPITests // // Created by Mathew Polzin on 12/21/18. // import Foundation import XCTest @testable import JSONAPI import JSONAPITesting private struct TransformedWrapper<Value: Equatable & Codable, Transform: Transformer>: Codable where Value == Transform.From { let x: TransformedAttribute<Value, Transform> init(x: TransformedAttribute<Value, Transform>) { self.x = x } } private struct Wrapper<Value: Equatable & Codable>: Codable { let x: Attribute<Value> init(x: Attribute<Value>) { self.x = x } } /// This function attempts to just cast to the type, so it only works /// for Attributes of primitive types (primitive to JSON). func testEncodedPrimitive<Value: Equatable & Codable, Transform: Transformer>(attribute: TransformedAttribute<Value, Transform>) { let encodedAttributeData = encoded(value: TransformedWrapper<Value, Transform>(x: attribute)) let wrapperObject = try! JSONSerialization.jsonObject(with: encodedAttributeData, options: []) as! [String: Any] let jsonObject = wrapperObject["x"] guard let jsonAttribute = jsonObject as? Transform.From else { XCTFail("Attribute did not encode to the correct type") return } XCTAssertEqual(attribute.rawValue, jsonAttribute) } /// This function attempts to just cast to the type, so it only works /// for Attributes of primitive types (primitive to JSON). func testEncodedPrimitive<Value: Equatable & Codable>(attribute: Attribute<Value>) { let encodedAttributeData = encoded(value: Wrapper<Value>(x: attribute)) let wrapperObject = try! JSONSerialization.jsonObject(with: encodedAttributeData, options: []) as! [String: Any] let jsonObject = wrapperObject["x"] guard let jsonAttribute = jsonObject as? Value else { XCTFail("Attribute did not encode to the correct type") return } XCTAssertEqual(attribute.value, jsonAttribute) }
32.275862
130
0.758547
38131034e40e2be1f31a5bb1370a15174bb971c9
960
// // BlurRepresentable.swift // HackDavis2020-Pets // // Created by Quentin on 2020/1/19. // Copyright © 2020 iDEX. All rights reserved. // import SwiftUI struct BlurView: UIViewRepresentable { let style: UIBlurEffect.Style func makeUIView(context: UIViewRepresentableContext<BlurView>) -> UIView { let view = UIView(frame: .zero) view.backgroundColor = .clear let blurEffect = UIBlurEffect(style: style) let blurView = UIVisualEffectView(effect: blurEffect) blurView.translatesAutoresizingMaskIntoConstraints = false view.insertSubview(blurView, at: 0) NSLayoutConstraint.activate([ blurView.heightAnchor.constraint(equalTo: view.heightAnchor), blurView.widthAnchor.constraint(equalTo: view.widthAnchor), ]) return view } func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<BlurView>) { } }
29.090909
78
0.675
112229be2c31e045b7f0cbaa90a8c492e16a987e
212
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func a func a( Void case for in a = [Void{
23.555556
87
0.75
89a6e40ef20228d0b33cbe6e7ee69688ddec1e0b
329
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing override func c<T : a { let start = f { } let d<T where g: e: e, g: b() enum S<T : e, g: e : a { protocol C { let d: e, g: c<T where g: Int { " typealias e : d
23.5
87
0.659574
e228dbbdab65201ecfb5228c6f7d50d449cb95a9
1,278
// // 111-MinimumDepthBinaryTree.swift // LeetCode // // Created by 张银龙 on 2019/11/12. // Copyright © 2019 张银龙. All rights reserved. // import Cocoa /* 111. 二叉树的最小深度 给定一个二叉树,找出其最小深度。 最小深度是从根节点到最近叶子节点的最短路径上的节点数量。 说明: 叶子节点是指没有子节点的节点。 示例: 给定二叉树 [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 返回它的最小深度  2. 链接:https://leetcode-cn.com/problems/minimum-depth-of-binary-tree */ class MinimumDepthBinaryTree: NSObject { // 48 ms func minDepth(_ root: TreeNode?) -> Int { if (root == nil) { return 0 } if root?.left == nil, root?.right == nil { return 1 } var depth = Int.max if root?.left != nil { depth = min(minDepth(root?.left), depth) } if root?.right != nil { depth = min(minDepth(root?.right), depth) } return depth + 1 } // 48 ms func minDepth_2(_ root: TreeNode?) -> Int { if root == nil { return 0 } if root?.left == nil { return minDepth(root?.right) + 1 } if root?.right == nil { return minDepth(root?.left) + 1 } return min(minDepth(root?.left), minDepth(root?.right)) + 1 } }
18.794118
67
0.513302
d91c6a205a2a45c68020ad5692923f28fd2282b5
813
// // Activity 2-Generic Queue.playground // Packt Progressional Swift Courseware // // Created by [email protected] on 8/17/17. // import UIKit struct Queue<Member> { var members : [Member] = [] mutating func add(member: Member) { members.append(member) } mutating func remove() -> Member? { if let topItem = members.first { members.remove(at: 0) return topItem } return nil } } struct Employee { var name: String var salary: Double } var q = Queue<Employee>() q.add(member: Employee(name: "John Smith", salary: 50_000.0)) q.add(member: Employee(name: "Alan Stirk", salary: 55_000.0)) q.add(member: Employee(name: "Mary Adams", salary: 60_000.0)) for _ in 1...4 { print(q.remove() ?? "Empty Queue") }
21.394737
61
0.617466
e645242d76df67c2b8559bbffd79da046ced22ec
6,479
// // FormValidatorTests.swift // DevKitTests // // Created by Stanle De La Cruz on 12/5/18. // Copyright © 2018 Prolific Interactive. All rights reserved. // import XCTest @testable import DevKit class FormValidatorTests: XCTestCase { var sut = FormValidator() // MARK:- Email func testValid_Email() { let email = "[email protected]" let valid = sut.isValid(email) XCTAssertTrue(valid) } func testInvalid_Email() { let email = "hellogmail.com" let valid = sut.isValid(email) XCTAssertFalse(valid) } // MARK:- Email and Password with Validation type. func testValidForm_WithEmailAndPassword_Validators() { let email = "[email protected]" let password = "hello123" let validators: [ValidationType] = [.numbers(count: 2)] let valid = sut.isValid(email, password: password, validators: validators) XCTAssertTrue(valid) } func testInvalidForm_WithEmailAndPassword_Validators() { let email = "hiiii" let password = "hello123" let validators: [ValidationType] = [.numbers(count: 2)] let valid = sut.isValid(email, password: password, validators: validators) XCTAssertFalse(valid) } func testValidForm_WithEmailAndPassword_WithRegexCode() { let email = "[email protected]" let password = "hello123!A" let code = "^(?=.*[a-z])(?=.*[0-9])(?=.*[A-Z])(?=.*[!@#$&*]).{1,}$" let valid = sut.isValid(email, password: password, passwordRegex: code) XCTAssertTrue(valid) } func testInvalidForm_WithEmailAndPassword_WithRegexCode() { let email = "hiiii" let password = "hello123" let code = "^(?=.*[a-z])(?=.*[0-9])(?=.*[A-Z])(?=.*[!@#$&*]).{1,}$" let valid = sut.isValid(email, password: password, passwordRegex: code) XCTAssertFalse(valid) } // MARK:- Email, Password and confirmation password with Validation types. func testValidForm_WithEmailAndPasswordAndConfirmationPassword_WithValidationType() { let email = "[email protected]" let password = "hello123!A" let confirmationPassword = "hello123!A" let validators: [ValidationType] = [.numbers(count: 1), .lowercasedLetters(count: 1)] let valid = sut.isValid(email, password: password, confirmationPassword: confirmationPassword, validators: validators) XCTAssertTrue(valid) } func testInValidForm_WithEmailAndPasswordAndConfirmationPassword_WithValidationType() { let email = "[email protected]" let password = "hello123!A" let confirmationPassword = "hello123!ZZZZZZ" let validators: [ValidationType] = [.numbers(count: 1), .lowercasedLetters(count: 1)] let valid = sut.isValid(email, password: password, confirmationPassword: confirmationPassword, validators: validators) XCTAssertFalse(valid) } // MARK:- Email, Password and confirmation password with Regex code. func testValidForm_WithEmailAndPasswordAndConfirmationPassword_WithRegexCode() { let email = "[email protected]" let password = "hello123!A" let confirmationPassword = "hello123!A" let code = "^(?=.*[a-z])(?=.*[0-9])(?=.*[A-Z])(?=.*[!@#$&*]).{1,}$" let valid = sut.isValid(email, password: password, confirmationPassword: confirmationPassword, passwordRegex: code) XCTAssertTrue(valid) } func testInValidForm_WithEmailAndPasswordAndConfirmationPassword_WithRegexCode() { let email = "[email protected]" let password = "hello123!A" let confirmationPassword = "hello123!ZZZZZZ" let code = "^(?=.*[a-z])(?=.*[0-9])(?=.*[A-Z])(?=.*[!@#$&*]).{1,}$" let valid = sut.isValid(email, password: password, confirmationPassword: confirmationPassword, passwordRegex: code) XCTAssertFalse(valid) } // MARK:- Password with Validation type. func testValidPassword_WithValidationType() { let password = "h2ss1" let validators: [ValidationType] = [.lowercasedLetters(count: 1)] let valid = sut.isValid(password, validators: validators) XCTAssertTrue(valid) } func testInvalidPassword_WithValidationType() { let password = "12345!!" let validators: [ValidationType] = [.lowercasedLetters(count: 1)] let valid = sut.isValid(password, validators: validators) XCTAssertFalse(valid) } func testValidPassword_WithValidationType_MinCharacters() { let password = "h2ss1" let validators: [ValidationType] = [.minCharacters(count: 1)] let valid = sut.isValid(password, validators: validators) XCTAssertTrue(valid) } func testInValidPassword_WithValidationType_MinCharacters() { let password = "h2ss1" let validators: [ValidationType] = [.minCharacters(count: password.count + 1)] let valid = sut.isValid(password, validators: validators) XCTAssertFalse(valid) } func testValidPassword_WithValidationType_EmptyValidator() { let password = "h2ss1" let validators: [ValidationType] = [] let valid = sut.isValid(password, validators: validators) XCTAssertTrue(valid) } func testInValidPassword_WithValidationType_EmptyValidator() { let password = "" let validators: [ValidationType] = [] let valid = sut.isValid(password, validators: validators) XCTAssertFalse(valid) } // MARK:- Password with Regex code. func testValidPassword_WithRegexCode() { let password = "h2A!" let code = "^(?=.*[a-z])(?=.*[0-9])(?=.*[A-Z])(?=.*[!@#$&*]).{1,}$" let valid = sut.isValid(password, passwordRegex: code) XCTAssertTrue(valid) } func testInvalidPassword_WithRegexCode() { let password = "h2A" let code = "^(?=.*[a-z])(?=.*[0-9])(?=.*[A-Z])(?=.*[!@#$&*]).{1,}$" let valid = sut.isValid(password, passwordRegex: code) XCTAssertFalse(valid) } }
35.021622
123
0.596543
75965aea292736d57072c4f2dd2051fd29948860
8,034
import Foundation import CocoaAsyncSocket /// The TCP socket build upon `GCDAsyncSocket`. /// /// - warning: This class is not thread-safe. open class GCDTCPSocket: NSObject, GCDAsyncSocketDelegate, RawTCPSocketProtocol { fileprivate let socket: GCDAsyncSocket fileprivate var enableTLS: Bool = false fileprivate var host: String? /** Initailize an instance with `GCDAsyncSocket`. - parameter socket: The socket object to work with. If this is `nil`, then a new `GCDAsyncSocket` instance is created. */ public init(socket: GCDAsyncSocket? = nil) { if let socket = socket { self.socket = socket self.socket.setDelegate(nil, delegateQueue: QueueFactory.getQueue()) } else { self.socket = GCDAsyncSocket(delegate: nil, delegateQueue: QueueFactory.getQueue(), socketQueue: QueueFactory.getQueue()) } super.init() self.socket.synchronouslySetDelegate(self) } // MARK: RawTCPSocketProtocol implementation /// The `RawTCPSocketDelegate` instance. weak open var delegate: RawTCPSocketDelegate? /// If the socket is connected. open var isConnected: Bool { return !socket.isDisconnected } /// The source address. open var sourceIPAddress: IPAddress? { guard let localHost = socket.localHost else { return nil } return IPAddress(fromString: localHost) } /// The source port. open var sourcePort: Port? { return Port(port: socket.localPort) } /// The destination address. /// /// - note: Always returns `nil`. open var destinationIPAddress: IPAddress? { return nil } /// The destination port. /// /// - note: Always returns `nil`. open var destinationPort: Port? { return nil } /** Connect to remote host. - parameter host: Remote host. - parameter port: Remote port. - parameter enableTLS: Should TLS be enabled. - parameter tlsSettings: The settings of TLS. - throws: The error occured when connecting to host. */ open func connectTo(host: String, port: Int, enableTLS: Bool = false, tlsSettings: [AnyHashable: Any]? = nil) throws { self.host = host try connectTo(host: host, withPort: port) self.enableTLS = enableTLS if enableTLS { startTLSWith(settings: tlsSettings) } } /** Disconnect the socket. The socket will disconnect elegantly after any queued writing data are successfully sent. */ open func disconnect() { socket.disconnectAfterWriting() } /** Disconnect the socket immediately. */ open func forceDisconnect() { socket.disconnect() } /** Send data to remote. - parameter data: Data to send. - warning: This should only be called after the last write is finished, i.e., `delegate?.didWriteData()` is called. */ open func write(data: Data) { write(data: data, withTimeout: -1) } /** Read data from the socket. - warning: This should only be called after the last read is finished, i.e., `delegate?.didReadData()` is called. */ open func readData() { socket.readData(withTimeout: -1, tag: 0) } /** Read specific length of data from the socket. - parameter length: The length of the data to read. - warning: This should only be called after the last read is finished, i.e., `delegate?.didReadData()` is called. */ open func readDataTo(length: Int) { readDataTo(length: length, withTimeout: -1) } /** Read data until a specific pattern (including the pattern). - parameter data: The pattern. - warning: This should only be called after the last read is finished, i.e., `delegate?.didReadData()` is called. */ open func readDataTo(data: Data) { readDataTo(data: data, maxLength: 0) } /** Read data until a specific pattern (including the pattern). - parameter data: The pattern. - parameter maxLength: Ignored since `GCDAsyncSocket` does not support this. The max length of data to scan for the pattern. - warning: This should only be called after the last read is finished, i.e., `delegate?.didReadData()` is called. */ open func readDataTo(data: Data, maxLength: Int) { readDataTo(data: data, withTimeout: -1) } // MARK: Other helper methods /** Send data to remote. - parameter data: Data to send. - parameter timeout: Operation timeout. - warning: This should only be called after the last write is finished, i.e., `delegate?.didWriteData()` is called. */ func write(data: Data, withTimeout timeout: Double) { guard data.count > 0 else { QueueFactory.getQueue().async { self.delegate?.didWrite(data: data, by: self) } return } socket.write(data, withTimeout: timeout, tag: 0) } /** Read specific length of data from the socket. - parameter length: The length of the data to read. - parameter timeout: Operation timeout. - warning: This should only be called after the last read is finished, i.e., `delegate?.didReadData()` is called. */ func readDataTo(length: Int, withTimeout timeout: Double) { socket.readData(toLength: UInt(length), withTimeout: timeout, tag: 0) } /** Read data until a specific pattern (including the pattern). - parameter data: The pattern. - parameter timeout: Operation timeout. - warning: This should only be called after the last read is finished, i.e., `delegate?.didReadData()` is called. */ func readDataTo(data: Data, withTimeout timeout: Double) { socket.readData(to: data, withTimeout: timeout, tag: 0) } /** Connect to remote host. - parameter host: Remote host. - parameter port: Remote port. - throws: The error occured when connecting to host. */ func connectTo(host: String, withPort port: Int) throws { try socket.connect(toHost: host, onPort: UInt16(port)) } /** Secures the connection using SSL/TLS. - parameter tlsSettings: TLS settings, refer to documents of `GCDAsyncSocket` for detail. */ func startTLSWith(settings: [AnyHashable: Any]!) { if let settings = settings as? [String: NSObject] { socket.startTLS(ensureSendPeerName(tlsSettings: settings)) } else { socket.startTLS(ensureSendPeerName(tlsSettings: nil)) } } // MARK: Delegate methods for GCDAsyncSocket open func socket(_ sock: GCDAsyncSocket, didWriteDataWithTag tag: Int) { delegate?.didWrite(data: nil, by: self) } open func socket(_ sock: GCDAsyncSocket, didRead data: Data, withTag tag: Int) { delegate?.didRead(data: data, from: self) } open func socketDidDisconnect(_ socket: GCDAsyncSocket, withError err: Error?) { delegate?.didDisconnectWith(socket: self) delegate = nil socket.setDelegate(nil, delegateQueue: nil) } open func socket(_ sock: GCDAsyncSocket, didConnectToHost host: String, port: UInt16) { if !enableTLS { delegate?.didConnectWith(socket: self) } } open func socketDidSecure(_ sock: GCDAsyncSocket) { if enableTLS { delegate?.didConnectWith(socket: self) } } private func ensureSendPeerName(tlsSettings: [String: NSObject]? = nil) -> [String: NSObject] { var setting = tlsSettings ?? [:] guard setting[kCFStreamSSLPeerName as String] == nil else { return setting } setting[kCFStreamSSLPeerName as String] = host! as NSString setting[(kCFStreamSSLValidatesCertificateChain as String)] = Int(truncating: false) as NSObject return setting } }
31.382813
133
0.632437
9cc46cef44d0131225f29850a952379b1ceab5e6
3,789
// // ToolmenuViewController.swift // DevToys // // Created by yuki on 2022/01/29. // import CoreUtil final class ToolmenuViewController: NSViewController { private let scrollView = NSScrollView() private let outlineView = NSOutlineView.list() private var searchQuery = Query() { didSet { outlineView.reloadData() } } @objc func onClick(_ outlineView: NSOutlineView) { self.onSelect(row: outlineView.clickedRow) } private func onSelect(row: Int) { guard let tool = outlineView.item(atRow: row) as? Tool else { return } self.appModel.tool = tool } override func loadView() { self.view = scrollView self.scrollView.drawsBackground = false self.scrollView.documentView = outlineView self.outlineView.setTarget(self, action: #selector(onClick)) self.outlineView.outlineTableColumn = self.outlineView.tableColumns[0] self.outlineView.selectionHighlightStyle = .sourceList self.outlineView.indentationPerLevel = 4 } override func chainObjectDidLoad() { self.appModel.$searchQuery .sink{[unowned self] in self.searchQuery = Query($0) }.store(in: &objectBag) // Datasource uses chainObject, call it in `chainObjectDidLoad` self.outlineView.delegate = self self.outlineView.dataSource = self self.outlineView.autosaveExpandedItems = true self.outlineView.autosaveName = "sidebar" } } extension ToolmenuViewController: NSOutlineViewDataSource { func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool { item is ToolCategory } func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any { if item == nil { return appModel.toolManager.flattenRootItems(searchQuery)[index] } guard let category = item as? ToolCategory else { return () } return appModel.toolManager.toolsForCategory(category, searchQuery)[index] } func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int { if item == nil { return appModel.toolManager.flattenRootItems(searchQuery).count } guard let category = item as? ToolCategory else { return 0 } return appModel.toolManager.toolsForCategory(category, searchQuery).count } public func outlineView(_ outlineView: NSOutlineView, heightOfRowByItem item: Any) -> CGFloat { return ToolmenuCell.height } public func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? { let cell = ToolmenuCell() if let category = item as? ToolCategory { cell.title = category.name cell.icon = category.icon } else if let tool = item as? Tool { cell.title = tool.sidebarTitle cell.icon = tool.icon } return cell } func outlineView(_ outlineView: NSOutlineView, persistentObjectForItem item: Any?) -> Any? { if let category = item as? ToolCategory { return category.identifier } else if let tool = item as? Tool { return tool.identifier } return nil } func outlineView(_ outlineView: NSOutlineView, itemForPersistentObject object: Any) -> Any? { guard let identifier = object as? String else { return nil } return appModel.toolManager.toolForIdentifier(identifier) ?? appModel.toolManager.categoryForIdentifier(identifier) } } extension ToolmenuViewController: NSOutlineViewDelegate { func outlineViewSelectionDidChange(_ notification: Notification) { self.onSelect(row: outlineView.selectedRow) } }
38.272727
123
0.670362
79e73f316db3874abaeb506fff0b1e112c76d856
2,375
// // LXMToolFunction.swift // Todo // // Created by edison on 2019/4/25. // Copyright © 2019年 EDC. All rights reserved. // import Foundation import UIKit func DLog(_ message: String, function: String = #function, line: Int = #line, file: String = #file) -> Void { #if DEBUG let tempArray = file.components(separatedBy: "/") let fileName = tempArray.last! let string = "file: \(fileName) line: \(line) func: \(function) log:\(message)" ConsoleInfoString += "\n" + string + "\n" NSLog(string) #endif } func delay(_ delay: Double, closure: @escaping ()->()) { DispatchQueue.main.asyncAfter( deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure) } /** 截取当前屏幕的某个区域为一个image */ func imageFromScreenshotWithRect(_ rect: CGRect) -> UIImage? { if let window = UIApplication.shared.delegate?.window { UIGraphicsBeginImageContextWithOptions(rect.size, false, 0) let targetRect = CGRect(x: -rect.origin.x, y: -rect.origin.y, width: kLXMScreenWidth, height: kLXMScreenHeight) window!.drawHierarchy(in: targetRect, afterScreenUpdates: false) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } else { return nil } } /** 把秒转换为时分秒的格式 */ func timeDurationFromSeconds(_ seconds: TimeInterval) -> String { let datecomponents = DateComponents() if let date = Calendar.current.date(from: datecomponents) { let timeInterval = date.timeIntervalSince1970 + seconds let newDate = Date(timeIntervalSince1970: timeInterval) let dateFormatter = DateFormatter() dateFormatter.dateFormat = "HH:mm:ss" return dateFormatter.string(from: newDate) } else { return "" } } extension UIColor { static func LXMColor(_ r: Int, g: Int, b: Int, a: Float) -> UIColor { return UIColor(red: CGFloat(r)/255.0, green: CGFloat(g)/255.0, blue: CGFloat(b)/255.0, alpha: CGFloat(a)) } static func LXMColorFromHex(_ hexRGBValue: Int) -> UIColor { let red = (hexRGBValue & 0xFF0000) >> 16 let green = (hexRGBValue & 0xFF00) >> 8 let blue = (hexRGBValue & 0xFF) return LXMColor(red, g: green, b: blue, a: 1.0) } }
28.27381
124
0.640421
fcec413614ac960850d45a105c12e596dea26940
1,294
// // TokenSyncViewController.swift // Apollo // // Created by Khaos Tian on 10/28/18. // Copyright © 2018 Oltica. All rights reserved. // import UIKit class TokenSyncViewController: StepViewController { override func viewDidLoad() { super.viewDidLoad() navigationItem.hidesBackButton = true heroImageView.image = UIImage(named: "Watch-Setup") titleLabel.text = "Almost there" descriptionLabel.text = "Please open Apollo on your Apple Watch to complete the setup." setupNotifications() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) WatchCommunicationManager.shared.start() } } // MARK: - Notification extension TokenSyncViewController { private func setupNotifications() { NotificationCenter.default.addObserver(self, selector: #selector(handleSyncCompleteNotification(_:)), name: .configurationSyncComplete, object: nil) } @objc private func handleSyncCompleteNotification(_ notification: Notification) { DispatchQueue.main.async { let viewController = SetupCompleteViewController() self.navigationController?.setViewControllers([viewController], animated: true) } } }
28.130435
156
0.683153
1c59dfe9ad4411bbcad4e2e3e564ef4e10e9577f
5,842
// // Generated by SwagGen // https://github.com/yonaskolb/SwagGen // // Template used API+CLI // https://github.com/csjones/SwagGen-templates // import Foundation extension Bitrise.AppleApiCredentials { /** List Apple API credentials for a specific user List Apple API credentials for a specific Bitrise user */ public enum AppleApiCredentialList { public static let service = APIService<Response>(id: "apple-api-credential-list", tag: "apple-api-credentials", method: "GET", path: "/users/{user-slug}/apple-api-credentials", hasBody: false, securityRequirement: SecurityRequirement(type: "PersonalAccessToken", scopes: [])) public final class Request: APIRequest<Response> { public struct Options { /** User slug */ public var userSlug: String public init(userSlug: String) { self.userSlug = userSlug } } public var options: Options public init(options: Options) { self.options = options super.init(service: AppleApiCredentialList.service) } /// convenience initialiser so an Option doesn't have to be created public convenience init(userSlug: String) { let options = Options(userSlug: userSlug) self.init(options: options) } public override var path: String { return super.path.replacingOccurrences(of: "{" + "user-slug" + "}", with: "\(self.options.userSlug)") } } public enum Response: APIResponseValue, SingleFailureType, CustomStringConvertible, CustomDebugStringConvertible { public typealias SuccessType = V0AppleAPICredentialsListResponse /** OK */ case status200(V0AppleAPICredentialsListResponse) /** Bad Request */ case status400(ServiceStandardErrorRespModel) /** Unauthorized */ case status401(ServiceStandardErrorRespModel) /** Not Found */ case status404(ServiceStandardErrorRespModel) /** Internal Server Error */ case status500(ServiceStandardErrorRespModel) public var success: V0AppleAPICredentialsListResponse? { switch self { case .status200(let response): return response default: return nil } } public var failure: ServiceStandardErrorRespModel? { switch self { case .status400(let response): return response case .status401(let response): return response case .status404(let response): return response case .status500(let response): return response default: return nil } } /// either success or failure value. Success is anything in the 200..<300 status code range public var responseResult: APIResponseResult<V0AppleAPICredentialsListResponse, ServiceStandardErrorRespModel> { if let successValue = success { return .success(successValue) } else if let failureValue = failure { return .failure(failureValue) } else { fatalError("Response does not have success or failure response") } } public var response: Any { switch self { case .status200(let response): return response case .status400(let response): return response case .status401(let response): return response case .status404(let response): return response case .status500(let response): return response } } public var statusCode: Int { switch self { case .status200: return 200 case .status400: return 400 case .status401: return 401 case .status404: return 404 case .status500: return 500 } } public var successful: Bool { switch self { case .status200: return true case .status400: return false case .status401: return false case .status404: return false case .status500: return false } } public init(statusCode: Int, data: Data, decoder: ResponseDecoder) throws { switch statusCode { case 200: self = try .status200(decoder.decode(V0AppleAPICredentialsListResponse.self, from: data)) case 400: self = try .status400(decoder.decode(ServiceStandardErrorRespModel.self, from: data)) case 401: self = try .status401(decoder.decode(ServiceStandardErrorRespModel.self, from: data)) case 404: self = try .status404(decoder.decode(ServiceStandardErrorRespModel.self, from: data)) case 500: self = try .status500(decoder.decode(ServiceStandardErrorRespModel.self, from: data)) default: throw APIClientError.unexpectedStatusCode(statusCode: statusCode, data: data) } } public var description: String { return "\(statusCode) \(successful ? "success" : "failure")" } public var debugDescription: String { var string = description let responseString = "\(response)" if responseString != "()" { string += "\n\(responseString)" } return string } } } }
37.935065
283
0.564875
f4ae99cac9897e87519b3cd9f76f3e3d9847e70e
2,084
// RUN: %target-swift-emit-silgen -enable-sil-ownership -enforce-exclusivity=checked %s | %FileCheck %s class C {} struct A {} struct B { var owner: C } var a = A() // CHECK-LABEL: sil @main : $@convention(c) (Int32, UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>) -> Int32 { // CHECK: assign {{%.*}} to {{%.*}} : $*A // CHECK: destroy_value {{%.*}} : $B // CHECK: } // end sil function 'main' (a, _) = (A(), B(owner: C())) class D { var child: C = C() } // Verify that the LHS is formally evaluated before the RHS. // CHECK-LABEL: sil hidden @$S10assignment5test1yyF : $@convention(thin) () -> () { func test1() { // CHECK: [[T0:%.*]] = metatype $@thick D.Type // CHECK: [[CTOR:%.*]] = function_ref @$S10assignment1DC{{[_0-9a-zA-Z]*}}fC // CHECK: [[D:%.*]] = apply [[CTOR]]([[T0]]) // CHECK: [[BORROWED_D:%.*]] = begin_borrow [[D]] // CHECK: [[T0:%.*]] = metatype $@thick C.Type // CHECK: [[CTOR:%.*]] = function_ref @$S10assignment1CC{{[_0-9a-zA-Z]*}}fC // CHECK: [[C:%.*]] = apply [[CTOR]]([[T0]]) : $@convention(method) (@thick C.Type) -> @owned C // CHECK: [[SETTER:%.*]] = class_method [[BORROWED_D]] : $D, #D.child!setter.1 // CHECK: apply [[SETTER]]([[C]], [[BORROWED_D]]) // CHECK: end_borrow [[BORROWED_D]] // CHECK: destroy_value [[D]] D().child = C() } // rdar://32039566 protocol P { var left: Int {get set} var right: Int {get set} } // Verify that the access to the LHS does not begin until after the // RHS is formally evaluated. // CHECK-LABEL: sil hidden @$S10assignment15copyRightToLeft1pyAA1P_pz_tF : $@convention(thin) (@inout P) -> () { func copyRightToLeft(p: inout P) { // CHECK: bb0(%0 : @trivial $*P): // CHECK: [[READ:%.*]] = begin_access [read] [unknown] %0 : $*P // CHECK: [[READ_OPEN:%.*]] = open_existential_addr immutable_access [[READ]] // CHECK: end_access [[READ]] : $*P // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 : $*P // CHECK: [[WRITE_OPEN:%.*]] = open_existential_addr mutable_access [[WRITE]] // CHECK: end_access [[WRITE]] : $*P p.left = p.right }
38.592593
122
0.595969
879fa6b46e254bbe0c250ad8b2c938881acb9be7
1,482
// // ManagedOrder+CoreDataProperties.swift // CleanStore // // Created by Raymond Law on 2/13/19. // Copyright © 2019 Clean Swift LLC. All rights reserved. // // import Foundation import CoreData extension ManagedOrder { @nonobjc public class func fetchRequest() -> NSFetchRequest<ManagedOrder> { return NSFetchRequest<ManagedOrder>(entityName: "ManagedOrder") } @NSManaged public var billingAddressCity: String? @NSManaged public var billingAddressState: String? @NSManaged public var billingAddressStreet1: String? @NSManaged public var billingAddressStreet2: String? @NSManaged public var billingAddressZIP: String? @NSManaged public var date: Date? @NSManaged public var email: String? @NSManaged public var firstName: String? @NSManaged public var id: String? @NSManaged public var lastName: String? @NSManaged public var paymentMethodCreditCardNumber: String? @NSManaged public var paymentMethodCVV: String? @NSManaged public var paymentMethodExpirationDate: Date? @NSManaged public var phone: String? @NSManaged public var shipmentAddressCity: String? @NSManaged public var shipmentAddressState: String? @NSManaged public var shipmentAddressStreet1: String? @NSManaged public var shipmentAddressStreet2: String? @NSManaged public var shipmentAddressZIP: String? @NSManaged public var shipmentMethodSpeed: NSNumber? @NSManaged public var total: NSDecimalNumber? }
35.285714
77
0.753036
ddc13b531f86dac74162fde61eb567a46bb6e171
1,395
// ---------------------------------------------------------------------------- // // CheckTests.NotValid.swift // // @author Alexander Bragin <[email protected]> // @copyright Copyright (c) 2017, Roxie Mobile Ltd. All rights reserved. // @link https://www.roxiemobile.com/ // // ---------------------------------------------------------------------------- @testable import SwiftCommonsDiagnostics import SwiftCommonsAbstractions import SwiftCommonsData import XCTest // ---------------------------------------------------------------------------- extension CheckTests { // MARK: - Tests func testNotValid() { let method = "Check.notValid" let validObject: Validatable = ValidModel() let notValidObject: Validatable = NotValidModel() checkThrowsError(method) { try Check.notValid(validObject) } checkNotThrowsError(method) { try Check.notValid(notValidObject) } } func testNotValidModel() { let method = "Check.notValid" var parking: ParkingModel? if let jsonObject = loadJson("test_parking_model_with_one_non_valid_vehicle_in_array") { checkThrowsError("\(method)_Model", errorType: JsonSyntaxError.self) { parking = try ParkingModel(from: jsonObject) } } XCTAssertNil(parking) } }
26.826923
96
0.534767
3998f687bfa6ee5814be49c9abe36f150a02be5a
25,062
import Quick import Moya import ReactiveSwift import Nimble import Foundation private func signalSendingData(_ data: Data, statusCode: Int = 200) -> SignalProducer<Response, MoyaError> { return SignalProducer(value: Response(statusCode: statusCode, data: data as Data, response: nil)) } final class SignalProducerMoyaSpec: QuickSpec { override func spec() { describe("status codes filtering") { it("filters out unrequested status codes closed range upperbound") { let data = Data() let signal = signalSendingData(data, statusCode: 10) var errored = false signal.filter(statusCodes: 0...9).startWithResult { event in switch event { case .success(let object): fail("called on non-correct status code: \(object)") case .failure: errored = true } } expect(errored).to(beTruthy()) } it("filters out unrequested status codes closed range lowerbound") { let data = Data() let signal = signalSendingData(data, statusCode: -1) var errored = false signal.filter(statusCodes: 0...9).startWithResult { event in switch event { case .success(let object): fail("called on non-correct status code: \(object)") case .failure: errored = true } } expect(errored).to(beTruthy()) } it("filters out unrequested status codes range upperbound") { let data = Data() let signal = signalSendingData(data, statusCode: 10) var errored = false signal.filter(statusCodes: 0..<10).startWithResult { event in switch event { case .success(let object): fail("called on non-correct status code: \(object)") case .failure: errored = true } } expect(errored).to(beTruthy()) } it("filters out unrequested status codes range lowerbound") { let data = Data() let signal = signalSendingData(data, statusCode: -1) var errored = false signal.filter(statusCodes: 0..<10).startWithResult { event in switch event { case .success(let object): fail("called on non-correct status code: \(object)") case .failure: errored = true } } expect(errored).to(beTruthy()) } it("filters out non-successful status codes") { let data = Data() let signal = signalSendingData(data, statusCode: 404) var errored = false signal.filterSuccessfulStatusCodes().startWithResult { result in switch result { case .success(let object): fail("called on non-success status code: \(object)") case .failure: errored = true } } expect(errored).to(beTruthy()) } it("passes through correct status codes") { let data = Data() let signal = signalSendingData(data) var called = false signal.filterSuccessfulStatusCodes().startWithResult { _ in called = true } expect(called).to(beTruthy()) } it("filters out non-successful status and redirect codes") { let data = Data() let signal = signalSendingData(data, statusCode: 404) var errored = false signal.filterSuccessfulStatusAndRedirectCodes().startWithResult { result in switch result { case .success(let object): fail("called on non-success status code: \(object)") case .failure: errored = true } } expect(errored).to(beTruthy()) } it("passes through correct status codes") { let data = Data() let signal = signalSendingData(data) var called = false signal.filterSuccessfulStatusAndRedirectCodes().startWithResult { _ in called = true } expect(called).to(beTruthy()) } it("passes through correct redirect codes") { let data = Data() let signal = signalSendingData(data, statusCode: 304) var called = false signal.filterSuccessfulStatusAndRedirectCodes().startWithResult { _ in called = true } expect(called).to(beTruthy()) } it("knows how to filter individual status codes") { let data = Data() let signal = signalSendingData(data, statusCode: 42) var called = false signal.filter(statusCode: 42).startWithResult { _ in called = true } expect(called).to(beTruthy()) } it("filters out different individual status code") { let data = Data() let signal = signalSendingData(data, statusCode: 43) var errored = false signal.filter(statusCode: 42).startWithResult { result in switch result { case .success(let object): fail("called on non-success status code: \(object)") case .failure: errored = true } } expect(errored).to(beTruthy()) } } describe("image maping") { it("maps data representing an image to an image") { let image = Image.testImage let data = image.asJPEGRepresentation(0.75) let signal = signalSendingData(data!) var size: CGSize? signal.mapImage().startWithResult { _ in size = image.size } expect(size).to(equal(image.size)) } it("ignores invalid data") { let data = Data() let signal = signalSendingData(data) var receivedError: MoyaError? signal.mapImage().startWithResult { result in switch result { case .success: fail("next called for invalid data") case .failure(let error): receivedError = error } } expect(receivedError).toNot(beNil()) let expectedError = MoyaError.imageMapping(Response(statusCode: 200, data: Data(), response: nil)) expect(receivedError).to(beOfSameErrorType(expectedError)) } } describe("JSON mapping") { it("maps data representing some JSON to that JSON") { let json = ["name": "John Crighton", "occupation": "Astronaut"] let data = try! JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) let signal = signalSendingData(data) var receivedJSON: [String: String]? signal.mapJSON().startWithResult { result in if case .success(let response) = result, let json = response as? [String: String] { receivedJSON = json } } expect(receivedJSON?["name"]).to(equal(json["name"])) expect(receivedJSON?["occupation"]).to(equal(json["occupation"])) } it("returns a Cocoa error domain for invalid JSON") { let json = "{ \"name\": \"john }" let data = json.data(using: String.Encoding.utf8) let signal = signalSendingData(data!) var receivedError: MoyaError? signal.mapJSON().startWithResult { result in switch result { case .success: fail("next called for invalid data") case .failure(let error): receivedError = error } } expect(receivedError).toNot(beNil()) switch receivedError { case .some(.jsonMapping): break default: fail("expected NSError with \(NSCocoaErrorDomain) domain") } } } describe("string mapping") { it("maps data representing a string to a string") { let string = "You have the rights to the remains of a silent attorney." let data = string.data(using: String.Encoding.utf8) let signal = signalSendingData(data!) var receivedString: String? signal.mapString().startWithResult { result in receivedString = try? result.get() } expect(receivedString).to(equal(string)) } it("maps data representing a string at a key path to a string") { let string = "You have the rights to the remains of a silent attorney." let json = ["words_to_live_by": string] let data = try! JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) let signal = signalSendingData(data) var receivedString: String? signal.mapString(atKeyPath: "words_to_live_by").startWithResult { result in receivedString = try? result.get() } expect(receivedString).to(equal(string)) } it("ignores invalid data") { let data = Data(bytes: [0x11FFFF] as [UInt32], count: 1) //Byte exceeding UTF8 let signal = signalSendingData(data as Data) var receivedError: MoyaError? signal.mapString().startWithResult { result in switch result { case .success: fail("next called for invalid data") case .failure(let error): receivedError = error } } expect(receivedError).toNot(beNil()) let expectedError = MoyaError.stringMapping(Response(statusCode: 200, data: Data(), response: nil)) expect(receivedError).to(beOfSameErrorType(expectedError)) } } describe("object mapping") { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss" let decoder = JSONDecoder() decoder.dateDecodingStrategy = .formatted(formatter) let json: [String: Any] = [ "title": "Hello, Moya!", "createdAt": "1995-01-14T12:34:56" ] it("maps data representing a json to a decodable object") { guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else { preconditionFailure("Failed creating Data from JSON dictionary") } let signal = signalSendingData(data) var receivedObject: Issue? _ = signal.map(Issue.self, using: decoder).startWithResult { result in receivedObject = try? result.get() } expect(receivedObject).notTo(beNil()) expect(receivedObject?.title) == "Hello, Moya!" expect(receivedObject?.createdAt) == formatter.date(from: "1995-01-14T12:34:56")! } it("maps data representing a json array to an array of decodable objects") { let jsonArray = [json, json, json] guard let data = try? JSONSerialization.data(withJSONObject: jsonArray, options: .prettyPrinted) else { preconditionFailure("Failed creating Data from JSON dictionary") } let signal = signalSendingData(data) var receivedObjects: [Issue]? _ = signal.map([Issue].self, using: decoder).startWithResult { result in receivedObjects = try? result.get() } expect(receivedObjects).notTo(beNil()) expect(receivedObjects?.count) == 3 expect(receivedObjects?.map { $0.title }) == ["Hello, Moya!", "Hello, Moya!", "Hello, Moya!"] } it("maps empty data to a decodable object with optional properties") { let signal = signalSendingData(Data()) var receivedObjects: OptionalIssue? _ = signal.map(OptionalIssue.self, using: decoder, failsOnEmptyData: false).startWithResult { result in receivedObjects = try? result.get() } expect(receivedObjects).notTo(beNil()) expect(receivedObjects?.title).to(beNil()) expect(receivedObjects?.createdAt).to(beNil()) } it("maps empty data to a decodable array with optional properties") { let signal = signalSendingData(Data()) var receivedObjects: [OptionalIssue]? _ = signal.map([OptionalIssue].self, using: decoder, failsOnEmptyData: false).startWithResult { result in receivedObjects = try? result.get() } expect(receivedObjects).notTo(beNil()) expect(receivedObjects?.count) == 1 expect(receivedObjects?.first?.title).to(beNil()) expect(receivedObjects?.first?.createdAt).to(beNil()) } context("when using key path mapping") { it("maps data representing a json to a decodable object") { let json: [String: Any] = ["issue": json] // nested json guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else { preconditionFailure("Failed creating Data from JSON dictionary") } let signal = signalSendingData(data) var receivedObject: Issue? _ = signal.map(Issue.self, atKeyPath: "issue", using: decoder).startWithResult { result in receivedObject = try? result.get() } expect(receivedObject).notTo(beNil()) expect(receivedObject?.title) == "Hello, Moya!" expect(receivedObject?.createdAt) == formatter.date(from: "1995-01-14T12:34:56")! } it("maps data representing a json array to a decodable object (#1311)") { let json: [String: Any] = ["issues": [json]] // nested json array guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else { preconditionFailure("Failed creating Data from JSON dictionary") } let signal = signalSendingData(data) var receivedObjects: [Issue]? _ = signal.map([Issue].self, atKeyPath: "issues", using: decoder).startWithResult { result in receivedObjects = try? result.get() } expect(receivedObjects).notTo(beNil()) expect(receivedObjects?.count) == 1 expect(receivedObjects?.first?.title) == "Hello, Moya!" expect(receivedObjects?.first?.createdAt) == formatter.date(from: "1995-01-14T12:34:56")! } it("maps empty data to a decodable object with optional properties") { let signal = signalSendingData(Data()) var receivedObjects: OptionalIssue? _ = signal.map(OptionalIssue.self, atKeyPath: "issue", using: decoder, failsOnEmptyData: false).startWithResult { result in receivedObjects = try? result.get() } expect(receivedObjects).notTo(beNil()) expect(receivedObjects?.title).to(beNil()) expect(receivedObjects?.createdAt).to(beNil()) } it("maps empty data to a decodable array with optional properties") { let signal = signalSendingData(Data()) var receivedObjects: [OptionalIssue]? _ = signal.map([OptionalIssue].self, atKeyPath: "issue", using: decoder, failsOnEmptyData: false).startWithResult { result in receivedObjects = try? result.get() } expect(receivedObjects).notTo(beNil()) expect(receivedObjects?.count) == 1 expect(receivedObjects?.first?.title).to(beNil()) expect(receivedObjects?.first?.createdAt).to(beNil()) } it("map Int data to an Int value") { let json: [String: Any] = ["count": 1] guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else { preconditionFailure("Failed creating Data from JSON dictionary") } let signal = signalSendingData(data) var count: Int? _ = signal.map(Int.self, atKeyPath: "count", using: decoder).startWithResult { result in count = try? result.get() } expect(count).notTo(beNil()) expect(count) == 1 } it("map Bool data to a Bool value") { let json: [String: Any] = ["isNew": true] guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else { preconditionFailure("Failed creating Data from JSON dictionary") } let signal = signalSendingData(data) var isNew: Bool? _ = signal.map(Bool.self, atKeyPath: "isNew", using: decoder).startWithResult { result in isNew = try? result.get() } expect(isNew).notTo(beNil()) expect(isNew) == true } it("map String data to a String value") { let json: [String: Any] = ["description": "Something interesting"] guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else { preconditionFailure("Failed creating Data from JSON dictionary") } let signal = signalSendingData(data) var description: String? _ = signal.map(String.self, atKeyPath: "description", using: decoder).startWithResult { result in description = try? result.get() } expect(description).notTo(beNil()) expect(description) == "Something interesting" } it("map String data to a URL value") { let json: [String: Any] = ["url": "http://www.example.com/test"] guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else { preconditionFailure("Failed creating Data from JSON dictionary") } let signal = signalSendingData(data) var url: URL? _ = signal.map(URL.self, atKeyPath: "url", using: decoder).startWithResult { result in url = try? result.get() } expect(url).notTo(beNil()) expect(url) == URL(string: "http://www.example.com/test") } it("shouldn't map Int data to a Bool value") { let json: [String: Any] = ["isNew": 1] guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else { preconditionFailure("Failed creating Data from JSON dictionary") } let signal = signalSendingData(data) var isNew: Bool? _ = signal.map(Bool.self, atKeyPath: "isNew", using: decoder).startWithResult { result in isNew = try? result.get() } expect(isNew).to(beNil()) } it("shouldn't map String data to an Int value") { let json: [String: Any] = ["test": "123"] guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else { preconditionFailure("Failed creating Data from JSON dictionary") } let signal = signalSendingData(data) var test: Int? _ = signal.map(Int.self, atKeyPath: "test", using: decoder).startWithResult { result in test = try? result.get() } expect(test).to(beNil()) } it("shouldn't map Array<String> data to an String value") { let json: [String: Any] = ["test": ["123", "456"]] guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else { preconditionFailure("Failed creating Data from JSON dictionary") } let signal = signalSendingData(data) var test: String? _ = signal.map(String.self, atKeyPath: "test", using: decoder).startWithResult { result in test = try? result.get() } expect(test).to(beNil()) } it("shouldn't map String data to an Array<String> value") { let json: [String: Any] = ["test": "123"] guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else { preconditionFailure("Failed creating Data from JSON dictionary") } let signal = signalSendingData(data) var test: [String]? _ = signal.map([String].self, atKeyPath: "test", using: decoder).startWithResult { result in test = try? result.get() } expect(test).to(beNil()) } } it("ignores invalid data") { var json = json json["createdAt"] = "Hahaha" // invalid date string guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else { preconditionFailure("Failed creating Data from JSON dictionary") } let signal = signalSendingData(data) var receivedError: Error? _ = signal.map(Issue.self, using: decoder).startWithResult { result in switch result { case .success: fail("next called for invalid data") case .failure(let error): receivedError = error } } if case let MoyaError.objectMapping(nestedError, _)? = receivedError { expect(nestedError).to(beAKindOf(DecodingError.self)) } else { fail("expected <MoyaError.objectMapping>, got <\(String(describing: receivedError))>") } } } } }
43.435009
145
0.498324
903f7fb6e5d264f341ac298a060516c6033db426
1,743
import AdaptiveCards_bridge import AppKit public protocol AdaptiveCardActionDelegate: AnyObject { func adaptiveCard(_ adaptiveCard: NSView, didSelectOpenURL urlString: String, actionView: NSView) func adaptiveCard(_ adaptiveCard: NSView, didSubmitUserResponses dict: [String: Any], actionView: NSView) } public protocol AdaptiveCardResourceResolver: AnyObject { func adaptiveCard(_ adaptiveCard: ImageResourceHandlerView, dimensionsForImageWith url: String) -> NSSize? func adaptiveCard(_ adaptiveCard: ImageResourceHandlerView, requestImageFor url: String) } enum HostConfigParseError: Error { case resultIsNil, configIsNil } open class AdaptiveCard { public static func from(jsonString: String) -> ACSParseResult { return BridgeConverter.parseAdaptiveCard(fromJSON: jsonString) } public static func parseHostConfig(from jsonString: String) -> Result<ACSHostConfig, Error> { guard let result = BridgeConverter.parseHostConfig(fromJSON: jsonString) else { return .failure(HostConfigParseError.resultIsNil) } guard result.isValid, let hostConfig = result.config else { return .failure(result.error ?? HostConfigParseError.configIsNil) } return .success(hostConfig) } public static func render(card: ACSAdaptiveCard, with hostConfig: ACSHostConfig, width: CGFloat, actionDelegate: AdaptiveCardActionDelegate?, resourceResolver: AdaptiveCardResourceResolver?) -> NSView { AdaptiveCardRenderer.shared.actionDelegate = actionDelegate AdaptiveCardRenderer.shared.resolverDelegate = resourceResolver return AdaptiveCardRenderer.shared.renderAdaptiveCard(card, with: hostConfig, width: width) } }
44.692308
206
0.760184
e4522c57a91a29504eabbe101ccad3726a65a194
686
// // UIColorExtensions.swift // Weathermate // // Created by parry on 7/19/16. // Copyright © 2016 MCP. All rights reserved. // import UIKit extension UIColor { convenience init(red: Int, green: Int, blue: Int) { assert(red >= 0 && red <= 255, "Invalid red component") assert(green >= 0 && green <= 255, "Invalid green component") assert(blue >= 0 && blue <= 255, "Invalid blue component") self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0) } convenience init(netHex:Int) { self.init(red:(netHex >> 16) & 0xff, green:(netHex >> 8) & 0xff, blue:netHex & 0xff) } }
28.583333
116
0.602041
b93cd7c3c88f3491a6e0171d8af5d59a0e36759a
2,602
// // InfoPopOverViewController.swift // Notification Agent // // Created by Simone Martorelli on 3/16/20. // Copyright © 2021 IBM Inc. All rights reserved // SPDX-License-Identifier: Apache2.0 // import Cocoa /// This class manage the popover that shows the informations related to a label. final class InfoPopOverViewController: NSViewController { // MAKR: - Outlets @IBOutlet var mainStackView: NSStackView! // MARK: - Variables var infoSection: InfoSection // MARK: - Initializers /// Initialize the popover with the infoSection that needs to be showed. /// - Parameter info: the InfoSection object that needs to be displayed ad popover. init(with info: InfoSection) { self.infoSection = info super.init(nibName: .init("InfoPopOverViewController"), bundle: nil) } required init?(coder: NSCoder) { return nil } // MARK: - Instance methods override func viewDidLoad() { super.viewDidLoad() for (index, field) in infoSection.fields.enumerated() { let itemView = InfoPopOverStackItem(with: field) self.mainStackView.insertArrangedSubview(itemView, at: index*2) guard index+1 < infoSection.fields.count else { return } let horizontalLine = HorizontalLine() let widthConstraint = NSLayoutConstraint(item: horizontalLine, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: mainStackView.frame.width-16) let heightConstraint = NSLayoutConstraint(item: horizontalLine, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 1) horizontalLine.addConstraints([widthConstraint, heightConstraint]) widthConstraint.isActive = true heightConstraint.isActive = true self.mainStackView.insertArrangedSubview(horizontalLine, at: (index*2)+1) } } }
39.424242
92
0.514988
0eb92578adae24943651cb657d118d9c3ad0bf95
376
// // BullsEyeGameView.swift // BullsEye // // Created by Chun Wu on 2020-06-07. // Copyright © 2020 Ray Wenderlich. All rights reserved. // import UIKit public class BullsEyeGameView: UIView { @IBOutlet weak var slider: UISlider! @IBOutlet weak var targetLabel: UILabel! @IBOutlet weak var scoreLabel: UILabel! @IBOutlet weak var roundLabel: UILabel! }
22.117647
57
0.710106
1cbbef5634427ac997ac7673a2475a7bdf0934ba
2,282
import AudioKit import SoundpipeAudioKit import AVFoundation import SwiftUI class PluckedStringConductor: ObservableObject { let engine = AudioEngine() let pluckedString = PluckedString() let pluckedString2 = PluckedString() var playRate = 3.0 var loop: CallbackLoop! @Published var isRunning = false { didSet { isRunning ? loop.start() : loop.stop() } } init() { let mixer = DryWetMixer(pluckedString, pluckedString2) let delay = Delay(mixer) delay.time = AUValue(1.5 / playRate) delay.dryWetMix = 0.7 delay.feedback = 0.9 let reverb = Reverb(delay) reverb.dryWetMix = 0.9 engine.output = reverb } func start() { do { try engine.start() loop = CallbackLoop(frequency: playRate) { let scale = [60, 62, 65, 66, 67, 69, 71] let note1 = Int(AUValue.random(in: 0.0..<Float(scale.count))) let note2 = Int(AUValue.random(in: 0.0..<Float(scale.count))) let newAmp = AUValue.random(in: 0.0...1.0) self.pluckedString.frequency = scale[note1].midiNoteToFrequency() self.pluckedString.amplitude = newAmp self.pluckedString2.frequency = scale[note2].midiNoteToFrequency() self.pluckedString2.amplitude = newAmp if AUValue.random(in: 0.0...30.0) > 15 { self.pluckedString.trigger() self.pluckedString2.trigger() } } } catch let err { Log(err) } } func stop() { engine.stop() loop.stop() } } struct PluckedStringView: View { @ObservedObject var conductor = PluckedStringConductor() var body: some View { Text(conductor.isRunning ? "Stop" : "Start").onTapGesture { conductor.isRunning.toggle() } .padding() .cookbookNavBarTitle("Plucked String") .onAppear { self.conductor.start() } .onDisappear { self.conductor.stop() } } } struct PluckedStringView_Previews: PreviewProvider { static var previews: some View { PluckedStringView() } }
27.829268
82
0.563103
48679a0fc9970f1f136e24ba1773c7823c652545
816
// swift-tools-version:5.2 import PackageDescription let package = Package( name: "NumPad", products: [ // Products define the executables and libraries produced by a package, and make them visible to other packages. .library( name: "NumPad", targets: ["NumPad"]), ], dependencies: [ // Dependencies declare other packages that this package depends on. // .package(url: /* package url */, from: "1.0.0"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages which this package depends on. .target( name: "NumPad", dependencies: []), ] )
34
122
0.609069
11205a77ab68cc754a752a3393e287055a6cd4da
4,096
// // Created by Marton Kerekes on 07/01/2020. // Copyright © 2020 Marton Kerekes. All rights reserved. // import Foundation import Domain import Presentation import MarvelDomain protocol SeriesPresentingItem { func setup(info: PresentableInfo, title: String?, imageURL: URL?, type: ListType) } protocol SeriesListPresenting { func viewReady() func viewDidReachEnd(index: IndexPath) var itemCount: Int { get } func setup(cell: SeriesPresentingItem, at index: Int) func didSelect(cell: SeriesPresentingItem, at index: Int) func didTapEmptyStateButton() var emptyStateTitle: NSAttributedString { get } var emptyStateTitleDetail: NSAttributedString? { get } var emptyStateButtonTitle: String? { get } var emptyStateShouldShow: Bool { get } } protocol SeriesListPresentationOutput: FontCalculating { func reload() } protocol SeriesListRouting: ErrorRouting { func routeSeries(_ story: Entities.Series) } class SeriesListPresenter: SeriesListPresenting { weak var output: SeriesListPresentationOutput! let router: SeriesListRouting let fetcher: SeriesListFetching let type: SeriesListType init(type: SeriesListType, fetcher: SeriesListFetching, router: SeriesListRouting) { self.type = type self.fetcher = fetcher self.router = router } var results: Entities.SeriesDataWrapper? { didSet { output.reload() } } var unwrappedItems: [Entities.Series]? { return results?.data?.results } func viewReady() { output.reload() fetcher.fetchStories(type: type) { [weak self] (result) in do { self?.results = try result.get() } catch { self?.router.route(message: .error(ServiceError(from: error))) } } } var lastLoaded: IndexPath? = nil func viewDidReachEnd(index: IndexPath) { guard let results = results, lastLoaded != index else { return } lastLoaded = index fetcher.fetchNext(result: results) { [weak self] (result) in do { self?.results = try result.get() } catch { self?.router.show(error: ServiceError(from: error)) } } } var itemCount: Int { return unwrappedItems?.count ?? 0 } func setup(cell: SeriesPresentingItem, at index: Int) { guard let item = unwrappedItems?[index], let name = item.title else { return } var text = [FontCalculable(text: name, style: .largeAuthor), ] if let desc = item.description { text.append(FontCalculable(text: desc, style: .normal)) } let info = BasicInfo(displayableText: text, tick: false) let profileInfo = PresentableInfo(info: info, helper: output) let url = item.thumbnail?.createURL(size: .portrait_uncanny) cell.setup(info: profileInfo, title: item.description, imageURL: url, type: .none) } func didSelect(cell: SeriesPresentingItem, at index: Int) { guard let item = unwrappedItems?[index] else { return } router.routeSeries(item) } func didTapEmptyStateButton() { viewReady() } var emptyStateTitle: NSAttributedString { guard let output = output else { return NSAttributedString() } return output.makeAttributedString(from: [FontCalculable(text: "list_empty_state_title".localised, style: .mention)]) } public var emptyStateTitleDetail: NSAttributedString? { guard let view = output else { return NSAttributedString() } return view.makeAttributedString(from: [FontCalculable(text: "list_empty_state_details".localised, style: .normal)]) } public var emptyStateButtonTitle: String? { return "list_empty_state_button".localised } public var emptyStateShouldShow: Bool { guard let results = unwrappedItems else { return false } return results.count == 0 } }
31.267176
125
0.640625
6982f23f3921537ea5b65bd0477c7ae57b2ca34e
1,094
// // MusicViewController.swift // HQPageViewDemo // // Created by 郝庆 on 2017/5/9. // Copyright © 2017年 Enroute. All rights reserved. // import UIKit class MusicViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white title = "网易云音乐" let frame = CGRect(x: 0, y: 64, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height - 64 - 44) let titles = ["个性推荐", "歌单", "主播电台", "排行榜"] let style = HQTitleStyle() style.normalColor = (0,0,0) style.selectedColor = (255, 0, 0) style.indicatorViewH = 2 style.isGradualChangeEnabel = false var childVcs = [UIViewController]() for _ in 0..<titles.count { let vc = UIViewController() vc.view.backgroundColor = UIColor.randomColor() childVcs.append(vc) } let pageView = HQPageView(frame: frame, titles: titles, style: style, childVcs: childVcs, parentVc: self) view.addSubview(pageView) } }
29.567568
121
0.608775
1418b0f7fde9be0aa57c6505b590fc4ff5d6ffe8
1,231
// // Advent // Copyright © 2020 David Jennes // import Foundation // swiftlint:disable identifier_name yoda_condition public func gcd<T: BinaryInteger>(_ a: T, _ b: T) -> T { assert(a >= 0 && b >= 0) // Assuming gcd(0,0)=0: guard a != 0 else { return b } guard b != 0 else { return a } var a = a, b = b, n = Int() // Remove the largest 2ⁿ from them: while (a | b) & 1 == 0 { a >>= 1; b >>= 1; n += 1 } // Reduce `a` to odd value: while a & 1 == 0 { a >>= 1 } repeat { // Reduce `b` to odd value while b & 1 == 0 { b >>= 1 } // Both `a` & `b` are odd here (or zero maybe?) // Make sure `b` is greater if a > b { swap(&a, &b) } // Subtract smaller odd `a` from the bigger odd `b`, // which always gives a positive even number (or zero) b -= a // keep repeating this, until `b` reaches zero } while b != 0 return a << n // 2ⁿ×a } public func gcd<T: BinaryInteger>(_ numbers: [T]) -> T { numbers.dropFirst().reduce(numbers.first ?? 0) { gcd($0, $1) } } public func lcm<T: BinaryInteger>(_ a: T, _ b: T) -> T { assert(a >= 0 && b >= 0) return a / gcd(a, b) * b } public func lcm<T: BinaryInteger>(_ numbers: [T]) -> T { numbers.dropFirst().reduce(numbers.first ?? 0) { lcm($0, $1) } }
21.982143
63
0.563769
9b6ef017c794c06b8b3b69d5943871534466f606
2,285
// // SceneDelegate.swift // YOWeight // // Created by SYQM on 2021/12/29. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). guard let _ = (scene as? UIWindowScene) else { return } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
43.113208
147
0.712473
ddd3ec32118bbdd230ac0810a3b2a1a7f6673da8
10,982
// // PhotoGridViewController.swift // Inphoto // // Created by liuding on 2018/10/23. // Copyright © 2018 eastree. All rights reserved. // import UIKit import Photos import PhotosUI class PhotoGridViewController: UICollectionViewController { @IBOutlet weak var titleView: UIButton! var fetchResult: PHFetchResult<PHAsset>! var assetCollection: PHAssetCollection! var album: Album? fileprivate let imageManager = PHCachingImageManager() fileprivate var lineSpace: CGFloat = 2.0 fileprivate var itemSpace: CGFloat = 2.0 fileprivate var numberOfItemsInRow: Int { get { if UIDevice.current.userInterfaceIdiom == .pad { switch UIDevice.current.orientation { case .portrait, .portraitUpsideDown: return 7 case .landscapeLeft, .landscapeRight: return 8 default: return 7 } } if UIDevice.current.userInterfaceIdiom == .phone { switch UIDevice.current.orientation { case .portrait, .portraitUpsideDown: return 4 case .landscapeLeft, .landscapeRight: return 7 default: return 4 } } return 4 } } fileprivate var thumbnailSize: CGSize! fileprivate var cellSize: CGSize! override func viewDidLoad() { super.viewDidLoad() if fetchResult == nil { let allPhotosOptions = PHFetchOptions() allPhotosOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)] allPhotosOptions.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.image.rawValue) fetchResult = PHAsset.fetchAssets(with: allPhotosOptions) } else { resetCachedAssets() } PHPhotoLibrary.shared().register(self) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) cellSize = calculateCellSize() thumbnailSize = CGSize(width: cellSize.width * UIScreen.main.scale, height: cellSize.height * UIScreen.main.scale) checkPermission { (hasPerm) in } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } deinit { PHPhotoLibrary.shared().unregisterChangeObserver(self) } func checkPermission(block: @escaping (Bool) -> Void) { let status = PHPhotoLibrary.authorizationStatus() switch status { case .authorized: block(true) case .restricted, .denied: let alert = UIAlertController(title: "相册未授权", message: "", preferredStyle: .alert) alert.addAction( UIAlertAction(title: "取消", style: UIAlertAction.Style.cancel, handler: { _ in block(false) })) alert.addAction( UIAlertAction(title: "去授权", style: .default, handler: { _ in if #available(iOS 10.0, *) { UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!) } })) present(alert, animated: true, completion: nil) case .notDetermined: PHPhotoLibrary.requestAuthorization { s in DispatchQueue.main.async { block(s == .authorized) } } } } func loadAlbum(_ album: Album) { let options = PHFetchOptions() options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)] options.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.image.rawValue) // 仅查询图片 self.fetchResult = PHAsset.fetchAssets(in: album.collection!, options: options) self.assetCollection = album.collection self.setTitle(album.title) self.collectionView?.reloadData() scrollToTop() resetCachedAssets() } func calculateCellSize() -> CGSize { let margins = itemSpace * CGFloat(numberOfItemsInRow - 1) let width = (collectionView!.bounds.width - margins) / CGFloat(numberOfItemsInRow) return CGSize(width: width, height: width) } func scrollToTop() { collectionView?.scrollToItem(at: IndexPath(item: 0, section: 0), at: .top, animated: false) } // MARK: Asset Caching fileprivate func resetCachedAssets() { imageManager.stopCachingImagesForAllAssets() } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == R.segue.photoGridViewController.grid_Album.identifier { if let navi = segue.destination as? UINavigationController, let albumVC = navi.viewControllers.first as? AlbumViewController { albumVC.didSelectAlbum = { [weak self] album in self?.loadAlbum(album) } } } if let dest = segue.destination as? DetailViewController { guard let cell = sender as? UICollectionViewCell else { return } let indexPath = collectionView!.indexPath(for: cell)! dest.asset = fetchResult.object(at: indexPath.item) } } // MARK: UICollectionViewDataSource override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return fetchResult.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: R.reuseIdentifier.photoCell.identifier, for: indexPath) as! PhotoCollectionViewCell let asset = fetchResult.object(at: indexPath.item) if asset.mediaSubtypes.contains(.photoLive) { cell.isLivePhoto = true } cell.assetIdentifier = asset.localIdentifier imageManager.requestImage(for: asset, targetSize: thumbnailSize, contentMode: .aspectFill, options: nil, resultHandler: { image, _ in if cell.assetIdentifier == asset.localIdentifier { cell.photoImageView.image = image } }) return cell } } extension PhotoGridViewController: PHPhotoLibraryChangeObserver { func photoLibraryDidChange(_ changeInstance: PHChange) { guard let changes = changeInstance.changeDetails(for: fetchResult) else { return } DispatchQueue.main.sync { self.fetchResult = changes.fetchResultAfterChanges if changes.hasIncrementalChanges { guard let collectionView = self.collectionView else { fatalError() } collectionView.performBatchUpdates({ if let removed = changes.removedIndexes, removed.count > 0 { collectionView.deleteItems(at: removed.map({ IndexPath(item: $0, section: 0) })) } if let inserted = changes.insertedIndexes, inserted.count > 0 { collectionView.insertItems(at: inserted.map({ IndexPath(item: $0, section: 0) })) } // if let changed = changes.changedIndexes, changed.count > 0 { // collectionView.reloadItems(at: changed.map({ IndexPath(item: $0, section: 0) })) // } if changes.hasMoves { // 'attempt to perform a delete and a move from the same index path (<NSIndexPath: {length = 2, path = 0 - 0})' changes.enumerateMoves { fromIndex, toIndex in print(fromIndex, toIndex) collectionView.moveItem(at: IndexPath(item: fromIndex, section: 0), to: IndexPath(item: toIndex, section: 0)) } } }) } else { self.collectionView!.reloadData() } self.resetCachedAssets() } } } extension PhotoGridViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return cellSize } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsets(top: lineSpace, left: 0, bottom: lineSpace, right: 0) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return itemSpace } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return lineSpace } } extension PhotoGridViewController: UICollectionViewDataSourcePrefetching { func collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath]) { let prefetchs = indexPaths.map { (indexPath) -> PHAsset in fetchResult.object(at: indexPath.item) } imageManager.startCachingImages(for: prefetchs, targetSize: thumbnailSize, contentMode: .aspectFill, options: nil) } func collectionView(_ collectionView: UICollectionView, cancelPrefetchingForItemsAt indexPaths: [IndexPath]) { let canceled = indexPaths.map { (indexPath) -> PHAsset in fetchResult.object(at: indexPath.item) } imageManager.stopCachingImages(for: canceled, targetSize: thumbnailSize, contentMode: .aspectFill, options: nil) } } extension PhotoGridViewController { func setTitle(_ title: String) { titleView.setTitle(title, for: .normal) } }
35.540453
175
0.582408
ff37abbad5347d3200fb85520b5494e7e104f448
575
// // ViewController.swift // codepath-twitter // // Created by Nisarga Patel on 2/28/16. // Copyright © 2016 Nisarga Patel. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func onLoginButton(sender: AnyObject) { } }
21.296296
80
0.673043
0995d9799239837f7362ee4d78b31378a13fd69d
2,018
// // AppGroup_t.swift // AppCatServer // // Created by 段林波 on 2018/12/12. // import PerfectLib import Foundation import StORM import MySQLStORM class AppGroup_t: MySQLStORM { var groupId: Int = 0 var owner: String = "" var channel: String = "" var bundleId: String = "" var creater: String = "" var createTime: String = "" var editer: String = "" var editTime: String = "" override open func table() -> String { return "app_group_t" } override func to(_ this: StORMRow) { groupId = Int(this.data["groupId"] as! Int32) if let o = this.data["owner"] { owner = o as! String } if let o = this.data["channel"] { channel = o as! String } if let o = this.data["bundleId"] { bundleId = o as! String } if let o = this.data["creater"] { creater = o as! String } if let o = this.data["createTime"] { createTime = o as! String } if let o = this.data["editer"] { editer = o as! String } if let o = this.data["editTime"] { editTime = o as! String } } func rows() -> [AppGroup_t] { var rows = [AppGroup_t]() for i in 0..<self.results.rows.count { let row = AppGroup_t() row.to(self.results.rows[i]) rows.append(row) } return rows } open func getJSONValues() -> [String : Any] { return [ // JSONDecoding.objectIdentifierKey:AppGroup.registerName, "groupId":groupId, "owner":owner, "channel":channel, "bundleId": bundleId, "creater": creater, "createTime": createTime, "editer": editer, "editTime": editTime, ] } // override func makeRow() { // self.to(self.results.rows[0]) // } }
24.609756
81
0.492071
754c9a47b3fde49fa921ce9539ba63a8afd299f8
272
// // CGColor+JSSwifter.swift // JSSwifter // // Created by Max on 2019/5/17. // Copyright © 2019 Max. All rights reserved. // import CoreGraphics public extension CGColor { // MARK: var uiColor: UIColor? { return UIColor(cgColor: self) } }
15.111111
46
0.621324
149535e840b2a4059e8f6f60d9b22fccc34f10c2
3,893
// // FirstViewController.swift // TabbarApp // // Created by Phoenix on 2017/4/25. // Copyright © 2017年 Phoenix. All rights reserved. // import UIKit class FirstViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var articleTableView: UITableView! var data = [ Article(avatarImage: "allen", sharedName: "Allen Wang", actionType: "Read Later", articleTitle: "Giphy Cam Lets You Create And Share Homemade Gifs", articleCoverImage: "giphy", articleSouce: "TheNextWeb", articleTime: "5min • 13:20"), Article(avatarImage: "Daniel Hooper", sharedName: "Daniel Hooper", actionType: "Shared on Twitter", articleTitle: "Principle. The Sketch of Prototyping Tools", articleCoverImage: "my workflow flow", articleSouce: "SketchTalk", articleTime: "3min • 12:57"), Article(avatarImage: "davidbeckham", sharedName: "David Beckham", actionType: "Shared on Facebook", articleTitle: "Ohlala, An Uber For Escorts, Launches Its ‘Paid Dating’ Service In NYC", articleCoverImage: "Ohlala", articleSouce: "TechCrunch", articleTime: "1min • 12:59"), Article(avatarImage: "bruce", sharedName: "Bruce Fan", actionType: "Shared on Weibo", articleTitle: "Lonely Planet’s new mobile app helps you explore major cities like a pro", articleCoverImage: "Lonely Planet", articleSouce: "36Kr", articleTime: "5min • 11:21"), ] override func viewDidLoad() { super.viewDidLoad() articleTableView.frame = view.bounds articleTableView.dataSource = self articleTableView.delegate = self articleTableView.separatorStyle = UITableViewCellSeparatorStyle.none articleTableView.tableFooterView = UIView(frame: CGRect.zero) } override func viewWillAppear(_ animated: Bool) { animateTable() } func animateTable() { self.articleTableView.reloadData() let cells = articleTableView.visibleCells let tableHeight: CGFloat = articleTableView.bounds.size.height for i in cells { let cell: UITableViewCell = i as UITableViewCell cell.transform = CGAffineTransform(translationX: 0, y: tableHeight) } var index = 0 for a in cells { let cell: UITableViewCell = a as UITableViewCell UIView.animate(withDuration: 1.0, delay: 0.05 * Double(index), usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: [], animations: { cell.transform = CGAffineTransform(translationX: 0, y: 0); }, completion: nil) index += 1 } } func numberOfSections(in tableView: UITableView) -> Int { return 10 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return data.count } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 165 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = articleTableView.dequeueReusableCell(withIdentifier: "ArticleCell", for: indexPath) as! ArticleCell let article = data[indexPath.row] cell.avatarImageView.image = UIImage(named: article.avatarImage) cell.articleCoverImage.image = UIImage(named: article.articleCoverImage) cell.sharedNameLabel.text = article.sharedName cell.actionTypeLabel.text = article.actionType cell.articleTitleLabel.text = article.articleTitle cell.articleSouceLabel.text = article.articleSouce cell.articelCreatedAtLabel.text = article.articleTime cell.selectionStyle = UITableViewCellSelectionStyle.none return cell } }
41.414894
284
0.666067
d7ae713b104e4d2304581ac813842a333045ed8a
1,722
// // GATTModelNumber.swift // Bluetooth // // Created by Carlos Duclos on 6/21/18. // Copyright © 2018 PureSwift. All rights reserved. // import Foundation /** Model Number String [Model Number String](https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.model_number_string.xml) The value of this characteristic is a UTF-8 string representing the model number assigned by the device vendor. */ public struct GATTModelNumber: RawRepresentable, GATTCharacteristic { public static var uuid: BluetoothUUID { return .modelNumberString } public let rawValue: String public init(rawValue: String) { self.rawValue = rawValue } public init?(data: Data) { guard let rawValue = String(data: data, encoding: .utf8) else { return nil } self.init(rawValue: rawValue) } public var data: Data { return Data(rawValue.utf8) } } extension GATTModelNumber: Equatable { public static func == (lhs: GATTModelNumber, rhs: GATTModelNumber) -> Bool { return lhs.rawValue == rhs.rawValue } } extension GATTModelNumber: CustomStringConvertible { public var description: String { return rawValue } } extension GATTModelNumber: ExpressibleByStringLiteral { public init(stringLiteral value: String) { self.init(rawValue: value) } public init(extendedGraphemeClusterLiteral value: String) { self.init(rawValue: value) } public init(unicodeScalarLiteral value: String) { self.init(rawValue: value) } }
22.657895
146
0.643438
115300a9c3e3f6fd1901fb8c2179d3508578e1ed
3,036
// // ViewController.swift // AnimableRefresh // // Created by [email protected] on 10/22/2019. // Copyright (c) 2019 [email protected]. All rights reserved. // import AnimableRefresh import UIKit class ViewController: UIViewController { // MARK: - Interface Properties lazy var tableView: UITableView = { let view = UITableView() view.translatesAutoresizingMaskIntoConstraints = false return view }() // MARK: - Properties var numbers = Array(1...100) // MARK: - LifeCycle override func viewDidLoad() { super.viewDidLoad() self.configure() } // MARK: - Configuration private func configure() { title = "Test" self.configureTableView() self.configureNavBar() self.configureRefresher() } // MARK: - Refresh handler private func configureRefresher() { tableView.addRefresh(custom: CustomLoader()) { self.fetch() } } private func fetch() { let fetchDuration = Int.random(in: 0...5) DispatchQueue.global(qos: .background).asyncAfter(deadline: .now() + .seconds(fetchDuration)) { self.didFetch() } } private func didFetch() { DispatchQueue.main.async { self.tableView.endRefresh() self.tableView.reloadData() } } @objc private func addTapped() { self.tableView.startRefresh() } } // MARK: - UITableViewDataSource extension ViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { numbers.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell() cell.textLabel?.text = "\(numbers[indexPath.row])" return cell } } // MARK: - View configuration extension ViewController { private func configureTableView() { tableView.dataSource = self view.addSubview(tableView) tableView.topAnchor.constraint(equalToSystemSpacingBelow: self.view.topAnchor, multiplier: 1).isActive = true tableView.leftAnchor.constraint(equalToSystemSpacingAfter: self.view.leftAnchor, multiplier: 1).isActive = true tableView.rightAnchor.constraint(equalToSystemSpacingAfter: self.view.rightAnchor, multiplier: 1).isActive = true tableView.bottomAnchor.constraint(equalToSystemSpacingBelow: self.view.bottomAnchor, multiplier: 1).isActive = true } private func configureNavBar() { self.navigationController?.navigationBar.isTranslucent = true self.navigationController?.navigationBar.backgroundColor = .clear edgesForExtendedLayout = [] let add = UIBarButtonItem(barButtonSystemItem: .refresh, target: self, action: #selector(addTapped)) navigationItem.rightBarButtonItems = [add] } }
29.192308
123
0.651186
469a2ccf3c45316a32826c5702e1e6938812e9d2
1,698
// // View+.swift // // // Created by Q Trang on 7/20/20. // import SwiftUI extension View { @inlinable public func pad(edges: Edge.Set = .all, spacing: Spacing? = nil) -> some View { padding(edges, spacing != nil ? spacing!.value : nil) } @inlinable public func pad(edges: Edge.Set = .all, spacing: BaseSpacing? = nil) -> some View { padding(edges, spacing != nil ? spacing!.value : nil) } @inlinable public func offset(x: Spacing, y: Spacing) -> some View { offset(x: x.value, y: y.value) } @inlinable public func offset(x: BaseSpacing = .s0, y: BaseSpacing = .s0) -> some View { offset(x: x.value, y: y.value) } @inlinable public func frame(width: Width? = nil, height: Height? = nil, alignment: Alignment = .center) -> some View { frame(width: width?.value, height: height?.value, alignment: alignment) } @inlinable public func frame(width: BaseWidth? = nil, height: BaseHeight? = nil, alignment: Alignment = .center) -> some View { frame(width: width?.value, height: height?.value, alignment: alignment) } @inlinable public func frame(minWidth: Width, maxWidth: Width, minHeight: Height, maxHeight: Height) -> some View { frame(minWidth: minWidth.value, maxWidth: maxWidth.value, minHeight: minHeight.value, maxHeight: maxHeight.value) } @inlinable public func frame(minWidth: BaseWidth = .w0, maxWidth: BaseWidth = .infinity, minHeight: BaseHeight = .h0, maxHeight: BaseHeight = .infinity) -> some View { frame(minWidth: minWidth.value, maxWidth: maxWidth.value, minHeight: minHeight.value, maxHeight: maxHeight.value) } }
39.488372
171
0.643698
62bae0813a02d4126fd88b48cf1f146817400996
266
// // Encodable.swift // doglist // // Created by Hélio Mesquita on 25/05/19. // Copyright © 2019 Hélio Mesquita. All rights reserved. // import Foundation extension Encodable { func toJSONData() -> Data? { return try? JSONEncoder().encode(self) } }
14.777778
57
0.661654
1ade80e117a127f0d3e832ee39c3fbd50def75f3
710
// swift-tools-version:4.0 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "WarningsValidator", products: [ .executable(name: "WarningsValidator", targets: ["WarningsValidator"]), .library(name: "WarningsValidatorCore", targets: ["WarningsValidatorCore"]) ], targets: [ .target( name: "WarningsValidator", dependencies: ["WarningsValidatorCore"] ), .target(name: "WarningsValidatorCore"), .testTarget( name: "WarningsValidatorTests", dependencies: ["WarningsValidatorCore"] ) ] )
29.583333
96
0.632394
16bdbec2fb8d73e955c3969a6d949e21aec3284e
968
// // TrackTableViewCell.swift // Spochify // // Created by Alberto on 11/04/2019. // Copyright © 2019 com.github.albertopeam. All rights reserved. // import UIKit class TrackTableViewCell: UITableViewCell { static let identifier = "TrackCell" @IBOutlet weak var indexLabel: UILabel! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var popularityLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() } override func prepareForReuse() { super.prepareForReuse() indexLabel.text = nil titleLabel.text = nil popularityLabel.text = nil } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } func draw(index: Int, track: Track) { indexLabel.text = "\(index)" titleLabel.text = track.title popularityLabel.text = "\(track.popularity)/100" } }
24.2
65
0.643595
ef0f8bf77e939bda38bc3d88ac08f5a3f9201014
227
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing var d{{enum b{enum b:a{func b{class a{var _=a{func d{(v=D
37.833333
87
0.744493
abd35d1ba16b2c00fa3ad945b4ed887fe12b6338
2,202
// // HelpViewController.swift // DIT-Timetable-V2 // // Created by Timothy Barnard on 18/09/2016. // Copyright © 2016 Timothy Barnard. All rights reserved. // import UIKit class HelpViewController: UIViewController { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var nextButton: UIButton! @IBOutlet weak var startButton: UIButton! @IBOutlet weak var pageControl: UIPageControl! var activityIndicator : UIActivityIndicatorView? // self.dismiss(animated: true, completion: nil) // MARK: - Data model for each walkthrough screen var index = 0 // the current page index var imageURL = "" // Just to make sure that the status bar is white - it depends on your preference override var preferredStatusBarStyle : UIStatusBarStyle { return .lightContent } override func viewDidLoad() { super.viewDidLoad() self.activityIndicator = UIActivityIndicatorView() self.activityIndicator!.frame = CGRect(x: 0.0, y: 0.0, width: 40.0, height: 40.0); self.activityIndicator!.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.whiteLarge self.activityIndicator!.center = CGPoint(x: self.view.frame.size.width / 2, y: self.view.frame.size.height / 2); self.view.addSubview(self.activityIndicator!) imageView.downloadedFrom( actInd: self.activityIndicator!, link: imageURL) pageControl.currentPage = index startButton.isHidden = (index == 4) ? false : true nextButton.isHidden = (index == 5) ? true : false startButton.layer.cornerRadius = 5.0 startButton.layer.masksToBounds = true } @IBAction func startButton(_ sender: AnyObject) { let userDefaults = UserDefaults.standard userDefaults.set(true, forKey: "TimetableHelp") self.dismiss(animated: true, completion: nil) } @IBAction func nextButton(_ sender: AnyObject) { let pageViewController = self.parent as! HelpPageViewController pageViewController.nextPageWithIndex(index) } }
32.865672
90
0.65168
5bef59c48e7db2ebd3b0bb3633eda7ee16245558
966
// // NetModuleAmbience.swift // // // Created by Quentin Berry on 7/16/20. // import Foundation import SwiftyBytes /// This is a struct for the Ambience NetModule. public struct NetModuleAmbience: NetModule{ public var playerId: UInt8 = 0 public var number: Int32 = 0 public var type: UInt8 = 0 public init(){} public init(playerId: UInt8, number: Int32, type: UInt8){ self.playerId = playerId self.number = number self.type = type } public mutating func decode(_ reader: BinaryReader, _ context: TerrariaPacketContext) throws{ self.playerId = try reader.readUInt8() self.number = try reader.readInt32() self.type = try reader.readUInt8() } public mutating func encode(_ writer: BinaryWriter, _ context: TerrariaPacketContext) throws{ try writer.writeUInt8(self.playerId) try writer.writeInt32(self.number) try writer.writeUInt8(self.type) } }
26.833333
97
0.670807
eb79fa87d9862fd1f75a936cb3a2e4f29278a55f
2,609
// Copyright 2017-2020 Fitbit, Inc // SPDX-License-Identifier: Apache-2.0 // // ComboBoxViewController.swift // BluetoothConnection // // Created by Marcel Jackwerth on 4/3/18. // #if os(iOS) import RxCocoa import RxSwift import UIKit /// A view controller that allows selection of one item. class ComboBoxViewController<Element: Equatable>: UITableViewController { private let disposeBag = DisposeBag() public var viewModel: ComboBoxViewModel<Element>! override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = nil tableView.register(Cell.self) tableView.rx.modelSelected(Element.self) .take(1) .do(onNext: viewModel.setSelectedElement) .do(onNext: { [unowned self] _ in self.pop() }) .subscribe() .disposed(by: disposeBag) viewModel.elements .observe(on: MainScheduler.instance) .bind(to: tableView.rx.items) { [viewModel = viewModel!] tableView, _, element in let cell = tableView.dequeue(Cell.self)! let checked = viewModel.selectedElement.map { $0 == element } return cell.bind(Cell.ViewModel( label: .just("\(element)"), checked: checked )) } .disposed(by: disposeBag) } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) } private func pop() { navigationController?.popViewController(animated: true) } } private class Cell: UITableViewCell, ReusableTableViewCell { struct ViewModel { let label: Observable<String> let checked: Observable<Bool> } private let disposeBag = DisposeBag() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: .subtitle, reuseIdentifier: reuseIdentifier) } required init?(coder aDecoder: NSCoder) { fatalError("not implemented") } func bind(_ viewModel: ViewModel) -> Cell { viewModel.label .take(until: rx.methodInvoked(#selector(prepareForReuse))) .asDriver(onErrorJustReturn: "") .drive(textLabel!.rx.text) .disposed(by: disposeBag) viewModel.checked .take(until: rx.methodInvoked(#selector(prepareForReuse))) .asDriver(onErrorJustReturn: false) .drive(rx.checked) .disposed(by: disposeBag) return self } } #endif
28.67033
93
0.623227
5096401070f9f542555ac3981c385d92eaf39cbc
2,583
// // ViewController.swift // UITableViewSelfSizing // // Created by MilanPanchal on 12/12/14. // Copyright (c) 2014 Pantech. All rights reserved. // import UIKit class ViewController: UITableViewController { @IBOutlet var titleLabel:UILabel! @IBOutlet var valueLabel:UILabel! var basicInfoDict:[String:String] = ["Name":"Milan Panchal", "Email":"[email protected] / [email protected]", "LinkedIn":"https://www.linkedin.com/in/milanpanchal", "GitHub":"https://github.com/milanpanchal", "Stackoverflow":"http://stackoverflow.com/users/1748956/milanpanchal", "Google Plus":"https://plus.google.com/+MilanSamPanchal/", "Skype":"milan_panchal24", "Twitter":"https://twitter.com/milan_panchal24", "Slideshare":"http://www.slideshare.net/MilanPantech/", "Blog":"http://techfuzionwithsam.wordpress.com/" ] var basicInfoTitles:[String] = [] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. basicInfoTitles = [String](basicInfoDict.keys) tableView.estimatedRowHeight = 80.0 tableView.rowHeight = UITableViewAutomaticDimension } override func viewDidAppear(animated: Bool) { tableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return basicInfoTitles.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellIdentifier = "CustomCell" let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as CustomCell let infoTitle = basicInfoTitles[indexPath.row] cell.titleLabel.text = infoTitle cell.valueLabel.text = basicInfoDict[infoTitle] return cell } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "Personal Info" } }
35.383562
118
0.595045
337b0739d0cdf627b8647846c4017428ed6fdd34
2,041
// swift-tools-version:5.5 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "CocoaLumberjack", platforms: [ .iOS(.v13), .macOS(.v10_10), .watchOS(.v3), .tvOS(.v9), ], products: [ // Products define the executables and libraries produced by a package, and make them visible to other packages. .library( name: "CocoaLumberjack", targets: ["CocoaLumberjack"]), .library( name: "CocoaLumberjackSwift", targets: ["CocoaLumberjackSwift"]), .library( name: "CocoaLumberjackSwiftLogBackend", targets: ["CocoaLumberjackSwiftLogBackend"]), ], dependencies: [ .package(url: "https://github.com/apple/swift-log.git", from: "1.4.0"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages which this package depends on. .target(name: "CocoaLumberjack", exclude: ["Supporting Files"]), .target(name: "CocoaLumberjackSwiftSupport", dependencies: ["CocoaLumberjack"]), .target(name: "CocoaLumberjackSwift", dependencies: ["CocoaLumberjack", "CocoaLumberjackSwiftSupport"], exclude: ["Supporting Files"]), .target(name: "CocoaLumberjackSwiftLogBackend", dependencies: ["CocoaLumberjack", .product(name: "Logging", package: "swift-log")]), .testTarget(name: "CocoaLumberjackTests", dependencies: ["CocoaLumberjack"]), .testTarget(name: "CocoaLumberjackSwiftTests", dependencies: ["CocoaLumberjackSwift"]), .testTarget(name: "CocoaLumberjackSwiftLogBackendTests", dependencies: ["CocoaLumberjackSwiftLogBackend"]), ] )
41.653061
122
0.614895
21fa946c6194699e46b517aa99d96bdad828a9bf
1,474
// // LinearRegressionCommandTests.swift // UPNCalculatorTests // // Created by holgermayer on 11.02.20. // Copyright © 2020 holgermayer. All rights reserved. // import XCTest @testable import UPNCalculator class LinearRegressionCommandTests: XCTestCase { var engine : UPNEngine! var registerController : RegisterController! var display : CalculatorDisplay! var mockDelegate : DisplayMockDelegate! var testObject : Command! override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. engine = UPNEngine() registerController = RegisterController() registerController.delegate = engine display = CalculatorDisplay() mockDelegate = DisplayMockDelegate() display.delegate = mockDelegate testObject = LinearRegressionCommand( calculatorEngine: engine, display : display, registerController : registerController) } func testLinearRegressionForFarmer(){ let testSetup = StatisticsTestsSetup() testSetup.setupFarmerStatistic(engine: engine, display: display, registerController: registerController) let result = testObject.execute() XCTAssertEqual(result,.Default) XCTAssertEqual(engine.peek(register: .X)!,4.86, accuracy:0.01) XCTAssertEqual(engine.peek(register: .Y)!,0.04, accuracy:0.01) } }
30.708333
131
0.684532
cc754f6a7cea7f4cc559d4bf248fe88f29b46b85
7,578
protocol SeekbarDelegate: NSObjectProtocol { func seek(_: TimeInterval) func willBeginScrubbing() func didFinishScrubbing() } public class SeekbarView: UIView { public var progressColor: UIColor! = .blue public var bufferColor: UIColor! = .gray public var scrubberColor: UIColor! = .white public var hasTimeLabel = true @IBOutlet weak var seekBarContainerView: DragDetectorView! { didSet { seekBarContainerView.target = self seekBarContainerView.selector = #selector(handleSeekbarViewTouch(_:)) } } @IBOutlet weak var scrubberPosition: NSLayoutConstraint! @IBOutlet weak var scrubber: UIView! { didSet { scrubber.accessibilityIdentifier = "scrubber" } } @IBOutlet weak var scrubberOuterCircle: UIView? @IBOutlet weak var scrubberInnerCircle: UIView? @IBOutlet weak var bufferBar: UIView! @IBOutlet weak var progressBar: UIView! @IBOutlet weak var timeLabelView: UIView! { didSet { timeLabelView.isHidden = true } } @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var timeLabelPosition: NSLayoutConstraint! @IBOutlet weak var bufferWidth: NSLayoutConstraint! @IBOutlet open var scrubberOuterCircleWidthConstraint: NSLayoutConstraint? @IBOutlet open var scrubberOuterCircleHeightConstraint: NSLayoutConstraint? @IBOutlet open var progressBarWidthConstraint: NSLayoutConstraint? var isLive = false { didSet { isLive ? setupLiveStyle() : setupVODStyle() } } var videoDuration: CGFloat = 0 private(set) var isSeeking = false private(set) var previousSeekbarWidth: CGFloat = 0 weak var delegate: SeekbarDelegate? override public func layoutSubviews() { super.layoutSubviews() isLive ? putScrubberAtTheEnd() : repositionUIElements() previousSeekbarWidth = seekBarContainerView.frame.width } @objc func handleSeekbarViewTouch(_ view: DragDetectorView) { guard let touchPoint = view.currentTouch?.location(in: seekBarContainerView) else { return } moveScrubber(relativeTo: touchPoint.x) switch view.touchState { case .began, .moved, .idle: delegate?.willBeginScrubbing() isSeeking = true setOuterScrubberSize(outerCircleSizeFactor: 1.5, outerCircleBorderWidth: 1.0) case .ended, .canceled: delegate?.seek(seconds(relativeTo: scrubberPosition.constant)) delegate?.didFinishScrubbing() isSeeking = false setOuterScrubberSize(outerCircleSizeFactor: 1.0, outerCircleBorderWidth: 0.0) } } func updateScrubber(time: CGFloat) { guard videoDuration > 0, !isLive else { return } let position = (time / videoDuration) * (seekBarContainerView.frame.width) moveScrubber(relativeTo: position) } private func moveScrubber(relativeTo position: CGFloat) { let halfScrubberWidth = scrubber.frame.width / 2 let minBoundPosition = -halfScrubberWidth let maxBoundPosition = seekBarContainerView.frame.width - halfScrubberWidth var axisScrubberPosition = position - halfScrubberWidth if axisScrubberPosition <= minBoundPosition { axisScrubberPosition = minBoundPosition } else if axisScrubberPosition > maxBoundPosition { axisScrubberPosition = maxBoundPosition } scrubberPosition.constant = axisScrubberPosition progressBarWidthConstraint?.constant = axisScrubberPosition + halfScrubberWidth updateTimeLabel(relativeTo: scrubberPosition.constant) moveTimeLabel(relativeTo: position, state: .moved) } func moveTimeLabel(relativeTo horizontalTouchPoint: CGFloat, state: DragDetectorView.State) { if state == .moved { timeLabelView.isHidden = !hasTimeLabel let halfTimeLabelView: CGFloat = timeLabelView.frame.width / 2 var position = horizontalTouchPoint - halfTimeLabelView if position <= 0 { position = 0 } else if position > seekBarContainerView.frame.width - timeLabelView.frame.width { position = seekBarContainerView.frame.width - timeLabelView.frame.width } timeLabelPosition.constant = position } else { timeLabelView.isHidden = true } } private func updateTimeLabel(relativeTo horizontalTouchPoint: CGFloat) { let secs = seconds(relativeTo: horizontalTouchPoint) timeLabel.text = ClapprDateFormatter.formatSeconds(secs) } func updateBuffer(time: CGFloat) { guard videoDuration > 0 else { return } bufferWidth.constant = (time / videoDuration) * seekBarContainerView.frame.width } private func setOuterScrubberSize(outerCircleSizeFactor: CGFloat, outerCircleBorderWidth: CGFloat) { scrubberOuterCircleHeightConstraint?.constant = scrubber.frame.height * outerCircleSizeFactor scrubberOuterCircleWidthConstraint?.constant = scrubber.frame.width * outerCircleSizeFactor scrubberOuterCircle?.layer.cornerRadius = scrubber.frame.width * outerCircleSizeFactor / 2 scrubberOuterCircle?.layer.borderWidth = outerCircleBorderWidth } private func seconds(relativeTo scrubberPosition: CGFloat) -> Double { let width = seekBarContainerView.frame.width let positionPercentage = max(0, min((scrubberPosition + scrubber.frame.width / 2) / width, 1)) return Double(videoDuration * positionPercentage) } fileprivate func repositionScrubber() { let halfScrubber = scrubber.frame.width / 2 let previousPercentPosition = (scrubberPosition.constant + halfScrubber) / previousSeekbarWidth let newPercentPosition = previousPercentPosition * seekBarContainerView.frame.width moveScrubber(relativeTo: newPercentPosition) } fileprivate func redimentionBufferBar() { let previousPercentPosition = bufferWidth.constant / previousSeekbarWidth let newPercentPosition = previousPercentPosition * seekBarContainerView.frame.width bufferWidth.constant = newPercentPosition } private func repositionUIElements() { guard previousSeekbarWidth > 0 else { return } repositionScrubber() redimentionBufferBar() } private func setupLiveStyle() { progressBar.backgroundColor = .red bufferBar.isHidden = true timeLabelView.isHidden = true timeLabel.isHidden = true putScrubberAtTheEnd() scrubberInnerCircle?.backgroundColor = .red isUserInteractionEnabled = false } private func putScrubberAtTheEnd() { scrubberPosition.constant = seekBarContainerView.frame.width - scrubber.frame.width / 2 progressBarWidthConstraint?.constant = seekBarContainerView.frame.width } private func putScrubberAtTheBeginning() { scrubberPosition.constant = -(scrubber.frame.width / 2) progressBarWidthConstraint?.constant = 0 } private func setupVODStyle() { progressBar.backgroundColor = progressColor timeLabelView.isHidden = !hasTimeLabel timeLabel.isHidden = false bufferBar.isHidden = false putScrubberAtTheBeginning() scrubberInnerCircle?.backgroundColor = scrubberColor bufferBar.backgroundColor = bufferColor isUserInteractionEnabled = true } }
37.89
104
0.691607
fc21b57571d0e007a164dca527544f969c9e9563
284
// // Created by Efe Ejemudaro on 13/04/2021. // Copyright (c) 2021 TopTier labs. All rights reserved. // import Foundation struct VerifyUserRequest: Codable { var verificationCode: String private enum CodingKeys: String, CodingKey { case verificationCode } }
17.75
56
0.704225
acbd9d4940dc17e34b21cd90cac824a6ba9915a2
2,178
// // AppDelegate.swift // LeroLero // // Created by luizagarofalo on 01/17/2018. // Copyright (c) 2018 luizagarofalo. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.340426
285
0.75528
893feed6e6fc88651ecbd6d684c299fac6df3dde
3,751
class Solution { // Solution @ Sergey Leschev, Belarusian State University // 1872. Stone Game VIII // Alice and Bob take turns playing a game, with Alice starting first. // There are n stones arranged in a row. On each player's turn, while the number of stones is more than one, they will do the following: // Choose an integer x > 1, and remove the leftmost x stones from the row. // Add the sum of the removed stones' values to the player's score. // Place a new stone, whose value is equal to that sum, on the left side of the row. // The game stops when only one stone is left in the row // The score difference between Alice and Bob is (Alice's score - Bob's score). Alice's goal is to maximize the score difference, and Bob's goal is the minimize the score difference. // Given an integer array stones of length n where stones[i] represents the value of the ith stone from the left, return the score difference between Alice and Bob if they both play optimally. // Example 1: // Input: stones = [-1,2,-3,4,-5] // Output: 5 // Explanation: // - Alice removes the first 4 stones, adds (-1) + 2 + (-3) + 4 = 2 to her score, and places a stone of // value 2 on the left. stones = [2,-5]. // - Bob removes the first 2 stones, adds 2 + (-5) = -3 to his score, and places a stone of value -3 on // the left. stones = [-3]. // The difference between their scores is 2 - (-3) = 5. // Example 2: // Input: stones = [7,-6,5,10,5,-2,-6] // Output: 13 // Explanation: // - Alice removes all stones, adds 7 + (-6) + 5 + 10 + 5 + (-2) + (-6) = 13 to her score, and places a // stone of value 13 on the left. stones = [13]. // The difference between their scores is 13 - 0 = 13. // Example 3: // Input: stones = [-10,-12] // Output: -22 // Explanation: // - Alice can only make one move, which is to remove both stones. She adds (-10) + (-12) = -22 to her // score and places a stone of value -22 on the left. stones = [-22]. // The difference between their scores is (-22) - 0 = -22. // Constraints: // n == stones.length // 2 <= n <= 10^5 // -10^4 <= stones[i] <= 10^4 // Solution: DP // Let prefix sum prefix[i] = A[0] + ... + A[i]. // Let dp[i] be the maximum score difference the first player can get when the game starts at i, i.e. stones 0 ~ i are already merged as a new stone i whose value is prefix[i]. // Assume the first player merges stones 0 ~ j (i < j < N), according to the dp definition, the maximum score difference the next player can get using the remaining stones is dp[j]. And the score difference the first player gets is prefix[j] - dp[j]. // The first player will need to try all i < j < N and use the maximum prefix[j] - dp[j] as dp[i]. // Thus, we have: // dp[i] = max( prefix[j] - dp[j] | j > i ) // dp[N - 1] = prefix[N - 1] // Since we only care about the maximum value of prefix[j] - dp[j], we can use a mx value to store this maximum value. // - Complexity: // - time: O(n) // - space: O(1), only constant space is used. func stoneGameVIII(_ stones: [Int]) -> Int { let n = stones.count if n == 2 { return stones[0] + stones[1] } var sum = stones // sum[i] = stones[0] + stones[1] + ... + stones[i] var diff = Int.min for i in 1..<n { sum[i] += sum[i - 1] } var val = sum[n - 1] // dp[n - 1] = sum[n - 1] for i in stride(from: n - 2, through: 0, by: -1) { diff = max(diff, val) // dp[i] is val, use dp[i] to update diff val = max(val, sum[i] - val) // update val by using sum[i] - dp[i] } return diff } }
50.013333
254
0.597441
aca99f89cc62f711a0d9c231bd41ed0d9f8f152b
10,323
// Skype.swift // Skype ( https://github.com/xmartlabs/XLActionController ) // // Copyright (c) 2015 Xmartlabs ( http://xmartlabs.com ) // // // 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 XLActionController public class SkypeCell: UICollectionViewCell { @IBOutlet weak var actionTitleLabel: UILabel! public override init(frame: CGRect) { super.init(frame: frame) initialize() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public override func awakeFromNib() { super.awakeFromNib() initialize() } func initialize() { backgroundColor = .clearColor() actionTitleLabel?.textColor = .darkGrayColor() let backgroundView = UIView() backgroundView.backgroundColor = backgroundColor selectedBackgroundView = backgroundView } } public class SkypeActionController: ActionController<SkypeCell, String, UICollectionReusableView, Void, UICollectionReusableView, Void> { private var contextView: ContextView! private var normalAnimationRect: UIView! private var springAnimationRect: UIView! let topSpace = CGFloat(40) public override init(nibName nibNameOrNil: String? = nil, bundle nibBundleOrNil: NSBundle? = nil) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) cellSpec = .NibFile(nibName: "SkypeCell", bundle: NSBundle(forClass: SkypeCell.self), height: { _ in 60 }) settings.animation.scale = nil settings.animation.present.duration = 0.5 settings.animation.present.options = UIViewAnimationOptions.CurveEaseOut.union(.AllowUserInteraction) settings.animation.present.springVelocity = 0.0 settings.animation.present.damping = 0.7 settings.statusBar.style = .Default onConfigureCellForAction = { cell, action, indexPath in cell.actionTitleLabel.text = action.data cell.actionTitleLabel.textColor = .whiteColor() cell.alpha = action.enabled ? 1.0 : 0.5 } } public override func viewDidLoad() { super.viewDidLoad() contextView = ContextView(frame: CGRectMake(0, -topSpace, collectionView.bounds.width, contentHeight + topSpace + 20)) contextView.autoresizingMask = UIViewAutoresizing.FlexibleWidth.union(.FlexibleBottomMargin) collectionView.clipsToBounds = false collectionView.addSubview(contextView) collectionView.sendSubviewToBack(contextView) normalAnimationRect = UIView(frame: CGRect(x: 0, y: view.bounds.height/2, width: 30, height: 30)) normalAnimationRect.hidden = true view.addSubview(normalAnimationRect) springAnimationRect = UIView(frame: CGRect(x: 40, y: view.bounds.height/2, width: 30, height: 30)) springAnimationRect.hidden = true view.addSubview(springAnimationRect) backgroundView.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.65) } override public func onWillPresentView() { super.onWillPresentView() collectionView.frame.origin.y = contentHeight + (topSpace - contextView.topSpace) startAnimation() let initSpace = CGFloat(45.0) let initTime = 0.1 let animationDuration = settings.animation.present.duration - 0.1 let options = UIViewAnimationOptions.CurveEaseOut.union(.AllowUserInteraction) UIView.animateWithDuration(initTime, delay: settings.animation.present.delay, options: options, animations: { [weak self] in guard let me = self else { return } var frame = me.springAnimationRect.frame frame.origin.y = frame.origin.y - initSpace me.springAnimationRect.frame = frame }, completion: { [weak self] finished in guard let me = self where finished else { self?.finishAnimation() return } UIView.animateWithDuration(animationDuration - initTime, delay: 0, options: options, animations: { [weak self] in guard let me = self else { return } var frame = me.springAnimationRect.frame frame.origin.y -= (me.contentHeight - initSpace) me.springAnimationRect.frame = frame }, completion: { (finish) -> Void in me.finishAnimation() }) }) UIView.animateWithDuration(animationDuration - initTime, delay: settings.animation.present.delay + initTime, options: options, animations: { [weak self] in guard let me = self else { return } var frame = me.normalAnimationRect.frame frame.origin.y -= me.contentHeight me.normalAnimationRect.frame = frame }, completion:nil) } override public func dismissView(presentedView: UIView, presentingView: UIView, animationDuration: Double, completion: ((completed: Bool) -> Void)?) { finishAnimation() finishAnimation() let animationSettings = settings.animation.dismiss UIView.animateWithDuration(animationDuration, delay: animationSettings.delay, usingSpringWithDamping: animationSettings.damping, initialSpringVelocity: animationSettings.springVelocity, options: animationSettings.options, animations: { [weak self] in self?.backgroundView.alpha = 0.0 }, completion:nil) gravityBehavior.action = { [weak self] in if let me = self { let progress = min(1.0, me.collectionView.frame.origin.y / (me.contentHeight + (me.topSpace - me.contextView.topSpace))) let pixels = min(20, progress * 150.0) me.contextView.diff = -pixels me.contextView.setNeedsDisplay() if self?.collectionView.frame.origin.y > self?.view.bounds.size.height { self?.animator.removeAllBehaviors() completion?(completed: true) } } } animator.addBehavior(gravityBehavior) } //MARK : Private Helpers private var diff = CGFloat(0) private var displayLink: CADisplayLink! private var animationCount = 0 private lazy var animator: UIDynamicAnimator = { [unowned self] in let animator = UIDynamicAnimator(referenceView: self.view) return animator }() private lazy var gravityBehavior: UIGravityBehavior = { [unowned self] in let gravityBehavior = UIGravityBehavior(items: [self.collectionView]) gravityBehavior.magnitude = 2.0 return gravityBehavior }() @objc private func update(displayLink: CADisplayLink) { let normalRectLayer = normalAnimationRect.layer.presentationLayer() let springRectLayer = springAnimationRect.layer.presentationLayer() let normalRectFrame = normalRectLayer!.valueForKey("frame")!.CGRectValue let springRectFrame = springRectLayer!.valueForKey("frame")!.CGRectValue contextView.diff = normalRectFrame.origin.y - springRectFrame.origin.y contextView.setNeedsDisplay() } private func startAnimation() { if displayLink == nil { self.displayLink = CADisplayLink(target: self, selector: "update:") self.displayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode) } animationCount++ } private func finishAnimation() { animationCount-- if animationCount == 0 { displayLink.invalidate() displayLink = nil } } private class ContextView: UIView { let topSpace = CGFloat(25) var diff = CGFloat(0) override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .clearColor() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func drawRect(rect: CGRect) { let path = UIBezierPath() path.moveToPoint(CGPoint(x: 0, y: frame.height)) path.addLineToPoint(CGPoint(x: frame.width, y: frame.height)) path.addLineToPoint(CGPoint(x: frame.width, y: topSpace)) path.addQuadCurveToPoint(CGPoint(x: 0, y: topSpace), controlPoint: CGPoint(x: frame.width/2, y: topSpace - diff)) path.closePath() let context = UIGraphicsGetCurrentContext() CGContextAddPath(context, path.CGPath) UIColor(colorLiteralRed: 18/255.0, green: 165/255.0, blue: 244/255.0, alpha: 1.0).set() CGContextFillPath(context) } } }
39.857143
163
0.626368
e80c8d94261706b646610bf161fe169e8da7609a
936
// // TelegramProjectRefresh.swift // amon // // Created by Dr. Kerem Koseoglu on 20.04.2019. // Copyright © 2019 Dr. Kerem Koseoglu. All rights reserved. // import Foundation import UIKit import EasyTelegram class TelegramProjectRefresh : TelegramEmployedDronesTaskWorker { //////////////////////////////////////////////////////////// // TelegramEmployedDronesTaskWorker //////////////////////////////////////////////////////////// override internal func getBotCommand(employedDrone:ProjectDrone) -> String { return TelegramDroneStatus.getDroneQuestion(employedDrone.drone.state.name) } override internal func getExpectedBotReply() -> String { return TelegramDroneStatus.botReplyCommand } override internal func handleEmployedBotReply(repliedDrone: ProjectDrone, success: Bool, reply: TelegramBotReply, error: String) { if success { repliedDrone.drone.state = TelegramDroneStatus.parseReply(reply) } } }
29.25
131
0.680556
de210e4b139fbc88a080ceac4c1e7528eb4abe53
1,399
// // DetailOverviewViewCell.swift // sMovie // // Created by Sebass on 06/04/2019. // Copyright © 2019 Sebass. All rights reserved. // import UIKit class DetailOverviewViewCell: UITableViewCell { @IBOutlet weak var yearInfoLabel: UILabel! @IBOutlet weak var lengthInfoLabel: UILabel! @IBOutlet weak var overviewInfoLabel: UILabel! @IBOutlet weak var countryInfoLabel: UILabel! @IBOutlet weak var storyLineLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() addLabelValues(label: yearInfoLabel) addLabelValues(label: lengthInfoLabel) addLabelValues(label: countryInfoLabel) addLabelValues(label: overviewInfoLabel) addLabelValues(label: storyLineLabel) //Font addFont(to: storyLineLabel) addFont(to: yearInfoLabel) addFont(to: lengthInfoLabel) addFont(to: countryInfoLabel) overviewInfoLabel.sizeToFit() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } private func addLabelValues(label: UILabel){ label.textColor = UIColor.white } private func addFont(to label: UILabel){ label.font = UIFont(name: "Arial Rounded MT Bold", size: 15) } }
27.431373
68
0.663331