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
232778b1c8ef5f02e23386804700c977ada13359
2,586
// // ViewController.swift // AlamoUpload // // Created by Adi Nugroho on 5/18/16. // Copyright © 2016 Adi Nugroho. All rights reserved. // import UIKit import Alamofire class ViewController: UIViewController { @IBOutlet weak var imgView: UIImageView! let picker = UIImagePickerController() var pickedImagePath: NSURL? var pickedImageData: NSData? var localPath: String? override func viewDidLoad() { super.viewDidLoad() picker.allowsEditing = false picker.delegate = self } @IBAction func onBtnOpenClicked(sender: UIButton) { presentViewController(picker, animated: true, completion: nil) } @IBAction func onBtnSubmitClicked(sender: UIButton) { guard let path = localPath else { return } Alamofire.upload(.POST, "http://172.18.200.201:8080/FileUploaderRESTService/rest/upload" , multipartFormData: { formData in let filePath = NSURL(fileURLWithPath: path) formData.appendBodyPart(fileURL: filePath, name: "file") formData.appendBodyPart(data: "Alamofire".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name: "file") }, encodingCompletion: { encodingResult in switch encodingResult { case .Success: print("SUCCESS") case .Failure(let error): print(error) } }) } } extension ViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { guard let image = info[UIImagePickerControllerOriginalImage] as? UIImage else { return } imgView.image = image let documentDirectory: NSString = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! let imageName = "temp" let imagePath = documentDirectory.stringByAppendingPathComponent(imageName) if let data = UIImageJPEGRepresentation(image, 80) { data.writeToFile(imagePath, atomically: true) } localPath = imagePath dismissViewControllerAnimated(true, completion: { }) } func imagePickerControllerDidCancel(picker: UIImagePickerController) { dismissViewControllerAnimated(true, completion: nil) } }
31.925926
142
0.633024
edb3ede78127a85ff4a71a5a14ca4b98f1f96558
344
import Foundation extension String { func md5UUID() -> NSUUID { let data = self.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! let md = UnsafeMutablePointer<UInt8>.alloc(Int(CC_MD5_DIGEST_LENGTH)) CC_MD5(data.bytes, CC_LONG(data.length), md) return NSUUID(UUIDBytes: md) } }
28.666667
93
0.686047
bfb9c892e5d8bcc8bc871f7f0c74da5c6e7fe58e
424
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse 0 a {func b{class a{class case,
32.615385
78
0.747642
56317fe9f40894fce902941400f195eed28efb31
304
import UIKit import XCTest @testable import Glyptodon class UIViewGlyptodonExtensionTests: XCTestCase { func testGetCreatesAndStoresGlyptodonInstance() { let view = UIView() let glyptodon1 = view.glyptodon let glyptodon2 = view.glyptodon XCTAssert(glyptodon1 === glyptodon2) } }
23.384615
51
0.75
bb77900ad71bc40ff38547111ce07caf140bcb68
3,572
// // PlaybackDelegateTests+TrackCompletion.swift // Aural // // Copyright © 2021 Kartik Venugopal. All rights reserved. // // This software is licensed under the MIT software license. // See the file "LICENSE" in the project root directory for license terms. // import XCTest class PlaybackDelegateTests_TrackCompletion: PlaybackDelegateTestCase { func testTrackPlaybackCompleted_noSubsequentTrack() { let completedTrack = createTrack(title: "So Far Away", duration: 300) doTestTrackPlaybackCompleted(completedTrack, nil) } func testTrackPlaybackCompleted_hasSubsequentTrack() { let completedTrack = createTrack(title: "So Far Away", duration: 300) let subsequentTrack = createTrack(title: "Private Investigations", duration: 360) doTestTrackPlaybackCompleted(completedTrack, subsequentTrack) } private func doTestTrackPlaybackCompleted(_ completedTrack: Track, _ subsequentTrack: Track?) { doBeginPlayback(completedTrack) sequencer.subsequentTrack = subsequentTrack delegate.trackPlaybackCompleted(PlaybackSession.currentSession!) XCTAssertEqual(trackPlaybackCompletedChain.executionCount, 1) if let theSubsequentTrack = subsequentTrack { assertPlayingTrack(theSubsequentTrack) XCTAssertEqual(startPlaybackChain.executionCount, 2) XCTAssertTrue(trackPlaybackCompletedChain.executedContext! === startPlaybackChain.executedContext!) } else { assertNoTrack() XCTAssertEqual(startPlaybackChain.executionCount, 1) XCTAssertEqual(stopPlaybackChain.executionCount, 1) XCTAssertTrue(trackPlaybackCompletedChain.executedContext! === stopPlaybackChain.executedContext!) } } // ---------------------------------------------------------------------------- // MARK: End-to-end tests func testEndToEnd_noSubsequentTrack() { let track = createTrack(title: "Money for Nothing", duration: 420) doBeginPlayback(track) XCTAssertTrue(PlaybackSession.hasCurrentSession()) sequencer.subsequentTrack = nil // Publish a message for the delegate to process messenger.publish(.player_trackPlaybackCompleted, payload: PlaybackSession.currentSession!) executeAfter(0.2) { // Message should have been processed ... track playback should have continued XCTAssertEqual(self.trackPlaybackCompletedChain.executionCount, 1) XCTAssertEqual(self.startPlaybackChain.executionCount, 1) XCTAssertEqual(self.stopPlaybackChain.executionCount, 1) self.assertNoTrack() } } func testEndToEnd_hasSubsequentTrack() { let track = createTrack(title: "Money for Nothing", duration: 420) doBeginPlayback(track) XCTAssertTrue(PlaybackSession.hasCurrentSession()) let subsequentTrack = createTrack(title: "Private Investigations", duration: 360) sequencer.subsequentTrack = subsequentTrack // Publish a message for the delegate to process messenger.publish(.player_trackPlaybackCompleted, payload: PlaybackSession.currentSession!) executeAfter(0.2) { // Message should have been processed ... track playback should have continued XCTAssertEqual(self.trackPlaybackCompletedChain.executionCount, 1) XCTAssertEqual(self.startPlaybackChain.executionCount, 2) self.assertPlayingTrack(subsequentTrack) } } }
35.366337
111
0.693729
9c46556e4296b3ac3e714867b1bd77e38cd05c04
936
// // FeedImagesMapper.swift // FeedAPIChallenge // // Created by GD on 8/24/21. // Copyright © 2021 Essential Developer Ltd. All rights reserved. // import Foundation final class FeedImagesMapper { private struct Root: Decodable { let items: [Item] var feedImages: [FeedImage] { return items.map { $0.item } } } private struct Item: Decodable { let image_id: UUID let image_desc: String? let image_loc: String? let image_url: URL var item: FeedImage { return FeedImage(id: image_id, description: image_desc, location: image_loc, url: image_url) } } private static var OK_200: Int { return 200 } static func map(_ data: Data, from response: HTTPURLResponse) -> FeedLoader.Result { guard response.statusCode == OK_200, let root = try? JSONDecoder().decode(Root.self, from: data) else { return .failure(RemoteFeedLoader.Error.invalidData) } return .success(root.feedImages) } }
22.285714
95
0.702991
f5ac2ddc79c3e346c47a0579ae0b15bd05012821
2,445
/// Copyright (c) 2021 Razeware LLC /// /// Permission is hereby granted, free of charge, to any person obtaining a copy /// of this software and associated documentation files (the "Software"), to deal /// in the Software without restriction, including without limitation the rights /// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell /// copies of the Software, and to permit persons to whom the Software is /// furnished to do so, subject to the following conditions: /// /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software. /// /// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, /// distribute, sublicense, create a derivative work, and/or sell copies of the /// Software in any work that is designed, intended, or marketed for pedagogical or /// instructional purposes related to programming, coding, application development, /// or information technology. Permission for such use, copying, modification, /// merger, publication, distribution, sublicensing, creation of derivative works, /// or sale is expressly withheld. /// /// This project and source code may use libraries or frameworks that are /// released under various Open-Source licenses. Use of those libraries and /// frameworks are governed by their own individual licenses. /// /// 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 class EpisodeStore: ObservableObject { @Published var episodes: [Episode] = [] init() { #if DEBUG createDevData() #endif } } struct Episode { let name: String let description: String // description_plain_text let released: String // released_at let domain: String // enum let difficulty: String // enum let videoURLString: String // will be videoIdentifier: Int let uri: String // redirects to the real web page var linkURLString: String { "https://www.raywenderlich.com/redirect?uri=" + uri } }
42.894737
83
0.741922
39e26828881093e9b7c19a5c4bfd67184e1bb06c
2,488
// // LayoutConstraintSizeBuilder.swift // FlooidUI // // Created by Martin Lalev on 30.06.19. // Copyright © 2019 Martin Lalev. All rights reserved. // import Foundation import UIKit public struct NSLayoutSizeConstraints { public let width: NSLayoutConstraint public let height: NSLayoutConstraint } public extension NSLayoutSize { @discardableResult static func == (lhs: NSLayoutSize, rhs: NSLayoutSize) -> NSLayoutSizeConstraints { return .init(width: lhs.widthAnchor == rhs.widthProperties, height: lhs.heightAnchor == rhs.heightProperties) } @discardableResult static func <= (lhs: NSLayoutSize, rhs: NSLayoutSize) -> NSLayoutSizeConstraints { return .init(width: lhs.widthAnchor <= rhs.widthProperties, height: lhs.heightAnchor <= rhs.heightProperties) } @discardableResult static func >= (lhs: NSLayoutSize, rhs: NSLayoutSize) -> NSLayoutSizeConstraints { return .init(width: lhs.widthAnchor >= rhs.widthProperties, height: lhs.heightAnchor >= rhs.heightProperties) } @discardableResult static func == (lhs: NSLayoutSize, rhs: SizeConstraintParametersProvider) -> NSLayoutSizeConstraints { return .init(width: lhs.widthAnchor == rhs.widthProperties, height: lhs.heightAnchor == rhs.heightProperties) } @discardableResult static func <= (lhs: NSLayoutSize, rhs: SizeConstraintParametersProvider) -> NSLayoutSizeConstraints { return .init(width: lhs.widthAnchor <= rhs.widthProperties, height: lhs.heightAnchor <= rhs.heightProperties) } @discardableResult static func >= (lhs: NSLayoutSize, rhs: SizeConstraintParametersProvider) -> NSLayoutSizeConstraints { return .init(width: lhs.widthAnchor >= rhs.widthProperties, height: lhs.heightAnchor >= rhs.heightProperties) } @discardableResult static func == (lhs: NSLayoutSize, rhs: CGSize) -> NSLayoutSizeConstraints { return .init(width: lhs.widthAnchor == rhs.width, height: lhs.heightAnchor == rhs.height) } @discardableResult static func <= (lhs: NSLayoutSize, rhs: CGSize) -> NSLayoutSizeConstraints { return .init(width: lhs.widthAnchor <= rhs.width, height: lhs.heightAnchor <= rhs.height) } @discardableResult static func >= (lhs: NSLayoutSize, rhs: CGSize) -> NSLayoutSizeConstraints { return .init(width: lhs.widthAnchor >= rhs.width, height: lhs.heightAnchor >= rhs.height) } }
38.276923
117
0.702572
e53b3f9564905ac60ca1e5c1aa89622b5ff713c7
1,320
//---------------------------------------------------- // // Generated by www.easywsdl.com // Version: 5.7.0.0 // // Created by Quasar Development // //--------------------------------------------------- import Foundation public class EPA_FdV_AUTHZ_adxp_x002E_precinct : NSObject ,EPA_FdV_AUTHZ_ISerializableObject { private var __source:DDXMLNode? = nil public required override init() { super.init() } public func loadWithXml(__node: DDXMLElement, __request:EPA_FdV_AUTHZ_RequestResultHandler) { __source=__node; for i :UInt in 0 ..< __node.childCount { let node=__node.child(at:i) if node?.kind==UInt(XMLElementKind) { let __node=node as! DDXMLElement if loadProperty(__node:__node, __request:__request) == false { } } } } public func serialize(__parent:DDXMLElement, __request:EPA_FdV_AUTHZ_RequestResultHandler) { } public func loadProperty(__node: DDXMLElement, __request: EPA_FdV_AUTHZ_RequestResultHandler ) -> Bool { return false } public func getOriginalXmlSource() ->DDXMLNode? { return __source } }
25.384615
109
0.537121
eb07c98de157bb69a467fcb504308eb5974d76d2
5,596
// // Similar_Spec.swift // SwiftXtend-Tests // // Created by José Donor on 22/11/2018. // import Nimble import Quick @testable import SwiftXtend struct Object: Similar, Hashable { var id: String var value: Int init(id: String = UUID().uuidString, value: Int) { self.id = id self.value = value } var hashValue: Int { return id.hashValue } static func == (lhs: Object, rhs: Object) -> Bool { return lhs.id == rhs.id && lhs.value == rhs.value } static func ~~ (lhs: Object, rhs: Object) -> Bool { return lhs.id == rhs.id } } class Similar_Spec: QuickSpec { override func spec() { describe("Objects") { describe("`~~ (similar)`") { it("should be similar") { let A = Object(id: "1", value: 1) let B = Object(id: "1", value: 2) expect(A ~~ B).to(beTrue()) } } describe("`!~ (not similar)`") { it("should be not similar") { let A = Object(id: "1", value: 1) let B = Object(id: "2", value: 2) expect(A ~~ B).to(beFalse()) } } } describe("Optional objects") { describe("`~~ (similar)`") { context("non-nil objects") { it("should be similar") { let A: Object? = Object(id: "1", value: 1) let B: Object? = Object(id: "1", value: 2) expect(A ~~ B).to(beTrue()) } } context("nil objects") { it("should be similar") { let A: Object? = nil let B: Object? = nil expect(A ~~ B).to(beTrue()) } } } describe("`!~ (not similar)`") { context("non-nil objects") { it("should be not similar") { let A: Object? = Object(id: "1", value: 1) let B: Object? = Object(id: "2", value: 2) expect(A ~~ B).to(beFalse()) } } context("a nil & a non-nil objects") { it("should be not similar") { let A: Object? = Object(id: "1", value: 1) let B: Object? = nil expect(A ~~ B).to(beFalse()) } } } } describe("Arrays") { describe("`~~ (similar)`") { it("should be similar") { let A = Object(id: "1", value: 1) let B = Object(id: "2", value: 2) let C = Object(id: "3", value: 3) let a = Object(id: "1", value: 10) let b = Object(id: "2", value: 20) let c = Object(id: "3", value: 30) expect([A, B, C] ~~ [a, b, c]).to(beTrue()) } } describe("`!~ (not similar)`") { context("when arrays are different size") { it("should be not similar") { let A = Object(id: "1", value: 1) let B = Object(id: "2", value: 2) let C = Object(id: "3", value: 3) let a = Object(id: "1", value: 10) let b = Object(id: "2", value: 20) expect([A, B, C] ~~ [a, b]).to(beFalse()) } } context("when two elements are not similar") { it("should be not similar") { let A = Object(id: "1", value: 1) let B = Object(id: "2", value: 2) let C = Object(id: "3", value: 3) let a = Object(id: "1", value: 10) let b = Object(id: "2", value: 20) let c = Object(id: "4", value: 3) expect([A, B, C] ~~ [a, b, c]).to(beFalse()) } } } } describe("Sets") { describe("`~~ (similar)`") { it("should be similar") { let A = Object(id: "1", value: 1) let B = Object(id: "2", value: 2) let C = Object(id: "3", value: 3) let a = Object(id: "1", value: 10) let b = Object(id: "2", value: 20) let c = Object(id: "3", value: 30) expect(Set([A, B, C]) ~~ Set([c, a, b])).to(beTrue()) } } describe("`!~ (not similar)`") { context("when arrays are different size") { it("should be not similar") { let A = Object(id: "1", value: 1) let B = Object(id: "2", value: 2) let C = Object(id: "3", value: 3) let a = Object(id: "1", value: 10) let b = Object(id: "2", value: 20) expect(Set([A, B, C]) ~~ Set([b, a])).to(beFalse()) } } context("when two elements are not similar") { it("should be not similar") { let A = Object(id: "1", value: 1) let B = Object(id: "2", value: 2) let C = Object(id: "3", value: 3) let a = Object(id: "1", value: 10) let b = Object(id: "2", value: 20) let c = Object(id: "4", value: 3) expect(Set([A, B, C]) ~~ Set([c, b, a])).to(beFalse()) } } } } describe("Dictionaries") { describe("`~~ (similar)`") { it("should be similar") { let A = Object(id: "1", value: 1) let B = Object(id: "2", value: 2) let C = Object(id: "3", value: 3) let a = Object(id: "1", value: 10) let b = Object(id: "2", value: 20) let c = Object(id: "3", value: 30) expect([1: A, 2: B, 3: C] ~~ [1: a, 2: b, 3: c]).to(beTrue()) } } describe("`!~ (not similar)`") { context("when arrays are different size") { it("should be not similar") { let A = Object(id: "1", value: 1) let B = Object(id: "2", value: 2) let C = Object(id: "3", value: 3) let a = Object(id: "1", value: 10) let b = Object(id: "2", value: 20) expect([1: A, 2: B, 3: C] ~~ [1: a, 2: b]).to(beFalse()) } } context("when two values are not similar") { it("should be not similar") { let A = Object(id: "1", value: 1) let B = Object(id: "2", value: 2) let C = Object(id: "3", value: 3) let a = Object(id: "1", value: 10) let b = Object(id: "2", value: 20) let c = Object(id: "4", value: 3) expect([1: A, 2: B, 3: C] ~~ [1: a, 2: b, 3: c]).to(beFalse()) } } } } } }
19.164384
68
0.493209
2f1944d86c440141c2fbd6d25bfbd3e8ee887513
12,918
import UIKit let dhRingStorkeAnimationKey = "IDLoading.stroke" let dhRingRotationAnimationKey = "IDLoading.rotation" let dhCompletionAnimationDuration: TimeInterval = 0.3 let dhHidesWhenCompletedDelay: TimeInterval = 0.5 public typealias Block = () -> Void public class CircleProgress: UIView, CAAnimationDelegate { public enum ProgressStatus: Int { case Unknown, Loading, Progress, Completion } @IBInspectable public var lineWidth: CGFloat = 2.0 { didSet { progressLayer.lineWidth = lineWidth shapeLayer.lineWidth = lineWidth setProgressLayerPath() } } @IBInspectable public var strokeColor: UIColor = UIColor(red: 0.0, green: 122.0/255.0, blue: 1.0, alpha: 1.0){ didSet{ progressLayer.strokeColor = strokeColor.cgColor shapeLayer.strokeColor = strokeColor.cgColor progressLabel.textColor = strokeColor } } @IBInspectable public var fontSize: Float = 25 { didSet{ progressLabel.font = UIFont(name: "Didot", size: CGFloat(fontSize)) } } public var hidesWhenCompleted: Bool = false public var hideAfterTime: TimeInterval = dhHidesWhenCompletedDelay public private(set) var status: ProgressStatus = .Unknown private var _progress: Double = 0.0 public var progress: Double { get { setNeedsDisplay() return _progress } set(newProgress) { //Avoid calling excessively if (newProgress - _progress >= 0.001 || newProgress >= 100.0) { _progress = min(max(0, newProgress), 1) progressLayer.strokeEnd = CGFloat(_progress) if status == .Loading { progressLayer.removeAllAnimations() } else if(status == .Completion) { shapeLayer.strokeStart = 0 shapeLayer.strokeEnd = 0 shapeLayer.removeAllAnimations() } status = .Progress // progressLabel.isHidden = false let progressInt: Int = Int(_progress * 100) progressLabel.text = "\(progressInt)" setNeedsDisplay() } } } private let progressLayer: CAShapeLayer! = CAShapeLayer() private let shapeLayer: CAShapeLayer! = CAShapeLayer() private let progressLabel: UILabel! = UILabel() private var completionBlock: Block? public override init(frame: CGRect) { super.init(frame: frame) initialize() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } deinit{ NotificationCenter.default.removeObserver(self) } override public func layoutSubviews() { super.layoutSubviews() let width = self.bounds.width let height = self.bounds.height let square = min(width, height) let bounds = CGRect(origin: CGPoint(x:0, y:0), size: CGSize(width:square, height:square)) progressLayer.frame = CGRect(origin:CGPoint(x:0, y:0), size:CGSize(width:width, height:height)) setProgressLayerPath() shapeLayer.bounds = bounds shapeLayer.position = CGPoint(x:self.bounds.midX, y:self.bounds.midY) let labelSquare = sqrt(2) / 2.0 * square progressLabel.bounds = CGRect(origin:CGPoint(x:0, y:0), size:CGSize(width:labelSquare, height:labelSquare)) progressLabel.center = CGPoint(x:self.bounds.midX, y:self.bounds.midY) } public func startLoading() { if status == .Loading { return } status = .Loading //progressLabel.isHidden = true progressLabel.text = "0" _progress = 0 shapeLayer.strokeStart = 0 shapeLayer.strokeEnd = 0 shapeLayer.removeAllAnimations() //self.isHidden = false progressLayer.strokeEnd = 0.0 progressLayer.removeAllAnimations() let animation = CABasicAnimation(keyPath: "transform.rotation") animation.duration = 4.0 animation.fromValue = 0.0 animation.toValue = 2 * Double.pi animation.repeatCount = Float.infinity progressLayer.add(animation, forKey: dhRingRotationAnimationKey) let totalDuration = 1.0 let firstDuration = 2.0 * totalDuration / 3.0 let secondDuration = totalDuration / 3.0 let headAnimation = CABasicAnimation(keyPath: "strokeStart") headAnimation.duration = firstDuration headAnimation.fromValue = 0.0 headAnimation.toValue = 0.25 let tailAnimation = CABasicAnimation(keyPath: "strokeEnd") tailAnimation.duration = firstDuration tailAnimation.fromValue = 0.0 tailAnimation.toValue = 1.0 let endHeadAnimation = CABasicAnimation(keyPath: "strokeStart") endHeadAnimation.beginTime = firstDuration endHeadAnimation.duration = secondDuration endHeadAnimation.fromValue = 0.25 endHeadAnimation.toValue = 1.0 let endTailAnimation = CABasicAnimation(keyPath: "strokeEnd") endTailAnimation.beginTime = firstDuration endTailAnimation.duration = secondDuration endTailAnimation.fromValue = 1.0 endTailAnimation.toValue = 1.0 let animations = CAAnimationGroup() animations.duration = firstDuration + secondDuration animations.repeatCount = Float.infinity animations.animations = [headAnimation, tailAnimation, endHeadAnimation, endTailAnimation] progressLayer.add(animations, forKey: dhRingRotationAnimationKey) } public func completeLoading(success: Bool, completion: Block? = nil) { if status == .Completion { return } completionBlock = completion // progressLabel.isHidden = true progressLayer.strokeEnd = 1.0 progressLayer.removeAllAnimations() if success { setStrokeSuccessShapePath() self.strokeColor = UIColor.green } else { setStrokeFailureShapePath() self.strokeColor = UIColor.red } var strokeStart :CGFloat = 0.25 var strokeEnd :CGFloat = 0.8 var phase1Duration = 0.7 * dhCompletionAnimationDuration var phase2Duration = 0.3 * dhCompletionAnimationDuration var phase3Duration = 0.0 if !success { let square = min(self.bounds.width, self.bounds.height) let point = errorJoinPoint() let increase = 1.0/3 * square - point.x let sum = 2.0/3 * square strokeStart = increase / (sum + increase) strokeEnd = (increase + sum/2) / (sum + increase) phase1Duration = 0.5 * dhCompletionAnimationDuration phase2Duration = 0.2 * dhCompletionAnimationDuration phase3Duration = 0.3 * dhCompletionAnimationDuration } shapeLayer.strokeEnd = 1.0 shapeLayer.strokeStart = strokeStart let timeFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut) let headStartAnimation = CABasicAnimation(keyPath: "strokeStart") headStartAnimation.fromValue = 0.0 headStartAnimation.toValue = 0.0 headStartAnimation.duration = phase1Duration headStartAnimation.timingFunction = timeFunction let headEndAnimation = CABasicAnimation(keyPath: "strokeEnd") headEndAnimation.fromValue = 0.0 headEndAnimation.toValue = strokeEnd headEndAnimation.duration = phase1Duration headEndAnimation.timingFunction = timeFunction let tailStartAnimation = CABasicAnimation(keyPath: "strokeStart") tailStartAnimation.fromValue = 0.0 tailStartAnimation.toValue = strokeStart tailStartAnimation.beginTime = phase1Duration tailStartAnimation.duration = phase2Duration tailStartAnimation.timingFunction = timeFunction let tailEndAnimation = CABasicAnimation(keyPath: "strokeEnd") tailEndAnimation.fromValue = strokeEnd tailEndAnimation.toValue = success ? 1.0 : strokeEnd tailEndAnimation.beginTime = phase1Duration tailEndAnimation.duration = phase2Duration tailEndAnimation.timingFunction = timeFunction let extraAnimation = CABasicAnimation(keyPath: "strokeEnd") extraAnimation.fromValue = strokeEnd extraAnimation.toValue = 1.0 extraAnimation.beginTime = phase1Duration + phase2Duration extraAnimation.duration = phase3Duration extraAnimation.timingFunction = timeFunction let groupAnimation = CAAnimationGroup() groupAnimation.animations = [headEndAnimation, headStartAnimation, tailStartAnimation, tailEndAnimation] if !success { groupAnimation.animations?.append(extraAnimation) } groupAnimation.duration = phase1Duration + phase2Duration + phase3Duration groupAnimation.delegate = self shapeLayer.add(groupAnimation, forKey: nil) } public func animationDidStop(_: CAAnimation, finished flag: Bool) { if hidesWhenCompleted { Timer.scheduledTimer(timeInterval: dhHidesWhenCompletedDelay, target: self, selector: #selector(hiddenLoadingView), userInfo: nil, repeats: false) } else { status = .Completion if completionBlock != nil { completionBlock!() } } } //MARK: - Private private func initialize() { //progressLabel progressLabel.font = UIFont(name: "Didot", size: CGFloat(fontSize)) progressLabel.textColor = strokeColor progressLabel.textAlignment = .center progressLabel.adjustsFontSizeToFitWidth = true // progressLabel.isHidden = true self.addSubview(progressLabel) //progressLayer progressLayer.strokeColor = strokeColor.cgColor progressLayer.fillColor = nil progressLayer.lineWidth = lineWidth self.layer.addSublayer(progressLayer) //shapeLayer shapeLayer.strokeColor = UIColor.gray.cgColor//strokeColor.cgColor shapeLayer.fillColor = nil shapeLayer.lineWidth = lineWidth shapeLayer.lineCap = CAShapeLayerLineCap.round shapeLayer.lineJoin = CAShapeLayerLineJoin.round shapeLayer.strokeStart = 0.0 shapeLayer.strokeEnd = 0.0 self.layer.addSublayer(shapeLayer) NotificationCenter.default.addObserver(self, selector:#selector(resetAnimations), name: UIApplication.didBecomeActiveNotification, object: nil) } private func setProgressLayerPath() { let center = CGPoint(x:self.bounds.midX, y:self.bounds.midY) let radius = (min(self.bounds.width, self.bounds.height) - progressLayer.lineWidth) / 2 let path = UIBezierPath(arcCenter: center, radius: radius, startAngle: CGFloat(0.0), endAngle: CGFloat(2 * Double.pi), clockwise: true) progressLayer.path = path.cgPath progressLayer.strokeStart = 0.0 progressLayer.strokeEnd = 0.0 } private func setStrokeSuccessShapePath() { let width = self.bounds.width let height = self.bounds.height let square = min(width, height) let b = square/2 let oneTenth = square/10 let xOffset = oneTenth let yOffset = 1.5 * oneTenth let ySpace = 3.2 * oneTenth let point = correctJoinPoint() let path = CGMutablePath() path.move(to: CGPoint(x:point.x, y:point.y)) path.addLine(to: CGPoint(x:point.x, y:point.y)) path.addLine(to: CGPoint(x: b - xOffset, y: b + yOffset)) path.addLine(to: CGPoint(x: 2 * b - xOffset + yOffset - ySpace, y:ySpace )) shapeLayer.path = path shapeLayer.cornerRadius = square/2 shapeLayer.masksToBounds = true shapeLayer.strokeStart = 0.0 shapeLayer.strokeEnd = 0.0 } private func setStrokeFailureShapePath() { let width = self.bounds.width let height = self.bounds.height let square = min(width, height) let b = square/2 let space = square/3 let point = errorJoinPoint() let path = CGMutablePath() path.move(to: CGPoint(x:point.x, y:point.y)) path.addLine(to: CGPoint(x:2 * b - space, y: 2 * b - space)) path.move(to: CGPoint(x:2 * b - space, y: space)) path.addLine(to: CGPoint(x:space, y:2 * b - space)) shapeLayer.path = path shapeLayer.cornerRadius = square/2 shapeLayer.masksToBounds = true shapeLayer.strokeStart = 0 shapeLayer.strokeEnd = 0.0 } private func correctJoinPoint() -> CGPoint { let r = min(self.bounds.width, self.bounds.height)/2 let m = r/2 let k = lineWidth/2 let a: CGFloat = 2.0 let b = -4 * r + 2 * m let c = (r - m) * (r - m) + 2 * r * k - k * k let x = (-b - sqrt(b * b - 4 * a * c))/(2 * a) let y = x + m return CGPoint(x:x, y:y) } private func errorJoinPoint() -> CGPoint { let r = min(self.bounds.width, self.bounds.height)/2 let k = lineWidth/2 let a: CGFloat = 2.0 let b = -4 * r let c = r * r + 2 * r * k - k * k let x = (-b - sqrt(b * b - 4 * a * c))/(2 * a) return CGPoint(x:x, y:x) } @objc private func resetAnimations() { if status == .Loading { status = .Unknown progressLayer.removeAnimation(forKey: dhRingRotationAnimationKey) progressLayer.removeAnimation(forKey: dhRingStorkeAnimationKey) startLoading() } } @objc private func hiddenLoadingView() { status = .Completion // self.isHidden = true if completionBlock != nil { completionBlock!() } } }
32.539043
152
0.684858
21014419d181abc9691b3d350a3e2a7b4ca28b9b
8,550
/* ActionsTableViewController.swift RestAPIExplorerSwift Created by Nicholas McDonald on 1/9/18. Copyright (c) 2018-present, salesforce.com, inc. All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of salesforce.com, inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of salesforce.com, inc. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit protocol ActionTableViewDelegate: class { func userDidSelectAction(_ action: Action) } class ActionTableViewController: UIViewController { weak var delegate: ActionTableViewDelegate? let actions: [Action] fileprivate var tableView = UITableView(frame: .zero, style: .plain) init() { let versions = Action(type: ActionType.versions, method: "versions", objectTypes: nil) let resources = Action(type: ActionType.resources, method: "resources", objectTypes: nil) let describeGlobal = Action(type: ActionType.describeGlobal, method: "describeGlobal", objectTypes: nil) let metadata = Action(type: ActionType.metadataWithObjectType, method: "metadataWithObjectType", objectTypes: "objectType") let describe = Action(type: ActionType.describeWithObjectType, method: "describeWithObjectType:", objectTypes: "objectType") let retrieve = Action(type: ActionType.retrieveWithObjectType, method: "retrieveWithObjectType:objectId:fieldList", objectTypes: "objectType, objectId, fieldList") let create = Action(type: ActionType.createWithObjectType, method: "createWithObjectType:fields", objectTypes: "objectType, fields") let upsert = Action(type: ActionType.upsertWithObjectType, method: "upsertWithObjectType:externalField:externalId:fields", objectTypes: "objectType, externalField, externalId, fields") let update = Action(type: ActionType.updateWithObjectType, method: "updateWithObjectType:externalField:externalId:fields", objectTypes: "objectType, objectId, fields") let delete = Action(type: ActionType.deleteWithObjectType, method: "deleteWithObjectType:objectId", objectTypes:"objectType, objectId") let query = Action(type: ActionType.query, method: "query:", objectTypes: "query") let search = Action(type: ActionType.search, method: "search:", objectTypes: "search") let searchScope = Action(type: ActionType.searchScopeAndOrder, method: "searchScopeAndOrder:", objectTypes: nil) let searchResultLayout = Action(type: ActionType.searchResultLayout, method: "searchResultLayout:", objectTypes: "objectList") let ownedFiles = Action(type: ActionType.ownedFilesList, method: "ownedFilesList:page", objectTypes: "userId, page") let filesInUserGroups = Action(type: ActionType.filesInUserGroups, method: "filesInUserGroups:page", objectTypes: "userId, page") let filesShared = Action(type: ActionType.filesSharedWithUser, method: "filesSharedWithUser:page", objectTypes: "userId, page") let fileDetails = Action(type: ActionType.fileDetails, method: "fileDetails:forVersions", objectTypes: "objectId, version") let batchFileDetails = Action(type: ActionType.batchFileDetails, method: "batchFileDetails:", objectTypes: "objectIdList") let fileShares = Action(type: ActionType.fileShares, method: "fileShares:page", objectTypes: "objectId, page") let addFileShare = Action(type: ActionType.addFileShare, method: "addFileShare:entityId:shareType", objectTypes: "objectId, entityId, sharedType") let deleteFileShare = Action(type: ActionType.deleteFileShare, method: "deleteFileShares:", objectTypes: "objectId") let currentUserInfo = Action(type: ActionType.currentUserInfo, method: "current user info", objectTypes: nil) let enableBiometric = Action(type: ActionType.enableBiometric, method: "Enable Touch/Face Id", objectTypes: nil) let logout = Action(type: ActionType.logout, method: "logout", objectTypes: nil) let switchUser = Action(type: ActionType.switchUser, method: "switch user", objectTypes: nil) let exportCredentials = Action(type: ActionType.exportCredentials, method: "Export Credentials to pasteboard", objectTypes: nil) let overrideStyleLight = Action(type: ActionType.overrideStyleLight, method: "Override user interface style: light", objectTypes: nil) let overrideStyleDark = Action(type: ActionType.overrideStyleDark, method: "Override user interface style: dark", objectTypes: nil) let overrideStyleUnspecified = Action(type: ActionType.overrideStyleUnspecified, method: "Override user interface style: unspecified", objectTypes: nil) self.actions = [versions, resources, describeGlobal, metadata, describe, retrieve, create, upsert, update, delete, query, search, searchScope, searchResultLayout, ownedFiles, filesInUserGroups, filesShared, fileDetails, batchFileDetails, fileShares, addFileShare, deleteFileShare, currentUserInfo, enableBiometric, logout, switchUser, exportCredentials, overrideStyleLight, overrideStyleDark, overrideStyleUnspecified] super.init(nibName: nil, bundle: nil) self.tableView.delegate = self self.tableView.dataSource = self } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.tableView.translatesAutoresizingMaskIntoConstraints = false self.tableView.register(ActionTableViewCell.self, forCellReuseIdentifier: "cell") self.tableView.separatorInset = UIEdgeInsets.zero self.view.addSubview(self.tableView) self.tableView.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true self.tableView.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true self.tableView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true self.tableView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true } } extension ActionTableViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let del = self.delegate { let action = self.actions[indexPath.row] del.userDidSelectAction(action) } } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 60 } } extension ActionTableViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let action = self.actions[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) if let actionCell = cell as? ActionTableViewCell { actionCell.actionLabel.text = action.method if let types = action.objectTypes { actionCell.objectLabel.text = "params: " + types } else { actionCell.objectLabel.text = "no params" } } return cell } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.actions.count } }
64.285714
426
0.742456
eb77b15afa35eff5098df8fd24210af27dd4d64c
1,646
// // DequeueCell.swift // CurrencyExchanger // // Created by Racing on 2020/12/16. // import UIKit extension UITableView { func dequeueReusableCell<T>(for indexPath: IndexPath) -> T where T: UITableViewCell { return dequeueReusableCell(withIdentifier: String(describing: T.self), for: indexPath) as! T } func dequeueReusableHeaderFooterView<T>() -> T where T: UITableViewHeaderFooterView { return dequeueReusableHeaderFooterView(withIdentifier: String(describing: T.self)) as! T } } extension UICollectionView { func dequeueReusableCell<T>(for indexPath: IndexPath) -> T where T: UICollectionViewCell { return dequeueReusableCell(withReuseIdentifier: String(describing: T.self), for: indexPath) as! T } func dequeueReusableSupplementaryView<T>(ofKind kind: String, for indexPath: IndexPath) -> T where T: UICollectionReusableView { return dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: String(describing: T.self), for: indexPath) as! T } func dequeueReusableHeaderView<T>(for indexPath: IndexPath) -> T where T: UICollectionReusableView { let kind = UICollectionView.elementKindSectionHeader return dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: String(describing: T.self), for: indexPath) as! T } func dequeueReusableFooterView<T>(for indexPath: IndexPath) -> T where T: UICollectionReusableView { let kind = UICollectionView.elementKindSectionFooter return dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: String(describing: T.self), for: indexPath) as! T } }
42.205128
132
0.744228
6983ebd1ae0ab99e03b5987328ae42f20de65073
3,079
protocol PlacePageBookmarkViewControllerDelegate: AnyObject { func bookmarkDidPressEdit() } class PlacePageBookmarkViewController: UIViewController { @IBOutlet var stackView: UIStackView! @IBOutlet var spinner: UIImageView! @IBOutlet var editButton: UIButton! @IBOutlet var topConstraint: NSLayoutConstraint! @IBOutlet var expandableLabel: ExpandableLabel! { didSet { expandableLabel.font = UIFont.regular14() expandableLabel.textColor = UIColor.blackPrimaryText() expandableLabel.numberOfLines = 5 expandableLabel.expandColor = UIColor.linkBlue() expandableLabel.expandText = L("placepage_more_button") } } var bookmarkData: PlacePageBookmarkData? { didSet { updateViews() } } weak var delegate: PlacePageBookmarkViewControllerDelegate? override func viewDidLoad() { super.viewDidLoad() updateViews() } func updateViews() { guard let bookmarkData = bookmarkData else { return } editButton.isEnabled = true if let description = bookmarkData.bookmarkDescription { if bookmarkData.isHtmlDescription { setHtmlDescription(description) topConstraint.constant = 16 } else { expandableLabel.text = description topConstraint.constant = description.count > 0 ? 16 : 0 } } else { topConstraint.constant = 0 } } private func setHtmlDescription(_ htmlDescription: String) { DispatchQueue.global().async { let font = UIFont.regular14() let color = UIColor.blackPrimaryText() let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineSpacing = 4 let attributedString: NSAttributedString if let str = NSMutableAttributedString(htmlString: htmlDescription, baseFont: font, paragraphStyle: paragraphStyle) { str.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: NSRange(location: 0, length: str.length)) attributedString = str; } else { attributedString = NSAttributedString(string: htmlDescription, attributes: [NSAttributedString.Key.font : font, NSAttributedString.Key.foregroundColor: color, NSAttributedString.Key.paragraphStyle: paragraphStyle]) } DispatchQueue.main.async { self.expandableLabel.attributedText = attributedString } } } private func startSpinner() { editButton.isHidden = true let postfix = UIColor.isNightMode() ? "dark" : "light" spinner.image = UIImage(named: "Spinner_" + postfix) spinner.isHidden = false spinner.startRotation() } private func stopSpinner() { editButton.isHidden = false spinner.isHidden = true spinner.stopRotation() } @IBAction func onEdit(_ sender: UIButton) { delegate?.bookmarkDidPressEdit() } override func applyTheme() { super.applyTheme() updateViews() } }
31.742268
123
0.660279
5b19c2e7de10f5133f642c741ffb002bebd78ccc
341
// // City.swift // ForecastApp // // Created by Rodrigo López-Romero Guijarro on 27/04/2018. // Copyright © 2018 rlrg. All rights reserved. // import Foundation /** City Model/Logic entity which contains the name of the city and the last time requested. */ public struct City { let name: String let timeRequested: Date }
17.05
84
0.692082
fee40c7255a7e9fc5b8fa0fa2323e1c1153a2215
2,320
// // GradientImageButton.swift // JXGradientKit // // Created by jiaxin on 2020/6/25. // Copyright © 2020 jiaxin. All rights reserved. // import UIKit /// 配置gradientLayer的属性无法生效,使用GradientImageButton的相关属性才行。 @IBDesignable open class GradientImageButton: UIButton, GradientAvaliable { public private(set) var gradientLayer: CAGradientLayer = CAGradientLayer() var isLayouted = false public var colors: [UIColor]? { didSet { refreshGradient() updateBackroundImageIfNeeded() } } @IBInspectable public var startColor: UIColor? { didSet { refreshGradient() updateBackroundImageIfNeeded() } } @IBInspectable public var middleColor: UIColor? { didSet { refreshGradient() updateBackroundImageIfNeeded() } } @IBInspectable public var endColor: UIColor? { didSet { refreshGradient() updateBackroundImageIfNeeded() } } @IBInspectable public var direction: GradientDirection = .leftToRight { didSet { refreshGradient() updateBackroundImageIfNeeded() } } @IBInspectable public var angle: CGFloat = 0 { didSet { refreshGradient() updateBackroundImageIfNeeded() } } @IBInspectable public var locations: String? { didSet { refreshGradient() updateBackroundImageIfNeeded() } } public override init(frame: CGRect) { super.init(frame: frame) refreshGradient() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) refreshGradient() } open override func layoutSubviews() { super.layoutSubviews() if gradientLayer.frame != bounds { isLayouted = true gradientLayer.frame = bounds let image = UIImage.gradientImageWithLayer(gradientLayer) setBackgroundImage(image, for: .normal) } } func updateBackroundImageIfNeeded() { if isLayouted { let image = UIImage.gradientImageWithLayer(gradientLayer) setBackgroundImage(image, for: .normal) } } }
23.917526
78
0.592241
0312f307a4c1e1c5f7a153492b24f0f3ee156fe1
1,859
// Copyright 2021 Chip Jarred // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import SwiftUI // ------------------------------------- struct ThemeEditorCellNotePreview: View { static let width = CellNoteView.width static let height = CellNoteView.height var note: Int? @Binding var currentTheme: Theme // ------------------------------------- var displayText: Text { let s: String if let n = note { s = "\(n)" } else { s = "" } return Text(s) } // ------------------------------------- var body: some View { displayText .font(Font(currentTheme.noteFont)) .foregroundColor(Color(currentTheme.noteColor)) .frame(width: Self.width, height: Self.height, alignment: .center) } }
35.075472
80
0.645508
28640b20f65e3590166215d733457a18060ed451
572
import SwiftUI import shared struct ContentView: View { @State private var componentHolder = ComponentHolder { RootComponent(componentContext: $0, storeFactory: DefaultStoreFactory(), quotesApi: SwansonQuotes()) } var body: some View { RootView(componentHolder.component) .onAppear { LifecycleRegistryExtKt.resume(self.componentHolder.lifecycle) } .onDisappear { LifecycleRegistryExtKt.stop(self.componentHolder.lifecycle) } } }
26
88
0.611888
d7bb67ebf912c0d70f3674e994096128798542a0
1,155
// // ClassSearchCollectionViewController.swift // AnywhereFitness // // Created by Josh Kocsis on 6/22/20. // Copyright © 2020 Matthew Martindale. All rights reserved. // import UIKit private let reuseIdentifier = "ClassSearchCell" class ClassSearchCollectionViewController: UICollectionViewController { let classSearchController = ClassSearchController() override func viewDidLoad() { super.viewDidLoad() } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return classSearchController.classSearch.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as? ClassSearchCollectionViewCell else { return UICollectionViewCell() } let classSearch = classSearchController.classSearch[indexPath.item] cell.classSearchImage.image = classSearch.image cell.classSearchLabel.text = classSearch.className return cell } }
33
186
0.760173
ddf006ad149cce69d37feabd072ed8d7fe0fc43d
234
// 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 f<T { class B { deinit { class A : ExtensibleCollectionType
26
87
0.764957
fb00563863ec390eeaae0a9d4800cde4a3fa59e6
666
// // FirebaseCoreBridge.swift // Pods // // Created by eps on 6/26/20. // private let kTag = "\(FirebaseInitializer.self)" class FirebaseInitializer { private static let _sharedInstance = FirebaseInitializer() private let _logger = PluginManager.instance.logger private var _initialized = false public class var instance: FirebaseInitializer { return _sharedInstance } private init() { _logger.info("\(kTag): constructor") } public func initialize() -> Bool { if _initialized { return true } _initialized = true FirebaseApp.configure() return true } }
20.181818
62
0.632132
75e4f37ba35d0305f67de5cb6a597840d9e48966
1,109
// // TabBarRootThreeViewController.swift // FlipTheBlinds // // Created by Joel Bell on 1/2/17. // Copyright © 2017 Joel Bell. All rights reserved. // import UIKit // MARK: Main class TabBarRootThreeViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() configImageView() } } // MARK: Configure View extension TabBarRootThreeViewController { fileprivate func configImageView() { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill imageView.image = #imageLiteral(resourceName: "blueImage") view.addSubview(imageView) imageView.translatesAutoresizingMaskIntoConstraints = false imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true imageView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true imageView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true imageView.heightAnchor.constraint(equalTo: view.heightAnchor).isActive = true } }
26.404762
87
0.689811
d6a1e674770471be30701a1b88ef77a4f61b9185
5,757
// Copyright 2022 Pera Wallet, LDA // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // PassphraseVerifyCardView.swift import UIKit import MacaroonUIKit final class PassphraseVerifyCardView: View, ViewModelBindable { weak var delegate: PassphraseVerifyCardViewDelegate? private lazy var theme = PassphraseVerifyCardViewTheme() private lazy var headerLabel = Label() private lazy var containerView = TripleShadowView() private lazy var stackView = VStackView() private lazy var firstMnemonicLabel = Label() private lazy var secondMnemonicLabel = Label() private lazy var thirdMnemonicLabel = Label() private var cardIndex: Int? override init(frame: CGRect) { super.init(frame: frame) linkInteractors() } func customize(_ theme: PassphraseVerifyCardViewTheme) { addHeader(theme) addContainerView(theme) } func customizeAppearance(_ styleSheet: NoStyleSheet) {} func prepareLayout(_ layoutSheet: NoLayoutSheet) {} func linkInteractors() { firstMnemonicLabel.addGestureRecognizer( UITapGestureRecognizer( target: self, action: #selector(updateForSelection(_:)) ) ) secondMnemonicLabel.addGestureRecognizer( UITapGestureRecognizer( target: self, action: #selector(updateForSelection(_:)) ) ) thirdMnemonicLabel.addGestureRecognizer( UITapGestureRecognizer( target: self, action: #selector(updateForSelection(_:)) ) ) } func bindData(_ viewModel: PassphraseVerifyCardViewModel?) { cardIndex = viewModel?.cardIndex headerLabel.editText = viewModel?.headerText firstMnemonicLabel.editText = viewModel?.firstMnemonic secondMnemonicLabel.editText = viewModel?.secondMnemonic thirdMnemonicLabel.editText = viewModel?.thirdMnemonic } } extension PassphraseVerifyCardView { @objc private func updateForSelection(_ sender: UITapGestureRecognizer) { guard let labelTag = sender.view?.tag else { return } switch labelTag { case 0: updateBackground(word: firstMnemonicLabel) case 1: updateBackground(word: secondMnemonicLabel) case 2: updateBackground(word: thirdMnemonicLabel) default: return } delegate?.passphraseVerifyCardViewDidSelectWord(self, item: labelTag) } private func updateBackground(word: Label) { stackView.subviews.forEach { $0.backgroundColor = theme.deactiveColor } word.backgroundColor = theme.activeColor } func reset() { cardIndex = nil stackView.subviews.forEach { $0.backgroundColor = theme.deactiveColor } } } extension PassphraseVerifyCardView { private func addHeader(_ theme: PassphraseVerifyCardViewTheme) { headerLabel.customizeAppearance(theme.headerLabel) addSubview(headerLabel) headerLabel.snp.makeConstraints { $0.top.equalToSuperview() $0.leading.trailing.equalToSuperview().inset(theme.horizontalPadding) } } private func addContainerView(_ theme: PassphraseVerifyCardViewTheme) { containerView.draw(corner: theme.containerViewCorner) containerView.draw(shadow: theme.containerViewFirstShadow) containerView.draw(secondShadow: theme.containerViewSecondShadow) containerView.draw(thirdShadow: theme.containerViewThirdShadow) addSubview(containerView) containerView.snp.makeConstraints { $0.top.equalTo(headerLabel.snp.bottom).offset(theme.containerViewTopPadding) $0.leading.trailing.equalToSuperview().inset(theme.horizontalPadding) $0.bottom.equalToSuperview() } addStackView(theme) } private func addStackView(_ theme: PassphraseVerifyCardViewTheme) { stackView.alignment = .fill stackView.spacing = theme.stackViewSpacing containerView.addSubview(stackView) stackView.snp.makeConstraints { $0.edges.equalToSuperview().inset(theme.stackViewSpacing) } addMnemonicLabel(theme, firstMnemonicLabel, tag: 0) addMnemonicLabel(theme, secondMnemonicLabel, tag: 1) addMnemonicLabel(theme, thirdMnemonicLabel, tag: 2) } private func addMnemonicLabel( _ theme: PassphraseVerifyCardViewTheme, _ mnemonicLabel: Label, tag: Int ) { mnemonicLabel.tag = tag mnemonicLabel.contentEdgeInsets = theme.mnemonicLabelContentInset mnemonicLabel.customizeAppearance(theme.mnemonicLabel) mnemonicLabel.draw(corner: theme.mnemonicLabelCorner) stackView.addArrangedSubview(mnemonicLabel) } } protocol PassphraseVerifyCardViewDelegate: AnyObject { func passphraseVerifyCardViewDidSelectWord( _ passphraseVerifyCardView: PassphraseVerifyCardView, item: Int ) }
32.525424
88
0.665451
d68045562f78ee6d7f54c10aee9976e3b9af8c52
15,829
// REQUIRES: concurrency func withError(_ completion: @escaping (String?, Error?) -> Void) { } func notOptional(_ completion: @escaping (String, Error?) -> Void) { } func errorOnly(_ completion: @escaping (Error?) -> Void) { } func test(_ str: String) -> Bool { return false } // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNRELATED %s withError { res, err in if test("unrelated") { print("unrelated") } else { print("else unrelated") } } // UNRELATED: convert_params_single.swift // UNRELATED-NEXT: let res = try await withError() // UNRELATED-NEXT: if test("unrelated") { // UNRELATED-NEXT: print("unrelated") // UNRELATED-NEXT: } else { // UNRELATED-NEXT: print("else unrelated") // UNRELATED-NEXT: } // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=BOUND %s withError { res, err in print("before") if let bad = err { print("got error \(bad)") return } if let str = res { print("got result \(str)") } print("after") } // BOUND: do { // BOUND-NEXT: let str = try await withError() // BOUND-NEXT: print("before") // BOUND-NEXT: print("got result \(str)") // BOUND-NEXT: print("after") // BOUND-NEXT: } catch let bad { // BOUND-NEXT: print("got error \(bad)") // BOUND-NEXT: } // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=BOUND-COMMENT %s withError { res, err in // a // b print("before") // c if let bad = err { // d // e print("got error \(bad)") // f return // g } // h if let str = res { // i // j print("got result \(str)") // k } // l print("after") // m } // BOUND-COMMENT: do { // BOUND-COMMENT-NEXT: let str = try await withError() // BOUND-COMMENT-NEXT: // a // BOUND-COMMENT-NEXT: // b // BOUND-COMMENT-NEXT: print("before") // BOUND-COMMENT-NEXT: // c // BOUND-COMMENT-NEXT: // h // BOUND-COMMENT-NEXT: // i // BOUND-COMMENT-NEXT: // j // BOUND-COMMENT-NEXT: print("got result \(str)") // BOUND-COMMENT-NEXT: // k // BOUND-COMMENT-NEXT: // l // BOUND-COMMENT-NEXT: print("after") // BOUND-COMMENT-NEXT: // m // BOUND-COMMENT-EMPTY: // BOUND-COMMENT-NEXT: } catch let bad { // BOUND-COMMENT-NEXT: // d // BOUND-COMMENT-NEXT: // e // BOUND-COMMENT-NEXT: print("got error \(bad)") // BOUND-COMMENT-NEXT: // f // BOUND-COMMENT-NEXT: // g // BOUND-COMMENT-NEXT: {{ }} // BOUND-COMMENT-NEXT: } // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNBOUND-ERR %s withError { res, err in print("before") guard let str = res else { print("got error \(err!)") return } print("got result \(str)") print("after") } // UNBOUND-ERR: do { // UNBOUND-ERR-NEXT: let str = try await withError() // UNBOUND-ERR-NEXT: print("before") // UNBOUND-ERR-NEXT: print("got result \(str)") // UNBOUND-ERR-NEXT: print("after") // UNBOUND-ERR-NEXT: } catch let err { // UNBOUND-ERR-NEXT: print("got error \(err)") // UNBOUND-ERR-NEXT: } // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=BOUND %s withError { res, err in print("before") if let bad = err { print("got error \(bad)") } else if let str = res { print("got result \(str)") } print("after") } // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=BOUND %s withError { res, err in print("before") if let bad = err { print("got error \(bad)") return } if let str = res { print("got result \(str)") } print("after") } // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNBOUND-RES %s withError { res, err in print("before") if let bad = err { print("got error \(bad)") return } print("got result \(res!)") print("after") } // UNBOUND-RES: do { // UNBOUND-RES-NEXT: let res = try await withError() // UNBOUND-RES-NEXT: print("before") // UNBOUND-RES-NEXT: print("got result \(res)") // UNBOUND-RES-NEXT: print("after") // UNBOUND-RES-NEXT: } catch let bad { // UNBOUND-RES-NEXT: print("got error \(bad)") // UNBOUND-RES-NEXT: } // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNBOUND-ERR %s withError { res, err in print("before") if let str = res { print("got result \(str)") print("after") return } print("got error \(err!)") } // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNBOUND-RES %s withError { res, err in print("before") if let bad = err { print("got error \(bad)") } else { print("got result \(res!)") } print("after") } // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNBOUND-ERR %s withError { res, err in print("before") if let str = res { print("got result \(str)") } else { print("got error \(err!)") } print("after") } // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNBOUND %s withError { res, err in print("before") if err != nil { print("got error \(err!)") return } print("got result \(res!)") print("after") } // UNBOUND: do { // UNBOUND-NEXT: let res = try await withError() // UNBOUND-NEXT: print("before") // UNBOUND-NEXT: print("got result \(res)") // UNBOUND-NEXT: print("after") // UNBOUND-NEXT: } catch let err { // UNBOUND-NEXT: print("got error \(err)") // UNBOUND-NEXT: } // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNBOUND %s withError { res, err in print("before") if res != nil { print("got result \(res!)") print("after") return } print("got error \(err!)") } // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNBOUND %s withError { res, err in print("before") if err != nil { print("got error \(err!)") } else { print("got result \(res!)") } print("after") } // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNBOUND %s withError { res, err in print("before") if res != nil { print("got result \(res!)") } else { print("got error \(err!)") } print("after") } // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNBOUND %s withError { res, err in print("before") if err == nil { print("got result \(res!)") } else { print("got error \(err!)") } print("after") } // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNBOUND %s withError { res, err in print("before") if res == nil { print("got error \(err!)") } else { print("got result \(res!)") } print("after") } // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNHANDLEDNESTED %s withError { res, err in print("before") if let bad = err { print("got error \(bad)") } else { if let str = res { print("got result \(str)") } } print("after") } // UNHANDLEDNESTED: do { // UNHANDLEDNESTED-NEXT: let res = try await withError() // UNHANDLEDNESTED-NEXT: print("before") // UNHANDLEDNESTED-NEXT: if let str = <#res#> { // UNHANDLEDNESTED-NEXT: print("got result \(str)") // UNHANDLEDNESTED-NEXT: } // UNHANDLEDNESTED-NEXT: print("after") // UNHANDLEDNESTED-NEXT: } catch let bad { // UNHANDLEDNESTED-NEXT: print("got error \(bad)") // UNHANDLEDNESTED-NEXT: } // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=NOERR %s withError { res, err in print("before") if let str = res { print("got result \(str)") } print("after") } // NOERR: convert_params_single.swift // NOERR-NEXT: let str = try await withError() // NOERR-NEXT: print("before") // NOERR-NEXT: print("got result \(str)") // NOERR-NEXT: print("after") // NOERR-NOT: } // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=NORES %s withError { res, err in print("before") if let bad = err { print("got error \(bad)") } print("after") } // NORES: do { // NORES-NEXT: let res = try await withError() // NORES-NEXT: print("before") // NORES-NEXT: print("after") // NORES-NEXT: } catch let bad { // NORES-NEXT: print("got error \(bad)") // NORES-NEXT: } // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNBOUND %s withError { res, err in print("before") if ((res != (nil)) && err == nil) { print("got result \(res!)") } else { print("got error \(err!)") } print("after") } // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNKNOWN-COND %s withError { res, err in print("before") if res != nil && test(res!) { print("got result \(res!)") } print("after") } // UNKNOWN-COND: convert_params_single.swift // UNKNOWN-COND-NEXT: let res = try await withError() // UNKNOWN-COND-NEXT: print("before") // UNKNOWN-COND-NEXT: if <#res#> != nil && test(res) { // UNKNOWN-COND-NEXT: print("got result \(res)") // UNKNOWN-COND-NEXT: } // UNKNOWN-COND-NEXT: print("after") // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNKNOWN-CONDELSE %s withError { res, err in print("before") if res != nil && test(res!) { print("got result \(res!)") } else { print("bad") } print("after") } // UNKNOWN-CONDELSE: var res: String? = nil // UNKNOWN-CONDELSE-NEXT: var err: Error? = nil // UNKNOWN-CONDELSE-NEXT: do { // UNKNOWN-CONDELSE-NEXT: res = try await withError() // UNKNOWN-CONDELSE-NEXT: } catch { // UNKNOWN-CONDELSE-NEXT: err = error // UNKNOWN-CONDELSE-NEXT: } // UNKNOWN-CONDELSE-EMPTY: // UNKNOWN-CONDELSE-NEXT: print("before") // UNKNOWN-CONDELSE-NEXT: if res != nil && test(res!) { // UNKNOWN-CONDELSE-NEXT: print("got result \(res!)") // UNKNOWN-CONDELSE-NEXT: } else { // UNKNOWN-CONDELSE-NEXT: print("bad") // UNKNOWN-CONDELSE-NEXT: } // UNKNOWN-CONDELSE-NEXT: print("after") // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=MULTIBIND %s withError { res, err in print("before") if let str = res { print("got result \(str)") } if let str2 = res { print("got result \(str2)") } if case (let str3?) = (res) { print("got result \(str3)") } print("after") } // MULTIBIND: let str = try await withError() // MULTIBIND-NEXT: print("before") // MULTIBIND-NEXT: print("got result \(str)") // MULTIBIND-NEXT: print("got result \(str)") // MULTIBIND-NEXT: print("got result \(str)") // MULTIBIND-NEXT: print("after") // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=NESTEDRET %s withError { res, err in print("before") if let str = res { if test(str) { return } print("got result \(str)") } print("after") } // NESTEDRET: convert_params_single.swift // NESTEDRET-NEXT: let str = try await withError() // NESTEDRET-NEXT: print("before") // NESTEDRET-NEXT: if test(str) { // NESTEDRET-NEXT: <#return#> // NESTEDRET-NEXT: } // NESTEDRET-NEXT: print("got result \(str)") // NESTEDRET-NEXT: print("after") // NESTEDRET-NOT: } // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNBOUND-ERR %s withError { res, err in print("before") guard let str = res, err == nil else { print("got error \(err!)") return } print("got result \(str)") print("after") } // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNBOUND %s withError { res, err in print("before") guard res != nil else { print("got error \(err!)") return } print("got result \(res!)") print("after") } // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNBOUND %s withError { res, err in print("before") guard err == nil else { print("got error \(err!)") return } print("got result \(res!)") print("after") } // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNBOUND %s withError { res, err in print("before") guard res != nil && err == nil else { print("got error \(err!)") return } print("got result \(res!)") print("after") } // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNWRAPPING %s withError { str, err in print("before") guard err == nil else { return } _ = str!.count _ = /*before*/str!/*after*/.count _ = str?.count _ = str!.count.bitWidth _ = str?.count.bitWidth _ = (str?.count.bitWidth)! _ = str!.first?.isWhitespace _ = str?.first?.isWhitespace _ = (str?.first?.isWhitespace)! print("after") } // UNWRAPPING: let str = try await withError() // UNWRAPPING-NEXT: print("before") // UNWRAPPING-NEXT: _ = str.count // UNWRAPPING-NEXT: _ = /*before*/str/*after*/.count // UNWRAPPING-NEXT: _ = str.count // UNWRAPPING-NEXT: _ = str.count.bitWidth // UNWRAPPING-NEXT: _ = str.count.bitWidth // Note this transform results in invalid code as str.count.bitWidth is no // longer optional, but arguably it's more useful than leaving str as a // placeholder. In general, the tranform we perform here is locally valid // within the optional chain, but may change the type of the overall chain. // UNWRAPPING-NEXT: _ = (str.count.bitWidth)! // UNWRAPPING-NEXT: _ = str.first?.isWhitespace // UNWRAPPING-NEXT: _ = str.first?.isWhitespace // UNWRAPPING-NEXT: _ = (str.first?.isWhitespace)! // UNWRAPPING-NEXT: print("after") // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NOT-OPTIONAL %s notOptional { str, err in print("before") if let err2 = err { print("got error \(err2)") return } print("got result \(str)") print("after") } // NOT-OPTIONAL: do { // NOT-OPTIONAL-NEXT: let str = try await notOptional() // NOT-OPTIONAL-NEXT: print("before") // NOT-OPTIONAL-NEXT: print("got result \(str)") // NOT-OPTIONAL-NEXT: print("after") // NOT-OPTIONAL-NEXT: } catch let err2 { // NOT-OPTIONAL-NEXT: print("got error \(err2)") // NOT-OPTIONAL-NEXT: } // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=ERROR-ONLY %s errorOnly { err in print("before") if let err2 = err { print("got error \(err2)") return } print("after") } // ERROR-ONLY: convert_params_single.swift // ERROR-ONLY-NEXT: do { // ERROR-ONLY-NEXT: try await errorOnly() // ERROR-ONLY-NEXT: print("before") // ERROR-ONLY-NEXT: print("after") // ERROR-ONLY-NEXT: } catch let err2 { // ERROR-ONLY-NEXT: print("got error \(err2)") // ERROR-ONLY-NEXT: } // ERROR-ONLY-NOT: }
30.150476
147
0.64028
89da704d36100a215532f2609ebc3a73bec5d369
1,072
//: Playground - noun: a place where people can play import UIKit let monet1 = RGBAImage(image: UIImage(named: "monet1")!)! let monet2 = RGBAImage(image: UIImage(named: "monet2")!)! let tiger = RGBAImage(image: UIImage(named: "tiger")!)! ImageProcess.composite(monet1.clone(), monet2.clone(), tiger.clone()).toUIImage() ImageProcess.add(monet1.clone(), monet2.clone()).toUIImage() ImageProcess.sub(monet1.clone(), monet2.clone()).toUIImage() ImageProcess.mul(monet1.clone(), monet2.clone()).toUIImage() ImageProcess.sub(ImageProcess.div(tiger.clone(), monet2.clone()), factor: 0.5).toUIImage() let factor = 0.3 ImageProcess.add(monet1.clone(), factor: factor).toUIImage() ImageProcess.sub(monet1.clone(), factor: factor).toUIImage() ImageProcess.mul(monet1.clone(), factor: factor).toUIImage() ImageProcess.div(monet1.clone(), factor: factor).toUIImage() let R1 = ImageProcess.gray5(monet1.clone()) let img1 = ImageProcess.add(R1.clone(), factor: 0.5) let img2 = ImageProcess.sub(R1.clone(), factor: 0.7) ImageProcess.sub(img1.clone(), img2.clone()).toUIImage()
36.965517
90
0.733209
912a30fe9f5b486b428dcc42b87ae3b93ba852e5
2,738
// // BluetoothKit // // Copyright (c) 2015 Rasmus Taulborg Hummelmose - https://github.com/rasmusth // // 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 CoreBluetooth /** Class that represents a configuration used when starting a BKCentral object. */ public class BKConfiguration { // MARK: Properties /// The UUID for the service used to send data. This should be unique to your applications. public let dataServiceUUID: CBUUID /// The UUID for the characteristic used to send data. This should be unique to your application. public var dataServiceCharacteristicUUID: CBUUID /// Data used to indicate that no more data is coming when communicating. public var endOfDataMark: NSData /// Data used to indicate that a transfer was cancellen when communicating. public var dataCancelledMark: NSData internal var serviceUUIDs: [CBUUID] { let serviceUUIDs = [ dataServiceUUID ] return serviceUUIDs } // MARK: Initialization public init(dataServiceUUID: NSUUID, dataServiceCharacteristicUUID: NSUUID) { self.dataServiceUUID = CBUUID(NSUUID: dataServiceUUID) self.dataServiceCharacteristicUUID = CBUUID(NSUUID: dataServiceCharacteristicUUID) endOfDataMark = "EOD".dataUsingEncoding(NSUTF8StringEncoding)! dataCancelledMark = "COD".dataUsingEncoding(NSUTF8StringEncoding)! } // MARK Functions internal func characteristicUUIDsForServiceUUID(serviceUUID: CBUUID) -> [CBUUID] { if serviceUUID == dataServiceUUID { return [ dataServiceCharacteristicUUID ] } return [] } }
38.56338
101
0.721695
ffd592c60ec8e842111ede5ee726b64d865b1b66
197
public class BracketFilter: EmotionFilter { public init(emotionList: [Emotion]) { super.init(pattern: "\\[[ a-zA-Z0-9\\u4e00-\\u9fa5]+\\]", emotionList: emotionList) } }
21.888889
91
0.604061
c1a401d926348854c4191cb8b5f03d3aa51e591b
794
// // APIClient.swift // Catedra // // Created by Raul Lopez Martinez on 18/01/21. // Copyright © 2021 Raul Lopez Martinez. All rights reserved. // import Foundation enum SectionPath: String { case democracyReports = "informesdemocracia" case humaRightsReports = "informesderechoshumanos" case forum = "forocatedramadero" case volunteers = "voluntarios" case podcast = "podcast" case contact = "contacto" } final class APIClient { private static let baseURL = "https://www.catedramadero.com" static func url(for path: SectionPath? = nil) -> URL? { var completeURL = APIClient.baseURL if let pathValue = path?.rawValue { completeURL = completeURL + "/" + pathValue } return URL(string: completeURL) } }
25.612903
64
0.661209
72f57c46e5006a9d4e949f1aeacd5d44d9fc1a7b
439
// swift-tools-version:5.5 import PackageDescription let package = Package( name: "SVGView", platforms: [ .macOS(.v12), .iOS(.v14), .watchOS(.v6) ], products: [ .library( name: "SVGView", targets: ["SVGView"] ) ], targets: [ .target( name: "SVGView", path: "Source", exclude: ["Info.plist"] ) ], swiftLanguageVersions: [.v5] )
16.259259
35
0.492027
1860291183898b80d9b13cca5ed145254708b543
371
// // PlansWorker.swift // aywa // // Created by Bestpeers on 18/01/18. // Copyright (c) 2018 Alpha Solutions. All rights reserved. // // This file was generated by the Clean Swift Xcode Templates so // you can apply clean architecture to your iOS and Mac projects, // see http://clean-swift.com // import UIKit class PlansWorker { func doSomeWork() { } }
17.666667
66
0.684636
1d3c77b9d869fb507273fff6096ecc0f83bd9557
3,454
// // Copyright © 2020 Optimize Fitness Inc. // Licensed under the MIT license // https://github.com/OptimizeFitness/Minerva/blob/master/LICENSE // import Foundation import RxSwift import UIKit open class ImageCellModel: BaseListCellModel { public var imageColor: UIColor? public var contentMode: UIView.ContentMode = .scaleAspectFit public var directionalLayoutMargins = NSDirectionalEdgeInsets( top: 8, leading: 16, bottom: 8, trailing: 16 ) public let imageObservable: Observable<UIImage?> public let imageSize: CGSize public convenience init(imageObservable: Observable<UIImage?>, imageSize: CGSize) { self.init(identifier: "ImageCellModel", imageObservable: imageObservable, imageSize: imageSize) } public init(identifier: String, imageObservable: Observable<UIImage?>, imageSize: CGSize) { self.imageObservable = imageObservable self.imageSize = imageSize super.init(identifier: identifier) } // MARK: - BaseListCellModel override open func identical(to model: ListCellModel) -> Bool { guard let model = model as? Self, super.identical(to: model) else { return false } return imageSize == model.imageSize && contentMode == model.contentMode && imageColor == model.imageColor } override open func size(constrainedTo containerSize: CGSize) -> ListCellSize { let width = containerSize.width let cellHeight = imageSize.height + directionalLayoutMargins.top + directionalLayoutMargins.bottom return .explicit(size: CGSize(width: width, height: cellHeight)) } } public final class ImageCell: BaseReactiveListCell<ImageCellModel> { private let imageView: UIImageView = { let imageView = UIImageView() return imageView }() private let imageWidthConstraint: NSLayoutConstraint override public init(frame: CGRect) { self.imageWidthConstraint = imageView.widthAnchor.constraint(equalToConstant: 0) super.init(frame: frame) contentView.addSubview(imageView) setupConstraints() } override public func prepareForReuse() { super.prepareForReuse() imageView.image = nil } override public func bind(model: ImageCellModel, sizing: Bool) { super.bind(model: model, sizing: sizing) imageWidthConstraint.constant = model.imageSize.width contentView.directionalLayoutMargins = model.directionalLayoutMargins guard !sizing else { return } imageView.contentMode = model.contentMode model.imageObservable .observeOn(MainScheduler.instance) .subscribe( onNext: { [weak self] image -> Void in guard let strongSelf = self else { return } if let imageColor = model.imageColor { strongSelf.imageView.image = image?.withRenderingMode(.alwaysTemplate) strongSelf.imageView.tintColor = imageColor } else { strongSelf.imageView.image = image } } ) .disposed(by: disposeBag) } } // MARK: - Constraints extension ImageCell { private func setupConstraints() { let layoutGuide = contentView.layoutMarginsGuide imageView.anchor( toLeading: nil, top: layoutGuide.topAnchor, trailing: nil, bottom: layoutGuide.bottomAnchor ) imageView.centerXAnchor.constraint(equalTo: layoutGuide.centerXAnchor).isActive = true imageWidthConstraint.isActive = true contentView.shouldTranslateAutoresizingMaskIntoConstraints(false) } }
29.775862
99
0.717429
e9bb7214821d13956e72e923c139fe7a791d75d5
1,096
// // BannerTableViewCell.swift // StarbucksClone // // Created by 박지승 on 2020/03/07. // Copyright © 2020 Hailey. All rights reserved. // import UIKit class BannerTableViewCell: UITableViewCell { static let identifier = "bannerItemCell" private let itemView = GiftHomeBannerView() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setUI() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setUI() { contentView.addSubview(itemView) itemView.translatesAutoresizingMaskIntoConstraints = false itemView.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true itemView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true itemView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor).isActive = true itemView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true } }
30.444444
95
0.713504
0eccfaeb779c48d261921b60c2a8a1ecde78aa4b
346
// // Copyright 2018-2020 Amazon.com, // Inc. or its affiliates. All Rights Reserved. // // SPDX-License-Identifier: Apache-2.0 // import Foundation extension AmplifyAPICategory: APICategoryAuthProviderFactoryBehavior { public func apiAuthProviderFactory() -> APIAuthProviderFactory { return plugin.apiAuthProviderFactory() } }
23.066667
70
0.748555
01821b7a3851c7f412269976d95d3f2f328d509a
2,875
// // WebPDecodeTests.swift // Nuke-WebP-PluginTests iOS // // Created by nagisa-kosuge on 2018/01/25. // Copyright © 2018年 RyoKosuge. All rights reserved. // import XCTest import Nuke @testable import NukeWebPPlugin class WebPDecodeTests: XCTestCase { private lazy var webpImagePath: URL = { let webpImagePath = Bundle(for: type(of: self)).url(forResource: "sample", withExtension: "webp")! return webpImagePath }() private lazy var gifImagePath: URL = { let gifImagePath = Bundle(for: type(of: self)).url(forResource: "sample", withExtension: "gif")! return gifImagePath }() override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testsDecodeWebPImage() { let webpData = try! Data(contentsOf: self.webpImagePath) let image: UIImage? = UIImage(data: webpData) XCTAssertNil(image) let decoder = NukeWebPPlugin.WebPDataDecoder(); let webpImage: UIImage? = decoder.decode(webpData) XCTAssertNotNil(webpImage) } func testsDecodeNotWebPImage() { let gifData = try! Data(contentsOf: self.gifImagePath) let image: UIImage? = UIImage(data: gifData) XCTAssertNotNil(image) let decoder = NukeWebPPlugin.WebPDataDecoder(); let webpImage: UIImage? = decoder.decode(gifData) XCTAssertNil(webpImage) } func testsProgressiveDecodeWebPImage() { let webpData = try! Data(contentsOf: self.webpImagePath) let decoder = NukeWebPPlugin.WebPDataDecoder(); // no image XCTAssertNil(decoder.incrementallyDecode(webpData[0...500])) // created image let scan1 = decoder.incrementallyDecode(webpData[0...3702]) XCTAssertNotNil(scan1) XCTAssertEqual(scan1!.size.width, 320) XCTAssertEqual(scan1!.size.height, 235) let scan2 = decoder.incrementallyDecode(webpData) XCTAssertNotNil(scan2) XCTAssertEqual(scan2!.size.width, 320) XCTAssertEqual(scan2!.size.height, 235) } func testPerformanceDecodeWebP() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. let webpData = try! Data(contentsOf: self.webpImagePath) let image: UIImage? = UIImage(data: webpData) XCTAssertNil(image) let decoder = NukeWebPPlugin.WebPDataDecoder(); let webpImage: UIImage? = decoder.decode(webpData) XCTAssertNotNil(webpImage) } } }
32.670455
111
0.64487
f8c9f8946b4f2a93d8dfbf2524a08005b9811b8a
1,110
// // MovieListFakeErrorInteractor.swift // MovieDB-VIPERTests // // Created by Conrado Mateu on 14/12/20. // @testable import MovieDB_VIPER import Combine import SwiftUI class MovieListFakeErrorInteractor: ObservableObject, MovieListInteractorProtocol { var anyCancellables = Set<AnyCancellable>() var canc: AnyCancellable? @Published var model: MovieListViewModel init(model: MovieListViewModel) { self.model = model } func error(for apiError: ApiError) { self.model.error = apiError } func sucess(for movies: [MovieEntity]) { self.model.movies = movies } func fetchData() -> AnyCancellable{ doRequest() .on(queue: .main) .on(success: {err in self.sucess(for: err.results)}, failure: {e in self.error(for: e)}) } private func doRequest() -> AnyPublisher<MainEntity, ApiError> { // In the real world this does a request to a REST API, returning either a User object or an error containing a Challenge. return Fail(outputType: MainEntity .self, failure: ApiError.invalidData) .eraseToAnyPublisher() } }
22.2
128
0.695495
de75856c6a00587be318c7bce52ef59d4bc7017f
1,206
import PerfectHTTP import PerfectLogger import Dispatch import PerfectLib import Foundation struct APIRequestFilter: HTTPRequestFilter { public func filter(request: HTTPRequest, response: HTTPResponse, callback: (HTTPRequestFilterResult) -> ()) { if request.method == .post { if let postBody = request.postBodyString, !postBody.isEmpty { if postBody.contains(string: "<script") { _ = try? response.setBody(json: ["msg":"Internal server error"]) response.status = HTTPResponseStatus.statusFrom(code: 500) response.addHeader(.contentType, value: "application/json") response.completed() } } else { _ = try? response.setBody(json: ["msg": "Incomplete request"]) response.status = HTTPResponseStatus.statusFrom(code: 400) response.addHeader(.contentType, value: "application/json") response.completed() } } callback(HTTPRequestFilterResult.continue(request, response)) } }
34.457143
84
0.562189
bb5142b311f0698e1ceb5284cb45d0ee14ac013d
550
// // Copyright 2018-2020 Amazon.com, // Inc. or its affiliates. All Rights Reserved. // // SPDX-License-Identifier: Apache-2.0 // /// The conforming type supports pausing and resuming of an in-process operation. The exact semantics of "pausing" and /// "resuming" are not defined in the protocol. Specifically, there is no guarantee that a `pause` results in an /// immediate suspention of activity, and no guarantee that `resume` will result in an immediate resumption of activity. public protocol Resumable { func pause() func resume() }
36.666667
120
0.74
013129ee8746077900bcad7adf8905c8acfca0b9
921
// // TipTests.swift // TipTests // // Created by Huong on 9/4/20. // Copyright © 2020 Codepath. All rights reserved. // import XCTest @testable import Tip class TipTests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() throws { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
26.314286
111
0.65798
0150a1f70856d861e7aff2a92919a19fe4078b9b
133
// // BaseService.swift // Monotone // // Created by Xueliang Chen on 2020/12/8. // import Foundation class BaseService{ }
10.230769
42
0.646617
d64988abba5fdde88e92176744d9bed237946172
1,945
// // StriationsViewTests.swift // StriationsTests // // Created by Kamil Góralski on 28/09/2020. // import XCTest @testable import Striations final class StriationsViewTests: XCTestCase { func test_longerSide_whenSizeZero_return0() throws { let striationsView = StriationsView(striations: .init(), size: .zero) XCTAssertEqual(0, striationsView.longerSide) } func test_longerSide_whenHeightSideIsLonger_returnHeightSize() throws { let striationsView = StriationsView(striations: .init(), size: .init(width: 100, height: 300)) XCTAssertEqual(300, striationsView.longerSide) } func test_longerSide_whenWidthSideIsLonger_returnWidthSize() throws { let striationsView = StriationsView(striations: .init(), size: .init(width: 400, height: 200)) XCTAssertEqual(400, striationsView.longerSide) } func test_itemHeight_whenSizeZero_return0() throws { let striationsView = StriationsView(striations: .init(), size: .zero) XCTAssertEqual(0, striationsView.itemHeight) } func test_itemHeight_whenSizeIsNotZero_returnDiagonalLengthOfSquareOfLongerSide() throws { let striationsView = StriationsView(striations: .init(), size: .init(width: 0, height: 25)) XCTAssertEqual(25 * sqrt(2), striationsView.itemHeight) } func test_numberOfItems_whenSizeZero_return0() throws { let striationsView = StriationsView(striations: .init(), size: .zero) XCTAssertEqual(0, striationsView.numberOfItems) } func test_numberOfItems_whenDefaultStriations_returnItemHeightDividedByItemWidth() throws { let striations = Striations() let striationsView = StriationsView(striations: striations, size: .init(width: 200, height: 500)) let numberOfItems = Int(striationsView.itemHeight / striations.itemWidth) XCTAssertEqual(numberOfItems, striationsView.numberOfItems) } }
29.923077
105
0.725964
7237f1a460e75a6b9e21fbb8a56000df2f671e5f
661
// RUN: %target-run-simple-swift( -Xfrontend -disable-availability-checking %import-libdispatch -parse-as-library) | %FileCheck %s // REQUIRES: executable_test // REQUIRES: concurrency // REQUIRES: libdispatch // rdar://76038845 // REQUIRES: concurrency_runtime // UNSUPPORTED: back_deployment_runtime struct Boom: Error {} func boom() throws -> Int { throw Boom() } @available(SwiftStdlib 5.5, *) func test() async { async let result = boom() do { _ = try await result } catch { print("error: \(error)") // CHECK: error: Boom() } } @available(SwiftStdlib 5.5, *) @main struct Main { static func main() async { await test() } }
19.441176
130
0.670197
de4e094e93ae9030d18d8f44e40a9b2d7cbd4f64
8,298
// // GroupController.swift // ShoppingList // // Created by Nikita Thomas on 2/14/19. // Copyright © 2019 Lambda School Labs. All rights reserved. // import Foundation import Alamofire import SwiftKeychainWrapper import Auth0 import PusherSwift import PushNotifications class GroupController { struct Profile: Codable { let profile: User } struct User: Codable { let id: Int let name: String } static let shared = GroupController() private var baseURL = URL(string: "https://shoptrak-backend.herokuapp.com/api/")! func getUserID(completion: @escaping (Profile?) -> Void) { guard let accessToken = SessionManager.tokens?.idToken else {return} let url = baseURL.appendingPathComponent("user").appendingPathComponent("check").appendingPathComponent("getid") var request = URLRequest(url: url) request.addValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization") Alamofire.request(request).validate().responseData { (response) in switch response.result { case .success(let value): do { let decoder = JSONDecoder() let user = try decoder.decode(Profile.self, from: value) completion(user) } catch { print("Could not turn json into user") completion(nil) return } case .failure(let error): NSLog("getUser: \(error.localizedDescription)") completion(nil) return } } } private func groupToJSON(group: Group) -> [String: Any]? { guard let jsonData = try? JSONEncoder().encode(group) else { return nil } do { let jsonDict = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any] return jsonDict } catch { return nil } } func newGroup(withName name: String, completion: @escaping (Group?) -> Void) { guard let accessToken = SessionManager.tokens?.idToken else {return} self.getUserID { (id) in guard let userID = id?.profile.id else { completion(nil); return } let headers: HTTPHeaders = [ "Authorization": "Bearer \(accessToken)"] let url = self.baseURL.appendingPathComponent("group") let token = "12345" let parameters: Parameters = ["userID": userID, "name": name, "token": token] Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).validate().responseJSON { (response) in switch response.result { case .success(let value): guard let jsonDict = value as? [String: Any], let group = jsonDict["group"] as? [String: Any], let groupID = group["id"] as? Int else { print("Could not get groupID from API response") completion(nil) return } let newGroup = Group(name: name, userID: userID, token: token, groupID: groupID) completion(newGroup) case .failure(let error): print(error.localizedDescription) completion(nil) return } } } } // Updates the group and downloads all groups from server. Optional success completion. func updateGroup( group: Group, name: String?, userID: Int?, pusher: PushNotifications, completion: @escaping (Bool) -> Void = {_ in } ) { guard let accessToken = SessionManager.tokens?.idToken else {return} let headers: HTTPHeaders = [ "Authorization": "Bearer \(accessToken)"] let myGroup = group if let name = name { myGroup.name = name } if let userID = userID { myGroup.userID = userID } myGroup.updatedAt = Date().dateToString() let url = baseURL.appendingPathComponent("group").appendingPathComponent(String(myGroup.groupID)) guard let groupJSON = groupToJSON(group: myGroup) else { return } Alamofire.request(url, method: .put, parameters: groupJSON, encoding: JSONEncoding.default, headers: headers).validate().responseJSON { (response) in switch response.result { case .success(_): // This downloads allGroups from server so we have fresh data self.getGroups(forUserID: userID!, pusher: pusher, completion: { (success) in if success { completion(true) } else { completion(false) } }) return case .failure(let error): print(error.localizedDescription) completion(false) return } } } // Gets groups from server and updates the singleton. Optional success completion func getGroups( forUserID userID: Int, pusher: PushNotifications, completion: @escaping (Bool) -> Void = { _ in } ) { guard let accessToken = SessionManager.tokens?.idToken else {return} let url = baseURL.appendingPathComponent("group").appendingPathComponent("user").appendingPathComponent(String(userID)) var request = URLRequest(url: url) request.addValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization") Alamofire.request(request).validate().responseData { (response) in switch response.result { case .success(let value): do { let decoder = JSONDecoder() let groups = try decoder.decode(GroupsList.self, from: value) allGroups = groups.groups for group in groups.groups { let chan = "group-\(group.groupID)" try! PushNotifications.shared.addDeviceInterest(interest:chan) } completion(true) } catch { print("Error getting groups from API response\(error)") completion(false) return } case .failure(let error): print(error.localizedDescription) completion(false) return } } } func delete(group: Group, completion: @escaping (Bool) -> Void) { guard let accessToken = SessionManager.tokens?.idToken else {return} let headers: HTTPHeaders = [ "Authorization": "Bearer \(accessToken)"] let url = baseURL.appendingPathComponent("group").appendingPathComponent("remove").appendingPathComponent("\(group.groupID)").appendingPathComponent("\(userID)") print(url) Alamofire.request(url, method: .delete, parameters: nil, encoding: JSONEncoding.default, headers: headers).validate().response { (response) in if let error = response.error { print(error.localizedDescription) completion(false) return } completion(true) } } }
33.595142
169
0.503736
d980b4572cdc40aff1bfbc390935de29d3a3a2be
5,187
// // ImageZoomView.swift // Day9-ImageZoomEffect // // Created by 田逸昕 on 2020/2/5. // Copyright © 2020 田逸昕. All rights reserved. // import UIKit class ImageZoomView: UIView, UIScrollViewDelegate { let maxScale: CGFloat = 3.0 // 最大缩放倍数 let minScale: CGFloat = 0.5 // 最小倍数 let scaleDuration = 0.3 // 缩放动画时间 var lastScale: CGFloat = 1.0 // 最后一次的缩放比例 var tapOffset: CGPoint? // 双击放大偏移的 point // MARK: - Getter lazy var scrollView: UIScrollView = { let view = UIScrollView.init(frame: self.bounds) view.delegate = self view.maximumZoomScale = maxScale view.contentSize = self.bounds.size view.contentMode = .scaleAspectFill view.showsVerticalScrollIndicator = false view.showsHorizontalScrollIndicator = false view.addSubview(self.imgView) return view }() lazy var imgView: UIImageView = { let view = UIImageView.init(frame: self.bounds) return view }() // MARK: - init override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - SetupUI func setupUI() { let doubleTap = UITapGestureRecognizer.init(target: self, action: #selector(doubleTap(tap:))) doubleTap.numberOfTapsRequired = 2 addGestureRecognizer(doubleTap) self.addSubview(scrollView) } // MARK: - Customized /// 设置缩放比例 fileprivate func setZoom(scale: CGFloat) { // 缩放比例限制(在最大最小中间) lastScale = max(min(scale, maxScale), minScale) imgView.transform = CGAffineTransform.init(scaleX: lastScale, y: lastScale) let imageW = imgView.frame.size.width let imageH = imgView.frame.size.height if lastScale > 1 { // 内边距是针对 scrollView 捏合缩放,图片居中设置的边距 scrollView.contentInset = UIEdgeInsets.zero // 内边距清空 // 修改中心点 imgView.center = CGPoint.init(x: imageW / 2, y: imageH / 2) scrollView.contentSize = CGSize.init(width: imageW, height: imageH) if let offset = tapOffset { scrollView.contentOffset = offset } } else { calculateInset() scrollView.contentSize = CGSize.zero } } /** 计算双击放大偏移量 */ fileprivate func calculateOffset(tapPoint: CGPoint) { let viewSize = self.bounds.size let imgViewSize = imgView.bounds.size // 计算最大偏移 x y let maxOffsetX = imgViewSize.width * maxScale - viewSize.width let maxOffsetY = imgViewSize.height * maxScale - viewSize.height var tapX: CGFloat = tapPoint.x var tapY: CGFloat = tapPoint.y if imgViewSize.width == viewSize.width { // 将 tap superview 的 point 转换 tap 到 imageView 上的距离 tapY = tapPoint.y - (viewSize.height - imgViewSize.height) / 2 } else { tapX = tapPoint.x - (viewSize.width - imgViewSize.width) / 2 } // 计算偏移量 let offsetX = (tapX * maxScale - (self.superview?.center.x)!) let offsetY = (tapY * maxScale - (self.superview?.center.y)!) // 判断偏移量是否超出限制(0, maxOffset) let x = min(max(offsetX, 0), maxOffsetX) let y = min(max(offsetY, 0), maxOffsetY) tapOffset = CGPoint.init(x: x, y: y) } /** 计算内边距 */ fileprivate func calculateInset() { let imgViewSize = imgView.frame.size let scrollViewSize = scrollView.bounds.size // 垂直内边距 let paddingV = imgViewSize.height < scrollViewSize.height ? (scrollViewSize.height - imgViewSize.height) / 2 : 0 // 水平内边距 let paddingH = imgViewSize.width < scrollViewSize.width ? (scrollViewSize.width - imgViewSize.width) / 2 : 0 scrollView.contentInset = UIEdgeInsets.init(top: paddingV, left: paddingH, bottom: paddingV, right: 0) imgView.center = CGPoint.init(x: imgViewSize.width / 2, y: imgViewSize.height / 2) } // MARK: - Callbacks /** 单击复原 */ @objc func singleTap(tap: UITapGestureRecognizer) { UIView.animate(withDuration: scaleDuration) { self.setZoom(scale: 1.0) } } /// 双击放大 @objc func doubleTap(tap: UITapGestureRecognizer) { // 获取点击的位置 let point = tap.location(in: self) // 根据点击的位置计算偏移量 calculateOffset(tapPoint: point) if lastScale > 1 { lastScale = 1 } else { lastScale = maxScale // 单击手势放在这里 let singleTap = UITapGestureRecognizer.init(target: self, action: #selector(singleTap(tap:))) addGestureRecognizer(singleTap) } UIView.animate(withDuration: scaleDuration) { self.setZoom(scale: self.lastScale) } } // MARK: - UIScrollViewDelegate func viewForZooming(in scrollView: UIScrollView) -> UIView? { return imgView } func scrollViewDidZoom(_ scrollView: UIScrollView) { // 捏合动画完成计算内边距 calculateInset() } }
33.25
120
0.598805
285c82676b7a7ced7b96235d201cb3f02efbe0b3
1,150
// // HoverButton.swift // LYTabBarView // // Created by Lu Yibin on 16/3/31. // Copyright © 2016年 Lu Yibin. All rights reserved. // import Foundation import Cocoa class LYHoverButton: NSButton { var hoverBackgroundColor: NSColor? var backgroundColor = NSColor.clear var hovered = false private var trackingArea: NSTrackingArea? override func updateTrackingAreas() { super.updateTrackingAreas() if let trackingArea = self.trackingArea { self.removeTrackingArea(trackingArea) } let options: NSTrackingArea.Options = [.enabledDuringMouseDrag, .mouseEnteredAndExited, .activeAlways] self.trackingArea = NSTrackingArea(rect: self.bounds, options: options, owner: self, userInfo: nil) self.addTrackingArea(self.trackingArea!) } override func mouseEntered(with theEvent: NSEvent) { if hovered { return } hovered = true needsDisplay = true } override func mouseExited(with theEvent: NSEvent) { if !hovered { return } hovered = false needsDisplay = true } }
24.468085
110
0.646957
1c3c9c0c7ce856ec920011edc7b46da6cc98a013
4,317
/// Copyright (c) 2019 Razeware LLC /// /// Permission is hereby granted, free of charge, to any person obtaining a copy /// of this software and associated documentation files (the "Software"), to deal /// in the Software without restriction, including without limitation the rights /// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell /// copies of the Software, and to permit persons to whom the Software is /// furnished to do so, subject to the following conditions: /// /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software. /// /// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, /// distribute, sublicense, create a derivative work, and/or sell copies of the /// Software in any work that is designed, intended, or marketed for pedagogical or /// instructional purposes related to programming, coding, application development, /// or information technology. Permission for such use, copying, modification, /// merger, publication, distribution, sublicensing, creation of derivative works, /// or sale is expressly withheld. /// /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN /// THE SOFTWARE. import Foundation // // MARK: - Query Service // /// Runs query data task, and stores results in array of Tracks class QueryService { // // MARK: - Constants let defaultSession: URLSession = URLSession(configuration: .default) // // MARK: - Variables And Properties var dataTask: URLSessionDataTask? var errorMessage: String = "" var tracks: [Track] = [] // // MARK: - Type Alias // typealias JSONDictionary = [String: Any] typealias QueryResult = ([Track]?, String) -> Void // // MARK: - Internal Methods // func getSearchResults(searchTerm: String, completion: @escaping QueryResult) { dataTask?.cancel() if var urlComponents = URLComponents(string: "https://itunes.apple.com/search") { urlComponents.query = "media=music&entity=song&term=\(searchTerm)" guard let url = urlComponents.url else { return } dataTask = defaultSession.dataTask(with: url) { [weak self] (data, response, error) in defer { self?.dataTask = nil } if let error = error { self?.errorMessage += "DataTask error: " + error.localizedDescription + "\n" } else if let data = data, let response = response as? HTTPURLResponse, response.statusCode == 200 { self?.updateSearchResults(data) DispatchQueue.main.async { completion(self?.tracks, self?.errorMessage ?? "") } } } dataTask?.resume() } } // // MARK: - Private Methods // private func updateSearchResults(_ data: Data) { var response: JSONDictionary? tracks.removeAll() do { response = try JSONSerialization.jsonObject(with: data, options: []) as? JSONDictionary } catch let parseError as NSError { // if let errorMessage = errorMessage {} errorMessage += "JSONSerialization error: \(parseError.localizedDescription)\n" return } guard let array = response!["results"] as? [Any] else { errorMessage += "Dictionary does not contain results key\n" return } var index = 0 for trackDictionary in array { if let trackDictionary = trackDictionary as? JSONDictionary, let previewURLString = trackDictionary["previewUrl"] as? String, let previewURL = URL(string: previewURLString), let name = trackDictionary["trackName"] as? String, let artist = trackDictionary["artistName"] as? String { tracks.append(Track(name: name, artist: artist, previewURL: previewURL, index: index)) index += 1 } else { errorMessage += "Problem parsing trackDictionary\n" } } } }
36.277311
108
0.679407
bbae694fe5bc27149e29e95457d09d4ef1583baa
3,873
/* * Copyright (c) 2019, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ import Foundation internal struct SegmentedControlMessage: SegmentedMessage { let message: MeshMessage? let localElement: Element? let userInitiated: Bool let source: Address let destination: Address let networkKey: NetworkKey /// Message Op Code. let opCode: UInt8 let sequenceZero: UInt16 let segmentOffset: UInt8 let lastSegmentNumber: UInt8 let upperTransportPdu: Data var transportPdu: Data { let octet0: UInt8 = 0x80 | (opCode & 0x7F) // SEG = 1 let octet1 = UInt8(sequenceZero >> 5) let octet2 = UInt8((sequenceZero & 0x3F) << 2) | (segmentOffset >> 3) let octet3 = ((segmentOffset & 0x07) << 5) | (lastSegmentNumber & 0x1F) return Data([octet0, octet1, octet2, octet3]) + upperTransportPdu } let type: LowerTransportPduType = .controlMessage /// Creates a Segment of an Control Message from a Network PDU that contains /// a segmented control message. If the PDU is invalid, the /// init returns `nil`. /// /// - parameter networkPdu: The received Network PDU with segmented /// Upper Transport message. init?(fromSegment networkPdu: NetworkPdu) { let data = networkPdu.transportPdu guard data.count >= 5, data[0] & 0x80 != 0 else { return nil } opCode = data[0] & 0x7F guard opCode != 0x00 else { return nil } sequenceZero = (UInt16(data[1] & 0x7F) << 6) | UInt16(data[2] >> 2) segmentOffset = ((data[2] & 0x03) << 3) | ((data[3] & 0xE0) >> 5) lastSegmentNumber = data[3] & 0x1F guard segmentOffset <= lastSegmentNumber else { return nil } upperTransportPdu = data.advanced(by: 4) source = networkPdu.source destination = networkPdu.destination networkKey = networkPdu.networkKey message = nil localElement = nil userInitiated = false } } extension SegmentedControlMessage: CustomDebugStringConvertible { var debugDescription: String { return "Segmented \(type) (opCode: \(opCode), seqZero: \(sequenceZero), segO: \(segmentOffset), segN: \(lastSegmentNumber), data: 0x\(upperTransportPdu.hex))" } }
39.121212
166
0.680609
eb88e0bc385b1c7067bcd20c0a80d7181ee59888
1,450
// // CaretToArcAnimationUITests.swift // CaretToArcAnimationUITests // // Created by Duncan Champney on 4/19/21. // import XCTest class CaretToArcAnimationUITests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // UI tests must launch the application that they test. let app = XCUIApplication() app.launch() // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testLaunchPerformance() throws { if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) { // This measures how long it takes to launch your application. measure(metrics: [XCTApplicationLaunchMetric()]) { XCUIApplication().launch() } } } }
33.72093
182
0.664138
e9462f4cd8bc7d93b10ba7391f5436c1551505c0
8,965
// // BaseTextView.swift // ListExample-iOS // // Created by Mostafa Taghipour on 1/21/18. // Copyright © 2018 RainyDay. All rights reserved. // import Foundation import UIKit @objc public protocol BaseTextViewDelegate: UITextViewDelegate { @objc optional func textViewDidChangeHeight(_ textView: BaseTextView, height: CGFloat) } @IBDesignable @objc open class BaseTextView: UITextView { // Maximum length of text. 0 means no limit. @IBInspectable open var maxLength: Int = 0 // Trim white space and newline characters when end editing. Default is true @IBInspectable open var trimWhiteSpaceWhenEndEditing: Bool = false // Maximm height of the textview @IBInspectable open var maxHeight: CGFloat = CGFloat(0) // growing textviewbox @IBInspectable open var growing: Bool = false @IBInspectable var cornerRadius: CGFloat = 0 { didSet{ layoutSubviews() } } @IBInspectable var borderWidth: CGFloat = 0 { didSet{ layoutSubviews() } } @IBInspectable var borderColor: UIColor = .clear { didSet{ layoutSubviews() } } @IBInspectable var background: UIColor = .clear { didSet{ layoutSubviews() } } // Placeholder properties private var _placeholderLabel:UILabel? @IBInspectable public var placeholder: String? { get { return _placeholderLabel?.text } set { if let placeholderLabel = _placeholderLabel { placeholderLabel.text = newValue placeholderLabel.sizeToFit() } else { self.addPlaceholder(newValue!) } } } // Placeholder color properties @IBInspectable public var placeholderColor: UIColor = UIColor.lightGray { didSet { if let placeholderLabel = _placeholderLabel { placeholderLabel.textColor=placeholderColor } } } override open var font: UIFont?{ didSet{ if let placeholderLabel = _placeholderLabel { placeholderLabel.font=font } } } override open var bounds: CGRect { didSet { self.resizePlaceholder() } } override open var textContainerInset: UIEdgeInsets{ didSet{ self.resizePlaceholder() } } override open var text: String! { didSet { self.textDidChanged(textView: self) setNeedsDisplay() } } fileprivate var heightConstraint: NSLayoutConstraint? // Initialize override public init(frame: CGRect, textContainer: NSTextContainer?) { super.init(frame: frame, textContainer: textContainer) commonInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } open override var intrinsicContentSize: CGSize { return CGSize(width: UIView.noIntrinsicMetric, height: 38) } func associateConstraints() { // iterate through all text view's constraints and identify // height,from: https://github.com/legranddamien/MBAutoGrowingTextView for constraint in self.constraints { if (constraint.firstAttribute == .height) { if (constraint.relation == .equal) { self.heightConstraint = constraint; } } } } // Listen to UITextView notification to handle trimming, placeholder and maximum length fileprivate func commonInit() { self.contentMode = .redraw associateConstraints() NotificationCenter.default.addObserver(self, selector: #selector(textDidChange), name: UITextView.textDidChangeNotification, object: self) NotificationCenter.default.addObserver(self, selector: #selector(textDidEndEditing), name: UITextView.textDidEndEditingNotification, object: self) } // Remove notification observer when deinit deinit { NotificationCenter.default.removeObserver(self, name: UITextView.textDidChangeNotification, object: self) NotificationCenter.default.removeObserver(self, name: UITextView.textDidEndEditingNotification, object: self) } // Calculate height of textview private var oldText = "" private var oldWidth = CGFloat(0) private func handleHeight(){ guard growing else { return } if text == oldText && oldWidth == bounds.width { return } oldText = text oldWidth = bounds.width let size = sizeThatFits(CGSize(width:bounds.size.width, height: CGFloat.greatestFiniteMagnitude)) let height = maxHeight > 0 ? min(size.height, maxHeight) : size.height if (heightConstraint == nil) { heightConstraint = NSLayoutConstraint(item: self, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: height) addConstraint(heightConstraint!) } if height != heightConstraint?.constant { self.heightConstraint!.constant = height; scrollRangeToVisible(NSMakeRange(0, 0)) if let delegate = delegate as? BaseTextViewDelegate { delegate.textViewDidChangeHeight?(self, height: height) } } } // Trim white space and new line characters when end editing. @objc func textDidEndEditing(notification: Notification) { if let notificationObject = notification.object as? BaseTextView { if notificationObject === self { if trimWhiteSpaceWhenEndEditing { text = text?.trimmingCharacters(in: .whitespacesAndNewlines) setNeedsDisplay() } } } } // Limit the length of text @objc open func textDidChange(notification: Notification) { if let notificationObject = notification.object as? BaseTextView { if notificationObject === self { if maxLength > 0 && text.count > maxLength { let endIndex = text.index(text.startIndex, offsetBy: maxLength) text = String(text[..<endIndex]) undoManager?.removeAllActions() } setNeedsDisplay() if let placeholderLabel = _placeholderLabel { placeholderLabel.isHidden = self.text.count > 0 } } } } //placeHolder visibility open func textDidChanged(textView: UITextView) { if let placeholderLabel = _placeholderLabel { placeholderLabel.isHidden = textView.text.count > 0 } } /// Resize the placeholder UILabel to make sure it's in the same position as the UITextView text private func resizePlaceholder() { if let placeholderLabel = _placeholderLabel { let labelX = self.textContainer.lineFragmentPadding + textContainerInset.left let labelY = self.textContainerInset.top - 2 let labelWidth = self.frame.width - (labelX * 2) let labelHeight = placeholderLabel.frame.height placeholderLabel.frame = CGRect(x: labelX, y: labelY, width: labelWidth, height: labelHeight) } } /// Adds a placeholder UILabel to this UITextView private func addPlaceholder(_ placeholderText: String) { _placeholderLabel = UILabel() _placeholderLabel!.text = placeholderText _placeholderLabel!.sizeToFit() _placeholderLabel!.font = self.font _placeholderLabel!.textColor = placeholderColor _placeholderLabel!.isHidden = self.text.count > 0 self.addSubview(_placeholderLabel!) self.resizePlaceholder() } // handle view layer private func handleLayer() { layer.borderWidth = borderWidth layer.borderColor = borderColor.cgColor layer.backgroundColor = background.cgColor layer.cornerRadius = cornerRadius layer.masksToBounds=true clipsToBounds = true if growing{ let path = UIBezierPath(roundedRect: bounds.insetBy(dx: 0.5, dy: 0.5), cornerRadius: cornerRadius) let mask = CAShapeLayer() mask.path = path.cgPath layer.mask = mask } } override open func layoutSubviews() { super.layoutSubviews() handleLayer() handleHeight() } }
30.493197
176
0.595538
08ff394aebe807889894fc23a5fd0723d754cc6f
721
// // AppDelegate.swift // VectorInspector // // Created by Randall R. Judd on 1/16/17. // Copyright © 2017 JVSIP. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { var vectorExplorerControllerWindow: VectorExplorerControllerWindow? func applicationDidFinishLaunching(_ aNotification: Notification) { // Insert code here to initialize your application let window = VectorExplorerControllerWindow() window.showWindow(self) self.vectorExplorerControllerWindow = window } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } }
24.033333
71
0.723994
8aa3d863846c0185129d57999cc24af415f43048
7,072
// // MatlabUtils.swift // MatlabUtils // // Created by Kelly Hwong on 2017/11/29. // Copyright © 2017 HKUST. All rights reserved. // import Foundation extension RangeReplaceableCollection { public mutating func resize(_ size: IndexDistance, fillWith value: Iterator.Element) { let c = count if c < size { append(contentsOf: repeatElement(value, count: c.distance(to: size))) } else if c > size { let newEnd = index(startIndex, offsetBy: size) removeSubrange(newEnd ..< endIndex) } } } public func filter(a:Array<Double>, b:Array<Double>, x:Array<Double>, zi:Array<Double>) -> Array<Double> { assert(a.count == b.count) var zi = zi let filter_order = a.count zi.resize(filter_order, fillWith: 0) var y = [Double](repeating: 0.0, count: x.count) for i in 0...x.count-1 { var order = filter_order - 1 while(order>0){ if (i >= order) { zi[order - 1] = b[order] * x[i - order] - a[order] * y[i - order] + zi[order] } order = order - 1 } y[i] = b[0] * x[i] + zi[0] } zi.resize(filter_order - 1, fillWith: 0) return y } public func filter(a:Array<Double>, b:Array<Double>, x:Array<Double>) -> Array<Double> { var y = [Double](repeating: 0.0, count: x.count) y[0] = b[0] * x[0]; for i in 1...b.count-1 { y[i] = 0.0 for j in 0...i { y[i] += b[j] * x[i-j] } for j in 0...i-1 { y[i] -= a[j+1] * y[i-j-1]; } } for i in b.count...x.count-1 { y[i] = 0.0 for j in 0...b.count-1 { y[i] += b[j] * x[i-j] } for j in 0...b.count-2 { y[i] -= a[j+1] * y[i-j-1]; } } return y } public func filtfilt(a:Array<Double>, b:Array<Double>, x:Array<Double>) -> Array<Double> { let border_size = 3*(a.count-1) assert(a.count == b.count && x.count > 2*border_size) // Reduce boundary effect - grow the signal with its inverted replicas on both edges var xx = [Double](repeating: 0.0, count: x.count + 2*border_size) for i in 0...border_size-1 { xx[i] = 2*x[0] - x[border_size-i] //x[border_size-i+1] xx[xx.count-i-1] = 2*x.last! - x[x.count-border_size+i-1] } for i in 0...x.count-1 { xx[i+border_size] = x[i]; } //var a = a1; var b = b1; //var nfilt = 2; //var rows = 1; var cols = 1; let vals = 1+a[2-1]; let rhs = b[2-1] - b[1-1]*a[2-1] let zi:[Double] = [rhs / vals] //print("zi:\(zi)") //print(xx) var zi_multiplied = zi.map { $0 * xx[1-1] } //print("zi_multiplied:\(zi_multiplied)") // one-way filter let firstPass = filter(a:a,b:b,x:xx,zi:zi_multiplied) //print("firstPass:\(firstPass)") // reverse the series let rev = Array(firstPass.reversed()) //print("rev:\(rev)") // filter again zi_multiplied = zi.map { $0 * rev[1-1] } //print("zi_multiplied:\(zi_multiplied)") let secondPass = filter(a:a, b:b, x:rev, zi:zi_multiplied) //print("secondPass:\(secondPass)") // return a stripped series, reversed back let secondPassRev = Array(secondPass.reversed()) //print("secondPassRev:\(secondPassRev)") let secondPassStripped = Array(secondPassRev[border_size..<secondPassRev.count-border_size]) return secondPassStripped } public func filtfilt_backup(a:Array<Double>, b:Array<Double>, x:Array<Double>) -> Array<Double> { let border_size = 3*a.count assert(a.count == b.count && x.count > 2*border_size) // Reduce boundary effect - grow the signal with its inverted replicas on both edges var xx = [Double](repeating: 0.0, count: x.count + 2*border_size) //return secondPass for i in 0...border_size-1 { xx[i] = 2*x[0] - x[border_size-i-1] xx[xx.count-i-1] = 2*x.last! - x[x.count-border_size+i] } for i in 0...x.count-1 { xx[i+border_size] = x[i]; } // one-way filter let firstPass = filter(a:a,b:b,x:xx) // reverse the series let rev = Array(firstPass.reversed()) // filter again let secondPass = filter(a:a, b:b, x:rev) // return a stripped series, reversed back let secondPassRev = Array(secondPass.reversed()) let secondPassStripped = Array(secondPassRev[border_size..<secondPassRev.count-border_size]) return secondPassStripped } public func norm(x:[Double]) -> Double{ var sqr_sum:Double = 0; for i in 0...x.count-1 { sqr_sum = sqr_sum + x[i] * x[i] } return sqrt(sqr_sum) } public func cross(a:[Double],b:[Double]) -> [Double] { var c:[Double] = [0,0,0] c[0] = a[1]*b[2] - a[2]*b[1] c[1] = a[2]*b[0] - a[0]*b[2] c[2] = a[0]*b[1] - a[1]*b[0] return c } public func mean(a:[Double]) -> Double { var sum:Double = 0 for (_, ia) in zip(a.indices, a) { sum = sum + ia } return sum/Double(a.count) } public func deg2rad(D:Double) -> Double { return D * Double.pi / 180.0 } public func quaternProd(a:[Double],b:[Double]) -> [Double] { var ab:[Double] = [0,0,0,0] ab[0] = a[0]*b[0]-a[1]*b[1]-a[2]*b[2]-a[3]*b[3]; ab[1] = a[0]*b[1]+a[1]*b[0]+a[2]*b[3]-a[3]*b[2]; ab[2] = a[0]*b[2]-a[1]*b[3]+a[2]*b[0]+a[3]*b[1]; ab[3] = a[0]*b[3]+a[1]*b[2]-a[2]*b[1]+a[3]*b[0]; return ab } public func quaternProd(a:[[Double]],b:[[Double]]) -> [[Double]] { var ab = a for i in 0...a.count-1 { ab[i][0] = a[i][0]*b[i][0]-a[i][1]*b[i][1]-a[i][2]*b[i][2]-a[i][3]*b[i][3]; ab[i][1] = a[i][0]*b[i][1]+a[i][1]*b[i][0]+a[i][2]*b[i][3]-a[i][3]*b[i][2]; ab[i][2] = a[i][0]*b[i][2]-a[i][1]*b[i][3]+a[i][2]*b[i][0]+a[i][3]*b[i][1]; ab[i][3] = a[i][0]*b[i][3]+a[i][1]*b[i][2]-a[i][2]*b[i][1]+a[i][3]*b[i][0]; } return ab } public func quaternConj(q:[Double]) -> [Double] { var qConj:[Double] = [0,0,0,0] qConj[0] = q[0] qConj[1] = -q[1] qConj[2] = -q[2] qConj[3] = -q[3] return qConj } public func quaternConj(q:[[Double]]) -> [[Double]] { var qConj = q for i in 0...q.count-1 { qConj[i][0] = q[i][0] qConj[i][1] = -q[i][1] qConj[i][2] = -q[i][2] qConj[i][3] = -q[i][3] } return qConj } public func quaternRotate(v:[[Double]], q:[[Double]]) -> [[Double]] { var v0 = v for i in 0...v0.count-1 { v0[i].insert(0.0, at:0) } let qConj = quaternConj(q:q) let qProd = quaternProd(a:q, b:v0) let v0XYZ = quaternProd(a:qProd, b:qConj) var v = v0XYZ for i in 0...v.count-1 { v[i].remove(at:0) } return v } public func diff(X:[Int]) -> [Int] { var Y:[Int] = [] for i in 1...X.count-1 { Y.append(X[i]-X[i-1]) } return Y } public func find(X:[Int],num:Int) -> [Int] { var k:[Int] = [] for i in 0...X.count-1 { if X[i] == num { k.append(i) } } return k }
27.733333
106
0.525594
728d20d481ba2c0b9bf58f096d3d061dae756fbf
623
// // ImageDownloaderPublisher.swift // wallabag // // Created by Marinel Maxime on 19/04/2020. // import Combine import Foundation import UIKit.UIImage class ImageDownloaderPublisher: ObservableObject { @Published var image: UIImage? private var cancellable: Cancellable? private let url: URL? init(url: String?) { self.url = url?.url loadImage() } func loadImage() { guard let url = url else { return } cancellable = ImageDownloader.shared.loadImage(url: url) .receive(on: DispatchQueue.main) .assign(to: \.image, on: self) } }
20.096774
64
0.637239
7a32e1b5a806799c61e1750fdfb7cd4985e26622
1,002
// // Article.swift // JohoFeed // // Created by alumno on 02/11/16. // Copyright © 2016 Evan Juárez. All rights reserved. // import Gloss public struct Article : Decodable { public let id : Int? public let uId : String? public let title : String? public let link : String? public let imageUrl : String? public let description : String? public let author : String? public let publishDate : String? public let feedTitle : String? public let createdAt : String? public let updatedAt : String? public init?(json: JSON) { id = "id" <~~ json uId = "uid" <~~ json title = "title" <~~ json link = "link" <~~ json imageUrl = "image_url" <~~ json description = "description" <~~ json author = "author" <~~ json publishDate = "publish_date" <~~ json feedTitle = "feed_title" <~~ json createdAt = "created_at" <~~ json updatedAt = "updated_at" <~~ json } }
25.692308
54
0.580838
0e612f353e6a29810e8f9fca324472b9dd29be67
16,883
import XCTest import BigInt import Quick import Nimble import Cuckoo @testable import EthereumKit class LESPeerTests: QuickSpec { override func spec() { let mockDevP2PPeer = MockIDevP2PPeer() let mockRequestHolder = MockLESPeerRequestHolder() let mockRandomHelper = MockIRandomHelper() let mockNetwork = MockINetwork() var lastBlockHeader = BlockHeader() let mockDelegate = MockIPeerDelegate() var peer: LESPeer! let protocolVersion = LESPeer.capability.version let networkId = 1 let genesisHash = Data(repeating: 1, count: 10) let blockTotalDifficulty: BigUInt = 12345 let blockHash = Data(repeating: 3, count: 10) let blockHeight = 100 beforeEach { stub(mockNetwork) { mock in when(mock.chainId.get).thenReturn(networkId) when(mock.genesisBlockHash.get).thenReturn(genesisHash) } lastBlockHeader = BlockHeader(hashHex: blockHash, totalDifficulty: blockTotalDifficulty, height: blockHeight) peer = LESPeer(devP2PPeer: mockDevP2PPeer, requestHolder: mockRequestHolder, randomHelper: mockRandomHelper, network: mockNetwork, lastBlockHeader: lastBlockHeader) peer.delegate = mockDelegate } afterEach { reset(mockDevP2PPeer, mockRequestHolder, mockRandomHelper, mockNetwork, mockDelegate) } describe("#connect") { it("connects devP2P peer") { stub(mockDevP2PPeer) { mock in when(mock.connect()).thenDoNothing() } peer.connect() verify(mockDevP2PPeer).connect() } } describe("#disconnect") { it("disconnects devP2P peer") { let error = TestError() stub(mockDevP2PPeer) { mock in when(mock.disconnect(error: any())).thenDoNothing() } peer.disconnect(error: error) verify(mockDevP2PPeer).disconnect(error: equal(to: error, type: TestError.self)) } } describe("#requestBlockHeaders") { let requestId = 123 let blockHeight = 123456 let blockHeader = BlockHeader(height: blockHeight) let reverse = true let limit = 100 beforeEach { stub(mockRandomHelper) { mock in when(mock.randomInt.get).thenReturn(requestId) } stub(mockRequestHolder) { mock in when(mock.set(blockHeaderRequest: any(), id: any())).thenDoNothing() } stub(mockDevP2PPeer) { mock in when(mock.send(message: any())).thenDoNothing() } peer.requestBlockHeaders(blockHeader: blockHeader, limit: limit, reverse: reverse) } it("sets request to holder") { let argumentCaptor = ArgumentCaptor<BlockHeaderRequest>() verify(mockRequestHolder).set(blockHeaderRequest: argumentCaptor.capture(), id: requestId) let request = argumentCaptor.value! expect(request.blockHeader).to(equal(blockHeader)) expect(request.reverse).to(equal(reverse)) } it("sends message to devP2P peer") { let argumentCaptor = ArgumentCaptor<IOutMessage>() verify(mockDevP2PPeer).send(message: argumentCaptor.capture()) let message = argumentCaptor.value as! GetBlockHeadersMessage expect(message.requestId).to(equal(requestId)) expect(message.blockHeight).to(equal(blockHeight)) expect(message.maxHeaders).to(equal(limit)) expect(message.reverse).to(equal(1)) } } describe("#requestAccountState") { let requestId = 123 let address = Data(repeating: 123, count: 20) let blockHash = Data(repeating: 234, count: 20) let blockHeader = BlockHeader(hashHex: blockHash) beforeEach { stub(mockRandomHelper) { mock in when(mock.randomInt.get).thenReturn(requestId) } stub(mockRequestHolder) { mock in when(mock.set(accountStateRequest: any(), id: any())).thenDoNothing() } stub(mockDevP2PPeer) { mock in when(mock.send(message: any())).thenDoNothing() } peer.requestAccountState(address: address, blockHeader: blockHeader) } it("sets request to holder") { let argumentCaptor = ArgumentCaptor<AccountStateRequest>() verify(mockRequestHolder).set(accountStateRequest: argumentCaptor.capture(), id: requestId) let request = argumentCaptor.value! expect(request.address).to(equal(address)) expect(request.blockHeader).to(equal(blockHeader)) } it("sends message to devP2P peer") { let argumentCaptor = ArgumentCaptor<IOutMessage>() verify(mockDevP2PPeer).send(message: argumentCaptor.capture()) let message = argumentCaptor.value as! GetProofsMessage expect(message.requestId).to(equal(requestId)) expect(message.proofRequests.count).to(equal(1)) expect(message.proofRequests[0].blockHash).to(equal(blockHash)) expect(message.proofRequests[0].key).to(equal(address)) } } describe("#sendTransaction") { let requestId = 123 let rawTransaction = RawTransaction() let signature: (v: BigUInt, r: BigUInt, s: BigUInt) = (0, 0, 0) beforeEach { stub(mockRandomHelper) { mock in when(mock.randomInt.get).thenReturn(requestId) } stub(mockDevP2PPeer) { mock in when(mock.send(message: any())).thenDoNothing() } peer.send(rawTransaction: rawTransaction, signature: signature) } it("sends message to devP2P peer") { let argumentCaptor = ArgumentCaptor<IOutMessage>() verify(mockDevP2PPeer).send(message: argumentCaptor.capture()) let message = argumentCaptor.value as! SendTransactionMessage expect(message.requestId).to(equal(requestId)) expect(message.rawTransaction).to(beIdenticalTo(rawTransaction)) expect(message.signature.v).to(equal(signature.v)) expect(message.signature.r).to(equal(signature.r)) expect(message.signature.s).to(equal(signature.s)) } } describe("#didConnect") { let argumentCaptor = ArgumentCaptor<IOutMessage>() beforeEach { stub(mockDevP2PPeer) { mock in when(mock.send(message: any())).thenDoNothing() } peer.didConnect() } it("sends status message") { verify(mockDevP2PPeer).send(message: argumentCaptor.capture()) let message = argumentCaptor.value as! StatusMessage expect(message.protocolVersion).to(equal(protocolVersion)) expect(message.networkId).to(equal(networkId)) expect(message.genesisHash).to(equal(genesisHash)) expect(message.headTotalDifficulty).to(equal(blockTotalDifficulty)) expect(message.headHash).to(equal(blockHash)) expect(message.headHeight).to(equal(blockHeight)) } } describe("#didDisconnect") { let error = TestError() beforeEach { stub(mockDelegate) { mock in when(mock.didDisconnect(error: any())).thenDoNothing() } peer.didDisconnect(error: error) } it("notifies delegate") { verify(mockDelegate).didDisconnect(error: equal(to: error, type: TestError.self)) } } describe("#didReceiveMessage") { beforeEach { stub(mockDevP2PPeer) { mock in when(mock.disconnect(error: any())).thenDoNothing() } } context("when message is StatusMessage") { let statusMessage = StatusMessage() beforeEach { statusMessage.protocolVersion = protocolVersion statusMessage.networkId = networkId statusMessage.genesisHash = genesisHash statusMessage.headHeight = blockHeight } context("when valid") { it("notifies delegate that connected") { stub(mockDelegate) { mock in when(mock.didConnect()).thenDoNothing() } peer.didReceive(message: statusMessage) verify(mockDelegate).didConnect() } } context("when invalid") { it("does not notify delegate that connected") { verify(mockDelegate, never()).didConnect() } context("protocolVersion") { beforeEach { statusMessage.protocolVersion = protocolVersion + 1 peer.didReceive(message: statusMessage) } it("disconnects with invalidProtocolVersion error") { verify(mockDevP2PPeer).disconnect(error: equal(to: LESPeer.ValidationError.invalidProtocolVersion, type: LESPeer.ValidationError.self)) } } context("networkId") { beforeEach { statusMessage.networkId = 10 peer.didReceive(message: statusMessage) } it("disconnects with wrongNetwork error") { verify(mockDevP2PPeer).disconnect(error: equal(to: LESPeer.ValidationError.wrongNetwork, type: LESPeer.ValidationError.self)) } } context("genesisBlockHash") { beforeEach { statusMessage.genesisHash = Data(repeating: 123, count: 10) peer.didReceive(message: statusMessage) } it("disconnects with wrongNetwork error") { verify(mockDevP2PPeer).disconnect(error: equal(to: LESPeer.ValidationError.wrongNetwork, type: LESPeer.ValidationError.self)) } } context("bestBlockHeight") { beforeEach { statusMessage.headHeight = blockHeight - 1 peer.didReceive(message: statusMessage) } it("disconnects with expiredBestBlockHeight error") { verify(mockDevP2PPeer).disconnect(error: equal(to: LESPeer.ValidationError.expiredBestBlockHeight, type: LESPeer.ValidationError.self)) } } } } context("when message is BlockHeadersMessage") { let requestId = 123 let blockHeaders = [BlockHeader()] let message = BlockHeadersMessage(requestId: requestId, headers: blockHeaders) context("when request exists in holder") { let blockHeader = BlockHeader() let reverse = true beforeEach { let request = BlockHeaderRequest(blockHeader: blockHeader, reverse: reverse) stub(mockRequestHolder) { mock in when(mock.removeBlockHeaderRequest(id: requestId)).thenReturn(request) } stub(mockDelegate) { mock in when(mock.didReceive(blockHeaders: any(), blockHeader: any(), reverse: any())).thenDoNothing() } peer.didReceive(message: message) } it("notifies delegate") { verify(mockDelegate).didReceive(blockHeaders: equal(to: blockHeaders), blockHeader: equal(to: blockHeader), reverse: equal(to: reverse)) } } context("when request does not exist in holder") { beforeEach { stub(mockRequestHolder) { mock in when(mock.removeBlockHeaderRequest(id: requestId)).thenReturn(nil) } peer.didReceive(message: message) } it("disconnects with unexpectedMessage error") { verify(mockDevP2PPeer).disconnect(error: equal(to: LESPeer.ConsistencyError.unexpectedMessage, type: LESPeer.ConsistencyError.self)) } it("does not notify delegate") { verify(mockDelegate, never()).didReceive(blockHeaders: any(), blockHeader: any(), reverse: any()) } } } context("when message is ProofsMessage") { let requestId = 123 let message = ProofsMessage(requestId: requestId) context("when request exists in holder") { let address = Data(repeating: 1, count: 10) let blockHeader = BlockHeader() let accountState = AccountStateSpv() beforeEach { let mockRequest = MockAccountStateRequest(address: address, blockHeader: blockHeader) stub(mockRequest) { mock in when(mock.accountState(proofsMessage: equal(to: message))).thenReturn(accountState) } stub(mockRequestHolder) { mock in when(mock.removeAccountStateRequest(id: requestId)).thenReturn(mockRequest) } stub(mockDelegate) { mock in when(mock.didReceive(accountState: any(), address: any(), blockHeader: any())).thenDoNothing() } peer.didReceive(message: message) } it("notifies delegate") { verify(mockDelegate).didReceive(accountState: equal(to: accountState), address: equal(to: address), blockHeader: equal(to: blockHeader)) } } context("when request does not exist in holder") { beforeEach { stub(mockRequestHolder) { mock in when(mock.removeAccountStateRequest(id: requestId)).thenReturn(nil) } peer.didReceive(message: message) } it("disconnects with unexpectedMessage error") { verify(mockDevP2PPeer).disconnect(error: equal(to: LESPeer.ConsistencyError.unexpectedMessage, type: LESPeer.ConsistencyError.self)) } it("does not notify delegate") { verify(mockDelegate, never()).didReceive(accountState: any(), address: any(), blockHeader: any()) } } } context("when message is AnnounceMessage") { let blockHash = Data(repeating: 111, count: 4) let blockHeight = 1234 let message = AnnounceMessage(lastBlockHash: blockHash, lastBlockHeight: blockHeight) beforeEach { stub(mockDelegate) { mock in when(mock.didAnnounce(blockHash: any(), blockHeight: any())).thenDoNothing() } peer.didReceive(message: message) } it("notifies delegate") { verify(mockDelegate).didAnnounce(blockHash: equal(to: blockHash), blockHeight: equal(to: blockHeight)) } } } } }
40.486811
176
0.523367
ed9e3310ac905cb0ea88f71ccc6d5349dd2213b0
2,878
// // XVTableViewHolderDelegate.swift // RTSwift // // Created by zuer on 2021/9/10. // import UIKit class XVTableViewDelegate: XVCollectionBuilderGetter<XVTableViewBuilder>, UITableViewDelegate { typealias HeaderFooter = (UITableViewHeaderFooterView & XVSectionItemViews) func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let builder = self.builder, let rowGetter = self.rowGetter(indexPath: indexPath) else { return } builder.uiSelecter?(true, rowGetter) } func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { guard let builder = self.builder, let rowGetter = self.rowGetter(indexPath: indexPath) else { return } builder.uiSelecter?(false, rowGetter) } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { guard let sectionGetter = self.sectionGetter(section: section), let header = sectionGetter.header else { return 0.0 } return header.size.height } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { guard let sectionGetter = self.sectionGetter(section: section), let footer = sectionGetter.footer else { return 0.0 } return footer.size.height } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { guard let rowGetter = self.rowGetter(indexPath: indexPath) else { return 0.0 } return rowGetter.size.height } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { guard let sectionGetter = self.sectionGetter(section: section), let header = sectionGetter.header else { return nil } guard let view = tableView.dequeueReusableHeaderFooterView(withIdentifier: header.identifier) as? HeaderFooter else { fatalError("[XVTableViewDelegate] we can't take an any useable header with id|\(header.identifier)! Please Check it!") } view.model = header return view } func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { guard let sectionGetter = self.sectionGetter(section: section), let footer = sectionGetter.footer else { return nil } guard let view = tableView.dequeueReusableHeaderFooterView(withIdentifier: footer.identifier) as? HeaderFooter else { fatalError("[XVTableViewDelegate] we can't take an any useable footer with id|\(footer.identifier)! Please Check it!") } view.model = footer return view } }
37.376623
130
0.651494
f5db9dd100c3654e25890c33eefe417eae3703ae
2,262
// // MediaEditorCompletedDateView.swift // Clematis (iOS) // // Created by Kyle Erhabor on 2/16/21. // import SwiftUI struct MediaEditorCompletedDateView: View { @EnvironmentObject private var viewModel: MediaEditorViewModel var body: some View { let binding = Binding<Date> { // `viewModel.media?.mediaListEntry?.completedAt` may have a value, but there's no guarantee the values // inside it will not be `nil`. This may result in unethical dates to navigate through (such as the 1st of // January in the year 1). if let day = viewModel.media?.mediaListEntry?.completedAt?.day, let month = viewModel.media?.mediaListEntry?.completedAt?.month, let year = viewModel.media?.mediaListEntry?.completedAt?.year { return DateComponents( calendar: .current, year: year, month: month, day: day ).date ?? Date() } return Date() } set: { date in let components = Calendar.current.dateComponents([.day, .month, .year], from: date) let completedAt = MediaEditorQuery.Data.Medium.MediaListEntry.CompletedAt( day: components.day, year: components.year, month: components.month ) if viewModel.media?.mediaListEntry == nil { viewModel.media?.mediaListEntry = .init(id: -1, completedAt: completedAt) } else { viewModel.media?.mediaListEntry?.completedAt = completedAt } } if viewModel.media?.mediaListEntry?.completedAt?.day == nil && viewModel.media?.mediaListEntry?.completedAt?.month == nil && viewModel.media?.mediaListEntry?.completedAt?.year == nil { HStack { Text("Finish Date") Spacer() Button("Set") { withAnimation { binding.wrappedValue = .init() } } } } else { DatePicker("Finish Date", selection: binding, displayedComponents: .date) } } }
35.34375
118
0.543324
160578266689d646f0e3b224ac56f03767a266ef
655
import Foundation let myName = "Aji" var myAge = 25 var originCountry = "Indonesia 🇮🇩" var myNextAge = myAge + 1 let yearBorn = 1994 var myNameCharacterCountString = "" if myName.count > 1 { myNameCharacterCountString = "characters" } else { myNameCharacterCountString = "character" } //MARK: Exercise 1 print("--------------------------------- \n") print("Hi all, ") print("my name is \(myName)! ") print("my name consists of \(myName.count) \(myNameCharacterCountString) ") print("Nice to meet you all 🙌🏻 ") print("I am from \(originCountry) ") print("I am \(myAge) y.o, next month I'll be \(myNextAge) ") print("I was born in \(yearBorn) ")
26.2
75
0.651908
33ff4f0ee4a8a9ec5aff517e3e6546be8cd36211
970
// // FordMenuCollectionViewCell.swift // Menuator // // Created by Aguele/Rafaj on 05/09/2017. // Copyright (c) 2017 Ford. All rights reserved. // import Foundation import UIKit import SnapKit class MenuatorCollectionViewCell: UICollectionViewCell { static var identifier = "FordMenuCollectionViewCell" var label = UILabel() var menuItem: MenuatorDataController.MenuItem? { didSet { label.text = menuItem?.text menuItem?.configure?(&label) } } // MARK: Initialization override init(frame: CGRect) { super.init(frame: frame) contentView.addSubview(label) label.snp.makeConstraints { (make) in make.edges.equalToSuperview() } } convenience init() { self.init(frame: CGRect.zero) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
17.636364
59
0.613402
87ee4a4a475cbbb91223542572c26d8d7c5c8fa1
326
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let:{ let:{ protocol P{ typealias e:e let t:e struct A{ struct a{ struct A{ { } protocol A{ { } { } var d={ { { } } b({ class b { { } {{ } } let:{ { } let i(
9.055556
87
0.644172
20e3c869e0eac566cf11bf56c066fe26ff6e9384
13,414
// // PassthroughSubjectTests.swift // // // Created by Sergej Jaskiewicz on 11.06.2019. // import XCTest #if OPENCOMBINE_COMPATIBILITY_TEST import Combine #else import OpenCombine #endif @available(macOS 10.15, iOS 13.0, *) final class PassthroughSubjectTests: XCTestCase { private typealias Sut = PassthroughSubject<Int, TestingError> // Reactive Streams Spec: Rules #1, #2, #9 func testRequestingDemand() { let initialDemands: [Subscribers.Demand?] = [ nil, .max(1), .max(2), .max(10), .unlimited ] let subsequentDemands: [[Subscribers.Demand]] = [ Array(repeating: .max(0), count: 5), Array(repeating: .max(1), count: 10), [.max(1), .max(0), .max(1), .max(0)], [.max(0), .max(1), .max(2)], [.unlimited, .max(1)] ] var numberOfInputsHistory: [Int] = [] let expectedNumberOfInputsHistory = [ 0, 0, 0, 0, 0, 1, 11, 2, 1, 20, 2, 12, 4, 5, 20, 10, 20, 12, 13, 20, 20, 20, 20, 20, 20 ] for initialDemand in initialDemands { for subsequentDemand in subsequentDemands { var subscriptions: [Subscription] = [] var inputs: [Int] = [] var completions: [Subscribers.Completion<TestingError>] = [] var i = 0 let passthrough = Sut() let subscriber = AnySubscriber<Int, TestingError>( receiveSubscription: { subscription in subscriptions.append(subscription) initialDemand.map(subscription.request) }, receiveValue: { value in defer { i += 1 } inputs.append(value) return i < subsequentDemand.endIndex ? subsequentDemand[i] : .none }, receiveCompletion: { completion in completions.append(completion) } ) XCTAssertEqual(subscriptions.count, 0) XCTAssertEqual(inputs.count, 0) XCTAssertEqual(completions.count, 0) passthrough.subscribe(subscriber) XCTAssertEqual(subscriptions.count, 1) XCTAssertEqual(inputs.count, 0) XCTAssertEqual(completions.count, 0) for j in 0..<20 { passthrough.send(j) } passthrough.send(completion: .finished) XCTAssertEqual(subscriptions.count, 1) XCTAssertEqual(completions.count, 1) numberOfInputsHistory.append(inputs.count) } } XCTAssertEqual(numberOfInputsHistory, expectedNumberOfInputsHistory) } func testCrashOnZeroInitialDemand() { assertCrashes { let subscriber = TrackingSubscriber( receiveSubscription: { $0.request(.none) } ) Sut().subscribe(subscriber) } } func testSendFailureCompletion() { let cvs = Sut() let subscriber = TrackingSubscriber( receiveSubscription: { subscription in subscription.request(.unlimited) } ) cvs.subscribe(subscriber) XCTAssertEqual(subscriber.history, [.subscription("PassthroughSubject")]) cvs.send(completion: .failure(.oops)) XCTAssertEqual(subscriber.history, [.subscription("PassthroughSubject"), .completion(.failure(.oops))]) } func testMultipleSubscriptions() { let passthrough = Sut() final class MySubscriber: Subscriber { typealias Input = Sut.Output typealias Failure = Sut.Failure let sut: Sut var subscriptions: [Subscription] = [] var inputs: [Int] = [] var completions: [Subscribers.Completion<TestingError>] = [] init(sut: Sut) { self.sut = sut } func receive(subscription: Subscription) { subscription.request(.unlimited) subscriptions.append(subscription) if subscriptions.count < 10 { // This must recurse sut.subscribe(self) } } func receive(_ input: Input) -> Subscribers.Demand { inputs.append(input) return .none } func receive(completion: Subscribers.Completion<Failure>) { completions.append(completion) } } let subscriber = MySubscriber(sut: passthrough) passthrough.subscribe(subscriber) XCTAssertEqual(subscriber.subscriptions.count, 10) XCTAssertEqual(subscriber.inputs.count, 0) XCTAssertEqual(subscriber.completions.count, 0) passthrough.subscribe(subscriber) XCTAssertEqual(subscriber.subscriptions.count, 11) XCTAssertEqual(subscriber.inputs.count, 0) XCTAssertEqual(subscriber.completions.count, 0) } // Reactive Streams Spec: Rule #6 func testMultipleCompletions() { var subscriptions: [Subscription] = [] var inputs: [Int] = [] var completions: [Subscribers.Completion<TestingError>] = [] let passthrough = Sut() let subscriber = AnySubscriber<Int, TestingError>( receiveSubscription: { subscription in subscriptions.append(subscription) subscription.request(.unlimited) }, receiveValue: { value in inputs.append(value) return .none }, receiveCompletion: { completion in passthrough.send(completion: .failure("must not recurse")) completions.append(completion) } ) passthrough.subscribe(subscriber) passthrough.send(42) XCTAssertEqual(subscriptions.count, 1) XCTAssertEqual(inputs.count, 1) XCTAssertEqual(completions.count, 0) passthrough.send(completion: .finished) XCTAssertEqual(subscriptions.count, 1) XCTAssertEqual(inputs.count, 1) XCTAssertEqual(completions.count, 1) passthrough.send(completion: .finished) XCTAssertEqual(subscriptions.count, 1) XCTAssertEqual(inputs.count, 1) XCTAssertEqual(completions.count, 1) passthrough.send(completion: .failure("oops")) XCTAssertEqual(subscriptions.count, 1) XCTAssertEqual(inputs.count, 1) XCTAssertEqual(completions.count, 1) } // Reactive Streams Spec: Rule #6 func testValuesAfterCompletion() { var subscriptions: [Subscription] = [] var inputs: [Int] = [] var completions: [Subscribers.Completion<TestingError>] = [] let passthrough = Sut() let subscriber = AnySubscriber<Int, TestingError>( receiveSubscription: { subscription in subscriptions.append(subscription) subscription.request(.unlimited) }, receiveValue: { value in inputs.append(value) return .none }, receiveCompletion: { completion in passthrough.send(42) completions.append(completion) } ) passthrough.subscribe(subscriber) passthrough.send(42) XCTAssertEqual(subscriptions.count, 1) XCTAssertEqual(inputs.count, 1) XCTAssertEqual(completions.count, 0) passthrough.send(completion: .finished) XCTAssertEqual(subscriptions.count, 1) XCTAssertEqual(inputs.count, 1) XCTAssertEqual(completions.count, 1) passthrough.send(42) XCTAssertEqual(subscriptions.count, 1) XCTAssertEqual(inputs.count, 1) XCTAssertEqual(completions.count, 1) } func testSubscriptionAfterCompletion() { let passthrough = Sut() passthrough.send(completion: .finished) let subscriber = TrackingSubscriber() passthrough.subscribe(subscriber) XCTAssertEqual(subscriber.history, [.subscription("Empty"), .completion(.finished)]) } func testSendSubscription() { let subscription1 = CustomSubscription() let passthrough = Sut() passthrough.send(subscription: subscription1) XCTAssertEqual(subscription1.history, []) let subscriber1 = TrackingSubscriber(receiveSubscription: { $0.request(.max(1)) }) passthrough.subscribe(subscriber1) XCTAssertEqual(subscription1.history, [.requested(.unlimited)]) XCTAssertEqual(subscriber1.history, [.subscription("PassthroughSubject")]) let subscriber2 = TrackingSubscriber(receiveSubscription: { $0.request(.max(2)) }) passthrough.subscribe(subscriber2) XCTAssertEqual(subscription1.history, [.requested(.unlimited)]) XCTAssertEqual(subscriber1.history, [.subscription("PassthroughSubject")]) XCTAssertEqual(subscriber2.history, [.subscription("PassthroughSubject")]) passthrough.send(subscription: subscription1) XCTAssertEqual(subscription1.history, [.requested(.unlimited), .requested(.unlimited)]) passthrough.send(0) passthrough.send(0) let subscription2 = CustomSubscription() passthrough.send(subscription: subscription2) XCTAssertEqual(subscription2.history, [.requested(.unlimited)]) } func testLifecycle() throws { var deinitCounter = 0 let onDeinit = { deinitCounter += 1 } do { let passthrough = Sut() let emptySubscriber = TrackingSubscriber(onDeinit: onDeinit) XCTAssertTrue(emptySubscriber.history.isEmpty) passthrough.subscribe(emptySubscriber) XCTAssertEqual(emptySubscriber.subscriptions.count, 1) passthrough.send(31) XCTAssertEqual(emptySubscriber.inputs.count, 0) passthrough.send(completion: .failure("failure")) XCTAssertEqual(emptySubscriber.completions.count, 1) } XCTAssertEqual(deinitCounter, 1) do { let passthrough = Sut() let emptySubscriber = TrackingSubscriber(onDeinit: onDeinit) XCTAssertTrue(emptySubscriber.history.isEmpty) passthrough.subscribe(emptySubscriber) XCTAssertEqual(emptySubscriber.subscriptions.count, 1) XCTAssertEqual(emptySubscriber.inputs.count, 0) XCTAssertEqual(emptySubscriber.completions.count, 0) } XCTAssertEqual(deinitCounter, 1) var subscription: Subscription? do { let passthrough = Sut() let emptySubscriber = TrackingSubscriber( receiveSubscription: { subscription = $0; $0.request(.unlimited) }, onDeinit: onDeinit ) XCTAssertTrue(emptySubscriber.history.isEmpty) passthrough.subscribe(emptySubscriber) XCTAssertEqual(emptySubscriber.subscriptions.count, 1) passthrough.send(31) XCTAssertEqual(emptySubscriber.inputs.count, 1) XCTAssertEqual(emptySubscriber.completions.count, 0) XCTAssertNotNil(subscription) } XCTAssertEqual(deinitCounter, 1) try XCTUnwrap(subscription).cancel() XCTAssertEqual(deinitCounter, 2) } func testSynchronization() { let subscriptions = Atomic<[Subscription]>([]) let inputs = Atomic<[Int]>([]) let completions = Atomic<[Subscribers.Completion<TestingError>]>([]) let passthrough = Sut() let subscriber = AnySubscriber<Int, TestingError>( receiveSubscription: { subscription in subscriptions.do { $0.append(subscription) } subscription.request(.unlimited) }, receiveValue: { value in inputs.do { $0.append(value) } return .none }, receiveCompletion: { completion in completions.do { $0.append(completion) } } ) race( { passthrough.subscribe(subscriber) }, { passthrough.subscribe(subscriber) } ) XCTAssertEqual(subscriptions.value.count, 200) race( { passthrough.send(31) }, { passthrough.send(42) } ) XCTAssertEqual(inputs.value.count, 40000) race( { subscriptions.value[0].request(.max(4)) }, { subscriptions.value[0].request(.max(10)) } ) race( { passthrough.send(completion: .finished) }, { passthrough.send(completion: .failure("")) } ) XCTAssertEqual(completions.value.count, 200) } }
31.12297
90
0.568585
dbdcd37facfc472285dd8c03bfb8892e491ec13e
7,288
import UIKit // MARK: - Color Builders public extension UIColor { /// Constructing color from hex string /// /// - Parameter hex: A hex string, can either contain # or not convenience init(hex string: String) { var hex = string.hasPrefix("#") ? String(string.dropFirst()) : string guard hex.count == 3 || hex.count == 6 else { self.init(white: 1.0, alpha: 0.0) return } if hex.count == 3 { for (index, char) in hex.enumerated() { hex.insert(char, at: hex.index(hex.startIndex, offsetBy: index * 2)) } } self.init( red: CGFloat((Int(hex, radix: 16)! >> 16) & 0xFF) / 255.0, green: CGFloat((Int(hex, radix: 16)! >> 8) & 0xFF) / 255.0, blue: CGFloat((Int(hex, radix: 16)!) & 0xFF) / 255.0, alpha: 1.0) } /// Adjust color based on saturation /// /// - Parameter minSaturation: The minimun saturation value /// - Returns: The adjusted color public func color(minSaturation: CGFloat) -> UIColor { var (hue, saturation, brightness, alpha): (CGFloat, CGFloat, CGFloat, CGFloat) = (0.0, 0.0, 0.0, 0.0) getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) return saturation < minSaturation ? UIColor(hue: hue, saturation: minSaturation, brightness: brightness, alpha: alpha) : self } /// Convenient method to change alpha value /// /// - Parameter value: The alpha value /// - Returns: The alpha adjusted color public func alpha(_ value: CGFloat) -> UIColor { return withAlphaComponent(value) } } // MARK: - Helpers public extension UIColor { public func hex(hashPrefix: Bool = true) -> String { var (r, g, b, a): (CGFloat, CGFloat, CGFloat, CGFloat) = (0.0, 0.0, 0.0, 0.0) getRed(&r, green: &g, blue: &b, alpha: &a) let prefix = hashPrefix ? "#" : "" return String(format: "\(prefix)%02X%02X%02X", Int(r * 255), Int(g * 255), Int(b * 255)) } internal func rgbComponents() -> [CGFloat] { var (r, g, b, a): (CGFloat, CGFloat, CGFloat, CGFloat) = (0.0, 0.0, 0.0, 0.0) getRed(&r, green: &g, blue: &b, alpha: &a) return [r, g, b] } public var isDark: Bool { let RGB = rgbComponents() return (0.2126 * RGB[0] + 0.7152 * RGB[1] + 0.0722 * RGB[2]) < 0.5 } public var isBlackOrWhite: Bool { let RGB = rgbComponents() return (RGB[0] > 0.91 && RGB[1] > 0.91 && RGB[2] > 0.91) || (RGB[0] < 0.09 && RGB[1] < 0.09 && RGB[2] < 0.09) } public var isBlack: Bool { let RGB = rgbComponents() return (RGB[0] < 0.09 && RGB[1] < 0.09 && RGB[2] < 0.09) } public var isWhite: Bool { let RGB = rgbComponents() return (RGB[0] > 0.91 && RGB[1] > 0.91 && RGB[2] > 0.91) } public func isDistinct(from color: UIColor) -> Bool { let bg = rgbComponents() let fg = color.rgbComponents() let threshold: CGFloat = 0.25 var result = false if abs(bg[0] - fg[0]) > threshold || abs(bg[1] - fg[1]) > threshold || abs(bg[2] - fg[2]) > threshold { if abs(bg[0] - bg[1]) < 0.03 && abs(bg[0] - bg[2]) < 0.03 { if abs(fg[0] - fg[1]) < 0.03 && abs(fg[0] - fg[2]) < 0.03 { result = false } } result = true } return result } public func isContrasting(with color: UIColor) -> Bool { let bg = rgbComponents() let fg = color.rgbComponents() let bgLum = 0.2126 * bg[0] + 0.7152 * bg[1] + 0.0722 * bg[2] let fgLum = 0.2126 * fg[0] + 0.7152 * fg[1] + 0.0722 * fg[2] let contrast = bgLum > fgLum ? (bgLum + 0.05) / (fgLum + 0.05) : (fgLum + 0.05) / (bgLum + 0.05) return 1.6 < contrast } } // MARK: - Gradient public extension Array where Element : UIColor { public func gradient(_ transform: ((_ gradient: inout CAGradientLayer) -> CAGradientLayer)? = nil) -> CAGradientLayer { var gradient = CAGradientLayer() gradient.colors = self.map { $0.cgColor } if let transform = transform { gradient = transform(&gradient) } return gradient } } // MARK: - Components public extension UIColor { var redComponent : CGFloat { get { var r : CGFloat = 0 self.getRed(&r, green: nil , blue: nil, alpha: nil) return r } } var greenComponent : CGFloat { get { var g : CGFloat = 0 self.getRed(nil, green: &g , blue: nil, alpha: nil) return g } } var blueComponent : CGFloat { get { var b : CGFloat = 0 self.getRed(nil, green: nil , blue: &b, alpha: nil) return b } } var alphaComponent : CGFloat { get { var a : CGFloat = 0 self.getRed(nil, green: nil , blue: nil, alpha: &a) return a } } } // MARK: - Blending public extension UIColor { /**adds hue, saturation, and brightness to the HSB components of this color (self)*/ public func add(hue: CGFloat, saturation: CGFloat, brightness: CGFloat, alpha: CGFloat) -> UIColor { var (oldHue, oldSat, oldBright, oldAlpha) : (CGFloat, CGFloat, CGFloat, CGFloat) = (0,0,0,0) getHue(&oldHue, saturation: &oldSat, brightness: &oldBright, alpha: &oldAlpha) // make sure new values doesn't overflow var newHue = oldHue + hue while newHue < 0.0 { newHue += 1.0 } while newHue > 1.0 { newHue -= 1.0 } let newBright: CGFloat = max(min(oldBright + brightness, 1.0), 0) let newSat: CGFloat = max(min(oldSat + saturation, 1.0), 0) let newAlpha: CGFloat = max(min(oldAlpha + alpha, 1.0), 0) return UIColor(hue: newHue, saturation: newSat, brightness: newBright, alpha: newAlpha) } /**adds red, green, and blue to the RGB components of this color (self)*/ public func add(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) -> UIColor { var (oldRed, oldGreen, oldBlue, oldAlpha) : (CGFloat, CGFloat, CGFloat, CGFloat) = (0,0,0,0) getRed(&oldRed, green: &oldGreen, blue: &oldBlue, alpha: &oldAlpha) // make sure new values doesn't overflow let newRed: CGFloat = max(min(oldRed + red, 1.0), 0) let newGreen: CGFloat = max(min(oldGreen + green, 1.0), 0) let newBlue: CGFloat = max(min(oldBlue + blue, 1.0), 0) let newAlpha: CGFloat = max(min(oldAlpha + alpha, 1.0), 0) return UIColor(red: newRed, green: newGreen, blue: newBlue, alpha: newAlpha) } public func add(hsb color: UIColor) -> UIColor { var (h,s,b,a) : (CGFloat, CGFloat, CGFloat, CGFloat) = (0,0,0,0) color.getHue(&h, saturation: &s, brightness: &b, alpha: &a) return self.add(hue: h, saturation: s, brightness: b, alpha: 0) } public func add(rgb color: UIColor) -> UIColor { return self.add(red: color.redComponent, green: color.greenComponent, blue: color.blueComponent, alpha: 0) } public func add(hsba color: UIColor) -> UIColor { var (h,s,b,a) : (CGFloat, CGFloat, CGFloat, CGFloat) = (0,0,0,0) color.getHue(&h, saturation: &s, brightness: &b, alpha: &a) return self.add(hue: h, saturation: s, brightness: b, alpha: a) } /**adds the rgb components of two colors*/ public func add(rgba color: UIColor) -> UIColor { return self.add(red: color.redComponent, green: color.greenComponent, blue: color.blueComponent, alpha: color.alphaComponent) } }
31.27897
129
0.596186
dd2513aee3c77cac41370b987b2371a183c182fd
1,024
// // LocationData.swift // MiniRemoto // // Created by Pedro Giuliano Farina on 25/05/20. // Copyright © 2020 Pedro Giuliano Farina. All rights reserved. // import UIKit import MapKit public class LocationData: Module { public static let storyboardName: String = "LocationModule" public static let preferredRow: Int = 1 public var addImage: UIImage? = UIImage(named: "LocationAddModule") public var removeImage: UIImage? = UIImage(named: "LocationRemoveModule") public var image: UIImage? = UIImage(named: "LocationModule") public var title: String? = "Endereço".localized() public var subtitle: String? = "Complemento".localized() public func isFilled() -> Bool { return location != nil } public var location: MKMapItem? { didSet { title = location?.placemark.name ?? "Endereço".localized() } } public var addressLine2: String? { didSet { subtitle = addressLine2 ?? "Complemento".localized() } } }
28.444444
77
0.654297
e81ca3ceb23fa7f5756523cda7c8a9f583dbafe1
2,093
// // SlicingProfileCoordinator.swift // OctoPhone // // Created by Josef Dolezal on 02/04/2017. // Copyright © 2017 Josef Dolezal. All rights reserved. // import UIKit /// Controls flow of slicing profile detail final class SlicingProfileCoordinator: ContextCoordinator { /// Printer requests provider private let provider: OctoPrintProvider /// Slicer associated to requested profile private let slicerID: String /// ID of slicing profile private let slicingProfileID: String? init(navigationController: UINavigationController?, contextManager: ContextManagerType, provider: OctoPrintProvider, slicerID: String, slicingProfileID: String?) { self.provider = provider self.slicerID = slicerID self.slicingProfileID = slicingProfileID super.init(navigationController: navigationController, contextManager: contextManager) } override func start() { var viewModel: SlicingProfileViewModelType if let slicingProfileID = slicingProfileID { viewModel = SlicingProfileViewModel(delegate: self, slicingProfileID: slicingProfileID, slicerID: slicerID, provider: provider, contextManager: contextManager) } else { viewModel = SlicingProfileCreationViewModel(delegate: self, provider: provider, slicerID: slicerID) } let controller = SlicingProfileViewController(viewModel: viewModel) let navigation = UINavigationController(rootViewController: controller) navigationController?.present(navigation, animated: true, completion: nil) } } extension SlicingProfileCoordinator: SlicingProfileViewControllerDelegate { func deletedSlicingProfile() { navigationController?.dismiss(animated: true, completion: nil) completed() } func doneButtonTapped() { navigationController?.dismiss(animated: true, completion: nil) completed() } }
33.222222
99
0.671763
fbb62baaccdcb05f8ce1d519ffe243dbf1578f50
3,476
/******************************************************************************* * * Copyright 2019, Manufactura de Ingenios Tecnológicos S.L. * <http://www.mintforpeople.com> * * Redistribution, modification and use of this software are permitted under * terms of the Apache 2.0 License. * * This software is distributed in the hope that it will be useful, * but WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * Apache 2.0 License for more details. * * You should have received a copy of the Apache 2.0 License along with * this software. If not, see <http://www.apache.org/licenses/>. * ******************************************************************************/ // // RemoteControlModule.swift // robobo-remote-control // // Created by Luis Felipe Llamas Luaces on 27/03/2019. // Copyright © 2019 mintforpeople. All rights reserved. // import robobo_framework_ios_pod class RemoteControlModule: NSObject, IRemoteControlModule { var processQueue: DispatchQueue! var delegates: [IRemoteDelegate]! var remoteControlProxies: [IRemoteControlProxy]! var password: String = "" var commandQueueProcessor: CommandQueueProcessor! var roboboManager: RoboboManager! func registerCommand(_ commandName: String, _ module: ICommandExecutor) { commandQueueProcessor.registerCommand(commandName, module) } func postStatus(_ status: Status) { for remoteProxy in remoteControlProxies{ remoteProxy.notifyStatus(status) } } func postResponse(_ response: Response) { for remoteProxy in remoteControlProxies{ remoteProxy.notifyResponse(response) } } func setPassword(_ password: String) { self.password = password } func getPassword() -> String { return password } func registerRemoteControlProxy(_ proxy: IRemoteControlProxy) { remoteControlProxies.append(proxy) } func unregisterRemoteControlProxy(_ proxy: IRemoteControlProxy) { remoteControlProxies = remoteControlProxies.filter {!($0 === proxy)} } func queueCommand(_ command: RemoteCommand) { do { try commandQueueProcessor.put(command) } catch { roboboManager.log("The command can not be added to the CommandQueueProcessor.", LogLevel.ERROR) } } func notifyConnection(_ connNumber: Int) { for delegate in delegates{ delegate.onConnection(connNumber) } } func notifyDisconnection(_ connNumber: Int) { for delegate in delegates{ delegate.onDisconnection(connNumber) } } func startup(_ manager: RoboboManager) throws { processQueue = DispatchQueue(label: "commandQueue.listAccess", qos: .utility, attributes: .concurrent) remoteControlProxies = [] delegates = [] commandQueueProcessor = CommandQueueProcessor(self, manager) commandQueueProcessor.start() roboboManager = manager } func shutdown() throws { commandQueueProcessor.dispose() } func getModuleInfo() -> String { return "Remote Control Module" } func getModuleVersion() -> String { return "v0.1" } }
28.491803
110
0.620541
032b9d09b67c2b00f379765dc902c66a9262ea93
499
// // ResourceAssembly.swift // Data.Resource // // Created by Kensuke Tamura on 2021/05/06. // import Foundation import Swinject public struct ResourceAssembly: Assembly { public init() { } public func assemble(container: Container) { container.register(DeveloperInfoDao.self) { _ in DeveloperInfoDao() }.inObjectScope(.container) container.register(AppInfoDao.self) { _ in AppInfoDao() }.inObjectScope(.container) } }
19.96
56
0.643287
67629274d699ea7841ac18cd62a86a153ee6867e
7,001
// // ProfileOrgsViewController.swift // BroncoCast // // Created by Ken Schenke on 1/21/19. // Copyright © 2019 Ken Schenke. All rights reserved. // import UIKit import ReSwift import Alertift class ProfileOrgsViewController: UIViewController, StoreSubscriber, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate { var userOrgs : [UserOrg] = [] var fetching = false var fetchingErrorMsg = "" var joining = false var joiningErrorMsg = "" var joinTag = "" var dropMemberId = 0 var dropping = false var droppingErrorMsg = "" @IBOutlet weak var tableView: UITableView! @IBOutlet weak var joinOrgTextField: UITextField! @IBOutlet weak var joinButton: ActivityButton! @IBOutlet weak var joinButtonBottomConstraint: NSLayoutConstraint! override func viewDidLoad() { super.viewDidLoad() store.subscribe(self) joinButton.activityLabel = "Joining" tableView.delegate = self tableView.dataSource = self joinOrgTextField.addTarget(self, action: #selector(textFieldChanged), for: .editingChanged) joinOrgTextField.delegate = self } func newState(state: AppState) { if state.profileOrgsState.userOrgs != userOrgs { userOrgs = state.profileOrgsState.userOrgs tableView.reloadData() } if state.profileOrgsState.userOrgsFetching != fetching { fetching = state.profileOrgsState.userOrgsFetching tableView.reloadData() } if state.profileOrgsState.userOrgsErrorMsg != fetchingErrorMsg { fetchingErrorMsg = state.profileOrgsState.userOrgsErrorMsg tableView.reloadData() } if state.navigationState.dataRefreshNeeded && state.navigationState.pathSegment == .profile_orgs_segment { store.dispatch(clearDataRefreshNeeded()) store.dispatch(getUserOrgs) } if state.profileOrgsState.joining != joining { joining = state.profileOrgsState.joining if joining { joinButton.showActivity() } else { joinButton.hideActivity() } } if state.profileOrgsState.joiningErrorMsg != joiningErrorMsg { joiningErrorMsg = state.profileOrgsState.joiningErrorMsg if !joiningErrorMsg.isEmpty { Alertift.alert(title: "An Error Occurred", message: joiningErrorMsg) .action(.default("Ok")) .show() } } if state.profileOrgsState.joinTag != joinTag { joinTag = state.profileOrgsState.joinTag joinOrgTextField.text = joinTag } if state.profileOrgsState.dropMemberId != dropMemberId { dropMemberId = state.profileOrgsState.dropMemberId tableView.reloadData() } if state.profileOrgsState.dropping != dropping { dropping = state.profileOrgsState.dropping tableView.reloadData() } if state.profileOrgsState.droppingErrorMsg != droppingErrorMsg { droppingErrorMsg = state.profileOrgsState.droppingErrorMsg if !droppingErrorMsg.isEmpty { Alertift.alert(title: "An Error Occurred", message: droppingErrorMsg) .action(.default("Ok")) .show() } } } @IBAction func joinButtonPressed(_ sender: Any) { joinUserOrg() } @objc func textFieldChanged() { store.dispatch(SetJoinTag(joinTag: joinOrgTextField.text!)) } func joinUserOrg() { let tag = joinTag.trimmingCharacters(in: .whitespacesAndNewlines) if tag.isEmpty { Alertift.alert(title: "An Error Occurred", message: "Tag cannot be empty") .action(.default("Ok")) .show() return } joinOrgTextField.resignFirstResponder() store.dispatch(joinOrg) } // MARK: - TableView Datasource methods func numberOfSections(in tableView: UITableView) -> Int { // Section 1 - organizations // Section 2 - fetching message // Section 3 - error message return 3 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return userOrgs.count } else if section == 1 { return fetching ? 1 : 0 } else if section == 2 { return fetchingErrorMsg.isEmpty ? 0 : 1 } return 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.section == 0 { if dropping && dropMemberId == userOrgs[indexPath.row].MemberId { return tableView.dequeueReusableCell(withIdentifier: "ProfileOrgDroppingOrg", for: indexPath) } let cell = tableView.dequeueReusableCell(withIdentifier: "ProfileOrgCell", for: indexPath) as! ProfileOrgTableViewCell cell.orgNameLabel?.text = "\(userOrgs[indexPath.row].OrgName)\(userOrgs[indexPath.row].IsAdmin ? " (Admin)" : "")" cell.memberId = userOrgs[indexPath.row].MemberId return cell } else if indexPath.section == 1 { return tableView.dequeueReusableCell(withIdentifier: "ProfileOrgFetchingCell", for: indexPath) } else if indexPath.section == 2 { let cell = tableView.dequeueReusableCell(withIdentifier: "ProfileOrgErrorMsgCell", for: indexPath) as! ProfileOrgsErrorMsgTableViewCell cell.errorMsgLabel.text = fetchingErrorMsg return cell } return tableView.dequeueReusableCell(withIdentifier: "", for: indexPath) } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.section == 0 { return 44; } else if indexPath.section == 1 { return fetching ? 32 : 0 } else if indexPath.section == 2 { return fetchingErrorMsg.isEmpty ? 0 : 32 } return 0 } // MARK: - UITextFieldDelegate Methods func textFieldDidBeginEditing(_ textField: UITextField) { UIView.animate(withDuration: 0.5) { self.joinButtonBottomConstraint.constant = 180 self.view.layoutIfNeeded() } } func textFieldShouldReturn(_ textField: UITextField) -> Bool { joinUserOrg() return true } func textFieldDidEndEditing(_ textField: UITextField) { UIView.animate(withDuration: 0.5) { self.joinButtonBottomConstraint.constant = 20 self.view.layoutIfNeeded() } } }
33.821256
148
0.603914
4b57df4c566494b18ba9100e5e64215983e3fe86
2,921
// // ImageDownloader.swift // RESegmentedControl // // Created by Sherzod Khashimov on 11/27/19. // Copyright © 2019 Sherzod Khashimov. All rights reserved. // import Foundation import UIKit /// Image downloader used to get image from remote server and caches image to local cache directory class ImageDownloader { enum ImageError: Error { case downloadFailed } private var task: URLSessionDataTask? /// Starts download image /// - Parameters: /// - url: Image remote location /// - completion: completion handler func downloadImage(url: URL, completion: ((_ image: UIImage?, _ url: URL, _ error: Error?) -> Void)?) { if let cachedImage = imageData(from: url) { DispatchQueue.main.async { completion?(cachedImage, url, nil) } } else { DispatchQueue.global(qos: .background).async { let configuration = URLSessionConfiguration.default let session = URLSession(configuration: configuration) self.task = session.dataTask(with: url, completionHandler: { (data, response, error) in guard error == nil else { DispatchQueue.main.async { completion?(nil, url, error) } return } guard let _data = data, let image = UIImage(data: _data) else { DispatchQueue.main.async { completion?(nil, url, ImageError.downloadFailed) } return } _ = self.save(_data, fromUrl: url) DispatchQueue.main.async { completion?(image, url, nil) } }) self.task?.resume() } } } /// Cancel started download task func cancel() { task?.cancel() } /// Saves image to local storage /// - Parameters: /// - data: Data that represent image /// - remoteUrl: Image remote location, used to get filename private func save(_ data: Data, fromUrl remoteUrl: URL) -> URL? { guard let filename = remoteUrl.filename else { return nil } let fileManager = FileManager() let fileLocation = fileManager.saveImage(data, filename: filename) return fileLocation } /// Retrives image from local storage /// - Parameter remoteUrl: Image remote location, used to get filename private func imageData(from remoteUrl: URL) -> UIImage? { guard let filename = remoteUrl.filename else { return nil } let fileManager = FileManager() guard let data = fileManager.imageData(filename: filename) else { return nil } return UIImage(data: data) } }
34.77381
107
0.55392
d9766b6c52ab4295836657b1355c794ce546ffa3
1,083
// // TriggeringPresenter.swift // Orchextra // // Created by Carlos Vicente on 24/8/17. // Copyright © 2017 Gigigo Mobile Services S.L. All rights reserved. // import Foundation import UIKit protocol TriggeringPresenterInput { func viewDidLoad() func userDidTapSettings() func userDidTapTabBarItem() } protocol TriggeringUI: class { func initializeTabBarItems(with items: [UIViewController]) func setTitleForSelectedItem() } struct TriggeringPresenter { // MARK: - Public attributes weak var view: TriggeringUI? let wireframe: TriggeringWireframe // MARK: - Interactors let interactor: TriggeringInteractor } extension TriggeringPresenter: TriggeringPresenterInput { func viewDidLoad() { let viewControllers = self.wireframe.showTriggeringViewControllers() self.view?.initializeTabBarItems(with: viewControllers) } func userDidTapSettings() { self.wireframe.showSettings() } func userDidTapTabBarItem() { self.view?.setTitleForSelectedItem() } }
21.66
76
0.701754
d521f3ee411d2b4b900654f31b39b7378ccc47a1
556
import UIKit @main class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { return true } func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } }
34.75
179
0.77518
e0d61f5fba25156c79754d36a0b3cd1dcfda9562
1,190
// // KnownFacets.swift // SoftU2F // // Created by Benjamin P Toews on 1/27/17. // import Foundation let KnownFacets: [Data: String] = [ SHA256.digest("https://github.com/u2f/trusted_facets"): "https://github.com", SHA256.digest("https://demo.yubico.com"): "https://demo.yubico.com", SHA256.digest("https://www.dropbox.com/u2f-app-id.json"): "https://dropbox.com", SHA256.digest("https://www.gstatic.com/securitykey/origins.json"): "https://google.com", SHA256.digest("https://vault.bitwarden.com/app-id.json"): "https://vault.bitwarden.com", SHA256.digest("https://keepersecurity.com"): "https://keepersecurity.com", SHA256.digest("https://api-9dcf9b83.duosecurity.com"): "https://api-9dcf9b83.duosecurity.com", SHA256.digest("https://dashboard.stripe.com"): "https://dashboard.stripe.com", SHA256.digest("https://id.fedoraproject.org/u2f-origins.json"): "https://id.fedoraproject.org", SHA256.digest("https://lastpass.com"): "https://lastpass.com", // When we return an error during authentication, Chrome will send a registration request with // a bogus AppID. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA".data(using: .ascii)!: "bogus" ]
45.769231
99
0.694958
fff73728b3106b25588a390c77e34f1889c16270
270
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class B<T where g:d{func b{struct B{class B{var e:T.a[
33.75
87
0.740741
bfbb97469481f717c20e29187be1b7fce90a311b
842
// // Placeholders.swift // Flicks // // Created by Evelio Tarazona on 10/23/16. // Copyright © 2016 Evelio Tarazona. All rights reserved. // import Foundation import UIKit public extension UIImage { public convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) { let rect = CGRect(origin: .zero, size: size) UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0) color.setFill() UIRectFill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() guard let cgImage = image?.cgImage else { return nil } self.init(cgImage: cgImage) } } public struct Placeholders { public static var image: UIImage { get { return UIImage(color: Colors.placeholder)! } } }
24.764706
90
0.646081
c1bccf12192e0bb658a585ca3846bcb24fde89fc
3,969
// // AppDelegate.swift // DBManager // // Created by 陈凯文 on 2019/9/19. // Copyright © 2019 陈凯文. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? private let dbVersionKey = "dbVersionKey" func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. DBManager.standard.initUpdateDB() // let dbVersion = (Bundle.main.infoDictionary!["DBVersion"] as! NSNumber).intValue // let olderVersion = UserDefaults.standard.integer(forKey: self.dbVersionKey) // ///判断当前数据库 是否 需要升级 // if dbVersion > olderVersion { // let path = Bundle.main.path(forResource: "DBModel", ofType: "plist") // let classDic = NSDictionary.init(contentsOfFile: path!) // let keyArray = classDic?.allKeys.sorted(by: { (obj1, obj2) -> Bool in // if Int(obj1 as! String)! > Int(obj2 as! String)! { // return false // } // return true // }) // for item in keyArray! { // let key = item as! String // if Int(key)! > olderVersion { // let classArray = classDic![key] as! [String] // for name in classArray { // //动态获取命名空间 // let namespace = Bundle.main.infoDictionary!["CFBundleExecutable"] as! String // //注意工程中必须有相关的类,否则程序会crash // let className : AnyClass? = NSClassFromString(namespace + "." + name) // // let classType = className as? BaseModel.Type // if let classType = className as? CKDBManager.Type { // classType.ck_initTable() // ck_print(className) // } // } // } // } // // UserDefaults.standard.set(dbVersion, forKey: self.dbVersionKey) // // UserDefaults.standard.synchronize() // } return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
49
285
0.629126
fcfc48663f5ec4de9e1195319eb3efd243597cda
5,090
// // DefaultLogger.swift // CoreStore // // Copyright © 2015 John Rommel Estropia // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation // MARK: - DefaultLogger /** The `DefaultLogger` is a basic implementation of the `CoreStoreLogger` protocol. */ public final class DefaultLogger: CoreStoreLogger { /** Creates a `DefaultLogger`. */ public init() { } /** Handles log messages sent by the `CoreStore` framework. - parameter level: the severity of the log message - parameter message: the log message - parameter fileName: the source file name - parameter lineNumber: the source line number - parameter functionName: the source function name */ public func log(level: LogLevel, message: String, fileName: StaticString, lineNumber: Int, functionName: StaticString) { #if DEBUG let icon: String let levelString: String switch level { case .trace: icon = "🔹" levelString = "Trace" case .notice: icon = "🔸" levelString = "Notice" case .warning: icon = "⚠️" levelString = "Warning" case .fatal: icon = "❗" levelString = "Fatal" } Swift.print("\(icon) [CoreStore: \(levelString)] \((String(describing: fileName) as NSString).lastPathComponent):\(lineNumber) \(functionName)\n ↪︎ \(message)\n") #endif } /** Handles errors sent by the `CoreStore` framework. - parameter error: the error - parameter message: the error message - parameter fileName: the source file name - parameter lineNumber: the source line number - parameter functionName: the source function name */ public func log(error: CoreStoreError, message: String, fileName: StaticString, lineNumber: Int, functionName: StaticString) { #if DEBUG Swift.print("⚠️ [CoreStore: Error] \((String(describing: fileName) as NSString).lastPathComponent):\(lineNumber) \(functionName)\n ↪︎ \(message)\n \(error)\n") #endif } /** Handles assertions made throughout the `CoreStore` framework. - parameter :condition: the assertion condition - parameter message: the assertion message - parameter fileName: the source file name - parameter lineNumber: the source line number - parameter functionName: the source function name */ public func assert(_ condition: @autoclosure () -> Bool, message: @autoclosure () -> String, fileName: StaticString, lineNumber: Int, functionName: StaticString) { #if DEBUG if condition() { return } Swift.print("❗ [CoreStore: Assertion Failure] \((String(describing: fileName) as NSString).lastPathComponent):\(lineNumber) \(functionName)\n ↪︎ \(message())\n") Swift.fatalError(file: fileName, line: UInt(lineNumber)) #endif } /** Handles fatal errors made throughout the `CoreStore` framework. - Important: Implementers should guarantee that this function doesn't return, either by calling another `Never` function such as `fatalError()` or `abort()`, or by raising an exception. - parameter message: the fatal error message - parameter fileName: the source file name - parameter lineNumber: the source line number - parameter functionName: the source function name */ public func abort(_ message: String, fileName: StaticString, lineNumber: Int, functionName: StaticString) { Swift.print("❗ [CoreStore: Fatal Error] \((String(describing: fileName) as NSString).lastPathComponent):\(lineNumber) \(functionName)\n ↪︎ \(message)\n") Swift.fatalError(file: fileName, line: UInt(lineNumber)) } }
39.457364
190
0.638703
3384d6ff86fbcad0a5332d82f1d2c9a0032755f8
1,855
import UIKit import RxSwift import ThemeKit import SnapKit import SectionsTableView class MarketDiscoveryViewController: MarketListViewController { private let marketViewModel: MarketViewModel private let viewModel: MarketDiscoveryViewModel private let disposeBag = DisposeBag() private let filterHeaderView = MarketDiscoveryFilterHeaderView() init(marketViewModel: MarketViewModel, listViewModel: MarketListViewModel, viewModel: MarketDiscoveryViewModel) { self.marketViewModel = marketViewModel self.viewModel = viewModel super.init(listViewModel: listViewModel) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() view.addSubview(filterHeaderView) filterHeaderView.snp.makeConstraints { maker in maker.leading.top.trailing.equalToSuperview() maker.height.equalTo(MarketDiscoveryFilterHeaderView.headerHeight) } tableView.snp.remakeConstraints { maker in maker.leading.trailing.bottom.equalToSuperview() maker.top.equalTo(filterHeaderView.snp.bottom) } filterHeaderView.onSelect = { [weak self] filterIndex in self?.viewModel.setFilter(at: filterIndex) } subscribe(disposeBag, viewModel.selectedFilterIndexDriver) { [weak self] index in self?.filterHeaderView.setSelected(index: index) } subscribe(disposeBag, marketViewModel.discoveryListTypeDriver) { [weak self] in self?.handle(listType: $0) } } private func handle(listType: MarketModule.ListType?) { guard let listType = listType else { return } listViewModel.set(listType: listType) viewModel.resetCategory() } }
31.440678
117
0.696496
8a94879f5321276892d5b954e969fe5719dbbc64
1,889
import Foundation import UIKit class ArticleContentViewController : UIViewController, UIWebViewDelegate { var _postItem: PostItem var _webView: UIWebView init(postItem: PostItem) { self._postItem = postItem self._webView = UIWebView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height)) self._webView.backgroundColor = UIColor.whiteColor() self._webView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() _webView.loadHTMLString((Css.head + Css.lightBody + ArticleContentViewController.titleHtml(_postItem.link!, time: _postItem.pubDate!, title: _postItem.title!, author: _postItem.creator!, feed: "") + _postItem.content! + Css.tail), baseURL: nil) self.view.addSubview(_webView) _webView.delegate = self } static func titleHtml(link: String, time: NSDate, title: String, author: String, feed: String) -> String { return String(format: "<div class=\"feature\"> <a href=\"%@\"></a> <titleCaption>%@</titleCaption> <articleTitle>%@</articleTitle> <titleCaption>%@</titleCaption> <titleCaption>%@</titleCaption></div>", link, time, title, author, feed) } func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { switch navigationType { case .LinkClicked: // Open links in Safari UIApplication.sharedApplication().openURL(request.URL!) return false default: // Handle other navigation types... return true } } }
42.931818
252
0.661196
693b9d2462ffc875c90071e2ac661eb1b18bdfd6
8,480
// // VoiceDetailController.swift // EnglistWords // // Created by Alexluan on 2019/9/29. // Copyright © 2019 Alexluan. All rights reserved. // import UIKit import WebKit import SnapKit import ReactiveCocoa import ReactiveSwift import RxSwift import CoreAudio import AVFoundation class VoiceDetailController: UIViewController { private let url: String private let navTitle: String private var avPlayer = AVPlayer() private let audioBar = PlayerTooBar() private var task: URLSessionDownloadTask? private let saveFolder = "/audio" init(url: String, title: String) { self.url = url navTitle = title super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() title = navTitle view.backgroundColor = .systemBackground createUI() createAction() reStart() } private func createUI() { view.addSubview(textFiled) view.addSubview(audioContainer) view.addSubview(clearButton) view.addSubview(reStartButton) audioContainer.addSubview(audioBar) textFiled.snp.makeConstraints { (make) in make.top.equalTo(view.snp.top).offset(view.safeAreaInsets.top) make.leading.trailing.equalToSuperview() make.height.equalTo(200) } clearButton.snp.makeConstraints { (make) in make.top.equalTo(textFiled.snp.bottom).offset(8) make.centerX.equalToSuperview() } reStartButton.snp.makeConstraints { (make) in make.top.equalTo(textFiled.snp.bottom).offset(8) make.leading.equalTo(clearButton.snp.trailing).offset(8) } audioContainer.snp.makeConstraints { (make) in make.bottom.equalTo(view.snp.bottomMargin) make.leading.trailing.equalToSuperview() make.height.equalTo(44) } audioBar.snp.makeConstraints { (make) in make.edges.equalToSuperview() } self.audioContainer.setNeedsLayout() self.audioContainer.layoutIfNeeded() self.audioContainer.removeFromSuperview() self.textFiled.inputAccessoryView = self.audioContainer } private func createAction() { audioBar.control.producer.startWithValues { [weak self] (value) in guard let `self` = self else { return } switch value { case .play: self.avPlayer.play() case .pause: self.avPlayer.pause() case .after: let current = self.avPlayer.currentTime() + CMTime(seconds: 2, preferredTimescale: CMTimeScale(bitPattern: 1000000000)) self.avPlayer.seek(to: current) case .before: let current = self.avPlayer.currentTime() - CMTime(seconds: 2, preferredTimescale: CMTimeScale(bitPattern: 1000000000)) self.avPlayer.seek(to: current) } } clearButton.reactive.controlEvents(UIControl.Event.touchUpInside) .observeValues { [weak self]_ in self?.textFiled.text = "" } reStartButton.reactive.controlEvents(UIControl.Event.touchUpInside) .observeValues { [weak self]_ in self?.reStart() } } /// 自动创建并播放 private func createAVPlayer(filePath: String?) { var playerUrl: URL? if filePath == nil { playerUrl = URL(string: self.url) } else { playerUrl = URL(fileURLWithPath: filePath!) } guard let currentUrl = playerUrl else { return } let playerItem = AVPlayerItem(url: currentUrl) if self.avPlayer.status == .readyToPlay { self.avPlayer.replaceCurrentItem(with: playerItem) } else { self.avPlayer = AVPlayer.init(playerItem: playerItem) } avPlayer.play() } /// 重新播放 private func reStart() { avPlayer.pause() if LYSFileManager.instance.isExist(relativePath: saveFolder, fileName: "\(navTitle).mp3") { let filePath = LYSFileManager.instance.getDocument() + "\(saveFolder)/\(navTitle).mp3" createAVPlayer(filePath: filePath) return } createAVPlayer(filePath: nil) task = LYSDownloadHelper.instance.downloadFile(url: URL(string: url)!, relativePath: "/audio", newName: self.navTitle + ".mp3") { (process, location) in print("process:\(process)") } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesEnded(touches, with: event) view.endEditing(true) } // MARK: UI private let audioContainer: UIView = { let webView = UIView() webView.backgroundColor = .gray return webView }() private let textFiled: UITextView = { let textFiled = UITextView() textFiled.textColor = .label textFiled.backgroundColor = .systemBackground textFiled.font = UIFont.systemFont(ofSize: 22) textFiled.textAlignment = .left textFiled.text = "语音输入,看看手机是否能正确翻译" textFiled.layer.borderColor = UIColor.lightGray.cgColor textFiled.layer.borderWidth = 1 return textFiled }() private let clearButton: UIButton = { let button = UIButton() button.titleLabel?.font = UIFont(name: "iconfont", size: 22) button.setTitle("\u{e72a}", for: .normal) button.setTitleColor(.label, for: .normal) button.setTitleColor(.blue, for: .highlighted) button.setTitleColor(.blue, for: .focused) return button }() private let reStartButton: UIButton = { let button = UIButton() button.titleLabel?.font = UIFont(name: "iconfont", size: 22) button.setTitle("\u{e7b8}", for: .normal) button.setTitleColor(.label, for: .normal) button.setTitleColor(.blue, for: .highlighted) button.setTitleColor(.blue, for: .focused) return button }() } // MARK: AUDIO BAR VIEW class PlayerTooBar: UIView { enum PlayControl: String { case play case pause case after case before } open var control = MutableProperty<PlayControl>(.play) override init(frame: CGRect) { super.init(frame: frame) createUI() createAction() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func createUI() { addSubview(playButton) addSubview(before) addSubview(after) before.snp.makeConstraints { (make) in make.leading.equalToSuperview().offset(16) make.centerY.equalToSuperview() } playButton.snp.makeConstraints { (make) in make.center.equalToSuperview() } after.snp.makeConstraints { (make) in make.trailing.equalToSuperview().offset(-16) make.centerY.equalToSuperview() } } private func createAction() { playButton.reactive.controlEvents(.touchUpInside).observeValues { (btn) in btn.isSelected = !btn.isSelected self.control.value = btn.isSelected ? .pause : .play } before.reactive.controlEvents(.touchUpInside).observeValues { (btn) in self.control.value = .before } after.reactive.controlEvents(.touchUpInside).observeValues { (btn) in self.control.value = .after } } // MARK: UI private let playButton: UIButton = { let button = UIButton() button.titleLabel?.font = UIFont(name: "iconfont", size: 22) button.setTitle("\u{e618}", for: UIControl.State.selected) button.setTitle("\u{e693}", for: UIControl.State.normal) return button }() private let before: UIButton = { let button = UIButton() button.titleLabel?.font = UIFont(name: "iconfont", size: 22) button.setTitle("\u{e74e}", for: UIControl.State.normal) return button }() private let after: UIButton = { let button = UIButton() button.titleLabel?.font = UIFont(name: "iconfont", size: 22) button.setTitle("\u{e750}", for: UIControl.State.normal) return button }() }
31.291513
160
0.611792
1e7cc9a8888a46bb867df75ddc213f17fdc2c6ee
2,035
// // Helpers.swift // KPCTabsControl // // Created by Cédric Foellmi on 03/09/16. // Licensed under the MIT License (see LICENSE file) // import Foundation /// Offset is a simple NSPoint typealias to increase readability. public typealias Offset = NSPoint extension Offset { init(x: CGFloat) { self.init() self.x = x self.y = 0 } init(y: CGFloat) { self.init() self.x = 0 self.y = y } } /** Addition operator for NSPoints and Offsets. - parameter lhs: lef-hand side point - parameter rhs: right-hand side offset to be added to the point. - returns: A new and offset NSPoint. */ public func +(lhs: NSPoint, rhs: Offset) -> NSPoint { return NSPoint(x: lhs.x + rhs.x, y: lhs.y + rhs.y) } /** A convenience extension to easily shrink a NSRect */ extension NSRect { /// Change width and height by `-dx` and `-dy`. public func shrinkBy(dx: CGFloat, dy: CGFloat) -> NSRect { var result = self result.size = CGSize(width: result.size.width - dx, height: result.size.height - dy) return result } } /** Convenience function to easily compare tab widths. - parameter t1: The first tab width - parameter t2: The second tab width - returns: A boolean to indicate whether the tab widths are identical or not. */ func ==(t1: TabWidth, t2: TabWidth) -> Bool { return String(describing: t1) == String(describing: t2) } /// Helper functions to let compare optionals func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } func >= <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l >= r default: return !(lhs < rhs) } } func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } }
20.765306
92
0.590663
fedc7be932d0106382990972d3a84435578b5bc2
2,175
// // AppDelegate.swift // MemorablePlaces // // Created by 丁偉倫 on 06/03/2017. // Copyright © 2017 whelan94crown. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.276596
285
0.756322
4ae5236a2677f74ed02aaa91af6867364bf4f693
1,361
// // AppDelegate.swift // SweetSwiftUIGeometryReader // // Created by hanwe on 2020/12/27. // import UIKit @main class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } }
36.783784
179
0.748714
ef2e1529efeb10f9ff656993af67711824d8c4d6
16,297
// // DKAssetGroupDetailVC.swift // DKImagePickerController // // Created by ZhangAo on 15/8/10. // Copyright (c) 2015年 ZhangAo. All rights reserved. // import UIKit import AVFoundation import Photos private extension UICollectionView { func indexPathsForElements(in rect: CGRect, _ hidesCamera: Bool) -> [IndexPath] { let allLayoutAttributes = collectionViewLayout.layoutAttributesForElements(in: rect)! if hidesCamera { return allLayoutAttributes.map { $0.indexPath } } else { return allLayoutAttributes.flatMap { $0.indexPath.item == 0 ? nil : IndexPath(item: $0.indexPath.item - 1, section: $0.indexPath.section) } } } } // Show all images in the asset group internal class DKAssetGroupDetailVC: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, DKGroupDataManagerObserver { private lazy var selectGroupButton: UIButton = { let button = UIButton() let globalTitleColor = UINavigationBar.appearance().titleTextAttributes?[NSForegroundColorAttributeName] as? UIColor button.setTitleColor(globalTitleColor ?? UIColor.black, for: .normal) let globalTitleFont = UINavigationBar.appearance().titleTextAttributes?[NSFontAttributeName] as? UIFont button.titleLabel!.font = globalTitleFont ?? UIFont.boldSystemFont(ofSize: 18.0) button.addTarget(self, action: #selector(DKAssetGroupDetailVC.showGroupSelector), for: .touchUpInside) return button }() internal var collectionView: UICollectionView! internal weak var imagePickerController: DKImagePickerController! private var selectedGroupId: String? private var groupListVC: DKAssetGroupListVC! private var hidesCamera: Bool = false private var footerView: UIView? private var currentViewSize: CGSize! private var registeredCellIdentifiers = Set<String>() private var thumbnailSize = CGSize.zero override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() if let currentViewSize = self.currentViewSize, currentViewSize.equalTo(self.view.bounds.size) { return } else { currentViewSize = self.view.bounds.size } self.collectionView?.collectionViewLayout.invalidateLayout() } override func viewDidLoad() { super.viewDidLoad() let layout = self.imagePickerController.UIDelegate.layoutForImagePickerController(self.imagePickerController).init() self.collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout) self.collectionView.backgroundColor = self.imagePickerController.UIDelegate.imagePickerControllerCollectionViewBackgroundColor() self.collectionView.allowsMultipleSelection = true self.collectionView.delegate = self self.collectionView.dataSource = self self.view.addSubview(self.collectionView) self.footerView = self.imagePickerController.UIDelegate.imagePickerControllerFooterView(self.imagePickerController) if let footerView = self.footerView { self.view.addSubview(footerView) } self.hidesCamera = self.imagePickerController.sourceType == .photo self.checkPhotoPermission() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.updateCachedAssets() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if let footerView = self.footerView { footerView.frame = CGRect(x: 0, y: self.view.bounds.height - footerView.bounds.height, width: self.view.bounds.width, height: footerView.bounds.height) self.collectionView.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height - footerView.bounds.height) } else { self.collectionView.frame = self.view.bounds } } internal func checkPhotoPermission() { func photoDenied() { self.view.addSubview(DKPermissionView.permissionView(.photo)) self.view.backgroundColor = UIColor.black self.collectionView?.isHidden = true } func setup() { self.resetCachedAssets() getImageManager().groupDataManager.addObserver(self) self.groupListVC = DKAssetGroupListVC(selectedGroupDidChangeBlock: { [unowned self] groupId in self.selectAssetGroup(groupId) }, defaultAssetGroup: self.imagePickerController.defaultAssetGroup) self.groupListVC.loadGroups() } DKImageManager.checkPhotoPermission { granted in granted ? setup() : photoDenied() } } func selectAssetGroup(_ groupId: String?) { if self.selectedGroupId == groupId { return } self.selectedGroupId = groupId self.updateTitleView() self.collectionView!.reloadData() } func updateTitleView() { let group = getImageManager().groupDataManager.fetchGroupWithGroupId(self.selectedGroupId!) self.title = group.groupName let groupsCount = getImageManager().groupDataManager.groupIds?.count ?? 0 self.selectGroupButton.setTitle(group.groupName + (groupsCount > 1 ? " \u{25be}" : "" ), for: .normal) self.selectGroupButton.sizeToFit() self.selectGroupButton.isEnabled = groupsCount > 1 self.navigationItem.titleView = self.selectGroupButton } func showGroupSelector() { DKPopoverViewController.popoverViewController(self.groupListVC, fromView: self.selectGroupButton) } func fetchAsset(for index: Int) -> DKAsset? { if !self.hidesCamera && index == 0 { return nil } let assetIndex = (index - (self.hidesCamera ? 0 : 1)) let group = getImageManager().groupDataManager.fetchGroupWithGroupId(self.selectedGroupId!) return getImageManager().groupDataManager.fetchAssetWithGroup(group, index: assetIndex) } func isCameraCell(indexPath: IndexPath) -> Bool { return indexPath.row == 0 && !self.hidesCamera } // MARK: - Cells func registerCellIfNeeded(cellClass: DKAssetGroupDetailBaseCell.Type) { let cellReuseIdentifier = cellClass.cellReuseIdentifier() if !self.registeredCellIdentifiers.contains(cellReuseIdentifier) { self.collectionView.register(cellClass, forCellWithReuseIdentifier: cellReuseIdentifier) self.registeredCellIdentifiers.insert(cellReuseIdentifier) } } func dequeueReusableCell(for indexPath: IndexPath) -> DKAssetGroupDetailBaseCell { let asset = self.fetchAsset(for: indexPath.row)! let cellClass: DKAssetGroupDetailBaseCell.Type! if asset.isVideo { cellClass = self.imagePickerController.UIDelegate.imagePickerControllerCollectionVideoCell() } else { cellClass = self.imagePickerController.UIDelegate.imagePickerControllerCollectionImageCell() } self.registerCellIfNeeded(cellClass: cellClass) let cell = self.collectionView.dequeueReusableCell(withReuseIdentifier: cellClass.cellReuseIdentifier(), for: indexPath) as! DKAssetGroupDetailBaseCell self.setup(assetCell: cell, for: indexPath, with: asset) return cell } func dequeueReusableCameraCell(for indexPath: IndexPath) -> DKAssetGroupDetailBaseCell { let cellClass = self.imagePickerController.UIDelegate.imagePickerControllerCollectionCameraCell() self.registerCellIfNeeded(cellClass: cellClass) let cell = self.collectionView.dequeueReusableCell(withReuseIdentifier: cellClass.cellReuseIdentifier(), for: indexPath) return cell as! DKAssetGroupDetailBaseCell } func setup(assetCell cell: DKAssetGroupDetailBaseCell, for indexPath: IndexPath, with asset: DKAsset) { cell.asset = asset let tag = indexPath.row + 1 cell.tag = tag if self.thumbnailSize.equalTo(CGSize.zero) { self.thumbnailSize = self.collectionView!.collectionViewLayout.layoutAttributesForItem(at: indexPath)!.size.toPixel() } asset.fetchImageWithSize(self.thumbnailSize, options: nil, contentMode: .aspectFill) { (image, info) in if cell.tag == tag { cell.thumbnailImage = image } } if let index = self.imagePickerController.selectedAssets.index(of: asset) { cell.isSelected = true cell.index = index self.collectionView!.selectItem(at: indexPath, animated: false, scrollPosition: []) } else { cell.isSelected = false self.collectionView!.deselectItem(at: indexPath, animated: false) } } // MARK: - UICollectionViewDelegate, UICollectionViewDataSource methods func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { guard let selectedGroupId = self.selectedGroupId else { return 0 } let group = getImageManager().groupDataManager.fetchGroupWithGroupId(selectedGroupId) return (group.totalCount ?? 0) + (self.hidesCamera ? 0 : 1) } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell: DKAssetGroupDetailBaseCell! if self.isCameraCell(indexPath: indexPath) { cell = self.dequeueReusableCameraCell(for: indexPath) } else { cell = self.dequeueReusableCell(for: indexPath) } return cell } func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool { if let firstSelectedAsset = self.imagePickerController.selectedAssets.first, let selectedAsset = (collectionView.cellForItem(at: indexPath) as? DKAssetGroupDetailBaseCell)?.asset, self.imagePickerController.allowMultipleTypes == false && firstSelectedAsset.isVideo != selectedAsset.isVideo { let alert = UIAlertController( title: DKImageLocalizedStringWithKey("selectPhotosOrVideos") , message: DKImageLocalizedStringWithKey("selectPhotosOrVideosError") , preferredStyle: .alert) alert.addAction(UIAlertAction(title: DKImageLocalizedStringWithKey("ok"), style: .cancel) { _ in }) self.imagePickerController.present(alert, animated: true){} return false } let shouldSelect = self.imagePickerController.selectedAssets.count < self.imagePickerController.maxSelectableCount if !shouldSelect { self.imagePickerController.UIDelegate.imagePickerControllerDidReachMaxLimit(self.imagePickerController) } return shouldSelect } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if self.isCameraCell(indexPath: indexPath) { if UIImagePickerController.isSourceTypeAvailable(.camera) { self.imagePickerController.presentCamera() } } else { let selectedAsset = (collectionView.cellForItem(at: indexPath) as? DKAssetGroupDetailBaseCell)?.asset self.imagePickerController.selectImage(selectedAsset!) if let cell = collectionView.cellForItem(at: indexPath) as? DKAssetGroupDetailBaseCell { cell.index = self.imagePickerController.selectedAssets.count - 1 } } } func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) { if let removedAsset = (collectionView.cellForItem(at: indexPath) as? DKAssetGroupDetailBaseCell)?.asset { let removedIndex = self.imagePickerController.selectedAssets.index(of: removedAsset)! /// Minimize the number of cycles. let indexPathsForSelectedItems = collectionView.indexPathsForSelectedItems! let indexPathsForVisibleItems = collectionView.indexPathsForVisibleItems let intersect = Set(indexPathsForVisibleItems).intersection(Set(indexPathsForSelectedItems)) for selectedIndexPath in intersect { if let selectedCell = (collectionView.cellForItem(at: selectedIndexPath) as? DKAssetGroupDetailBaseCell) { let selectedIndex = self.imagePickerController.selectedAssets.index(of: selectedCell.asset)! if selectedIndex > removedIndex { selectedCell.index = selectedCell.index - 1 } } } self.imagePickerController.deselectImage(removedAsset) } } func scrollViewDidScroll(_ scrollView: UIScrollView) { self.updateCachedAssets() } // MARK: - Asset Caching var previousPreheatRect = CGRect.zero fileprivate func resetCachedAssets() { getImageManager().stopCachingForAllAssets() self.previousPreheatRect = .zero } func updateCachedAssets() { // Update only if the view is visible. guard isViewLoaded && view.window != nil && self.selectedGroupId != nil else { return } // The preheat window is twice the height of the visible rect. let preheatRect = view!.bounds.insetBy(dx: 0, dy: -0.5 * view!.bounds.height) // Update only if the visible area is significantly different from the last preheated area. let delta = abs(preheatRect.midY - self.previousPreheatRect.midY) guard delta > view.bounds.height / 3 else { return } let fetchResult = getImageManager().groupDataManager.fetchGroupWithGroupId(self.selectedGroupId!).fetchResult! // Compute the assets to start caching and to stop caching. let (addedRects, removedRects) = self.differencesBetweenRects(self.previousPreheatRect, preheatRect) let addedAssets = addedRects .flatMap { rect in self.collectionView!.indexPathsForElements(in: rect, self.hidesCamera) } .map { indexPath in fetchResult.object(at: indexPath.item) } let removedAssets = removedRects .flatMap { rect in self.collectionView!.indexPathsForElements(in: rect, self.hidesCamera) } .map { indexPath in fetchResult.object(at: indexPath.item) } // Update the assets the PHCachingImageManager is caching. getImageManager().startCachingAssets(for: addedAssets, targetSize: self.thumbnailSize, contentMode: .aspectFill, options: nil) getImageManager().stopCachingAssets(for: removedAssets, targetSize: self.thumbnailSize, contentMode: .aspectFill, options: nil) // Store the preheat rect to compare against in the future. self.previousPreheatRect = preheatRect } fileprivate func differencesBetweenRects(_ old: CGRect, _ new: CGRect) -> (added: [CGRect], removed: [CGRect]) { if old.intersects(new) { var added = [CGRect]() if new.maxY > old.maxY { added += [CGRect(x: new.origin.x, y: old.maxY, width: new.width, height: new.maxY - old.maxY)] } if old.minY > new.minY { added += [CGRect(x: new.origin.x, y: new.minY, width: new.width, height: old.minY - new.minY)] } var removed = [CGRect]() if new.maxY < old.maxY { removed += [CGRect(x: new.origin.x, y: new.maxY, width: new.width, height: old.maxY - new.maxY)] } if old.minY < new.minY { removed += [CGRect(x: new.origin.x, y: old.minY, width: new.width, height: new.minY - old.minY)] } return (added, removed) } else { return ([new], [old]) } } // MARK: - DKGroupDataManagerObserver methods func groupDidUpdate(_ groupId: String) { if self.selectedGroupId == groupId { self.updateTitleView() } } func group(_ groupId: String, didRemoveAssets assets: [DKAsset]) { for (_, selectedAsset) in self.imagePickerController.selectedAssets.enumerated() { for removedAsset in assets { if selectedAsset.isEqual(removedAsset) { self.imagePickerController.deselectImage(selectedAsset) } } } } func groupDidUpdateComplete(_ groupId: String) { if self.selectedGroupId == groupId { self.resetCachedAssets() self.collectionView?.reloadData() } } }
40.539801
226
0.687611
21c0ceccfeb7d5439c6939a774b3bcfc5ec805ea
1,453
import UIKit import RxSwift public extension UINavigationController { func makePushPresentation(of viewController: UIViewController) -> DismissablePresentation { let present: DismissablePresentation.MakePresent = { [weak self] (viewController, animated) in guard let self = self else { fatalError() } return self.rx.pushViewController.execute((viewController, animated)) .catchError { _ in return Observable<Never>.empty() } .ignoreElements() } let dismiss: DismissablePresentation.MakeDismiss = { [weak self] (viewController, animated) in guard let self = self else { fatalError() } return self.rx.popViewController.execute((viewController, animated)) .catchError { _ in return Observable<Never>.empty() } .ignoreElements() } let didDismiss = viewController.rx.didMoveToNilParent() .map { _ in return () } .asObservable() let presentation = DismissablePresentation( presentedViewController: viewController, present: present, dismiss: dismiss, didDismiss: didDismiss) // Retain the presentation for its lifecycle. _ = presentation.didDismiss .untilDisposal(retain: presentation) .takeUntil(rx.deallocated) .subscribe() return presentation } }
33.790698
102
0.624914
ff032507354eeee8af5bc854b88b3a2c34064c42
1,250
// // Assignment1UITests.swift // Assignment1UITests // // Created by Vinupriya on 12/30/16. // Copyright © 2016 Vinupriya. All rights reserved. // import XCTest class Assignment1UITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
33.783784
182
0.6656
e55f72d652a1ef5943034a9c4c7f5a6180943da1
693
// // HomeTableViewCell.swift // DesafioInfoGlobo // // Created by Giovane Barreira on 12/13/20. // import UIKit import Kingfisher class HomeTableViewCell: UITableViewCell { //MARK: - Outlets @IBOutlet weak var newsImage: UIImageView! @IBOutlet weak var sectionNameLbl: UILabel! @IBOutlet weak var titleLbl: UILabel! override func awakeFromNib() { super.awakeFromNib() } func setup(viewData: HomeSceneViewDataItemType?) { sectionNameLbl.text = viewData?.sectionTitle titleLbl.text = viewData?.newsTitle viewData?.newsImage.forEach { newsImage.kf.setImage(with: URL(string: $0)) } } }
22.354839
56
0.65368
ffa1a18865442024b23e35dce736e0f425d2b9d0
3,103
/// Copyright (c) 2021 Razeware LLC /// /// Permission is hereby granted, free of charge, to any person obtaining a copy /// of this software and associated documentation files (the "Software"), to deal /// in the Software without restriction, including without limitation the rights /// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell /// copies of the Software, and to permit persons to whom the Software is /// furnished to do so, subject to the following conditions: /// /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software. /// /// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, /// distribute, sublicense, create a derivative work, and/or sell copies of the /// Software in any work that is designed, intended, or marketed for pedagogical or /// instructional purposes related to programming, coding, application development, /// or information technology. Permission for such use, copying, modification, /// merger, publication, distribution, sublicensing, creation of derivative works, /// or sale is expressly withheld. /// /// This project and source code may use libraries or frameworks that are /// released under various Open-Source licenses. Use of those libraries and /// frameworks are governed by their own individual licenses. /// /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN /// THE SOFTWARE. import SwiftUI struct CardsView: View { @EnvironmentObject var viewState: ViewState @EnvironmentObject var store: CardStore var body: some View { ZStack { CardsListView() VStack { Spacer() createButton } if !viewState.showAllCards { SingleCardView() } } .background(Color("background") .edgesIgnoringSafeArea(.all)) } var createButton: some View { Button { viewState.selectedCard = store.addCard() viewState.showAllCards = false } label: { Label("Create New", systemImage: "plus") .frame(maxWidth: .infinity) } .font(.system(size: 16, weight: .bold)) .padding([.top, .bottom], 10) .background(Color("barColor")) .accentColor(/*@START_MENU_TOKEN@*/.white/*@END_MENU_TOKEN@*/) } } struct CardsView_Previews: PreviewProvider { static var previews: some View { CardsView() .environmentObject(ViewState()) .environmentObject(CardStore(defaultData: true)) } }
39.278481
83
0.667419
ccec5d1cbf2c1766b6f0c4371912bbaad9e16ce1
964
// // Created by 蒋具宏 on 2020/10/29. // import Foundation import ImSDK /// 自定义好友信息实体 class CustomFriendInfoEntity: V2TIMFriendInfo { convenience init(json: String) { self.init(dict: JsonUtil.getDictionaryFromJSONString(jsonString: json)) } init(dict: [String: Any]) { super.init(); self.userID = (dict["userID"] as? String); self.friendRemark = (dict["friendRemark"] as? String); self.friendCustomInfo = (dict["friendCustomInfo"] as? [String: Data]); } /// 根据对象获得字典对象 public static func getDict(info: V2TIMFriendInfo) -> [String: Any] { var result: [String: Any] = [:]; result["userID"] = info.userID; result["friendRemark"] = info.friendRemark; result["friendGroups"] = info.friendGroups; result["friendCustomInfo"] = info.friendCustomInfo; result["userProfile"] = CustomUserEntity.getDict(info: info.userFullInfo); return result; } }
29.212121
82
0.637967
efa8b3ec39b569cc1f0614426d271032fa9ef657
391
// // IPAddressDemoViewController.swift // Example // // Created by tcui on 6/2/2018. // Copyright © 2018 LuckyTR. All rights reserved. // import QuickSwift final class IPAddressDemoViewController: LogListViewController { override func viewDidLoad() { super.viewDidLoad() append(line: "IP Address : (\(Networking.getIPAddress() ?? "Not Available"))") } }
20.578947
86
0.672634
cc5478f578bc9fe18b497c718d1fb625d03eccc0
6,241
// // SwifterMessages.swift // Swifter // // Copyright (c) 2014 Matt Donnelly. // // 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 extension Swifter { /* GET direct_messages Returns the 20 most recent direct messages sent to the authenticating user. Includes detailed information about the sender and recipient user. You can request up to 200 direct messages per call, up to a maximum of 800 incoming DMs. */ func getDirectMessagesSinceID(sinceID: Int?, maxID: Int?, count: Int?, includeEntities: Bool?, skipStatus: Bool?, success: ((messages: JSONValue[]?) -> Void)?, failure: FailureHandler?) { let path = "direct_messages.json" var parameters = Dictionary<String, AnyObject>() if sinceID { parameters["since_id"] = sinceID! } if maxID { parameters["max_id"] = maxID! } if count { parameters["count"] = count! } if includeEntities { parameters["include_entities"] = includeEntities! } if skipStatus { parameters["skip_status"] = skipStatus! } self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: { json, response in success?(messages: json.array) return }, failure: failure) } /* GET direct_messages/sent Returns the 20 most recent direct messages sent by the authenticating user. Includes detailed information about the sender and recipient user. You can request up to 200 direct messages per call, up to a maximum of 800 outgoing DMs. */ func getSentDirectMessagesSinceID(sinceID: Int?, maxID: Int?, count: Int?, page: Int?, includeEntities: Bool?, success: ((messages: JSONValue[]?) -> Void)?, failure: FailureHandler?) { let path = "direct_messages/sent.json" var parameters = Dictionary<String, AnyObject>() if sinceID { parameters["since_id"] = sinceID! } if maxID { parameters["max_id"] = maxID! } if count { parameters["count"] = count! } if page { parameters["page"] = page! } if includeEntities { parameters["include_entities"] = includeEntities! } self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: { json, response in success?(messages: json.array) return }, failure: failure) } /* GET direct_messages/show Returns a single direct message, specified by an id parameter. Like the /1.1/direct_messages.format request, this method will include the user objects of the sender and recipient. */ func getDirectMessagesShowWithID(id: Int, success: ((messages: JSONValue[]?) -> Void)?, failure: FailureHandler?) { let path = "direct_messages/show.json" var parameters = Dictionary<String, AnyObject>() parameters["id"] = id self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: { json, response in success?(messages: json.array) return }, failure: failure) } /* POST direct_messages/destroy Destroys the direct message specified in the required ID parameter. The authenticating user must be the recipient of the specified direct message. */ func postDestroyDirectMessageWithID(id: Int, includeEntities: Bool?, success: ((messages: Dictionary<String, JSONValue>?) -> Void)?, failure: FailureHandler?) { let path = "direct_messages/destroy.json" var parameters = Dictionary<String, AnyObject>() parameters["id"] = id if includeEntities { parameters["include_entities"] = includeEntities! } self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: { json, response in success?(messages: json.object) return }, failure: failure) } /* POST direct_messages/new Sends a new direct message to the specified user from the authenticating user. Requires both the user and text parameters and must be a POST. Returns the sent message in the requested format if successful. */ func postDirectMessagesWithStatus(status: String, to screenName: String, success: ((messages: Dictionary<String, JSONValue>?) -> Void)?, failure: FailureHandler?) { let path = "direct_messages/new.json" var parameters = Dictionary<String, AnyObject>() parameters["status"] = status parameters["sceen_name"] = screenName self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: { json, response in success?(messages: json.object) return }, failure: failure) } }
38.054878
235
0.654703
568e7f6f62772dcd918079b56c5f9555ac2914fb
1,887
// // SearchResultDefaultTableViewCell.swift // Monchify // // Created by DJ perrier on 24/2/22. // import UIKit import SDWebImage class SearchResultDefaultTableViewCell: UITableViewCell { static let identifier = "SearchResultDefaultTableViewCell" private let label: UILabel = { let label = UILabel() label.numberOfLines = 1 return label }() private let iconImageView: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill return imageView }() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.addSubview(label) contentView.addSubview(iconImageView) contentView.clipsToBounds = true accessoryType = .disclosureIndicator } required init?(coder: NSCoder) { fatalError() } override func layoutSubviews() { super.layoutSubviews() let imageSize: CGFloat = contentView.height-10 iconImageView.frame = CGRect(x: 10, y: 0, width: imageSize, height: imageSize) iconImageView.layer.cornerRadius = imageSize/2 iconImageView.layer.masksToBounds = true label.frame = CGRect(x: iconImageView.right+10, y: 0, width: contentView.width-iconImageView.right-15, height: contentView.height) } override func prepareForReuse() { super.prepareForReuse() iconImageView.image = nil label.text = nil } func configure(with viewModel: SearchResultDefaultTableViewCellViewModel) { label.text = viewModel.title iconImageView.sd_setImage(with: viewModel.imageURL, completed: nil) } }
29.484375
138
0.627981
61d31b0a3b5bb45cc5f014562a68f60a4dbfa90a
313
// // UIColor+.swift // SwiftyHome // // Created by Yuto Mizutani on 2019/02/24. // Copyright © 2019 Yuto Mizutani. All rights reserved. // import UIKit extension UIColor { static var officialApplePlaceholderGray: UIColor { return UIColor(red: 0, green: 0, blue: 0.0980392, alpha: 0.22) } }
19.5625
70
0.667732
2280310601e9cdc12d409311bac9ac3b8321a72e
734
// // BuilldingMap.swift // rmf_ar_app // // Created by Matthew Booker on 18/6/21. // import Foundation struct BuildingMap: Codable { let name: String let levels: [Level] } struct Level: Codable { let name: String let elevation: Double let navGraphs: [NavGraph] let wallGraph: NavGraph } struct NavGraph: Codable { let name: String let vertices: [Vertex] let edges: [Edge] } struct Vertex: Codable { let x: Float let y: Float let name: String let params: [Param?] } struct Edge: Codable { let v1Idx: Int let v2Idx: Int let edgeType: Int let params: [Param?] } struct Param: Codable { let name: String let type: String let value: String }
14.979592
41
0.632153
2877ae5011ecc5c5bb32a2a9d594f86a9981b1d6
2,668
// Copyright © 2020 Brad Howes. All rights reserved. import AVFoundation public struct DelayConfig: Codable { public enum Key: String, CaseIterable { case enabled case time case feedback case cutoff case wetDryMix } public let enabled: Bool public let time: AUValue public let feedback: AUValue public let cutoff: AUValue public let wetDryMix: AUValue } extension DelayConfig { public init(settings: Settings) { self.init( enabled: settings.delayEnabled, time: settings.delayTime, feedback: settings.delayFeedback, cutoff: settings.delayCutoff, wetDryMix: settings.delayWetDryMix) } public init?(state: [String: Any]) { guard let enabled = state[.enabled] == 0.0 ? false : true, let time = state[.time], let feedback = state[.feedback], let cutoff = state[.cutoff], let wetDryMix = state[.wetDryMix] else { return nil } self.init( enabled: enabled, time: time, feedback: feedback, cutoff: cutoff, wetDryMix: wetDryMix) } public func setEnabled(_ enabled: Bool) -> DelayConfig { DelayConfig( enabled: enabled, time: time, feedback: feedback, cutoff: cutoff, wetDryMix: wetDryMix) } public func setTime(_ time: Float) -> DelayConfig { DelayConfig( enabled: enabled, time: time, feedback: feedback, cutoff: cutoff, wetDryMix: wetDryMix) } public func setFeedback(_ feedback: Float) -> DelayConfig { DelayConfig( enabled: enabled, time: time, feedback: feedback, cutoff: cutoff, wetDryMix: wetDryMix) } public func setCutoff(_ cutoff: Float) -> DelayConfig { DelayConfig( enabled: enabled, time: time, feedback: feedback, cutoff: cutoff, wetDryMix: wetDryMix) } public func setWetDryMix(_ wetDryMix: Float) -> DelayConfig { DelayConfig( enabled: enabled, time: time, feedback: feedback, cutoff: cutoff, wetDryMix: wetDryMix) } public subscript(_ key: Key) -> AUValue { switch key { case .enabled: return AUValue(enabled ? 1.0 : 0.0) case .time: return time case .feedback: return feedback case .cutoff: return cutoff case .wetDryMix: return wetDryMix } } public var fullState: [String: Any] { [String: Any]( uniqueKeysWithValues: zip(Key.allCases.map { $0.rawValue }, Key.allCases.map { self[$0] })) } } extension DelayConfig: CustomStringConvertible { public var description: String { "<Delay \(enabled) \(time) \(feedback) \(cutoff) \(wetDryMix)>" } } extension Dictionary where Key == String, Value == Any { fileprivate subscript(_ key: DelayConfig.Key) -> AUValue? { self[key.rawValue] as? AUValue } }
30.318182
100
0.676537
5b636dd4e1dcba96f90eae214c029ed010f2915b
7,193
/* * Copyright 2020 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import XCTest @testable import Beagle import SnapshotTesting import BeagleSchema final class BeagleSetupTests: XCTestCase { // swiftlint:disable discouraged_direct_init override func setUp() { super.setUp() BeagleSchema.dependencies = DefaultDependencies() } func testDefaultDependencies() { let dependencies = BeagleDependencies() dependencies.appBundle = Bundle() assertSnapshot(matching: dependencies, as: .dump) } func testChangedDependencies() { let dep = BeagleDependencies() dep.appBundle = Bundle() dep.deepLinkHandler = DeepLinkHandlerDummy() dep.theme = AppThemeDummy() dep.validatorProvider = ValidatorProviding() dep.localFormHandler = LocalFormHandlerSpy() if let url = URL(string: "www.test.com") { dep.urlBuilder.baseUrl = url } dep.networkClient = NetworkClientDummy() dep.style = { _ in return StyleViewConfiguratorDummy() } dep.decoder = ComponentDecodingDummy() dep.cacheManager = nil dep.windowManager = WindowManagerDumb() dep.opener = URLOpenerDumb() dep.globalContext = GlobalContextDummy() assertSnapshot(matching: dep, as: .dump) } func test_whenChangingGlobalDependency_itShouldUpdateAllLibs() { // Given let old = Beagle.dependencies let new = BeagleDependencies() // When Beagle.dependencies = new // Then XCTAssert(BeagleSchema.dependencies as AnyObject === new) XCTAssert(BeagleSchema.dependencies.decoder as AnyObject === new.decoder as AnyObject) XCTAssert(BeagleSchema.dependencies.schemaLogger as AnyObject? === new.logger as AnyObject) // Teardown Beagle.dependencies = old } func test_ifChangingDependency_othersShouldUseNewInstance() { let dependencies = BeagleDependencies() let themeSpy = ThemeSpy() dependencies.theme = themeSpy let view = UIView() let styleId = "custom-style" dependencies.theme.applyStyle(for: view, withId: styleId) XCTAssertEqual(themeSpy.styledView, view) XCTAssertEqual(themeSpy.styleApplied, styleId) } } // MARK: - Testing Helpers final class DeepLinkHandlerDummy: DeepLinkScreenManaging { func getNativeScreen(with path: String, data: [String: String]?) throws -> UIViewController { return UIViewController() } } final class FormDataStoreHandlerDummy: FormDataStoreHandling { func formManagerDidSubmitForm(group: String?) { } func save(data: [String: String], group: String) { } func read(group: String) -> [String: String]? { return nil } } final class ComponentDecodingDummy: ComponentDecoding { func register<T>(_ type: T.Type, for typeName: String) where T: BeagleSchema.RawComponent {} func register<A>(_ type: A.Type, for typeName: String) where A: BeagleSchema.RawAction {} func componentType(forType type: String) -> Decodable.Type? { return nil } func actionType(forType type: String) -> Decodable.Type? { return nil } func decodeComponent(from data: Data) throws -> BeagleSchema.RawComponent { return ComponentDummy() } func decodeAction(from data: Data) throws -> RawAction { return ActionDummy() } } final class CacheManagerDummy: CacheManagerProtocol { func addToCache(_ reference: CacheReference) { } func getReference(identifiedBy id: String) -> CacheReference? { return nil } func isValid(reference: CacheReference) -> Bool { return true } } final class PreFetchHelperDummy: BeaglePrefetchHelping { func prefetchComponent(newPath: Route.NewPath) { } } struct ComponentDummy: ServerDrivenComponent, CustomStringConvertible { private let resultView: UIView? var description: String { return "ComponentDummy()" } init(resultView: UIView? = nil) { self.resultView = resultView } init(from decoder: Decoder) throws { self.resultView = nil } func toView(renderer: BeagleRenderer) -> UIView { return resultView ?? UIView() } } struct ActionDummy: Action, Equatable { func execute(controller: BeagleController, sender: Any) {} } struct BeagleScreenDependencies: BeagleDependenciesProtocol { var isLoggingEnabled: Bool = true var analytics: Analytics? var repository: Repository = RepositoryStub() var theme: Theme = AppThemeDummy() var validatorProvider: ValidatorProvider? var preFetchHelper: BeaglePrefetchHelping = PreFetchHelperDummy() var appBundle: Bundle = Bundle(for: ImageTests.self) var cacheManager: CacheManagerProtocol? var decoder: ComponentDecoding = ComponentDecodingDummy() var logger: BeagleLoggerType = BeagleLoggerDumb() var formDataStoreHandler: FormDataStoreHandling = FormDataStoreHandlerDummy() var navigationControllerType = BeagleNavigationController.self var schemaLogger: SchemaLogger? var urlBuilder: UrlBuilderProtocol = UrlBuilder() var networkClient: NetworkClient = NetworkClientDummy() var deepLinkHandler: DeepLinkScreenManaging? var localFormHandler: LocalFormHandler? var navigation: BeagleNavigation = BeagleNavigationDummy() var windowManager: WindowManager = WindowManagerDumb() var opener: URLOpener = URLOpenerDumb() var globalContext: GlobalContext = GlobalContextDummy() var renderer: (BeagleController) -> BeagleRenderer = { return BeagleRenderer(controller: $0) } var viewConfigurator: (UIView) -> ViewConfiguratorProtocol = { return ViewConfigurator(view: $0) } var style: (UIView) -> StyleViewConfiguratorProtocol = { _ in return StyleViewConfiguratorDummy() } } class NetworkClientDummy: NetworkClient { func executeRequest(_ request: Request, completion: @escaping RequestCompletion) -> RequestToken? { return nil } } final class AppThemeDummy: Theme { func applyStyle<T>(for view: T, withId id: String) where T: UIView { } } class BeagleNavigationDummy: BeagleNavigation { var defaultAnimation: BeagleNavigatorAnimation? func navigate(action: Navigate, controller: BeagleController, animated: Bool) { } } class GlobalContextDummy: GlobalContext { let globalId: String = "" let context: Observable<Context> = Observable(value: .init(id: "", value: .empty)) func isGlobal(id: String?) -> Bool { true } func setValue(_ value: DynamicObject) {} }
33.769953
105
0.700681
69872e675550ec37944795d9f94fcb02062c826c
5,797
/** * Copyright (c) 2017 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, * distribute, sublicense, create a derivative work, and/or sell copies of the * Software in any work that is designed, intended, or marketed for pedagogical or * instructional purposes related to programming, coding, application development, * or information technology. Permission for such use, copying, modification, * merger, publication, distribution, sublicensing, creation of derivative works, * or sale is expressly withheld. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit import StitchCore import StitchLocalMongoDBService import StitchRemoteMongoDBService import MongoSwiftMobile // required for BSON Documents struct Quiz: Codable { var quizId: Int = -1 var quizName: String = "" var shortDescription: String = "" var points: String = "" var q1: String = "" var options1: String = "" var a1: Int = -1 var q2: String = "" var options2: String = "" var a2: Int = -1 var q3: String = "" var options3: String = "" var a3: Int = -1 var info: String = "" init?(document: Document) { self.quizId = document["id"] as? Int ?? -1 self.quizName = document["quizName"] as? String ?? "" self.shortDescription = document["shortDescription"] as? String ?? "" self.points = document["points"] as? String ?? "" self.a1 = document["a1"] as? Int ?? -1 self.options1 = document["options1"] as? String ?? "" self.q1 = document["q1"] as? String ?? "" self.a2 = document["a2"] as? Int ?? -1 self.options2 = document["options2"] as? String ?? "" self.q2 = document["q2"] as? String ?? "" self.a3 = document["a3"] as? Int ?? -1 self.options3 = document["options3"] as? String ?? "" self.q3 = document["q3"] as? String ?? "" self.info = document["info"] as? String ?? "" } } class ManagePageViewController: UIPageViewController { var photos: [String] = [] var photoName: [String] = [] var currentIndex: Int! var quizArray: [Quiz] = [] override func viewDidLoad() { super.viewDidLoad() dataSource = self //self.navigationItem.setHidesBackButton(true, animated: false) //self.navigationController?.navigationItem.setHidesBackButton(true, animated: true) self.title = "DigiKnow" } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.quizArray = QuizData.quizArray self.photos = QuizData.photoArray goToNextStep() } func goToNextStep() { DispatchQueue.main.async { if let viewController = self.viewPhotoCommentController(self.currentIndex ?? 0) { let viewControllers = [viewController] self.setViewControllers( viewControllers, direction: .forward, animated: false, completion: nil ) } } } func viewPhotoCommentController(_ index: Int) -> PhotoCommentViewController? { if let storyboard = storyboard, let page = storyboard.instantiateViewController(withIdentifier: "PhotoCommentViewController") as? PhotoCommentViewController { page.photoName = photos[index] page.photoIndex = index page.quiz = self.quizArray[index] return page } return nil } } //MARK: implementation of UIPageViewControllerDataSource extension ManagePageViewController: UIPageViewControllerDataSource { // 1 func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { if let viewController = viewController as? PhotoCommentViewController, let index = viewController.photoIndex, index > 0 { return viewPhotoCommentController(index - 1) } return nil } // 2 func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { if let viewController = viewController as? PhotoCommentViewController, let index = viewController.photoIndex, (index + 1) < photos.count { return viewPhotoCommentController(index + 1) } return nil } // MARK: UIPageControl func presentationCount(for pageViewController: UIPageViewController) -> Int { return photos.count } func presentationIndex(for pageViewController: UIPageViewController) -> Int { return currentIndex ?? 0 } }
35.347561
132
0.664309
6298f72f4ca2b6eeb0f56ebe8ce767d53edab7be
1,569
class DerivationSettingsPresenter { weak var view: IDerivationSettingsView? private let router: IDerivationSettingsRouter private let interactor: IDerivationSettingsInteractor private let factory = DerivationSettingsViewItemFactory() private var items = [DerivationSettingsItem]() init(router: IDerivationSettingsRouter, interactor: IDerivationSettingsInteractor) { self.router = router self.interactor = interactor } private func updateUI() { items = interactor.allActiveSettings.map { setting, wallets in DerivationSettingsItem(firstCoin: wallets[0].coin, setting: setting) } let viewItems = items.map { factory.sectionViewItem(item: $0) } view?.set(viewItems: viewItems) } } extension DerivationSettingsPresenter: IDerivationSettingsViewDelegate { func onLoad() { updateUI() } func onSelect(chainIndex: Int, settingIndex: Int) { let item = items[chainIndex] let derivation = MnemonicDerivation.allCases[settingIndex] guard item.setting.derivation != derivation else { return } let newSetting = DerivationSetting(coinType: item.setting.coinType, derivation: derivation) router.showChangeConfirmation(coinTitle: item.firstCoin.title, setting: newSetting, delegate: self) } } extension DerivationSettingsPresenter: IDerivationSettingConfirmationDelegate { func onConfirm(setting: DerivationSetting) { interactor.save(setting: setting) updateUI() } }
29.055556
107
0.706182
f7efcdaa8805c7198dd007222a8f214e05b207ef
4,382
// // BusinessCell.swift // Yelp // // Created by Guoliang Wang on 4/9/17. // Copyright © 2017 Timothy Lee. All rights reserved. // import UIKit import SnapKit class BusinessCell: UITableViewCell { @IBOutlet weak var thumbImageView: UIImageView! @IBOutlet weak var ratingImageView: UIImageView! @IBOutlet weak var reviewCountLabel: UILabel! @IBOutlet weak var priceyLabel: UILabel! @IBOutlet weak var distanceLabel: UILabel! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var addressLabel: UILabel! @IBOutlet weak var categoriesLabel: UILabel! var restaurant: Restaurant! { didSet { self.bind(restaurant) } } override func awakeFromNib() { super.awakeFromNib() thumbImageView.layer.cornerRadius = 3 } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } override func layoutSubviews() { thumbImageView.snp.makeConstraints { (make) in make.left.top.equalToSuperview().inset(8) make.width.height.equalTo(65) } nameLabel.snp.makeConstraints { (make) in make.top.equalToSuperview().inset(8) make.left.equalTo(thumbImageView.snp.right).offset(8) } ratingImageView.snp.makeConstraints { (make) in make.top.equalTo(nameLabel.snp.bottom).offset(8) make.left.equalTo(thumbImageView.snp.right).offset(8) make.width.equalTo(83) make.height.equalTo(15) } reviewCountLabel.snp.makeConstraints { (make) in make.centerY.equalTo(ratingImageView) make.left.equalTo(ratingImageView.snp.right).offset(8) } addressLabel.snp.makeConstraints { (make) in make.left.equalTo(thumbImageView.snp.right).offset(8) make.top.equalTo(ratingImageView.snp.bottom).offset(8) make.right.equalToSuperview().offset(8) } categoriesLabel.snp.makeConstraints { (make) in // make.leading.equalTo(addressLabel.snp.leading) make.left.equalTo(thumbImageView.snp.right).offset(8) make.top.equalTo(addressLabel.snp.bottom).offset(8) make.bottom.equalToSuperview().inset(10) } priceyLabel.snp.makeConstraints { (make) in make.centerY.equalTo(reviewCountLabel) make.right.equalToSuperview().inset(8) } distanceLabel.snp.makeConstraints { (make) in make.centerY.equalTo(nameLabel) make.right.equalToSuperview().inset(8) // make.left.greaterThanOrEqualTo(nameLabel.snp.right).offset(8) } nameLabel.numberOfLines = 2 nameLabel.lineBreakMode = .byWordWrapping addressLabel.lineBreakMode = .byWordWrapping } private func randomPriceyness() -> String { let priceyness: [String] = ["$", "$$", "$$$", "$$$$"] let randomIndex = Int(arc4random_uniform(UInt32(priceyness.count))) return priceyness[randomIndex] } private func bind(_ restaurant: Restaurant) { thumbImageView.fadeInImageWith(remoteImgUrl: restaurant.imageUrl, placeholderImage: nil) if let name = restaurant.name { nameLabel.text = name } if let dist = restaurant.distance { let miles = Double(dist) * milesPerMeter distanceLabel.text = "\(String(format: "%.2f", miles)) mi" } if let urlString = restaurant.ratingImageUrl { ratingImageView.setImageWith(URL(string: urlString)!) } var reviewLabelContent = "No Reviews" if let reviewCount = restaurant.reviewCount, reviewCount > 0 { reviewLabelContent = "\(reviewCount) " reviewLabelContent += reviewCount > 1 ? "Reviews" : "Review" } reviewCountLabel.text = reviewLabelContent addressLabel.text = restaurant.address.joined(separator: ", ") categoriesLabel.text = restaurant.categories.first?.joined(separator: ", ") priceyLabel.text = randomPriceyness() } }
33.450382
96
0.610452
39191596238763f92f9e6daf49655388ffd25bb5
320
// // TagEntity+Mapping.swift // Timmee // // Created by Ilya Kharabet on 22.10.17. // Copyright © 2017 Mesterra. All rights reserved. // import Workset public extension TagEntity { func map(from tag: Tag) { id = tag.id title = tag.title color = tag.color.hexString() } }
16
51
0.59375
de2688de8b613b7e2d9a3bcdff06fe236405d482
3,304
// // IssueCommentModelHandling.swift // Freetime // // Created by Ryan Nystrom on 7/5/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import UIKit import StyledTextKit func BodyHeightForComment( viewModel: Any, width: CGFloat, webviewCache: WebviewCellHeightCache?, imageCache: ImageCellHeightCache? ) -> CGFloat { if let viewModel = viewModel as? StyledTextRenderer { return viewModel.viewSize(in: width).height } else if let viewModel = viewModel as? IssueCommentCodeBlockModel { let inset = IssueCommentCodeBlockCell.scrollViewInset return viewModel.contentSize.height + inset.top + inset.bottom } else if let viewModel = viewModel as? IssueCommentImageModel { return (imageCache?.height(model: viewModel, width: width) ?? 200) + IssueCommentImageCell.bottomInset } else if let viewModel = viewModel as? IssueCommentQuoteModel { return viewModel.string.viewSize(in: width).height } else if viewModel is IssueCommentHrModel { return 3.0 + IssueCommentHrCell.inset.top + IssueCommentHrCell.inset.bottom } else if let cache = webviewCache, let viewModel = viewModel as? IssueCommentHtmlModel { return cache.height(model: viewModel, width: width) } else if let viewModel = viewModel as? IssueCommentTableModel { return viewModel.size.height } else { return Styles.Sizes.tableCellHeight } } func CellTypeForComment(viewModel: Any) -> AnyClass { switch viewModel { case is IssueCommentImageModel: return IssueCommentImageCell.self case is IssueCommentCodeBlockModel: return IssueCommentCodeBlockCell.self case is IssueCommentSummaryModel: return IssueCommentSummaryCell.self case is IssueCommentQuoteModel: return IssueCommentQuoteCell.self case is IssueCommentUnsupportedModel: return IssueCommentUnsupportedCell.self case is IssueCommentHtmlModel: return IssueCommentHtmlCell.self case is IssueCommentHrModel: return IssueCommentHrCell.self case is StyledTextRenderer: return IssueCommentTextCell.self case is IssueCommentTableModel: return IssueCommentTableCell.self default: fatalError("Unhandled model: \(viewModel)") } } func ExtraCommentCellConfigure( cell: UICollectionViewCell, imageDelegate: IssueCommentImageCellDelegate?, htmlDelegate: IssueCommentHtmlCellDelegate?, htmlNavigationDelegate: IssueCommentHtmlCellNavigationDelegate?, htmlImageDelegate: IssueCommentHtmlCellImageDelegate?, markdownDelegate: MarkdownStyledTextViewDelegate?, imageHeightDelegate: IssueCommentImageHeightCellDelegate ) { if let cell = cell as? IssueCommentImageCell { cell.delegate = imageDelegate cell.heightDelegate = imageHeightDelegate } else if let cell = cell as? IssueCommentHtmlCell { cell.delegate = htmlDelegate cell.navigationDelegate = htmlNavigationDelegate cell.imageDelegate = htmlImageDelegate } else if let cell = cell as? IssueCommentTextCell { cell.textView.tapDelegate = markdownDelegate } else if let cell = cell as? IssueCommentQuoteCell { cell.delegate = markdownDelegate } else if let cell = cell as? IssueCommentTableCell { cell.delegate = markdownDelegate } }
42.358974
93
0.747881
f73ff3e7704e2ce96282e6c0a2dcae012c603a35
7,680
// // AtomFeedLink.swift // // Copyright (c) 2016 - 2018 Nuno Manuel Dias // // 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 /// The "atom:link" element defines a reference from an entry or feed to /// a Web resource. This specification assigns no meaning to the content /// (if any) of this element. public class AtomFeedLink { /// The element's attributes. public class Attributes { /// The "href" attribute contains the link's IRI. atom:link elements MUST /// have an href attribute, whose value MUST be a IRI reference /// [RFC3987]. public var href: String? /// The atom:link elements MAY have a "rel" attribute that indicates the link /// relation type. If the "rel" attribute is not present, the link /// element MUST be interpreted as if the link relation type is /// "alternate". /// /// The value of "rel" MUST be a string that is non-empty and matches /// either the "isegment-nz-nc" or the "IRI" production in [RFC3987]. /// Note that use of a relative reference other than a simple name is not /// allowed. If a name is given, implementations MUST consider the link /// relation type equivalent to the same name registered within the IANA /// Registry of Link Relations (Section 7), and thus to the IRI that /// would be obtained by appending the value of the rel attribute to the /// string "http://www.iana.org/assignments/relation/". The value of /// "rel" describes the meaning of the link, but does not impose any /// behavioral requirements on Atom Processors. /// /// This document defines five initial values for the Registry of Link /// Relations: /// /// 1. The value "alternate" signifies that the IRI in the value of the /// href attribute identifies an alternate version of the resource /// described by the containing element. /// /// 2. The value "related" signifies that the IRI in the value of the /// href attribute identifies a resource related to the resource /// described by the containing element. For example, the feed for a /// site that discusses the performance of the search engine at /// "http://search.example.com" might contain, as a child of /// atom:feed: /// /// <link rel="related" href="http://search.example.com/"/> /// /// An identical link might appear as a child of any atom:entry whose /// content contains a discussion of that same search engine. /// /// 3. The value "self" signifies that the IRI in the value of the href /// attribute identifies a resource equivalent to the containing /// element. /// /// 4. The value "enclosure" signifies that the IRI in the value of the /// href attribute identifies a related resource that is potentially /// large in size and might require special handling. For atom:link /// elements with rel="enclosure", the length attribute SHOULD be /// provided. /// /// 5. The value "via" signifies that the IRI in the value of the href /// attribute identifies a resource that is the source of the /// information provided in the containing element. public var rel: String? /// On the link element, the "type" attribute's value is an advisory /// media type: it is a hint about the type of the representation that is /// expected to be returned when the value of the href attribute is /// dereferenced. Note that the type attribute does not override the /// actual media type returned with the representation. Link elements /// MAY have a type attribute, whose value MUST conform to the syntax of /// a MIME media type [MIMEREG]. public var type: String? /// The "hreflang" attribute's content describes the language of the /// resource pointed to by the href attribute. When used together with /// the rel="alternate", it implies a translated version of the entry. /// Link elements MAY have an hreflang attribute, whose value MUST be a /// language tag [RFC3066]. public var hreflang: String? /// The "title" attribute conveys human-readable information about the /// link. The content of the "title" attribute is Language-Sensitive. /// Entities such as "&amp;" and "&lt;" represent their corresponding /// characters ("&" and "<", respectively), not markup. Link elements /// MAY have a title attribute. public var title: String? /// The "length" attribute indicates an advisory length of the linked /// content in octets; it is a hint about the content length of the /// representation returned when the IRI in the href attribute is mapped /// to a URI and dereferenced. Note that the length attribute does not /// override the actual content length of the representation as reported /// by the underlying protocol. Link elements MAY have a length /// attribute. public var length: Int64? } /// The element's attributes. public var attributes: Attributes? public init() {} } // MARK: - Initializers extension AtomFeedLink { convenience init(attributes attributeDict: [String: String]) { self.init() attributes = AtomFeedLink.Attributes(attributes: attributeDict) } } extension AtomFeedLink.Attributes { convenience init?(attributes attributeDict: [String: String]) { if attributeDict.isEmpty { return nil } self.init() href = attributeDict["href"] hreflang = attributeDict["hreflang"] type = attributeDict["type"] rel = attributeDict["rel"] title = attributeDict["title"] length = Int64(attributeDict["length"] ?? "") } } // MARK: - Equatable extension AtomFeedLink: Equatable { public static func == (lhs: AtomFeedLink, rhs: AtomFeedLink) -> Bool { return lhs.attributes == rhs.attributes } } extension AtomFeedLink.Attributes: Equatable { public static func == (lhs: AtomFeedLink.Attributes, rhs: AtomFeedLink.Attributes) -> Bool { return lhs.href == rhs.href && lhs.hreflang == rhs.hreflang && lhs.type == rhs.type && lhs.rel == rhs.rel && lhs.title == rhs.title && lhs.length == rhs.length } }
44.651163
96
0.650521
030755392b91d3e91e3bd604ff221ae394c01ac6
3,317
// // AppyTextField.swift // Appykit // // Created by Appyist on 29/04/2017. // Copyright © 2017 Appyist. All rights reserved. // import UIKit @IBDesignable open class AppyTextField: UITextField { // MARK: - Variables @IBInspectable public var borderColor: UIColor = .clear { didSet { layer.borderColor = borderColor.cgColor } } @IBInspectable public var borderWidth: CGFloat = 0 { didSet { layer.borderWidth = borderWidth } } @IBInspectable public var cornerRadius: CGFloat = 0 { didSet { layer.cornerRadius = cornerRadius } } lazy var customClearButton: UIButton = { let button = UIButton(type: .custom) button.adjustsImageWhenHighlighted = false button.frame = CGRect(x: 0, y: 0, width: 18, height: 18) button.setImage(clearIcon, for: .normal) button.addTarget(self, action: #selector(clearText), for: .touchUpInside) button.isHidden = true return button }() @IBInspectable public var clearIconRightPadding: CGFloat = 0.0 @IBInspectable public var clearIcon: UIImage? { didSet { addTarget(self, action: #selector(textChanged), for: .editingChanged) rightView = customClearButton rightViewMode = .always } } override open func rightViewRect(forBounds bounds: CGRect) -> CGRect { var rightViewRect = super.rightViewRect(forBounds: bounds) rightViewRect.origin.x -= clearIconRightPadding return rightViewRect } open override var text: String? { willSet { customClearButton.isHidden = newValue?.isEmpty ?? true } } @objc func textChanged() { customClearButton.isHidden = text!.isEmpty } @IBInspectable public var leftPadding: CGFloat = 0 @IBInspectable public var rightPadding: CGFloat = 0 @IBInspectable public var topPadding: CGFloat = 0 @IBInspectable public var bottomPadding: CGFloat = 0 @IBInspectable public var placeholderColor: UIColor? // MARK: - Functions override open func draw(_ rect: CGRect) { super.draw(rect) if let placeholderColor = placeholderColor { attributedPlaceholder = NSAttributedString(string: placeholder ?? "", attributes: [.foregroundColor: placeholderColor]) } } override open func textRect(forBounds bounds: CGRect) -> CGRect { return bounds.inset(by: UIEdgeInsets(top: topPadding, left: leftPadding, bottom: bottomPadding, right: rightPadding)) } override open func placeholderRect(forBounds bounds: CGRect) -> CGRect { return bounds.inset(by: UIEdgeInsets(top: topPadding, left: leftPadding, bottom: bottomPadding, right: rightPadding)) } override open func editingRect(forBounds bounds: CGRect) -> CGRect { return bounds.inset(by: UIEdgeInsets(top: topPadding, left: leftPadding, bottom: bottomPadding, right: rightPadding)) } @objc func clearText() { text = "" } deinit { removeTarget(self, action: #selector(textChanged), for: .editingChanged) } }
31.590476
125
0.624962
ef316432759a526db2aca3e4f57a9008fd81f141
1,128
// // Image.swift // UserInterface // // Created by Fernando Moya de Rivas on 10/07/2019. // Copyright © 2019 fmoyader. All rights reserved. // import Foundation @IBDesignable class ImageView: UIImageView { @IBInspectable public var cornerRadius: CGFloat = 0 { didSet { layer.cornerRadius = cornerRadius setNeedsDisplay() } } @IBInspectable public var borderWidth: CGFloat = 0 { didSet { layer.borderWidth = borderWidth setNeedsDisplay() } } @IBInspectable public var borderColor: UIColor = .clear { didSet { layer.borderColor = borderColor.cgColor setNeedsDisplay() } } override public func draw(_ rect: CGRect) { super.draw(rect) layer.cornerRadius = cornerRadius layer.borderWidth = borderWidth layer.borderColor = borderColor.cgColor } public override init(frame: CGRect) { super.init(frame: frame) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
23.5
61
0.600177