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
2fd0f3906db69aab26a29f53d1d0abbfa7632c7d
360
// // Empty.swift // BaseUI // // Copyright © 2020 E-SOFT, OOO. All rights reserved. // import XCTest final class BaseUITests: XCTestCase { func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. XCTAssert(1 == 1) } }
18.947368
96
0.641667
6180196fe1b51149c2484cbc7b4a45e9e9d68e55
2,778
// RUN: %empty-directory(%t) // RUN: %target-build-swift -lswiftSwiftReflectionTest %s -o %t/reflect_Character // RUN: %target-codesign %t/reflect_Character // RUN: %target-run %target-swift-reflection-test %t/reflect_Character | %FileCheck %s --check-prefix=CHECK-%target-ptrsize %add_num_extra_inhabitants // REQUIRES: reflection_test_support // REQUIRES: executable_test // UNSUPPORTED: use_os_stdlib import SwiftReflectionTest class TestClass { var t: Character init(t: Character) { self.t = t } } var obj = TestClass(t: "A") reflect(object: obj) // CHECK-64: Reflecting an object. // CHECK-64: Type reference: // CHECK-64: (class reflect_Character.TestClass) // CHECK-64-LABEL: Type info: // CHECK-64: (class_instance size=32 alignment=8 stride=32 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=t offset=16 // CHECK-64-NEXT: (struct size=16 alignment=8 stride=16 num_extra_inhabitants=[[#num_extra_inhabitants_64bit]] bitwise_takable=1 // CHECK-64-NEXT: (field name=_str offset=0 // CHECK-64-NEXT: (struct size=16 alignment=8 stride=16 num_extra_inhabitants=[[#num_extra_inhabitants_64bit]] bitwise_takable=1 // CHECK-64-NEXT: (field name=_guts offset=0 // CHECK-64-NEXT: (struct size=16 alignment=8 stride=16 num_extra_inhabitants=[[#num_extra_inhabitants_64bit]] bitwise_takable=1 // CHECK-64-NEXT: (field name=_object offset=0 // CHECK-64-NEXT: (struct size=16 alignment=8 stride=16 num_extra_inhabitants=[[#num_extra_inhabitants_64bit]] bitwise_takable=1 // CHECK-64-NEXT: (field name=_countAndFlagsBits offset=0 // CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1)))) // CHECK-64-NEXT: (field name=_object offset=8 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[#num_extra_inhabitants_64bit]] bitwise_takable=1))))))))))) // CHECK-32: Reflecting an object. // CHECK-32: Type reference: // CHECK-32: (class reflect_Character.TestClass) // CHECK-32: Type info: // CHECK-32-NEXT: (class_instance size=20 alignment=4 stride=20 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=t offset=8 // CHECK-32-NEXT: (struct size=12 alignment=4 stride=12 num_extra_inhabitants=253 bitwise_takable=1 // CHECK-32-NEXT: (field name=_str offset=0 // CHECK-32-NEXT: (struct size=12 alignment=4 stride=12 num_extra_inhabitants=253 bitwise_takable=1 doneReflecting() // CHECK-64: Done. // CHECK-32: Done.
45.540984
156
0.706983
915713b5c2f273688ddf5f2fdafc86048717b7b7
1,025
// swift-tools-version:4.0 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "{PROJECT}", products: [ // Products define the executables and libraries produced by a package, and make them visible to other packages. .library( name: "{PROJECT}", targets: ["{PROJECT}"]), ], dependencies: [ // Dependencies declare other packages that this package depends on. // .package(url: /* package url */, from: "1.0.0"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages which this package depends on. .target( name: "{PROJECT}", dependencies: []), .testTarget( name: "{PROJECT}Tests", dependencies: ["{PROJECT}"]), ] )
35.344828
122
0.60878
69af03da82635488df9ea55546e391debed63a0a
5,886
// // Calculate.swift // News // // Created by 杨蒙 on 2017/12/10. // Copyright © 2017年 hrscy. All rights reserved. // import UIKit protocol Calculatable { // MARK: 计算宽度 static func collectionViewWidth(_ count: Int) -> CGFloat // MARK: 计算高度 static func collectionViewHeight(_ count: Int) -> CGFloat // MARK: 计算 collectionViewCell 的大小 static func collectionViewCellSize(_ count: Int) -> CGSize // MARK: 计算富文本的高度 static func attributedTextHeight(text: NSAttributedString, width: CGFloat) -> CGFloat // MARK: 计算文本的高度 static func textHeight(text: String, fontSize: CGFloat, width: CGFloat) -> CGFloat // MARK: 计算文本的宽度 static func textHieght(text: String, fontSize: CGFloat, height: CGFloat) -> CGFloat // MARK: 从文本内容中获取 uid 和 用户名 static func richContents(from content: String, idPattern: String, titlePattern: String) -> [RichContent] // MARK: 计算详情里的 collectionViewCell 的大小 static func detailCollectionViewCellSize(_ thumbImageList: [ThumbImageList]) -> CGSize // MARK: 计算详情里的高度 static func detailCollectionViewHieght(_ thumbImageList: [ThumbImageList]) -> CGFloat } extension Calculatable { /// 计算高度 static func detailCollectionViewHieght(_ thumbImageList: [ThumbImageList]) -> CGFloat { switch thumbImageList.count { case 1: let thumbImage = thumbImageList.first! return (screenWidth - 30) * thumbImage.height / thumbImage.width case 2: return (screenWidth - 35) * 0.5 case 3: return image3Width + 5 case 4: return (screenWidth - 3) case 5, 6: return (image3Width + 5) * 2 case 7...9: return (image3Width + 5) * 3 default: return 0 } } /// 计算情里的 collectionViewCell 的大小 static func detailCollectionViewCellSize(_ thumbImageList: [ThumbImageList]) -> CGSize { switch thumbImageList.count { case 1: let thumbImage = thumbImageList.first! let height = (screenWidth - 30) * thumbImage.height / thumbImage.width return CGSize(width: (screenWidth - 30), height: height) case 2, 4: let image2W = (screenWidth - 35) * 0.5 return CGSize(width: image2W, height: image2W) case 3, 5...9: return CGSize(width: image3Width, height: image3Width) default: return .zero } } /// 从文本内容中获取 uid 和 用户名 static func richContents(from content: String, idPattern: String, titlePattern: String) -> [RichContent] { // 富文本内容 var richContents = [RichContent]() // 临时数组 var temps = [RichContent]() // 创建正则表达式对象,匹配 id let uidRegex = try! NSRegularExpression(pattern: idPattern, options: []) // 开始匹配,返回结果 let uidResults = uidRegex.matches(in: content, options: [], range: NSRange(location: 0, length: content.count)) if uidResults.count != 0{ // 取出用户名,放到临时数组 temps = uidResults.map({ let uid = (content as NSString).substring(with: $0.range) return RichContent(uid, "") }) } // 创建正则表达式对象 let userRegex = try! NSRegularExpression(pattern: titlePattern, options: []) // 开始匹配,返回结果 let userResults = userRegex.matches(in: content, options: [], range: NSRange(location: 0, length: content.count)) if userResults.count != 0 { for (index, result) in userResults.enumerated() { // 取出临时数组中的模型 var richContent = temps[index] // 取出用户名 richContent.name = (content as NSString).substring(with: result.range) richContents.append(richContent) } } return richContents } /// 计算宽度 static func collectionViewWidth(_ count: Int) -> CGFloat { switch count { case 1, 2: return (image2Width + 5) * 2 case 3, 5...9: return screenWidth - 30 case 4: return (image3Width + 5) * 2 default: return 0 } } /// 计算高度 static func collectionViewHeight(_ count: Int) -> CGFloat { switch count { case 1, 2: return image2Width case 3: return image3Width + 5 case 4...6: return (image3Width + 5) * 2 case 7...9: return (image3Width + 5) * 3 default: return 0 } } /// 计算 collectionViewCell 的大小 static func collectionViewCellSize(_ count: Int) -> CGSize { switch count { case 1, 2: return CGSize(width: image2Width, height: image2Width) case 3...9: return CGSize(width: image3Width, height: image3Width) default: return .zero } } /// 计算富文本的高度 static func attributedTextHeight(text: NSAttributedString, width: CGFloat) -> CGFloat { return text.boundingRect(with: CGSize(width: width, height: CGFloat(MAXFLOAT)), options: .usesLineFragmentOrigin, context: nil).size.height + 5.0 } /// 计算文本的高度 static func textHeight(text: String, fontSize: CGFloat, width: CGFloat) -> CGFloat { return text.boundingRect(with: CGSize(width: width, height: CGFloat(MAXFLOAT)), options: .usesLineFragmentOrigin, attributes: [.font: UIFont.systemFont(ofSize: fontSize)], context: nil).size.height + 5 } /// 计算文本的宽度 static func textHieght(text: String, fontSize: CGFloat, height: CGFloat) -> CGFloat { return text.boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: height), options: .usesLineFragmentOrigin, attributes: [.font: UIFont.systemFont(ofSize: fontSize)], context: nil).size.height } } struct Calculate: Calculatable {}
35.672727
209
0.599218
14883300cd75c720e1c0010c0531f92fefd03acb
4,418
// // DataManager.swift // insulin_calculator // // Created by 李灿晨 on 10/11/19. // Copyright © 2019 李灿晨. All rights reserved. // import UIKit import CoreData class DataManager: NSObject { /** The shared instance of object `DataManager`. */ static var shared: DataManager = DataManager() // MARK: - `SessionRecord` manipulation. /** Insert a session record into the persistant container. - parameters: - record: The `SessionRecord` object to be inserted into the persistant container. */ func createSessionRecord(record: SessionRecord) { let entity = NSEntityDescription.entity(forEntityName: "ManagedSessionRecord", in: context) let newRecord = ManagedSessionRecord(entity: entity!, insertInto: context) newRecord.initialize(with: record) saveContext() } /** Update a session record in the persistant container. Do not update the URL related fields. - parameters: - record: The `SessionRecord` object to be updated. */ func updateSessionRecord(record: SessionRecord) { removeSessionRecord(record: record, withFiles: false) createSessionRecord(record: record) } /** Remove a session record from the persistant container. - parameters: - record: The `SessionRecord` object to be removed from the persistant container. - withFiles: Whether the files specified by URL fields of the `SessionRecord` object should also be removed with the record. */ func removeSessionRecord(record: SessionRecord, withFiles: Bool) { let fetchRequest: NSFetchRequest = ManagedSessionRecord.fetchRequest() fetchRequest.predicate = NSPredicate(format: "sessionId == \"\(record.sessionId)\"") let results = try! context.fetch(fetchRequest) for record in results { if withFiles { removeFile(url: record.photoURL) removeFile(url: record.captureJSONURL) removeFile(url: record.recognitionJSONURL) } context.delete(record) } saveContext() } /** Return all stored session records in an array. */ func getAllSessionRecords() -> [SessionRecord] { let fetchRequest: NSFetchRequest = ManagedSessionRecord.fetchRequest() let managedRecords = (try! context.fetch(fetchRequest)) as [ManagedSessionRecord] return managedRecords.map({$0.export()}) } // MARK: - File Manipulation. /** Save `data` as a temporary file in `documentDirectory` with extension name `extensionName`. The file name would be a UUID string. - parameters: - data: The data to be saved. Callers are responsible for converting objects to `Data` with proper encoding. - extensionName: The extension name of the saved file. - completion: The completion handler. This closure will be called once the saving process finished, the parameter is the URL of the saved temporary file. */ func saveFile( data: Data, extensionName: String, completion: ((URL) -> ())? ) { let url = FileManager.default.urls( for: .documentDirectory, in: .userDomainMask )[0].appendingPathComponent(UUID().uuidString).appendingPathExtension(extensionName) try! data.write(to: url) completion?(url) } /** Remove the file with the given URL. - parameters: - url: The url of the file to be removed. */ func removeFile(url: URL?) { guard url != nil else {return} guard FileManager.default.fileExists(atPath: url!.path) else {return} try! FileManager.default.removeItem(at: url!) } // MARK: - Utilties. /** A context representing a single object space that allows fetch, create, and remove managed objects. */ private var context: NSManagedObjectContext = { let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext return context }() /** Save CoreData context. */ private func saveContext() { do { try context.save() } catch { fatalError("Error occurred when saving a context.") } } }
32.485294
121
0.628112
22306d2541c1481b44bff9870cbb0dc98f0f7168
1,141
// swift-tools-version:5.1 // We're hiding dev, test, and danger dependencies with // dev to make sure they're not fetched by users of this package. import PackageDescription let package = Package( name: "UINotifications", platforms: [ .iOS(.v13) ], products: [ // dev .library(name: "DangerDeps", type: .dynamic, targets: ["DangerDependencies"]), // dev .library(name: "UINotifications", type: .static, targets: ["UINotifications"]) ], dependencies: [ // dev .package(url: "https://github.com/danger/swift", from: "3.0.0"), // dev .package(path: "Submodules/WeTransfer-iOS-CI/Danger-Swift") ], targets: [ // This is just an arbitrary Swift file in the app, that has // no dependencies outside of Foundation, the dependencies section // ensures that the library for Danger gets build also. // dev .target(name: "DangerDependencies", dependencies: ["Danger", "WeTransferPRLinter"], path: "Submodules/WeTransfer-iOS-CI/Danger-Swift", sources: ["DangerFakeSource.swift"]), .target(name: "UINotifications", path: "Sources") ] )
43.884615
187
0.650307
ab7e5b4e8dc4311d717796b8ca6d9185d3012ac3
1,512
// // ContactEntity+CoreDataProperties.swift // iOS_Example // // Created by Seyed Samad Gholamzadeh on 9/15/18. // Copyright © 2018 Seyed Samad Gholamzadeh. All rights reserved. // // import Foundation import CoreData import ModelAssistant extension ContactEntity: MAEntity { @nonobjc public class func fetchRequest() -> NSFetchRequest<ContactEntity> { return NSFetchRequest<ContactEntity>(entityName: "ContactEntity") } @NSManaged public var displayOrder: Int64 @NSManaged public var firstName: String @NSManaged public var id: Int32 @NSManaged public var imageURLString: String? @NSManaged public var lastName: String @NSManaged public var phone: String? var imageURL: URL { let string = imageURLString ?? "https://robohash.org/\(firstName)\(lastName)\(id).jpg?size=30x30&set=set1" return URL(string: string)! } var fullName: String { return firstName + " " + lastName } public var uniqueValue: Int { return Int(self.phone ?? "0")! } @objc public var index: String? { return String(Array(self.firstName)[0]).uppercased() } public subscript(key: String) -> String? { if key == "firstName" { return String(Array(self.firstName)[0]).uppercased() } if key == "lastName" { return String(Array(self.firstName)[0]).uppercased() } return nil } public func update(with newFetechedEntity: ContactEntity) { let entity = newFetechedEntity self.firstName = entity.firstName self.lastName = entity.lastName } }
23.625
108
0.70172
1e4394ba25f593496349495754d31f71b5de5f7c
10,304
// // CFAlertActionSheetInteractiveTransition.swift // CFAlertViewControllerDemo // // Created by Shivam Bhalla on 1/20/17. // Copyright © 2017 Codigami Inc. All rights reserved. // import UIKit class CFAlertActionSheetInteractiveTransition: CFAlertBaseInteractiveTransition { // MARK: - Initialisation Methods public override init(modalViewController: UIViewController, swipeGestureView: UIView?, contentScrollView: UIScrollView?) { super.init(modalViewController: modalViewController, swipeGestureView: swipeGestureView, contentScrollView: contentScrollView) } // MARK: - Override Methods public override func classForGestureRecognizer() -> CFAlertBaseTransitionGestureRecognizer.Type { return CFAlertActionSheetTransitionGestureRecognizer.self } public override func updateUIState(transitionContext: UIViewControllerContextTransitioning, percentComplete: CGFloat, transitionType: CFAlertTransitionType) { // Call Super Methods super.updateUIState(transitionContext: transitionContext, percentComplete: percentComplete, transitionType: transitionType) // Validation var currentPercentage = percentComplete if currentPercentage < 0.0 { currentPercentage = 0.0 } else if currentPercentage > 1.0 { currentPercentage = 1.0 } // Grab the from and to view controllers from the context // let duration = transitionDuration(using: transitionContext) // let containerView = transitionContext.containerView let fromViewController = transitionContext.viewController(forKey: .from) let toViewController = transitionContext.viewController(forKey: .to) var viewController : UIViewController? if transitionType == .present { viewController = toViewController } else { viewController = fromViewController } if let alertViewController = viewController as? CFAlertViewController, let alertContainerView = alertViewController.containerView { // Get Safe Area Bottom Inset var safeAreaTopInset : CGFloat = 0.0 var safeAreaBottomInset : CGFloat = 0.0 if #available(iOS 11.0, *) { safeAreaTopInset = alertViewController.view.safeAreaInsets.top safeAreaBottomInset = alertViewController.view.safeAreaInsets.bottom } // Slide Container View let startY = alertViewController.view.frame.size.height - safeAreaTopInset - alertContainerView.frame.size.height - 10 - safeAreaBottomInset let endY = alertViewController.view.frame.size.height - safeAreaBottomInset let currentTopOffset = CFAlertBaseInteractiveTransition.valueBetween(start: startY, andEnd: endY, forProgress: (1.0-currentPercentage)) alertContainerView.frame = CGRect(x: alertContainerView.frame.origin.x, y: currentTopOffset, width: alertContainerView.frame.size.width, height: alertContainerView.frame.size.height) // Fade background View if alertViewController.backgroundStyle == .blur { alertViewController.backgroundBlurView?.alpha = currentPercentage } alertViewController.backgroundColorView?.alpha = currentPercentage } } } extension CFAlertActionSheetInteractiveTransition { // MARK: Pan Gesture Handle Methods @objc override public func handlePan(_ recognizer: UIPanGestureRecognizer) { // Location reference var location = recognizer.location(in: swipeGestureView?.window) if let recognizerView = recognizer.view { location = location.applying(recognizerView.transform.inverted()) } // Velocity reference var velocity = recognizer.velocity(in: swipeGestureView?.window) if let recognizerView = recognizer.view { velocity = velocity.applying(recognizerView.transform.inverted()) } if recognizer.state == .began { isInteracting = true panStartLocation = location modalViewController?.dismiss(animated: true, completion: nil) } else if recognizer.state == .changed { if let alertViewController = modalViewController as? CFAlertViewController, let alertContainerView = alertViewController.containerView, let panStartLocation = panStartLocation { // Get Safe Area Bottom Inset var safeAreaBottomInset : CGFloat = 0.0 if #available(iOS 11.0, *) { safeAreaBottomInset = alertViewController.view.safeAreaInsets.bottom } let animationRatio = (location.y - panStartLocation.y) / (alertContainerView.bounds.height + 10 + safeAreaBottomInset) update(animationRatio) } } else if recognizer.state == .ended { if velocity.y > 100.0 { finish() } else { cancel() } isInteracting = false } } } // MARK: - UIViewControllerAnimatedTransitioning extension CFAlertActionSheetInteractiveTransition { public override func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return transitionDuration } public override func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { // Get context vars let duration: TimeInterval = transitionDuration(using: transitionContext) let containerView: UIView? = transitionContext.containerView let fromViewController: UIViewController? = transitionContext.viewController(forKey: .from) let toViewController: UIViewController? = transitionContext.viewController(forKey: .to) // Call Will System Methods fromViewController?.beginAppearanceTransition(false, animated: true) toViewController?.beginAppearanceTransition(true, animated: true) if transitionType == .present { /** SHOW ANIMATION **/ if let alertViewController = toViewController as? CFAlertViewController, let containerView = containerView { alertViewController.view?.frame = containerView.frame alertViewController.view?.autoresizingMask = [.flexibleWidth, .flexibleHeight] alertViewController.view?.translatesAutoresizingMaskIntoConstraints = true containerView.addSubview(alertViewController.view) alertViewController.view?.layoutIfNeeded() var frame: CGRect? = alertViewController.containerView?.frame frame?.origin.y = containerView.frame.size.height alertViewController.containerView?.frame = frame! // Background if alertViewController.backgroundStyle == .blur { alertViewController.backgroundBlurView?.alpha = 0.0 } alertViewController.backgroundColorView?.alpha = 0.0 // Animate height changes UIView.animate(withDuration: duration, delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.0, options: [.curveEaseIn, .beginFromCurrentState], animations: {() -> Void in self.updateUIState(transitionContext: transitionContext, percentComplete: 1.0, transitionType: .present) }, completion: {(_ finished: Bool) -> Void in // Call Did System Methods toViewController?.endAppearanceTransition() fromViewController?.endAppearanceTransition() // Declare Animation Finished transitionContext.completeTransition(!transitionContext.transitionWasCancelled) }) } else { // Call Did System Methods toViewController?.endAppearanceTransition() fromViewController?.endAppearanceTransition() // Declare Animation Finished transitionContext.completeTransition(!transitionContext.transitionWasCancelled) } } else if transitionType == .dismiss { /** HIDE ANIMATION **/ // Animate height changes UIView.animate(withDuration: duration, delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.0, options: [.curveEaseIn, .beginFromCurrentState], animations: {() -> Void in self.updateUIState(transitionContext: transitionContext, percentComplete: 0.0, transitionType: .dismiss) }, completion: {(_ finished: Bool) -> Void in // Call Did System Methods toViewController?.endAppearanceTransition() fromViewController?.endAppearanceTransition() // Declare Animation Finished transitionContext.completeTransition(!transitionContext.transitionWasCancelled) }) } } }
44.413793
199
0.586471
03929c4672e93fae63b89d4bb9df6ec837373bda
505
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck lazy } func m<u>() -> (u, u -> u) -> u { p o p.s = { } { u) { o } } s m { } class p: mass func s {} s p {
22.954545
79
0.673267
26751a8c8513770aaa918f1216006cc527ad9a62
647
// // ElementInteraction.swift // Skylark // // Created by Ross Butler on 3/3/19. // import Foundation struct ElementInteraction: Codable { typealias InteractionType = ElementInteractionType let action: InteractionType let element: Element.Identifier init(action: InteractionType, element: Element.Identifier) { self.action = action self.element = element } } extension ElementInteraction: Equatable { public static func == (lhs: ElementInteraction, rhs: ElementInteraction) -> Bool { return lhs.element == rhs.element && lhs.action.rawValue == rhs.action.rawValue } }
22.310345
87
0.680062
50d8a2fc3f2fd6cc1d59b8760cba00b0a3831722
403
//: [< Sommaire](Sommaire) /*: # Gestion des erreurs --- ### Maxime Britto - Swift 4 */ import Foundation let url = URL(string: "http://www.addpple.fr")! if let contenuHTML = try? String(contentsOf: url) { print(contenuHTML) } do { let contenuHTML = try String(contentsOf:url) print(contenuHTML) } catch let error as NSError { print(error) } /*: [< Sommaire](Sommaire) */
13.433333
51
0.630273
26e1f4b50b3c02d69109de63f7d4e7edc6e05b81
3,558
/* * Copyright IBM Corp. 2017 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import UIKit import GPSDK class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var resultLabel: UILabel! @IBOutlet weak var mixOne: UIPickerView! @IBOutlet weak var mixTwo: UIPickerView! @IBOutlet weak var mixButton: UIButton! let gp = GPService() func get(key: String) -> String { return gp.localizedString(key, nil) } func get(color: Color) -> String { return get(key: color.simpleDescription()) } override func viewDidLoad() { super.viewDidLoad() resultLabel.text = "Loading…" do { try gp.initService(url: ReaderCredentials.url, instanceId: ReaderCredentials.instanceId, bundleId: ReaderCredentials.bundleId, userId: ReaderCredentials.userId, password: ReaderCredentials.password, languageId:nil, alwaysLoadFromServer: false, expireAfter: 0) // set up strings titleLabel.text = get(key: "title") mixButton.setTitle(get(key: "mix"), for: UIControlState.normal) mixButton.titleLabel?.text = get(key: "mix") resultLabel.text = "" // clear this } catch GPService.GPError.languageNotSupported { resultLabel.text = ("This language is not supported...") } catch GPService.GPError.requestServerError(let errorDescription) { resultLabel.text = ("Request server error: " + errorDescription) } catch GPService.GPError.HTTPError(let statusCode) { resultLabel.text = ("Request server error: HTTP \(statusCode)") } catch { resultLabel.text = ("Other error") } } @IBAction func doMix(_ sender: Any) { let color1 = primaryColors[mixOne.selectedRow(inComponent: 0)] let color2 = primaryColors[mixTwo.selectedRow(inComponent: 0)] let newColor = color1.mix(with: color2) resultLabel.text = get(color: newColor) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // pickerview stuff func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1; } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return 3; } let primaryColors = [ Color.red, Color.blue, Color.yellow ] func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return get(color: primaryColors[row]) } }
35.58
111
0.606521
f5b94faec1926967715d018f43babc8711d49ed5
1,110
// // FooterKey.swift // Refresh // // Created by Gesen on 2020/3/22. // https://github.com/wxxsw/Refresh import SwiftUI @available(iOS 13.0, *) extension EnvironmentValues { var refreshFooterUpdate: Refresh.FooterUpdateKey.Value { get { self[Refresh.FooterUpdateKey.self] } set { self[Refresh.FooterUpdateKey.self] = newValue } } } @available(iOS 13.0, *) extension Refresh { enum FooterAnchorKey { static var defaultValue: Value = [] } enum FooterUpdateKey { static var defaultValue: Value = .init(enable: false) } } @available(iOS 13.0, *) extension Refresh.FooterAnchorKey: PreferenceKey { typealias Value = [Item] struct Item { let bounds: Anchor<CGRect> let preloadOffset: CGFloat let refreshing: Bool } static func reduce(value: inout Value, nextValue: () -> Value) { value.append(contentsOf: nextValue()) } } @available(iOS 13.0, *) extension Refresh.FooterUpdateKey: EnvironmentKey { struct Value: Equatable { let enable: Bool var refresh: Bool = false } }
21.764706
68
0.646847
d6e47792624b41a6ddbc297ab7246bc5472f8fe5
1,568
// // KeychainCreator.swift // StandUp-iOS // // Created by Peter on 12/01/19. // Copyright © 2019 BlockchainCommons. All rights reserved. // import Foundation import LibWally class KeychainCreator { func createKeyChain(completion: @escaping ((mnemonic: String?, error: Bool)) -> Void) { let bytesCount = 16 var randomBytes = [UInt8](repeating: 0, count: bytesCount) let status = SecRandomCopyBytes(kSecRandomDefault, bytesCount, &randomBytes) if status == errSecSuccess { let data = Data(randomBytes) let hex = data.hexString if let entropy = BIP39Entropy(hex) { if let mnemonic = BIP39Mnemonic.init(entropy) { var words = (mnemonic.words.description).replacingOccurrences(of: "\"", with: "") words = words.replacingOccurrences(of: ",", with: "") words = words.replacingOccurrences(of: "[", with: "") words = words.replacingOccurrences(of: "]", with: "") completion((words,false)) } else { completion((nil,true)) } } else { completion((nil,true)) } } else { completion((nil,true)) } } }
28
101
0.453444
265d273818d4e10279575e5e8ca51fc4a1559278
10,218
// // MultiLineChartData.swift // // // Created by Will Dale on 24/01/2021. // import SwiftUI import Combine /** Data for drawing and styling a multi line, line chart. This model contains all the data and styling information for a single line, line chart. */ public final class MultiLineChartData: CTLineChartDataProtocol, GetDataProtocol, Publishable, PointOfInterestProtocol { // MARK: Properties public let id: UUID = UUID() @Published public final var dataSets: MultiLineDataSet @Published public final var metadata: ChartMetadata @Published public final var xAxisLabels: [String]? @Published public final var yAxisLabels: [String]? @Published public final var chartStyle: LineChartStyle @Published public final var legends: [LegendData] @Published public final var viewData: ChartViewData @Published public final var infoView: InfoViewData<LineChartDataPoint> = InfoViewData() public final var noDataText: Text public final var chartType: (chartType: ChartType, dataSetType: DataSetType) @Published public final var extraLineData: ExtraLineData! // Publishable public var subscription = SubscriptionSet().subscription public let touchedDataPointPublisher = PassthroughSubject<DataPoint,Never>() // MARK: Initializers /// Initialises a Multi Line Chart. /// /// - Parameters: /// - dataSets: Data to draw and style the lines. /// - metadata: Data model containing the charts Title, Subtitle and the Title for Legend. /// - xAxisLabels: Labels for the X axis instead of the labels in the data points. /// - yAxisLabels: Labels for the Y axis instead of the labels generated from data point values. /// - chartStyle: The style data for the aesthetic of the chart. /// - noDataText: Customisable Text to display when where is not enough data to draw the chart. public init( dataSets: MultiLineDataSet, metadata: ChartMetadata = ChartMetadata(), xAxisLabels: [String]? = nil, yAxisLabels: [String]? = nil, chartStyle: LineChartStyle = LineChartStyle(), noDataText: Text = Text("No Data") ) { self.dataSets = dataSets self.metadata = metadata self.xAxisLabels = xAxisLabels self.yAxisLabels = yAxisLabels self.chartStyle = chartStyle self.noDataText = noDataText self.legends = [LegendData]() self.viewData = ChartViewData() self.chartType = (.line, .multi) self.setupLegends() } // MARK: Labels public final func getXAxisLabels() -> some View { Group { switch self.chartStyle.xAxisLabelsFrom { case .dataPoint(let angle): HStack(spacing: 0) { ForEach(dataSets.dataSets[0].dataPoints) { data in VStack { if self.chartStyle.xAxisLabelPosition == .bottom { RotatedText(chartData: self, label: data.wrappedXAxisLabel, rotation: angle) Spacer() } else { Spacer() RotatedText(chartData: self, label: data.wrappedXAxisLabel, rotation: angle) } } .frame(width: min(self.getXSection(dataSet: self.dataSets.dataSets[0], chartSize: self.viewData.chartSize), self.viewData.xAxislabelWidths.min() ?? 0), height: self.viewData.xAxisLabelHeights.max()) if data != self.dataSets.dataSets[0].dataPoints[self.dataSets.dataSets[0].dataPoints.count - 1] { Spacer() .frame(minWidth: 0, maxWidth: 500) } } } case .chartData(let angle): if let labelArray = self.xAxisLabels { HStack(spacing: 0) { ForEach(labelArray.indices, id: \.self) { i in VStack { if self.chartStyle.xAxisLabelPosition == .bottom { RotatedText(chartData: self, label: labelArray[i], rotation: angle) Spacer() } else { Spacer() RotatedText(chartData: self, label: labelArray[i], rotation: angle) } } .frame(width: self.viewData.xAxislabelWidths.min(), height: self.viewData.xAxisLabelHeights.max()) if i != labelArray.count - 1 { Spacer() .frame(minWidth: 0, maxWidth: 500) } } } } } } } private final func getXSection(dataSet: LineDataSet, chartSize: CGRect) -> CGFloat { chartSize.width / CGFloat(dataSet.dataPoints.count) } // MARK: Points public final func getPointMarker() -> some View { ForEach(self.dataSets.dataSets, id: \.id) { dataSet in PointsSubView(dataSets: dataSet, minValue: self.minValue, range: self.range, animation: self.chartStyle.globalAnimation, isFilled: false) } } public final func getTouchInteraction(touchLocation: CGPoint, chartSize: CGRect) -> some View { ZStack { ForEach(self.dataSets.dataSets, id: \.id) { dataSet in self.markerSubView(dataSet: dataSet, dataPoints: dataSet.dataPoints, lineType: dataSet.style.lineType, touchLocation: touchLocation, chartSize: chartSize) } self.extraLineData?.getTouchInteraction(touchLocation: touchLocation, chartSize: chartSize) } } // MARK: Accessibility public func getAccessibility() -> some View { ForEach(self.dataSets.dataSets, id: \.self) { dataSet in ForEach(dataSet.dataPoints.indices, id: \.self) { point in AccessibilityRectangle(dataPointCount: dataSet.dataPoints.count, dataPointNo: point) .foregroundColor(Color(.gray).opacity(0.000000001)) .accessibilityLabel(LocalizedStringKey(self.metadata.title)) .accessibilityValue(dataSet.dataPoints[point].getCellAccessibilityValue(specifier: self.infoView.touchSpecifier)) } } } public typealias SetType = MultiLineDataSet public typealias DataPoint = LineChartDataPoint public typealias CTStyle = LineChartStyle } // MARK: - Touch extension MultiLineChartData { public func getPointLocation(dataSet: LineDataSet, touchLocation: CGPoint, chartSize: CGRect) -> CGPoint? { let minValue: Double = self.minValue let range: Double = self.range let xSection: CGFloat = chartSize.width / CGFloat(dataSet.dataPoints.count - 1) let ySection: CGFloat = chartSize.height / CGFloat(range) let index: Int = Int((touchLocation.x + (xSection / 2)) / xSection) if index >= 0 && index < dataSet.dataPoints.count { if !dataSet.style.ignoreZero { return CGPoint(x: CGFloat(index) * xSection, y: (CGFloat(dataSet.dataPoints[index].value - minValue) * -ySection) + chartSize.height) } else { if dataSet.dataPoints[index].value != 0 { return CGPoint(x: CGFloat(index) * xSection, y: (CGFloat(dataSet.dataPoints[index].value - minValue) * -ySection) + chartSize.height) } } } return nil } public func getDataPoint(touchLocation: CGPoint, chartSize: CGRect) { self.infoView.touchOverlayInfo = dataSets.dataSets.indices.compactMap { setIndex in let xSection: CGFloat = chartSize.width / CGFloat(dataSets.dataSets[setIndex].dataPoints.count - 1) let index = Int((touchLocation.x + (xSection / 2)) / xSection) if index >= 0 && index < dataSets.dataSets[setIndex].dataPoints.count { if let data = self.extraLineData, let point = data.getDataPoint(touchLocation: touchLocation, chartSize: chartSize) { var dp = LineChartDataPoint(value: point.value, xAxisLabel: point.pointDescription, description: point.pointDescription) dp.legendTag = data.legendTitle self.infoView.touchOverlayInfo.append(dp) } touchedDataPointPublisher.send(dataSets.dataSets[setIndex].dataPoints[index]) if !dataSets.dataSets[setIndex].style.ignoreZero { dataSets.dataSets[setIndex].dataPoints[index].legendTag = dataSets.dataSets[setIndex].legendTitle return dataSets.dataSets[setIndex].dataPoints[index] } else { if dataSets.dataSets[setIndex].dataPoints[index].value != 0 { dataSets.dataSets[setIndex].dataPoints[index].legendTag = dataSets.dataSets[setIndex].legendTitle return dataSets.dataSets[setIndex].dataPoints[index] } else { dataSets.dataSets[setIndex].dataPoints[index].legendTag = dataSets.dataSets[setIndex].legendTitle dataSets.dataSets[setIndex].dataPoints[index].ignoreMe = true return dataSets.dataSets[setIndex].dataPoints[index] } } } return nil } } }
46.445455
175
0.56146
67f7db629e55b7ce5e763ede0e1647ec1d05c1de
3,929
// // Todo+Networking.swift // grokRouter // // Created by Christina Moulton on 2018-03-28. // Copyright © 2018 Christina Moulton. All rights reserved. // import Foundation import Alamofire enum BackendError: Error { case parsing(reason: String) case urlError(reason: String) } struct CreateTodoResult: Codable { var id: Int } extension Todo { static func todoByID(id: Int, completionHandler: @escaping (Result<Todo>) -> Void) { Alamofire.request(TodoRouter.get(id)) .responseData { response in let result = Todo.todoFromCodableResponse(response) completionHandler(result) } } func save(completionHandler: @escaping (Result<Int>) -> Void) { let encoder = JSONEncoder() do { let newTodoAsJSONData = try encoder.encode(self) Alamofire.request(TodoRouter.create(newTodoAsJSONData)) .responseData { response in guard response.result.error == nil else { // got an error in getting the data, need to handle it print(response.result.error!) completionHandler(.failure(response.result.error!)) return } // make sure we got JSON and it's a dictionary guard let responseData = response.result.value else { print("didn't get JSON data from API") completionHandler(.failure(BackendError.parsing(reason: "Did not get JSON data in response"))) return } let decoder = JSONDecoder() do { let createResult = try decoder.decode(CreateTodoResult.self, from: responseData) completionHandler(.success(createResult.id)) } catch { print("error parsing response from POST on /todos") print(error) completionHandler(.failure(error)) } } } catch { print(error) completionHandler(.failure(error)) } } private static func todoFromCodableResponse(_ response: DataResponse<Data>) -> Result<Todo> { guard response.result.error == nil else { // got an error in getting the data, need to handle it print(response.result.error!) return .failure(response.result.error!) } // make sure we got JSON and it's a dictionary guard let responseData = response.result.value else { print("didn't get any data from API") return .failure(BackendError.parsing(reason: "Did not get data in response")) } // turn data into Todo let decoder = JSONDecoder() do { let todo = try decoder.decode(Todo.self, from: responseData) return .success(todo) } catch { print("error trying to convert data to JSON") print(error) return .failure(error) } } static func allTodos(completionHandler: @escaping (Result<[Todo]>) -> Void) { Alamofire.request(TodoRouter.getAll) .responseData { response in let decoder = JSONDecoder() completionHandler(decoder.decodeResponse([Todo].self, from: response)) } } private static func todosFromCodableResponse(_ response: DataResponse<Data>) -> Result<[Todo]> { guard response.result.error == nil else { // got an error in getting the data, need to handle it print(response.result.error!) return .failure(response.result.error!) } // make sure we got JSON and it's a dictionary guard let responseData = response.result.value else { print("didn't get any data from API") return .failure(BackendError.parsing(reason: "Did not get data in response")) } // turn data into Todo let decoder = JSONDecoder() do { let todos = try decoder.decode([Todo].self, from: responseData) return .success(todos) } catch { print("error trying to convert data to JSON") print(error) return .failure(error) } } }
30.937008
98
0.63044
03408dff7c805aa70359d4b92292a55ef33b58e5
3,011
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). guard let _ = (scene as? UIWindowScene) else { return } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
46.323077
147
0.726005
7247a6a6c585ac9f9b43a94ecead34c39d56bf32
240
// // DetailsRouterInput.swift // SwinjectDependencyInjection // // Created by Igor Kotkovets on 12/24/16. // Copyright © 2016 Igor Kotkovets. All rights reserved. // import Foundation protocol DetailsRouterInput { func close() }
17.142857
57
0.725
5baa5b1a34c8cd7b87848aa9ef82dc8a7ced96cd
204
// // Clock.swift // VIPER-SWIFT // // Created by Conrad Stoll on 6/4/14. // Copyright (c) 2014 Mutual Mobile. All rights reserved. // import Foundation protocol Clock { func today() -> NSDate }
15.692308
58
0.651961
3963ce7399893e5dbe9efecb878f81b78034e227
4,708
// // MainViewController.swift // DaangnMarketStyleApp // // Created by 윤병일 on 2021/12/23. // import UIKit import RxSwift import RxCocoa import SnapKit class MainViewController : UIViewController { //MARK: - Properties let disposeBag = DisposeBag() let tableView = UITableView() let submitButton = UIBarButtonItem() //MARK: - Init override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) attribute() layout() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK: - Functions func bind(_ viewModel : MainViewModel) { // ViewModel 에서 View 로 전달되는거 먼저 viewModel.cellData .drive(tableView.rx.items) { tableView, row, data in switch row { case 0 : let cell = tableView.dequeueReusableCell(withIdentifier: TitleTextFieldCell.identifier, for: IndexPath(row: row, section: 0)) as! TitleTextFieldCell cell.selectionStyle = .none cell.titleInputField.placeholder = data cell.bind(viewModel.titleTextFieldCellViewModel) return cell case 1 : let cell = tableView.dequeueReusableCell(withIdentifier: "CategorySelectCell", for: IndexPath(row: row, section: 0)) cell.selectionStyle = .none cell.textLabel?.text = data cell.accessoryType = .disclosureIndicator return cell case 2 : let cell = tableView.dequeueReusableCell(withIdentifier: PriceTextFieldCell.identifier, for: IndexPath(row: row, section: 0)) as! PriceTextFieldCell cell.selectionStyle = .none cell.priceInputField.placeholder = data cell.bind(viewModel.priceTextFieldCellViewModel) return cell case 3 : let cell = tableView.dequeueReusableCell(withIdentifier: DetailWriteFormCell.identifier, for: IndexPath(row: row, section: 0)) as! DetailWriteFormCell cell.selectionStyle = .none cell.contentInputView.text = data cell.bind(viewModel.detailWriteFormCellViewModel) return cell default : fatalError() } }.disposed(by: self.disposeBag) viewModel.presentAlert .emit(to: self.rx.setAlert) .disposed(by: self.disposeBag) viewModel.push .drive(onNext: { viewModel in let viewController = CategoryListViewController() viewController.bind(viewModel) self.show(viewController, sender: nil) }).disposed(by: self.disposeBag) // View 에서 ViewModel 로 전달 tableView.rx.itemSelected .map { $0.row } .bind(to: viewModel.itemSelected) .disposed(by: self.disposeBag) submitButton.rx.tap .bind(to: viewModel.submitButtonTapped) .disposed(by: self.disposeBag) } private func attribute() { title = "중고거래 글쓰기" view.backgroundColor = .white self.submitButton.title = "제출" self.submitButton.style = .done UINavigationBar.appearance().tintColor = UIColor.black // 제출 버튼 색 변경 UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor : UIColor.black] // 네비 타이틀 색 변경 self.navigationItem.setRightBarButton(submitButton, animated: true) self.tableView.backgroundColor = .white self.tableView.separatorStyle = .singleLine self.tableView.tableFooterView = UIView() self.tableView.register(TitleTextFieldCell.self, forCellReuseIdentifier: TitleTextFieldCell.identifier) // index row 0 self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "CategorySelectCell") // index row 1 self.tableView.register(PriceTextFieldCell.self, forCellReuseIdentifier: PriceTextFieldCell.identifier) // index row 2 self.tableView.register(DetailWriteFormCell.self, forCellReuseIdentifier: DetailWriteFormCell.identifier) // index row 3 } private func layout() { view.addSubview(tableView) tableView.snp.makeConstraints { $0.edges.equalToSuperview() } } } typealias Alert = (title : String, message : String?) //MARK: - Reactive Extension extension Reactive where Base : MainViewController { var setAlert : Binder<Alert> { return Binder(base) { base, data in // base 는 MainViewController, data 는 Alert안에 있는 정보 let alertController = UIAlertController(title: data.title, message: data.message, preferredStyle: .alert) let action = UIAlertAction(title: "확인", style: .cancel, handler: nil) alertController.addAction(action) base.present(alertController, animated: true, completion: nil) } } }
35.134328
160
0.684792
0ec4e56155fff95e0b0817567ef2c4b671c8081f
236
// // File.swift // // // Created by Виталий Зарубин on 31.01.2022. // import Foundation struct Samsung: IPhone { var cpu: ICPU = Snapdragon() func call() { print("\(cpu.work()) -> call samsung") } }
13.111111
46
0.542373
7168c9896afd859dae285fcbc38eabba0517c09a
8,188
// // NSHTTPURLResponse+Utility.swift // swiftlets // // Created by Frank Vernon on 6/27/16. // Copyright © 2016 Frank Vernon. All rights reserved. // import Foundation /** Enumeration of HTTP result values categorized by class of status code. This is useful in processing results of web service calls, for example. ```` switch responseStatus { case .success: //happy path case .serverError(let serverStatus): switch serverStatus { case .internalServerError: //blame them case .notImplemented: //blame me default: //blame everyone } default: //what now? } ```` */ public enum HTTPURLReponseStatus { public enum informationalStatus: Int { case continuing = 100 case switchingProtocols = 101 case processing = 102 case checkpoint = 103 } public enum successStatus: Int { case ok = 200 case created = 201 case accepted = 202 case nonAuthoritative = 203 case noContent = 204 case resetContent = 205 case partialContent = 206 case multiStatus = 207 case alreadyReported = 208 case imUsed = 226 //test most common case var isOK: Bool { get { self == .ok } } } public enum redirectionSatus: Int { case multipleChoices = 300 case movedPermanently = 301 case found = 302 case seeOther = 303 case notModified = 304 case useProxy = 305 case switchProxy = 306 case temporaryRedirect = 307 case permanentRedirect = 308 } public enum clientErrorStatus: Int { case badRequest = 400 case unauthorized = 401 case paymentRequired = 402 case forbidden = 403 case notFound = 404 case methodNotAllowed = 405 case notAcceptable = 406 case proxyAuthenticationRequired = 407 case requestTimeout = 408 case conflict = 409 case gone = 410 case lengthRequired = 411 case preconditionFailed = 412 case payloadTooLarge = 413 case uriTooLong = 414 case unsupportedMediaType = 415 case rangeNotSatisfiable = 416 case expectationFailed = 417 case imATeapot = 418 case imAFox = 419 case enhanceYourCalm = 420 case misdirectedRequest = 421 case unprocessableEntity = 422 case locked = 423 case failedDependency = 424 case upgradeRequired = 426 case preconditionRequired = 428 case tooManyRequests = 429 case requestHeaderFieldsTooLarge = 431 case loginTimeout = 440 case noResponse = 444 case retryWith = 449 case unavailableForLegalReasons = 451 case sslCertificateError = 495 case sslCertificateRequired = 496 case httpRequestSentToHTTPSPort = 497 case invalidToken = 498 case tokenRequired = 499 } public enum serverErrorStatus: Int { case internalServerError = 500 case notImplemented = 501 case badGateway = 502 case serviceUnavailable = 503 case gatewayTimeout = 504 case httpVersionNotSupported = 505 case variantAlsoNegotiates = 506 case insufficientStorage = 507 case loopDetected = 508 case bandwidthLimitExceeded = 509 case notExtended = 510 case networkAuthenticationRequired = 511 case unknownError = 520 case webServerIsDown = 521 case connectionTimedOut = 522 case originIsUnreachable = 523 case timeoutOccurred = 524 case sslHandshakeFailed = 525 case invalidSSLCertificate = 526 case railgunError = 527 case siteIsFrozen = 530 var isInternalServerError: Bool { get { self == .internalServerError } } } case informational(informationalStatus) case success(successStatus) case redirection(redirectionSatus) case clientError(clientErrorStatus) case serverError(serverErrorStatus) case unknown(Int) init(statusCode: Int) { //default to unknown in the event parsing below fails to categorize the status code self = .unknown(statusCode) switch statusCode { case 100..<200: if let info = informationalStatus(rawValue: statusCode) { self = .informational(info) } case 200..<300: if let success = successStatus(rawValue: statusCode) { self = .success(success) } case 300..<400: if let redirect = redirectionSatus(rawValue: statusCode) { self = .redirection(redirect) } case 400..<500: if let clientError = clientErrorStatus(rawValue: statusCode) { self = .clientError(clientError) } case 500..<600: if let serverError = serverErrorStatus(rawValue: statusCode) { self = .serverError(serverError) } default: //set to .unknown handled above break } } func isSuccess() -> Bool { switch self { case .success: return true default: return false } } func isSuccessOK() -> Bool { switch self { case .success(let value): return value.isOK default: return false } } } //Extension of HTTPURLResponse to return custom response status enum public extension HTTPURLResponse { var status:HTTPURLReponseStatus { HTTPURLReponseStatus(statusCode: statusCode) } } //Extension of StringInterpolation to return localized strings for HTTPURLReponseStatus values extension String.StringInterpolation { mutating func appendInterpolation(_ status: HTTPURLReponseStatus.successStatus) { let localized = HTTPURLResponse.localizedString(forStatusCode: status.rawValue); appendInterpolation(localized) } mutating func appendInterpolation(_ status: HTTPURLReponseStatus.informationalStatus) { let localized = HTTPURLResponse.localizedString(forStatusCode: status.rawValue); appendInterpolation(localized) } mutating func appendInterpolation(_ status: HTTPURLReponseStatus.redirectionSatus) { let localized = HTTPURLResponse.localizedString(forStatusCode: status.rawValue); appendInterpolation(localized) } mutating func appendInterpolation(_ status: HTTPURLReponseStatus.clientErrorStatus) { let localized = HTTPURLResponse.localizedString(forStatusCode: status.rawValue); appendInterpolation(localized) } mutating func appendInterpolation(_ status: HTTPURLReponseStatus.serverErrorStatus) { let localized = HTTPURLResponse.localizedString(forStatusCode: status.rawValue); appendInterpolation(localized) } mutating func appendInterpolation(_ httpResponse: HTTPURLReponseStatus) { switch httpResponse { case .informational(let informational): appendInterpolation("\(informational)") case .success(let success): appendInterpolation("\(success)") case .redirection(let redirection): appendInterpolation("\(redirection)") case .clientError(let clientError): appendInterpolation("\(clientError)") case .serverError(let serverError): appendInterpolation("\(serverError)") case .unknown(let unknown): appendInterpolation(HTTPURLResponse.localizedString(forStatusCode: unknown)) } } } //Extension to print localized error string HTTPURLResponse extension String.StringInterpolation { mutating func appendInterpolation(_ httpResponse: HTTPURLResponse) { let localized = HTTPURLResponse.localizedString(forStatusCode: httpResponse.statusCode); appendInterpolation(localized) } }
30.102941
96
0.629213
484ef6bdaa11cafab2da6d6f0941bd67b29e9026
2,290
@objc(MWMDiscoveryLocalExpertCell) final class DiscoveryLocalExpertCell: UICollectionViewCell { @IBOutlet private weak var avatar: UIImageView! @IBOutlet private weak var name: UILabel! @IBOutlet private weak var rating: RatingSummaryView! { didSet { rating.defaultConfig() rating.textFont = UIFont.bold12() rating.textSize = 12 } } @IBOutlet private weak var price: UIButton! private lazy var formatter: NumberFormatter = { let f = NumberFormatter() f.numberStyle = .currency return f }() typealias Tap = () -> () private var tap: Tap! override var isHighlighted: Bool { didSet { UIView.animate(withDuration: kDefaultAnimationDuration, delay: 0, options: [.allowUserInteraction, .beginFromCurrentState], animations: { self.alpha = self.isHighlighted ? 0.3 : 1 }, completion: nil) } } @objc func config(avatarURL: String, name: String, ratingValue: String, ratingType: MWMRatingSummaryViewValueType, price: Double, currency: String, tap: @escaping Tap) { if avatarURL.count > 0, let url = URL(string: avatarURL) { avatar.af_setImage(withURL: url, placeholderImage: #imageLiteral(resourceName: "img_localsdefault"), imageTransition: .crossDissolve(kDefaultAnimationDuration)) } else { avatar.image = #imageLiteral(resourceName: "img_localsdefault") } self.name.text = name rating.value = ratingValue rating.type = ratingType let str: String if currency.count > 0, let cur = stringFor(price: price, currencyCode: currency) { str = String(coreFormat: L("price_per_hour"), arguments:[cur]) } else { str = L("free") } self.price.setTitle(str, for: .normal) self.tap = tap } @IBAction private func tapOnPrice() { tap?() } private func stringFor(price: Double, currencyCode: String) -> String? { formatter.currencyCode = currencyCode return formatter.string(for: price) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) layer.borderColor = UIColor.blackDividers().cgColor } }
30.945946
166
0.632314
e4866b758ae6ad9d15e6da559668c6ee1f25961d
7,971
// // ContactsCellContentView.swift // MyMonero // // Created by Paul Shapiro on 6/15/17. // Copyright (c) 2014-2019, MyMonero.com // // 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 UIKit class ContactCellContentView: UIView { var emojiLabel: UILabel! var titleLabel: UILabel! var subtitleLabel: UILabel! // // Lifecycle - Init init() { super.init(frame: .zero) self.setup() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setup() { do { let view = UILabel() view.font = UIFont.systemFont(ofSize: 16) view.numberOfLines = 1 self.addSubview(view) self.emojiLabel = view } do { let view = UILabel() view.textColor = UIColor(rgb: 0xFCFBFC) view.font = UIFont.middlingSemiboldSansSerif view.numberOfLines = 1 view.lineBreakMode = .byTruncatingTail self.addSubview(view) self.titleLabel = view } do { let view = UILabel() view.textColor = UIColor(rgb: 0x9E9C9E) view.font = UIFont.middlingRegularMonospace view.numberOfLines = 1 view.lineBreakMode = .byTruncatingTail self.addSubview(view) self.subtitleLabel = view } } // // Lifecycle - Teardown/Reuse deinit { self.tearDown_object() } func tearDown_object() { if self.object != nil { self._stopObserving_object() self.object = nil } } func prepareForReuse() { self.tearDown_object() } func _stopObserving_object() { assert(self.object != nil) self.__stopObserving(specificObject: self.object!) } func _stopObserving(objectBeingDeinitialized object: Contact) { assert(self.object == nil) // special case - since it's a weak ref I expect self.object to actually be nil assert(self.hasStoppedObservingObject_forLastNonNilSetOfObject != true) // initial expectation at least - this might be able to be deleted // self.__stopObserving(specificObject: object) } func __stopObserving(specificObject object: Contact) { if self.hasStoppedObservingObject_forLastNonNilSetOfObject == true { // then we've already handled this DDLog.Warn("ContactsCellContentView", "Not redundantly calling stopObserving") return } self.hasStoppedObservingObject_forLastNonNilSetOfObject = true // must set to true so we can set back to false when object is set back to non-nil // NotificationCenter.default.removeObserver(self, name: Contact.NotificationNames.infoUpdated.notificationName, object: object) NotificationCenter.default.removeObserver(self, name: PersistableObject.NotificationNames.willBeDeleted.notificationName, object: object) NotificationCenter.default.removeObserver(self, name: PersistableObject.NotificationNames.willBeDeinitialized.notificationName, object: object) } // // Accessors // // Imperatives - Configuration weak var object: Contact? // prevent self from preventing object from being freed (so we still get .willBeDeinitialized) var hasStoppedObservingObject_forLastNonNilSetOfObject = true // I'm using this addtl state var which is not weak b/c object will be niled purely by virtue of it being freed by strong reference holders (other objects)… and I still need to call stopObserving on that object - while also not doing so redundantly - therefore this variable must be set back to false after self.object is set back to non-nil or possibly more rigorously, in startObserving func configure(withObject object: Contact) { if self.object != nil { self.prepareForReuse() // in case this is not being used in an actual UITableViewCell (which has a prepareForReuse) } assert(self.object == nil) self.object = object self._configureUI() self.startObserving_object() } func _configureUI() { assert(self.object != nil) if self.object!.didFailToInitialize_flag == true || self.object!.didFailToBoot_flag == true { // unlikely but possible self.emojiLabel.text = "❌" self.titleLabel.text = NSLocalizedString("Error: Contact Support", comment: "") self.subtitleLabel.text = self.object!.didFailToBoot_errStr ?? "" } else { self.emojiLabel.text = self.object!.emoji self.titleLabel.text = self.object!.fullname self.subtitleLabel.text = self.object!.address } } // func startObserving_object() { assert(self.object != nil) assert(self.hasStoppedObservingObject_forLastNonNilSetOfObject == true) // verify that it was reset back to false self.hasStoppedObservingObject_forLastNonNilSetOfObject = false // set to false so we make sure to stopObserving NotificationCenter.default.addObserver(self, selector: #selector(_infoUpdated), name: Contact.NotificationNames.infoUpdated.notificationName, object: self.object!) NotificationCenter.default.addObserver(self, selector: #selector(_willBeDeleted), name: PersistableObject.NotificationNames.willBeDeleted.notificationName, object: self.object!) NotificationCenter.default.addObserver(self, selector: #selector(_willBeDeinitialized(_:)), name: PersistableObject.NotificationNames.willBeDeinitialized.notificationName, object: self.object!) } // // Imperatives - Overrides override func layoutSubviews() { super.layoutSubviews() self.emojiLabel.frame = CGRect( x: 17, y: 15, width: 24, height: 25 ) let labels_x: CGFloat = 50 let labels_rightMargin: CGFloat = 40 let labels_width = self.frame.size.width - labels_x - labels_rightMargin self.titleLabel.frame = CGRect( x: labels_x, y: 19, width: labels_width, height: 16 // TODO: size with font for accessibility? ).integral self.subtitleLabel.frame = CGRect( x: labels_x, y: self.titleLabel.frame.origin.y + self.titleLabel.frame.size.height + 2, width: labels_width, height: 20 // TODO: size with font for accessibility? NOTE: must support emoji, currently, for locked icon ).integral } // // Delegation - Notifications @objc func _infoUpdated() { self._configureUI() } @objc func _willBeDeleted() { self.tearDown_object() // stop observing, release } @objc func _willBeDeinitialized(_ note: Notification) { // This obviously doesn't work for calling stopObserving on self.object --- because self.object is nil by the time we get here!! let objectBeingDeinitialized = note.userInfo![PersistableObject.NotificationUserInfoKeys.object.key] as! Contact self._stopObserving( // stopObserving specific object - self.object will be nil by now - but also call specific method for this as it has addtl check objectBeingDeinitialized: objectBeingDeinitialized ) } }
38.694175
451
0.752478
5beb63691737da0c0320e660a7c938f230484415
5,030
// // BooksListViewController.swift // BooksList // // Created by Andrey Konstantinov on 04/06/2017. // Copyright © 2017 8of. All rights reserved. // import UIKit final class BooksListViewController: UIViewController { fileprivate weak var output: BooksListViewOutput? fileprivate let collectionView: UICollectionView = { let layout = UICollectionViewFlowLayout() layout.scrollDirection = .vertical layout.minimumLineSpacing = Style.Size.padding layout.minimumInteritemSpacing = Style.Size.padding let view = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout) view.allowsSelection = false return view }() fileprivate let refreshControl = UIRefreshControl() init(output: BooksListViewOutput?) { super.init(nibName: nil, bundle: nil) self.output = output } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } private init() { super.init(nibName: nil, bundle: nil) } private override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } override func loadView() { view = UIView() view.backgroundColor = UIColor.white view.addSubview(collectionView) collectionView.backgroundColor = view.backgroundColor collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight] refreshControl.addTarget(self, action: #selector(reloadDataAction), for: .valueChanged) collectionView.addSubview(refreshControl) } override func viewDidLoad() { super.viewDidLoad() registerCells(for: collectionView) collectionView.dataSource = self collectionView.delegate = self output?.viewDidLoad() } // MARK: - Private private func registerCells(for collectionView: UICollectionView) { for type: UICollectionViewCell.Type in [BooksListMetadataItemCollectionViewCell.self, BooksListItemCollectionViewCell.self, LoadingListItemCollectionViewCell.self] { collectionView.register(type, forCellWithReuseIdentifier: String(describing: type)) } } // MARK: - Actions @objc private func reloadDataAction() { output?.reloadBooks() } } extension BooksListViewController: BooksListViewInput { func didRefreshBooks() { refreshControl.endRefreshing() collectionView.reloadData() } func appendBooks(at indexes: [IndexPath]) { refreshControl.endRefreshing() collectionView.performBatchUpdates( { self.collectionView.insertItems(at: indexes) }, completion: { _ in }) } } extension BooksListViewController: UICollectionViewDataSource, UICollectionViewDelegate { fileprivate enum BooksListSection: Int { case header case books case loading } func numberOfSections(in collectionView: UICollectionView) -> Int { return 3 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { guard let output = output else { return 0 } switch BooksListSection(rawValue: section)! { case .header: return (output.header() != nil) ? 1 : 0 case .books: return output.booksCount() case .loading: return 1 } } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let output = output else { return UICollectionViewCell() } switch BooksListSection.init(rawValue: indexPath.section)! { case .header: let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: BooksListMetadataItemCollectionViewCell.self), for: indexPath) as! BooksListMetadataItemCollectionViewCell if let header = output.header() { cell.set(header: header) } return cell case .books: let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: BooksListItemCollectionViewCell.self), for: indexPath) as! BooksListItemCollectionViewCell cell.set(book: output.book(at: indexPath.row)) return cell case .loading: return collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: LoadingListItemCollectionViewCell.self), for: indexPath) } } func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { guard let output = output else { return } if indexPath.section == BooksListSection.loading.rawValue { output.loadMoreBooks() } } } extension BooksListViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let height: CGFloat! switch BooksListSection(rawValue: indexPath.section)! { case .header: height = 200 case .books: height = 100 case .loading: height = 40 } return CGSize.init(width: collectionView.bounds.width, height: height) } }
30.670732
198
0.733002
46be5688a2ab1813b8393b2653ad1b87466e044f
338
//:## User Data import VisualRecognitionV3 let visualRecognition = setupVisualRecognitionV3() //:### Delete labeled data visualRecognition.deleteUserData(customerID: "my-customer-id") { _, error in if let error = error { print(error.localizedDescription) return } print("delete request submitted") }
17.789474
64
0.689349
dd87b24d7b6f615db0ba995641efa7e0794720f9
5,498
// // RSClient+Plugins.swift // RudderStack // // Created by Pallab Maiti on 24/02/22. // Copyright © 2021 Rudder Labs India Pvt Ltd. All rights reserved. // import Foundation extension RSClient { internal func addPlugins() { add(plugin: RSReplayQueuePlugin()) let logPlugin = RSLoggerPlugin() logPlugin.loggingEnabled(config?.logLevel != RSLogLevel.none) add(plugin: logPlugin) add(plugin: RSIntegrationPlugin()) add(plugin: RudderDestinationPlugin()) add(plugin: RSGDPRPlugin()) if let platformPlugins = platformPlugins() { for plugin in platformPlugins { add(plugin: plugin) } } setupServerConfigCheck() } internal func platformPlugins() -> [RSPlatformPlugin]? { var plugins = [RSPlatformPlugin]() plugins.append(RSContextPlugin()) plugins.append(RSIdentifyTraitsPlugin()) plugins.append(RSAliasIdPlugin()) plugins.append(RSUserIdPlugin()) plugins.append(RSAnonymousIdPlugin()) plugins.append(RSAppTrackingConsentPlugin()) plugins.append(RSAdvertisingIdPlugin()) plugins += Vendor.current.requiredPlugins if config?.trackLifecycleEvents == true { #if os(iOS) || os(tvOS) || targetEnvironment(macCatalyst) plugins.append(RSiOSLifecycleEvents()) #endif #if os(watchOS) plugins.append(RSwatchOSLifecycleEvents()) #endif #if os(macOS) plugins.append(RSmacOSLifecycleEvents()) #endif } if config?.recordScreenViews == true { #if os(iOS) || os(tvOS) || targetEnvironment(macCatalyst) plugins.append(RSiOSScreenViewEvents()) #endif #if os(watchOS) plugins.append(RSwatchOSScreenViewEvents()) #endif #if os(macOS) plugins.append(RSmacOSScreenViewEvents()) #endif } if plugins.isEmpty { return nil } else { return plugins } } } #if os(iOS) || os(tvOS) || targetEnvironment(macCatalyst) import UIKit extension RSClient { internal func setupServerConfigCheck() { checkServerConfig() NotificationCenter.default.addObserver(forName: UIApplication.willEnterForegroundNotification, object: nil, queue: OperationQueue.main) { (notification) in guard let app = notification.object as? UIApplication else { return } if app.applicationState == .background { self.checkServerConfig() } } } } #elseif os(watchOS) extension RSClient { internal func setupServerConfigCheck() { checkServerConfig() } } #elseif os(macOS) import Cocoa extension RSClient { internal func setupServerConfigCheck() { checkServerConfig() RSQueueTimer.schedule(interval: .days(1), queue: .main) { self.checkServerConfig() } } } #endif extension RSClient { func update(serverConfig: RSServerConfig, type: UpdateType) { apply { (plugin) in update(plugin: plugin, serverConfig: serverConfig, type: type) } } func update(plugin: RSPlugin, serverConfig: RSServerConfig, type: UpdateType) { plugin.update(serverConfig: serverConfig, type: type) if let dest = plugin as? RSDestinationPlugin { dest.apply { (subPlugin) in subPlugin.update(serverConfig: serverConfig, type: type) } } } func checkServerConfig() { var retryCount = 0 var isCompleted = false while !isCompleted && retryCount < 4 { if let serverConfig = fetchServerConfig() { self.serverConfig = serverConfig RSUserDefaults.saveServerConfig(serverConfig) RSUserDefaults.updateLastUpdatedTime(RSUtils.getTimeStamp()) log(message: "server config download successful", logLevel: .debug) isCompleted = true } else { if error?.code == RSErrorCode.WRONG_WRITE_KEY.rawValue { log(message: "Wrong write key", logLevel: .debug) retryCount = 4 } else { log(message: "Retrying download in \(retryCount) seconds", logLevel: .debug) retryCount += 1 sleep(UInt32(retryCount)) } } } if !isCompleted { log(message: "Server config download failed.Using last stored config from storage", logLevel: .debug) } } private func fetchServerConfig() -> RSServerConfig? { var serverConfig: RSServerConfig? let semaphore = DispatchSemaphore(value: 0) let serviceManager = RSServiceManager(client: self) serviceManager.downloadServerConfig { [weak self] result in guard let self = self else { return } switch result { case .success(let config): serverConfig = config self.update(serverConfig: config, type: .refresh) case .failure(let error): self.error = error } semaphore.signal() } semaphore.wait() return serverConfig } }
32.152047
163
0.580029
fced4dc35bef6ecbb2bec3a7fb87d440a0666c5f
2,030
// // HLSNative+ExposureContext+Creation.swift // Exposure // // Created by Fredrik Sjöberg on 2017-11-27. // Copyright © 2017 emp. All rights reserved. // import Foundation import Player import Exposure /// Extends `Player` using `HLSNative` tech in an `ExposureContext` with a convenience initializer extension Player where Tech == HLSNative<ExposureContext> { // MARK: Creation /// Convenience initializer that creates and configures `Player` for use with `HLSNative`, `ExposureContext`. /// /// Attaches `ExposureAnalytics` to deal with *Exposure* relaed analytics dispatch. /// /// - parameter environment: The *Exposure* environment /// - parameter sessionToken: Token identifying this session public convenience init(environment: Environment, sessionToken: SessionToken) { self.init(environment: environment, sessionToken: sessionToken, analytics: ExposureAnalytics.self) } /// Creates and configures `Player` for use with `HLSNative` and `ExposureContext`. /// /// - parameter environment: The *Exposure* environment /// - parameter sessionToken: Token identifying this session /// - parameter analytics: The *Exposure* related `AnalyticsProvider` tasked with delivering analytics to the *EMP* backend. public convenience init<Analytics: ExposureStreamingAnalyticsProvider>(environment: Environment, sessionToken: SessionToken, analytics: Analytics.Type, cdn: CDNInfoFromEntitlement? = nil , analyticsFromPlayback: AnalyticsFromEntitlement? = nil ) { let generator: (Tech.Context.Source?) -> AnalyticsProvider = { _ in return analytics.init(environment: environment, sessionToken: sessionToken, cdn: cdn, analytics: analyticsFromPlayback) } let context = ExposureContext(environment: environment, sessionToken: sessionToken) let tech = HLSNative<ExposureContext>() tech.airplayHandler = context context.analyticsGenerators.append(generator) self.init(tech: tech, context: context) } }
48.333333
251
0.733498
6412d588f3ccab8bdfcc1c7046aa639170e56705
2,803
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. import Foundation import azureSwiftRuntime internal struct ComputeNodeRebootHeadersData : ComputeNodeRebootHeadersProtocol { public var clientRequestId: String? public var requestId: String? public var eTag: String? public var lastModified: Date? public var dataServiceId: String? enum CodingKeys: String, CodingKey {case clientRequestId = "client-request-id" case requestId = "request-id" case eTag = "ETag" case lastModified = "Last-Modified" case dataServiceId = "DataServiceId" } public init() { } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) if container.contains(.clientRequestId) { self.clientRequestId = try container.decode(String?.self, forKey: .clientRequestId) } if container.contains(.requestId) { self.requestId = try container.decode(String?.self, forKey: .requestId) } if container.contains(.eTag) { self.eTag = try container.decode(String?.self, forKey: .eTag) } if container.contains(.lastModified) { self.lastModified = DateConverter.fromString(dateStr: (try container.decode(String?.self, forKey: .lastModified)), format: .dateTimeRfc1123) } if container.contains(.dataServiceId) { self.dataServiceId = try container.decode(String?.self, forKey: .dataServiceId) } if var pageDecoder = decoder as? PageDecoder { if pageDecoder.isPagedData, let nextLinkName = pageDecoder.nextLinkName { pageDecoder.nextLink = try UnknownCodingKey.decodeStringForKey(decoder: decoder, keyForDecode: nextLinkName) } } } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) if self.clientRequestId != nil {try container.encode(self.clientRequestId, forKey: .clientRequestId)} if self.requestId != nil {try container.encode(self.requestId, forKey: .requestId)} if self.eTag != nil {try container.encode(self.eTag, forKey: .eTag)} if self.lastModified != nil { try container.encode(DateConverter.toString(date: self.lastModified!, format: .dateTimeRfc1123), forKey: .lastModified) } if self.dataServiceId != nil {try container.encode(self.dataServiceId, forKey: .dataServiceId)} } } extension DataFactory { public static func createComputeNodeRebootHeadersProtocol() -> ComputeNodeRebootHeadersProtocol { return ComputeNodeRebootHeadersData() } }
42.469697
149
0.700321
de83c1f019c40660e506ab0778c0f353fece75da
2,489
// // SceneDelegate.swift // Assignment1 // // Created by Mohmed Master on 2021/02/10. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). guard let _ = (scene as? UIWindowScene) else { return } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. // Save changes in the application's managed object context when the application transitions to the background. (UIApplication.shared.delegate as? AppDelegate)?.saveContext() } }
44.446429
147
0.71595
38989d90bf24b0dffbf6011c028c3bc8f82c6e1d
2,526
import Foundation import StandardLibraries public struct Day7 { public init() {} public typealias Reducer = (Int, (Int, Int)) throws -> Int /* Each submarine has a horizontal position (puzzle input). Moving 1 step costs 1 fuel. What is the least amount of fuel required to align all submarines to the same position? */ public func part1(_ input: [Int]) -> Int { let sorted = input.sorted() let min = sorted.first! let max = sorted.last! var mini = Int.max for i in (min...max) { let result = input.reduce(0) { $0 + abs(i - $1) } if result < mini { mini = result } else { break } } return mini } public func part1b(_ input: [Int]) -> Int { let (dict, min, max) = reduce(input) var mini = Int.max for i in (min...max) { let result = dict.reduce(0) { $0 + abs(i - $1.0) * $1.1 } if result < mini { mini = result } else { break } } return mini } public func part2(_ input: [Int]) -> Int { let sorted = input.sorted() let min = sorted.first! let max = sorted.last! var mini = Int.max for i in (min...max) { let result = input.reduce(0) { let n = abs(i - $1) return $0 + (n * (n + 1) / 2) } if result < mini { mini = result } } return mini } public func part2b(_ input: [Int]) -> Int { let (dict, min, max) = reduce(input) var mini = Int.max for i in (min...max) { let result = dict.reduce(0) { let n = abs(i - $1.0) return $0 + (n * (n + 1) / 2) * $1.1 } if result < mini { mini = result } else { break } } return mini } public func reduce(_ input: [Int]) -> ([Int:Int], Int, Int) { var dict = [Int:Int]() var min = Int.max var max = 0 for i in input { dict[i] = dict[i, default: 0] + 1 if i < min { min = i } if i > max { max = i } } return (dict, min, max) } }
25.515152
177
0.41053
508a0bb6cbdebec5954a76c391d48db9c1ef7ec6
898
// // MinifyCSSTransform.swift // FilestackSDK // // Created by Ruben Nine on 13/08/2019. // Copyright © 2019 Filestack. All rights reserved. // import Foundation /** Minifies your CSS files. */ @objc(FSMinifyCSSTransform) public class MinifyCSSTransform: Transform { /** Initializes a `MinifyCSSTransform` object. */ @objc public init() { super.init(name: "minify_css") } /** Adds the `level` option. - Parameter value: Minification level. */ @objc @discardableResult public func level(_ value: Int) -> Self { return appending(key: "level", value: value) } /** Adds the `gzip` option. - Parameter value: Whether to compress file and add content encoding gzip header. */ @objc @discardableResult public func gzip(_ value: Bool) -> Self { return appending(key: "gzip", value: value) } }
22.45
86
0.632517
b91cbbecf40dea8dab37719bc5185a3c9f0b407d
1,580
// swift-tools-version:5.1 // // Package.swift // // Copyright (c) Ramotion Inc. (https://www.ramotion.com/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import PackageDescription let package = Package( name: "PreviewTransition", platforms: [ .iOS(.v9) ], products: [ .library(name: "PreviewTransition", targets: ["PreviewTransition"]), ], targets: [ .target(name: "PreviewTransition", path: "PreviewTransition") ], swiftLanguageVersions: [.v5] )
35.909091
81
0.703165
f50a74722a8b70f43a42b493695236f551e8a611
16,011
// // Script.swift // // Copyright © 2018 BitcoinKit developers // // 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 CryptoSwift public class Script { // An array of Data objects (pushing data) or UInt8 objects (containing opcodes) private var chunks: [ScriptChunk] // Cached serialized representations for -data and -string methods. private var dataCache: Data? private var stringCache: String? public var data: Data { // When we calculate data from scratch, it's important to respect actual offsets in the chunks as they may have been copied or shifted in subScript* methods. if let cache = dataCache { return cache } dataCache = chunks.reduce(Data()) { $0 + $1.chunkData } return dataCache! } public var string: String { if let cache = stringCache { return cache } stringCache = chunks.map { $0.string }.joined(separator: " ") return stringCache! } public var hex: String { return data.hex } public func toP2SH() -> Script { return try! Script() .append(.OP_HASH160) .appendData(RIPEMD160.hash(data.sha256())) .append(.OP_EQUAL) } // Multisignature script attribute. // If multisig script is not detected, this is nil public typealias MultisigVariables = (nSigRequired: UInt, publickeys: [PublicKey]) public var multisigRequirements: MultisigVariables? public init() { self.chunks = [ScriptChunk]() } public init(chunks: [ScriptChunk]) { self.chunks = chunks } public convenience init?(data: Data) { // It's important to keep around original data to correctly identify the size of the script for BTC_MAX_SCRIPT_SIZE check // and to correctly calculate hash for the signature because in BitcoinQT scripts are not re-serialized/canonicalized. do { let chunks = try Script.parseData(data) self.init(chunks: chunks) } catch let error { print(error) return nil } } public convenience init(hex: String) { self.init(data: Data(hex: hex))! } public convenience init?(address: Address) { self.init() switch address.type { case .pubkeyHash: // OP_DUP OP_HASH160 <hash> OP_EQUALVERIFY OP_CHECKSIG do { try self.append(.OP_DUP) .append(.OP_HASH160) .appendData(address.data) .append(.OP_EQUALVERIFY) .append(.OP_CHECKSIG) } catch { return nil } case .scriptHash: // OP_HASH160 <hash> OP_EQUAL do { try self.append(.OP_HASH160) .appendData(address.data) .append(.OP_EQUAL) } catch { return nil } default: return nil } } // OP_<M> <pubkey1> ... <pubkeyN> OP_<N> OP_CHECKMULTISIG public convenience init?(publicKeys: [PublicKey], signaturesRequired: UInt) { // First make sure the arguments make sense. // We need at least one signature guard signaturesRequired > 0 else { return nil } // And we cannot have more signatures than available pubkeys. guard publicKeys.count >= signaturesRequired else { return nil } // Both M and N should map to OP_<1..16> let mOpcode: OpCode = OpCodeFactory.opcode(for: Int(signaturesRequired)) let nOpcode: OpCode = OpCodeFactory.opcode(for: publicKeys.count) guard mOpcode != .OP_INVALIDOPCODE else { return nil } guard nOpcode != .OP_INVALIDOPCODE else { return nil } do { self.init() try append(mOpcode) for pubkey in publicKeys { try appendData(pubkey.data) } try append(nOpcode) try append(.OP_CHECKMULTISIG) multisigRequirements = (signaturesRequired, publicKeys) } catch { return nil } } private static func parseData(_ data: Data) throws -> [ScriptChunk] { guard !data.isEmpty else { return [ScriptChunk]() } var chunks = [ScriptChunk]() var i: Int = 0 let count: Int = data.count while i < count { // Exit if failed to parse let chunk = try ScriptChunkHelper.parseChunk(from: data, offset: i) chunks.append(chunk) i += chunk.range.count } return chunks } public var isStandard: Bool { return isPayToPublicKeyHashScript || isPayToScriptHashScript || isPublicKeyScript || isStandardMultisignatureScript } public var isPublicKeyScript: Bool { guard chunks.count == 2 else { return false } guard let pushdata = pushedData(at: 0) else { return false } return pushdata.count > 1 && opcode(at: 1) == OpCode.OP_CHECKSIG } public var isPayToPublicKeyHashScript: Bool { guard chunks.count == 5 else { return false } guard let dataChunk = chunk(at: 2) as? DataChunk else { return false } return opcode(at: 0) == OpCode.OP_DUP && opcode(at: 1) == OpCode.OP_HASH160 && dataChunk.range.count == 21 && opcode(at: 3) == OpCode.OP_EQUALVERIFY && opcode(at: 4) == OpCode.OP_CHECKSIG } public var isPayToScriptHashScript: Bool { guard chunks.count == 3 else { return false } return opcode(at: 0) == OpCode.OP_HASH160 && pushedData(at: 1)?.count == 20 // this is enough to match the exact byte template, any other encoding will be larger. && opcode(at: 2) == OpCode.OP_EQUAL } // Returns true if the script ends with P2SH check. // Not used in CoreBitcoin. Similar code is used in bitcoin-ruby. I don't know if we'll ever need it. public var endsWithPayToScriptHash: Bool { guard chunks.count >= 3 else { return false } return opcode(at: -3) == OpCode.OP_HASH160 && pushedData(at: -2)?.count == 20 && opcode(at: -1) == OpCode.OP_EQUAL } public var isStandardMultisignatureScript: Bool { guard isMultisignatureScript else { return false } guard let multisigPublicKeys = multisigRequirements?.publickeys else { return false } return multisigPublicKeys.count <= 3 } public var isMultisignatureScript: Bool { guard let requirements = multisigRequirements else { return false } if requirements.nSigRequired == 0 { detectMultisigScript() } return requirements.nSigRequired > 0 } public var isStandardOpReturnScript: Bool { guard chunks.count == 2 else { return false } return opcode(at: 0) == .OP_RETURN && pushedData(at: 1) != nil } public func standardOpReturnData() -> Data? { guard isStandardOpReturnScript else { return nil } return pushedData(at: 1) } // If typical multisig tx is detected, sets requirements: private func detectMultisigScript() { // multisig script must have at least 4 ops ("OP_1 <pubkey> OP_1 OP_CHECKMULTISIG") guard chunks.count >= 4 else { return } // The last op is multisig check. guard opcode(at: -1) == OpCode.OP_CHECKMULTISIG else { return } let mOpcode: OpCode = opcode(at: 0) let nOpcode: OpCode = opcode(at: -2) let m: Int = OpCodeFactory.smallInteger(from: mOpcode) let n: Int = OpCodeFactory.smallInteger(from: nOpcode) guard m > 0 && m != Int.max else { return } guard n > 0 && n != Int.max && n >= m else { return } // We must have correct number of pubkeys in the script. 3 extra ops: OP_<M>, OP_<N> and OP_CHECKMULTISIG guard chunks.count == 3 + n else { return } var pubkeys: [PublicKey] = [] for i in 0...n { guard let data = pushedData(at: i) else { return } // TODO: Other coins let pubkey = PublicKey(privateKey: data, coin: .bitcoin) pubkeys.append(pubkey) } // Now we extracted all pubkeys and verified the numbers. multisigRequirements = (UInt(m), pubkeys) } // Include both PUSHDATA ops and OP_0..OP_16 literals. public var isDataOnly: Bool { return !chunks.contains { $0.opcodeValue > OpCode.OP_16 } } public var scriptChunks: [ScriptChunk] { return chunks } // MARK: - Modification public func invalidateSerialization() { dataCache = nil stringCache = nil multisigRequirements = nil } private func update(with updatedData: Data) throws { let updatedChunks = try Script.parseData(updatedData) chunks = updatedChunks invalidateSerialization() } @discardableResult public func append(_ opcode: OpCode) throws -> Script { let invalidOpCodes: [OpCode] = [.OP_PUSHDATA1, .OP_PUSHDATA2, .OP_PUSHDATA4, .OP_INVALIDOPCODE] guard !invalidOpCodes.contains(where: { $0 == opcode }) else { throw ScriptError.error("\(opcode.name) cannot be executed alone.") } var updatedData: Data = data updatedData += opcode try update(with: updatedData) return self } @discardableResult public func appendData(_ newData: Data) throws -> Script { guard !newData.isEmpty else { throw ScriptError.error("Data is empty.") } guard let addedScriptData = ScriptChunkHelper.scriptData(for: newData, preferredLengthEncoding: -1) else { throw ScriptError.error("Parse data to pushdata failed.") } var updatedData: Data = data updatedData += addedScriptData try update(with: updatedData) return self } @discardableResult public func appendScript(_ otherScript: Script) throws -> Script { guard !otherScript.data.isEmpty else { throw ScriptError.error("Script is empty.") } var updatedData: Data = self.data updatedData += otherScript.data try update(with: updatedData) return self } @discardableResult public func deleteOccurrences(of data: Data) throws -> Script { guard !data.isEmpty else { return self } let updatedData = chunks.filter { ($0 as? DataChunk)?.pushedData != data }.reduce(Data()) { $0 + $1.chunkData } try update(with: updatedData) return self } @discardableResult public func deleteOccurrences(of opcode: OpCode) throws -> Script { let updatedData = chunks.filter { $0.opCode != opcode }.reduce(Data()) { $0 + $1.chunkData } try update(with: updatedData) return self } public func subScript(from index: Int) throws -> Script { let subScript: Script = Script() for chunk in chunks[index..<chunks.count] { try subScript.appendData(chunk.chunkData) } return subScript } public func subScript(to index: Int) throws -> Script { let subScript: Script = Script() for chunk in chunks[0..<index] { try subScript.appendData(chunk.chunkData) } return subScript } // MARK: - Utility methods // Raise exception if index is out of bounds public func chunk(at index: Int) -> ScriptChunk { return chunks[index < 0 ? chunks.count + index : index] } // Returns an opcode in a chunk. // If the chunk is data, not an opcode, returns OP_INVALIDOPCODE // Raises exception if index is out of bounds. public func opcode(at index: Int) -> OpCode { let chunk = self.chunk(at: index) // If the chunk is not actually an opcode, return invalid opcode. guard chunk is OpcodeChunk else { return .OP_INVALIDOPCODE } return chunk.opCode } // Returns Data in a chunk. // If chunk is actually an opcode, returns nil. // Raises exception if index is out of bounds. public func pushedData(at index: Int) -> Data? { let chunk = self.chunk(at: index) return (chunk as? DataChunk)?.pushedData } public func execute(with context: ScriptExecutionContext) throws { for chunk in chunks { if let opChunk = chunk as? OpcodeChunk { try opChunk.opCode.execute(context) } else if let dataChunk = chunk as? DataChunk { if context.shouldExecute { try context.pushToStack(dataChunk.pushedData) } } else { throw ScriptMachineError.error("Unknown chunk") } } guard context.conditionStack.isEmpty else { throw ScriptMachineError.error("Condition branches not balanced.") } } } extension Script { // Standard Transaction to Bitcoin address (pay-to-pubkey-hash) // scriptPubKey: OP_DUP OP_HASH160 <pubKeyHash> OP_EQUALVERIFY OP_CHECKSIG public static func buildPublicKeyHashOut(pubKeyHash: Data) -> Data { let tmp: Data = Data() + OpCode.OP_DUP + OpCode.OP_HASH160 + UInt8(pubKeyHash.count) + pubKeyHash return tmp + OpCode.OP_EQUALVERIFY + OpCode.OP_CHECKSIG } public static func buildPublicKeyUnlockingScript(signature: Data, pubkey: PublicKey, hashType: SighashType) -> Data { var data: Data = Data([UInt8(signature.count + 1)]) + signature + UInt8(hashType) data += VarInt(pubkey.data.count).serialized() data += pubkey.data return data } public static func isPublicKeyHashOut(_ script: Data) -> Bool { return script.count == 25 && script[0] == OpCode.OP_DUP && script[1] == OpCode.OP_HASH160 && script[2] == 20 && script[23] == OpCode.OP_EQUALVERIFY && script[24] == OpCode.OP_CHECKSIG } public static func getPublicKeyHash(from script: Data) -> Data { return script[3..<23] } } extension Script: CustomStringConvertible { public var description: String { return string } } enum ScriptError: Error { case error(String) }
32.944444
165
0.593217
29061467ac3d11b0d1ebac762fb66c8af4dbc726
17,052
// // IQKeyboardReturnKeyHandler.swift // https://github.com/hackiftekhar/IQKeyboardManager // Copyright (c) 2013-16 Iftekhar Qurashi. // // 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 UIKit /** Manages the return key to work like next/done in a view hierarchy. */ public class IQKeyboardReturnKeyHandler: NSObject , UITextFieldDelegate, UITextViewDelegate { ///--------------- /// MARK: Settings ///--------------- /** Delegate of textField/textView. */ public var delegate: protocol<UITextFieldDelegate, UITextViewDelegate>? /** Set the last textfield return key type. Default is UIReturnKeyDefault. */ public var lastTextFieldReturnKeyType : UIReturnKeyType = UIReturnKeyType.Default { didSet { for infoDict in textFieldInfoCache { if let view = infoDict.objectForKey(kIQTextField) as? UIView { updateReturnKeyTypeOnTextField(view) } } } } ///-------------------------------------- /// MARK: Initialization/Deinitialization ///-------------------------------------- public override init() { super.init() } /** Add all the textFields available in UIViewController's view. */ public init(controller : UIViewController) { super.init() addResponderFromView(controller.view) } deinit { for infoDict in textFieldInfoCache { let view : AnyObject = infoDict.objectForKey(kIQTextField)! if let textField = view as? UITextField { let returnKeyTypeValue = infoDict[kIQTextFieldReturnKeyType] as! NSNumber textField.returnKeyType = UIReturnKeyType(rawValue: returnKeyTypeValue.integerValue)! textField.delegate = infoDict[kIQTextFieldDelegate] as! UITextFieldDelegate? } else if let textView = view as? UITextView { textView.returnKeyType = UIReturnKeyType(rawValue: (infoDict[kIQTextFieldReturnKeyType] as! NSNumber).integerValue)! let returnKeyTypeValue = infoDict[kIQTextFieldReturnKeyType] as! NSNumber textView.returnKeyType = UIReturnKeyType(rawValue: returnKeyTypeValue.integerValue)! textView.delegate = infoDict[kIQTextFieldDelegate] as! UITextViewDelegate? } } textFieldInfoCache.removeAllObjects() } ///------------------------ /// MARK: Private variables ///------------------------ private var textFieldInfoCache = NSMutableSet() private let kIQTextField = "kIQTextField" private let kIQTextFieldDelegate = "kIQTextFieldDelegate" private let kIQTextFieldReturnKeyType = "kIQTextFieldReturnKeyType" ///------------------------ /// MARK: Private Functions ///------------------------ private func textFieldCachedInfo(textField : UIView) -> [String : AnyObject]? { for infoDict in textFieldInfoCache { if infoDict.objectForKey(kIQTextField) as! NSObject == textField { return infoDict as? [String : AnyObject] } } return nil } private func updateReturnKeyTypeOnTextField(view : UIView) { var superConsideredView : UIView? //If find any consider responderView in it's upper hierarchy then will get deepResponderView. (Bug ID: #347) for disabledClassString in IQKeyboardManager.sharedManager().consideredToolbarPreviousNextViewClassesString() { if let disabledClass = NSClassFromString(disabledClassString) { superConsideredView = view.superviewOfClassType(disabledClass) if superConsideredView != nil { break } } } var textFields : [UIView]? //If there is a tableView in view's hierarchy, then fetching all it's subview that responds. if let unwrappedTableView = superConsideredView { // (Enhancement ID: #22) textFields = unwrappedTableView.deepResponderViews() } else { //Otherwise fetching all the siblings textFields = view.responderSiblings() //Sorting textFields according to behaviour switch IQKeyboardManager.sharedManager().toolbarManageBehaviour { //If needs to sort it by tag case .ByTag: textFields = textFields?.sortedArrayByTag() //If needs to sort it by Position case .ByPosition: textFields = textFields?.sortedArrayByPosition() default: break } } if let lastView = textFields?.last { if let textField = view as? UITextField { //If it's the last textField in responder view, else next textField.returnKeyType = (view == lastView) ? lastTextFieldReturnKeyType : UIReturnKeyType.Next } else if let textView = view as? UITextView { //If it's the last textField in responder view, else next textView.returnKeyType = (view == lastView) ? lastTextFieldReturnKeyType : UIReturnKeyType.Next } } } ///---------------------------------------------- /// MARK: Registering/Unregistering textFieldView ///---------------------------------------------- /** Should pass UITextField/UITextView intance. Assign textFieldView delegate to self, change it's returnKeyType. @param textFieldView UITextField/UITextView object to register. */ public func addTextFieldView(view : UIView) { var dictInfo : [String : AnyObject] = [String : AnyObject]() dictInfo[kIQTextField] = view if let textField = view as? UITextField { dictInfo[kIQTextFieldReturnKeyType] = textField.returnKeyType.rawValue if let textFieldDelegate = textField.delegate { dictInfo[kIQTextFieldDelegate] = textFieldDelegate } textField.delegate = self } else if let textView = view as? UITextView { dictInfo[kIQTextFieldReturnKeyType] = textView.returnKeyType.rawValue if let textViewDelegate = textView.delegate { dictInfo[kIQTextFieldDelegate] = textViewDelegate } textView.delegate = self } textFieldInfoCache.addObject(dictInfo) } /** Should pass UITextField/UITextView intance. Restore it's textFieldView delegate and it's returnKeyType. @param textFieldView UITextField/UITextView object to unregister. */ public func removeTextFieldView(view : UIView) { if let dict : [String : AnyObject] = textFieldCachedInfo(view) { if let textField = view as? UITextField { let returnKeyTypeValue = dict[kIQTextFieldReturnKeyType] as! NSNumber textField.returnKeyType = UIReturnKeyType(rawValue: returnKeyTypeValue.integerValue)! textField.delegate = dict[kIQTextFieldDelegate] as! UITextFieldDelegate? } else if let textView = view as? UITextView { let returnKeyTypeValue = dict[kIQTextFieldReturnKeyType] as! NSNumber textView.returnKeyType = UIReturnKeyType(rawValue: returnKeyTypeValue.integerValue)! textView.delegate = dict[kIQTextFieldDelegate] as! UITextViewDelegate? } textFieldInfoCache.removeObject(dict) } } /** Add all the UITextField/UITextView responderView's. @param UIView object to register all it's responder subviews. */ public func addResponderFromView(view : UIView) { let textFields = view.deepResponderViews() for textField in textFields { addTextFieldView(textField) } } /** Remove all the UITextField/UITextView responderView's. @param UIView object to unregister all it's responder subviews. */ public func removeResponderFromView(view : UIView) { let textFields = view.deepResponderViews() for textField in textFields { removeTextFieldView(textField) } } private func goToNextResponderOrResign(view : UIView) { var superConsideredView : UIView? //If find any consider responderView in it's upper hierarchy then will get deepResponderView. (Bug ID: #347) for disabledClassString in IQKeyboardManager.sharedManager().consideredToolbarPreviousNextViewClassesString() { if let disabledClass = NSClassFromString(disabledClassString) { superConsideredView = view.superviewOfClassType(disabledClass) if superConsideredView != nil { break } } } var textFields : [UIView]? //If there is a tableView in view's hierarchy, then fetching all it's subview that responds. if let unwrappedTableView = superConsideredView { // (Enhancement ID: #22) textFields = unwrappedTableView.deepResponderViews() } else { //Otherwise fetching all the siblings textFields = view.responderSiblings() //Sorting textFields according to behaviour switch IQKeyboardManager.sharedManager().toolbarManageBehaviour { //If needs to sort it by tag case .ByTag: textFields = textFields?.sortedArrayByTag() //If needs to sort it by Position case .ByPosition: textFields = textFields?.sortedArrayByPosition() default: break } } if let unwrappedTextFields = textFields { //Getting index of current textField. if let index = unwrappedTextFields.indexOf(view) { //If it is not last textField. then it's next object becomeFirstResponder. if index < (unwrappedTextFields.count - 1) { let nextTextField = unwrappedTextFields[index+1] nextTextField.becomeFirstResponder() } else { view.resignFirstResponder() } } } } ///---------------------------------------------- /// MARK: UITextField/UITextView delegates ///---------------------------------------------- public func textFieldShouldBeginEditing(textField: UITextField) -> Bool { if delegate?.respondsToSelector("textFieldShouldBeginEditing:") != nil { return (delegate?.textFieldShouldBeginEditing?(textField) == true) } else { return true } } public func textFieldShouldEndEditing(textField: UITextField) -> Bool { if delegate?.respondsToSelector("textFieldShouldEndEditing:") != nil { return (delegate?.textFieldShouldEndEditing?(textField) == true) } else { return true } } public func textFieldDidBeginEditing(textField: UITextField) { updateReturnKeyTypeOnTextField(textField) delegate?.textFieldShouldBeginEditing?(textField) } public func textFieldDidEndEditing(textField: UITextField) { delegate?.textFieldDidEndEditing?(textField) } public func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { if delegate?.respondsToSelector("textField:shouldChangeCharactersInRange:replacementString:") != nil { return (delegate?.textField?(textField, shouldChangeCharactersInRange: range, replacementString: string) == true) } else { return true } } public func textFieldShouldClear(textField: UITextField) -> Bool { if delegate?.respondsToSelector("textFieldShouldClear:") != nil { return (delegate?.textFieldShouldClear?(textField) == true) } else { return true } } public func textFieldShouldReturn(textField: UITextField) -> Bool { var shouldReturn = true if delegate?.respondsToSelector("textFieldShouldReturn:") != nil { shouldReturn = (delegate?.textFieldShouldReturn?(textField) == true) } if shouldReturn == true { goToNextResponderOrResign(textField) } return shouldReturn } public func textViewShouldBeginEditing(textView: UITextView) -> Bool { if delegate?.respondsToSelector("textViewShouldBeginEditing:") != nil { return (delegate?.textViewShouldBeginEditing?(textView) == true) } else { return true } } public func textViewShouldEndEditing(textView: UITextView) -> Bool { if delegate?.respondsToSelector("textViewShouldEndEditing:") != nil { return (delegate?.textViewShouldEndEditing?(textView) == true) } else { return true } } public func textViewDidBeginEditing(textView: UITextView) { updateReturnKeyTypeOnTextField(textView) delegate?.textViewDidBeginEditing?(textView) } public func textViewDidEndEditing(textView: UITextView) { delegate?.textViewDidEndEditing?(textView) } public func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool { var shouldReturn = true if delegate?.respondsToSelector("textView:shouldChangeCharactersInRange:replacementString:") != nil { shouldReturn = ((delegate?.textView?(textView, shouldChangeTextInRange: range, replacementText: text)) == true) } if shouldReturn == true && text == "\n" { goToNextResponderOrResign(textView) } return shouldReturn } public func textViewDidChange(textView: UITextView) { delegate?.textViewDidChange?(textView) } public func textViewDidChangeSelection(textView: UITextView) { delegate?.textViewDidChangeSelection?(textView) } public func textView(textView: UITextView, shouldInteractWithURL URL: NSURL, inRange characterRange: NSRange) -> Bool { if delegate?.respondsToSelector("textView:shouldInteractWithURL:inRange:") != nil { return ((delegate?.textView?(textView, shouldInteractWithURL: URL, inRange: characterRange)) == true) } else { return true } } public func textView(textView: UITextView, shouldInteractWithTextAttachment textAttachment: NSTextAttachment, inRange characterRange: NSRange) -> Bool { if delegate?.respondsToSelector("textView:shouldInteractWithTextAttachment:inRange:") != nil { return ((delegate?.textView?(textView, shouldInteractWithTextAttachment: textAttachment, inRange: characterRange)) == true) } else { return true } } }
36.358209
156
0.592482
7a5ea33310dc766c937f18f1283f772a065c17ec
3,039
// // AppDelegate.swift // iOSSwift // // Created by C.W. Betts on 10/3/14. // // import UIKit import CocoaLumberjack import CocoaLumberjackSwift let ddloglevel = DDLogLevel.verbose private func printSomething() { DDLogVerbose("Verbose") DDLogDebug("Debug") DDLogInfo("Info") DDLogWarn("Warn") DDLogError("Error") } @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. let formatter = Formatter() DDTTYLogger.sharedInstance.logFormatter = formatter DDLog.add(DDTTYLogger.sharedInstance) DDLogVerbose("Verbose") DDLogDebug("Debug") DDLogInfo("Info") DDLogWarn("Warn") DDLogError("Error") printSomething() dynamicLogLevel = ddloglevel DDLogVerbose("Verbose") DDLogDebug("Debug") DDLogInfo("Info") DDLogWarn("Warn") DDLogError("Error") DDLogVerbose("Verbose", level: ddloglevel) DDLogDebug("Debug", level: ddloglevel) DDLogInfo("Info", level: ddloglevel) DDLogWarn("Warn", level: ddloglevel) DDLogError("Error", level: ddloglevel) printSomething() return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
35.752941
279
0.731162
fe6e277c5751ee4090a3d7e3524117597ff91c4a
653
// // Created by Papp Imre on 2019-02-15. // Copyright (c) 2019 CocoaPods. All rights reserved. // import NMDEF_Base import RxFlow import Reusable class Tab2Flow: TabFlow, FlowWithNavigationRoot, StoryboardSceneBased { static var sceneIdentifier: String { return "Tab2Navigation" } func navigate(to step: Step) -> NextFlowItems { guard let step = step as? AppStep else { return .none } switch step { case .tab2: return pushNavigation(to: Tab2ViewController.self) case .tab2nav1: return pushNavigation(to: Nav3ViewController.self) default: return .none } } }
25.115385
74
0.658499
f575bf4ff8455e5aa6b2f8c2b6545666d1afca6a
181
import Foundation #if os(Linux) import FoundationNetworking #endif public extension URL { /// Easy request generation. var urlRequest: URLRequest { URLRequest(url: self) } }
13.923077
29
0.745856
f9ccf05d36d3158143718384827213947a640a9b
1,126
import UIKit /** Batch Actions View Controller, contains the replication and batch operation actions. */ class HomeActionsViewController: UIViewController { //@IBOutlet weak var dfdfgd: UIButton! fileprivate var eventAPI: EventAPI! fileprivate var remoteReplicator: RemoteReplicator! override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(_ animated: Bool) { self.eventAPI = EventAPI.sharedInstance self.remoteReplicator = RemoteReplicator.sharedInstance } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func deleteAllEventsButtonTapped(_ sender: AnyObject) { eventAPI.deleteAllEvents() self.navigationController?.popToRootViewController(animated: true) } @IBAction func replicateRemoteDataButtonTapped(_ sender: AnyObject) { remoteReplicator.fetchData() NotificationCenter.default.post(name: Notification.Name(rawValue: "setStateLoading"), object: nil) self.navigationController?.popToRootViewController(animated: true) } }
30.432432
106
0.728242
383bff4d953659825864ce71a20ef98a38682463
1,161
//: [⇐ Previous: 02 - Functions](@previous) //: ## Episode 03: Challenge - Functions /*: ## Challenge 1 - Create a closure version of the function below. - Try out the function & closure! */ // -------------------------------------- func calculateFullName(firstName: String, lastName: String?) -> String { firstName + " " + (lastName ?? "") } // -------------------------------------- // TODO: Write solution here var calculateFullNameClosure = { (firstName: String, lastName: String?) -> String in firstName + " " + (lastName ?? "") } //let philipsName = calculateFullName(firstName: Philip, lastName: Timothe) calculateFullNameClosure("Philip", "Timothe") /*: ## Challenge 2 - Call the `printResult` function below - Use an inline closure as an argument */ // -------------------------------------- typealias Operate = (Double, Double) -> Double func printResult(_ operate: Operate, _ a: Double, _ b: Double) { let result = operate(a, b) print(result) } // -------------------------------------- // TODO: Write solution here printResult( { ( a: Double, b: Double) -> Double in a * b }, 4, 5) //: [⇒ Next: 04 - Closure Syntax](@next)
25.23913
84
0.569337
efec532266ece66de510f196bddd897f5d44ea86
2,358
// // Context.swift // SlackBlocksModel // // Created by Helge Heß. // Copyright © 2020 ZeeZide GmbH. All rights reserved. // public extension Block { struct Context: Encodable { /** * Context's can contain just text (w/ or w/o markdown) and images. */ public enum Element: Encodable { case text (Text) case image(ImageElement) public func encode(to encoder: Encoder) throws { switch self { case .text (let element): try element.encode(to: encoder) case .image(let element): try element.encode(to: encoder) } } } public static let validInSurfaces : [ BlockSurfaceSet ] = [ .modals, .messages, .homeTabs ] public var id : BlockID public var elements : [ Element ] public init(id: BlockID, elements: [ Element ]) { self.id = id self.elements = elements } // MARK: - Encoding enum CodingKeys: String, CodingKey { case id = "block_id" case type, elements } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode("context", forKey: .type) try container.encode(id, forKey: .id) try container.encode(elements, forKey: .elements) } } } // MARK: - Markdown public extension Block.Context { @inlinable var blocksMarkdownString : String { var ms = "" for element in elements { switch element { case .text(let text): ms += text.blocksMarkdownString ms += "\n" case .image(let image): ms += "![\(image.alt)](image.url.absoluteString)\n" } } return ms } } // MARK: - Markdown extension Block.Context: CustomStringConvertible { @inlinable public var description : String { var ms = "<Context[\(id.id)]:" if elements.isEmpty { ms += " EMPTY" } else if elements.count == 1 { ms += " \(elements[0])" } else { ms += " \(elements)" } ms += ">" return ms } } extension Block.Context.Element: CustomStringConvertible { @inlinable public var description : String { switch self { case .text (let text) : return text.description case .image(let image) : return image.description } } }
23.117647
73
0.583545
03574c62496676d2903d1c440612a83d3ba3c5b8
2,288
// // SceneDelegate.swift // LableWhisperer // // Created by asc on 11/12/21. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). guard let _ = (scene as? UIWindowScene) else { return } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
43.169811
147
0.71285
3847619aa1e01290175ef4b71979258bd60b8e3c
94
public protocol SpeculidConfigurationProtocol { var mode: SpeculidApplicationMode { get } }
23.5
47
0.808511
db55fc8ba938f0c3ca7c79529e584addad1e0155
3,488
import UIKit //: # Lesson 2 Exercises //: ## Optionals //: ### Exercise 1 //: When retrieving a value from a dictionary, Swift returns an optional. //: //: 1a) The variable, director, is an optional type. Its value cannot be used until it is unwrapped. Use `if let` to carefully unwrap the value returned by `moviesDict[movie]` var moviesDict:Dictionary = [ "Star Wars":"George Lucas", "Point Break":"Kathryn Bigelow"] var movie = "Star Wars" var director = moviesDict[movie] //: 1b) Test your code by inserting different values for the variable `movie`. if let director = moviesDict[movie] { print(director) } else { print("nil") } //: ### Exercise 2 //: The LoginViewController class below needs a UITextField to hold a user's name. Declare a variable for this text field as a property of the class LoginViewController. Keep in mind that the textfield property will not be initialized until after the view controller is constructed. class LoginViewController: UIViewController { var userNameTextField:UITextField! } //: ### Exercise 3 //: The Swift Int type has an initializer that takes a string as a parameter and returns an optional of type Int?. //: //: 3a) Finish the code below by safely unwrapping the constant, `number`. var numericalString = "three" var number = Int(numericalString) //TODO: Unwrap number to make the following print statement more readable. if let number = number { print("\(number) is the magic number.") } else { print("Not a number") } //: 3b) Change the value of numericalString to "three" and execute the playground again. //: ### Exercise 4 //: The class UIViewController has a property called tabBarController. The tabBarController property is an optional of type UITabBarController?. The tabBarController itself holds a tabBar as a property. Complete the code below by filling in the appropriate use of optional chaining to access the tab bar property. var viewController = UIViewController() if let tabBar = viewController.tabBarController?.tabBar { print("Here's the tab bar.") } else { print("No tab bar controller found.") } //: ### Exercise 5 //: Below is a dictionary of paintings and artists. //: //: 5a) The variable, artist, is an optional type. Its value cannot be used until it is unwrapped. Use `if let` to carefully unwrap the value returned by `paintingDict[painting]`. var paintingDict:Dictionary = [ "Guernica":"Picasso", "Mona Lisa": "da Vinci", "No. 5": "Pollock"] var painting = "Guernica" if let artist = paintingDict[painting] { print ("The artist is \(artist)") } else { print("nil") } //: 5b) Test your code by inserting different values for the variable `painting`. //: ### Exercise 6 //: Set the width of the cancel button below. Notice that the cancelButton variable is declared as an implicitly unwrapped optional. var anotherViewController = UIViewController() var cancelButton: UIBarButtonItem! cancelButton = UIBarButtonItem() // TODO: Set the width of the cancel button. cancelButton.width = 55 //: ### Exercise 7 //: The class UIViewController has a property called parent. The parent property is an optional of type UIViewController?. We can't always be sure that a given view controller has a parent view controller. Safely unwrap the parent property below using if let. var childViewController = UIViewController() // TODO: Safely unwrap childViewController.parent if let parent = childViewController.parent { print("Got it!") } else { print("Don't got it!") }
44.717949
314
0.739392
ab522774bc3f8d38b66c443cee0614d99804c2e5
3,088
// // CGPointExtensions.swift // SSTests // // Created by Omar Albeik on 07/12/2016. // Copyright © 2016 Omar Albeik. All rights reserved. // #if os(macOS) import Cocoa #else import UIKit #endif // MARK: - Methods public extension CGPoint { /// SwifterSwift: Distance from another CGPoint. /// /// - Parameter point: CGPoint to get distance from. /// - Returns: Distance between self and given CGPoint. public func distance(from point: CGPoint) -> CGFloat { return CGPoint.distance(from: self, to: point) } /// SwifterSwift: Distance between two CGPoints. /// /// - Parameters: /// - point1: first CGPoint. /// - point2: second CGPoint. /// - Returns: distance between the two given CGPoints. public static func distance(from point1: CGPoint, to point2: CGPoint) -> CGFloat { // http://stackoverflow.com/questions/6416101/calculate-the-distance-between-two-cgpoints return sqrt(pow(point2.x - point1.x, 2) + pow(point2.y - point1.y, 2)) } } // MARK: - Operators public extension CGPoint { /// SwifterSwift: Add two CGPoints. /// /// - Parameters: /// - lhs: CGPoint to add to. /// - rhs: CGPoint to add. /// - Returns: result of addition of the two given CGPoints. public static func + (lhs: CGPoint, rhs: CGPoint) -> CGPoint { return CGPoint(x: lhs.x + rhs.x, y: lhs.y + rhs.y) } /// SwifterSwift: Add a CGPoints to self. /// /// - Parameters: /// - lhs: self /// - rhs: CGPoint to add. public static func += (lhs: inout CGPoint, rhs: CGPoint) { lhs = lhs + rhs } /// SwifterSwift: Subtract two CGPoints. /// /// - Parameters: /// - lhs: CGPoint to subtract from. /// - rhs: CGPoint to subtract. /// - Returns: result of subtract of the two given CGPoints. public static func - (lhs: CGPoint, rhs: CGPoint) -> CGPoint { return CGPoint(x: lhs.x - rhs.x, y: lhs.y - rhs.y) } /// SwifterSwift: Subtract a CGPoints from self. /// /// - Parameters: /// - lhs: self /// - rhs: CGPoint to subtract. public static func -= (lhs: inout CGPoint, rhs: CGPoint) { lhs = lhs + rhs } /// SwifterSwift: Multiply a CGPoint with a scalar /// /// - Parameters: /// - point: CGPoint to multiply. /// - scalar: scalar value. /// - Returns: result of multiplication of the given CGPoint with the scalar. public static func * (point: CGPoint, scalar: CGFloat) -> CGPoint { return CGPoint(x: point.x * scalar, y: point.y * scalar) } /// SwifterSwift: Multiply self with a scalar /// /// - Parameters: /// - point: self. /// - scalar: scalar value. /// - Returns: result of multiplication of the given CGPoint with the scalar. public static func *= (point: inout CGPoint, scalar: CGFloat) { point = point * scalar } /// SwifterSwift: Multiply a CGPoint with a scalar /// /// - Parameters: /// - scalar: scalar value. /// - point: CGPoint to multiply. /// - Returns: result of multiplication of the given CGPoint with the scalar. public static func * (scalar: CGFloat, point: CGPoint) -> CGPoint { return CGPoint(x: point.x * scalar, y: point.y * scalar) } }
27.087719
91
0.645725
c19a157c62fd5578fdb68363d9f9d72804bb87db
1,244
/* Copyright 2017 Ryuichi Intellectual Property and the Yanagiba project contributors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import XCTest @testable import Source class SourceRangeTests : XCTestCase { func testDummyRange() { let range = SourceRange.EMPTY XCTAssertEqual(range, SourceRange(start: .DUMMY, end: .DUMMY)) XCTAssertEqual(range.start.identifier, "dummy") XCTAssertEqual(range.start.line, 0) XCTAssertEqual(range.start.column, 0) XCTAssertEqual(range.end.identifier, "dummy") XCTAssertEqual(range.end.line, 0) XCTAssertEqual(range.end.column, 0) XCTAssertEqual(range.description, "dummy:0:0-0:0") } static var allTests = [ ("testDummyRange", testDummyRange), ] }
32.736842
85
0.737942
abe5534d2d4c5225008bc6df2641eb93e1a85571
5,332
/* THIS FILE WAS AUTOGENERATED! DO NOT EDIT! file to edit: 00_load_data.ipynb */ import Foundation import Just import Path public func shellCommand(_ launchPath: String, _ arguments: [String]) -> String? { let task = Process() task.executableURL = URL.init(fileURLWithPath:launchPath) task.arguments = arguments let pipe = Pipe() task.standardOutput = pipe do {try task.run()} catch {print("Unexpected error: \(error).")} let data = pipe.fileHandleForReading.readDataToEndOfFile() let output = String(data: data, encoding: String.Encoding.utf8) return output } public func downloadFile(_ url: String, dest: String?=nil, force: Bool=false){ let dest_name = (dest ?? (Path.cwd/url.split(separator: "/").last!).string) let url_dest = URL.init(fileURLWithPath: (dest ?? (Path.cwd/url.split(separator: "/").last!).string)) if (force || !Path(dest_name)!.exists){ print("Downloading \(url)...") if let cts = Just.get(url).content{ do {try cts.write(to: URL.init(fileURLWithPath:dest_name))} catch {print("Can't write to \(url_dest).\n\(error)")} } else {print("Can't reach \(url)")} } } import TensorFlow protocol ConvertableFromByte { init(_ d:UInt8) } extension Float : ConvertableFromByte{} extension Int32 : ConvertableFromByte{} func loadMNIST<T:ConvertableFromByte & TensorFlowScalar>(training: Bool, labels: Bool, path: Path, flat: Bool) -> Tensor<T> { let split = training ? "train" : "t10k" let kind = labels ? "labels" : "images" let batch = training ? Int32(60000) : Int32(10000) let shape: TensorShape = labels ? [batch] : (flat ? [batch, 784] : [batch, 28, 28]) let dropK = labels ? 8 : 16 let baseUrl = "http://yann.lecun.com/exdb/mnist/" let fname = split + "-" + kind + "-idx\(labels ? 1 : 3)-ubyte" let file = path/fname if !file.exists { downloadFile("\(baseUrl)\(fname).gz", dest:(path/"\(fname).gz").string) _ = shellCommand("/bin/gunzip", ["-fq", (path/"\(fname).gz").string]) } let data = try! Data.init(contentsOf: URL.init(fileURLWithPath: file.string)).dropFirst(dropK) if labels { return Tensor(data.map(T.init)) } else { return Tensor(data.map(T.init)).reshaped(to: shape)} } public func loadMNIST(path:Path, flat:Bool = false) -> (Tensor<Float>, Tensor<Int32>, Tensor<Float>, Tensor<Int32>) { try! path.mkdir(.p) return ( loadMNIST(training: true, labels: false, path: path, flat: flat) / 255.0, loadMNIST(training: true, labels: true, path: path, flat: flat), loadMNIST(training: false, labels: false, path: path, flat: flat) / 255.0, loadMNIST(training: false, labels: true, path: path, flat: flat) ) } public let mnistPath = Path.home/".fastai"/"data"/"mnist_tst" import Dispatch public func time(_ function: () -> ()) { let start = DispatchTime.now() function() let end = DispatchTime.now() let nanoseconds = Double(end.uptimeNanoseconds - start.uptimeNanoseconds) let milliseconds = nanoseconds / 1e6 print("\(milliseconds) ms") } public func time(repeating: Int, _ function: () -> ()) { function() var times:[Double] = [] for _ in 1...repeating{ let start = DispatchTime.now() function() let end = DispatchTime.now() let nanoseconds = Double(end.uptimeNanoseconds - start.uptimeNanoseconds) let milliseconds = nanoseconds / 1e6 times.append(milliseconds) } print("\(times.reduce(0.0, +)/Double(times.count)) ms") } public func notebookToScript(fname: String){ let url_fname = URL.init(fileURLWithPath: fname) let last = fname.lastPathComponent let out_fname = (url_fname.deletingLastPathComponent().appendingPathComponent("FastaiNotebooks", isDirectory: true) .appendingPathComponent("Sources", isDirectory: true) .appendingPathComponent("FastaiNotebooks", isDirectory: true).appendingPathComponent(last) .deletingPathExtension().appendingPathExtension("swift")) do{ let data = try Data.init(contentsOf: url_fname) let jsonData = try! JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String: Any] let cells = jsonData["cells"] as! [[String:Any]] var module = """ /* THIS FILE WAS AUTOGENERATED! DO NOT EDIT! file to edit: \(fname.lastPathComponent) */ """ for cell in cells{ if let source = cell["source"] as? [String]{ if source.isEmpty {continue} if source[0].range(of: #"^\s*//\s*export\s*$"#, options: .regularExpression) != nil{ module.append("\n" + source[1...].joined() + "\n") } } } try? module.write(to: out_fname, atomically: false, encoding: .utf8) } catch {print("Can't read the content of \(fname)")} } public func exportNotebooks(_ path: Path){ for entry in try! path.ls(){ if entry.kind == Entry.Kind.file{ if entry.path.basename().range(of: #"^\d*_.*ipynb$"#, options: .regularExpression) != nil { print("Converting \(entry.path.basename())") notebookToScript(fname: entry.path.basename()) } } } }
37.286713
125
0.626594
26c82d6c72bffdb0d05282386b0ef9c209c725ea
1,746
// // DrawTimerBarView.swift // drawAI // // Created by Alessandro Negrão on 25/10/21. // import UIKit protocol DrawTimerBarDelegate: AnyObject { func didFinishTime() } class DrawTimerBarView: ANView { private var timerValue: Double = 1.0 private var progressLayer = CAShapeLayer() weak var delegate: DrawTimerBarDelegate? var progress: CGFloat = 1.0 { didSet { setNeedsDisplay() } } override func awakeFromNib() { backgroundColor = AppColors.primaryColor } override init(frame: CGRect) { super.init(frame: frame) layer.addSublayer(progressLayer) } required init?(coder: NSCoder) { super.init(coder: coder) layer.addSublayer(progressLayer) } override func draw(_ rect: CGRect) { let backgroundMask: CAShapeLayer = CAShapeLayer() backgroundMask.path = UIBezierPath(roundedRect: rect, cornerRadius: rect.height * 0.4).cgPath layer.mask = backgroundMask let progressRect = CGRect(origin: .zero, size: CGSize(width: rect.width * progress, height: rect.height)) progressLayer.frame = progressRect progressLayer.backgroundColor = AppColors.accentColor.cgColor layer.addSublayer(progressLayer) } func startTimer() { Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true){ [weak self] timer in guard let self = self else { return } if self.timerValue > 0 { self.timerValue -= 0.01 self.progress = self.timerValue } else { timer.invalidate() self.delegate?.didFinishTime() } } } }
26.861538
113
0.607102
3a3136d762cbea5f878a98f045af5aad3de7e9a9
2,237
// // UIViewController+JX.swift // JXPhotoBrowser // // Created by JiongXing on 2018/10/14. // import Foundation import UIKit extension UIViewController: JXNamespaceWrappable {} extension JXTypeWrapperProtocol where JXWrappedType == UIViewController { /// Returns the current application's top most view controller. public static var topMost: UIViewController? { var rootViewController: UIViewController? for window in UIApplication.shared.windows where !window.isHidden { if let windowRootViewController = window.rootViewController { rootViewController = windowRootViewController break } } return self.topMost(of: rootViewController) } /// Returns the top most view controller from given view controller's stack. public static func topMost(of viewController: UIViewController?) -> UIViewController? { // presented view controller if let presentedViewController = viewController?.presentedViewController { return self.topMost(of: presentedViewController) } // UITabBarController if let tabBarController = viewController as? UITabBarController, let selectedViewController = tabBarController.selectedViewController { return self.topMost(of: selectedViewController) } // UINavigationController if let navigationController = viewController as? UINavigationController, let visibleViewController = navigationController.visibleViewController { return self.topMost(of: visibleViewController) } // UIPageController if let pageViewController = viewController as? UIPageViewController, pageViewController.viewControllers?.count == 1 { return self.topMost(of: pageViewController.viewControllers?.first) } // child view controller for subview in viewController?.view?.subviews ?? [] { if let childViewController = subview.next as? UIViewController { return self.topMost(of: childViewController) } } return viewController } }
36.080645
91
0.664283
eb3749fcf1a67449f39e5903f0511e85c7c1cc9f
68
import Foundation enum FormatError: Error { case stringError }
11.333333
25
0.75
4829cf1c3baec0fcd6d704b58d984daa744f511a
346
// // EmptyReuseView.swift // musicSheet // // Created by Jz D on 2020/8/24. // Copyright © 2020 Jz D. All rights reserved. // import UIKit class EmptyReuseView: UICollectionReusableView { override func awakeFromNib() { super.awakeFromNib() // Initialization code backgroundColor = .white } }
16.47619
48
0.624277
69dcb86b4e864ea1148b4c29a687eb5c54651023
8,755
// // Infallible+Tests.swift // Tests // // Created by Shai Mishali on 11/20/20. // Copyright © 2020 Krunoslav Zaher. All rights reserved. // import RxSwift import RxCocoa import RxRelay import RxTest import XCTest class InfallibleTest: RxTest { } extension InfallibleTest { func testAsInfallible_OnErrorJustReturn() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ .next(300, 9), .next(340, 13), .next(360, 111), .error(390, testError), .next(480, 320), ]) let inf = xs.asInfallible(onErrorJustReturn: 600) let observer = scheduler.createObserver(Int.self) _ = inf.bind(to: observer) scheduler.start() XCTAssertEqual(observer.events, [ .next(300, 9), .next(340, 13), .next(360, 111), .next(390, 600), .completed(390) ]) } func testAsInfallible_OnErrorFallbackTo() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ .next(300, 9), .next(340, 13), .next(360, 111), .error(390, testError), .next(480, 320), ]) let inf = xs.asInfallible(onErrorFallbackTo: Infallible<Int>.of(1, 2)) let observer = scheduler.createObserver(Int.self) _ = inf.bind(to: observer) scheduler.start() XCTAssertEqual(observer.events, [ .next(300, 9), .next(340, 13), .next(360, 111), .next(390, 1), .next(390, 2), .completed(390) ]) } func testAsInfallible_OnErrorRecover() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ .next(300, 9), .next(340, 13), .next(360, 111), .error(390, testError), .next(480, 320), ]) let ys = scheduler.createHotObservable([ .next(500, 25), .next(600, 33), .completed(620) ]) let inf = xs.asInfallible(onErrorRecover: { _ in ys.asInfallible(onErrorJustReturn: -1) }) let observer = scheduler.createObserver(Int.self) _ = inf.bind(to: observer) scheduler.start() XCTAssertEqual(observer.events, [ .next(300, 9), .next(340, 13), .next(360, 111), .next(500, 25), .next(600, 33), .completed(620) ]) } func testAsInfallible_BehaviourRelay() { let scheduler = TestScheduler(initialClock: 0) let xs = BehaviorRelay<Int>(value: 0) let ys = scheduler.createHotObservable([ .next(500, 25), .next(600, 33) ]) let inf = xs.asInfallible() let observer = scheduler.createObserver(Int.self) _ = inf.bind(to: observer) _ = ys.bind(to: xs) scheduler.start() XCTAssertEqual(observer.events, [ .next(0, 0), .next(500, 25), .next(600, 33) ]) } func testAsInfallible_PublishRelay() { let scheduler = TestScheduler(initialClock: 0) let xs = PublishRelay<Int>() let ys = scheduler.createHotObservable([ .next(500, 25), .next(600, 33) ]) let inf = xs.asInfallible() let observer = scheduler.createObserver(Int.self) _ = inf.bind(to: observer) _ = ys.bind(to: xs) scheduler.start() XCTAssertEqual(observer.events, [ .next(500, 25), .next(600, 33) ]) } func testAsInfallible_ReplayRelay() { let scheduler = TestScheduler(initialClock: 0) let xs = ReplayRelay<Int>.create(bufferSize: 2) let ys = scheduler.createHotObservable([ .next(500, 25), .next(600, 33) ]) let inf = xs.asInfallible() let observer = scheduler.createObserver(Int.self) _ = inf.bind(to: observer) _ = ys.bind(to: xs) scheduler.start() XCTAssertEqual(observer.events, [ .next(500, 25), .next(600, 33) ]) } func testAnonymousInfallible_detachesOnDispose() { var observer: ((InfallibleEvent<Int>) -> Void)! let a = Infallible.create { o in observer = o return Disposables.create() } as Infallible<Int> var elements = [Int]() let d = a.subscribe(onNext: { n in elements.append(n) }) XCTAssertEqual(elements, []) observer(.next(0)) XCTAssertEqual(elements, [0]) d.dispose() observer(.next(1)) XCTAssertEqual(elements, [0]) } func testAnonymousInfallible_detachesOnComplete() { var observer: ((InfallibleEvent<Int>) -> Void)! let a = Infallible.create { o in observer = o return Disposables.create() } as Infallible<Int> var elements = [Int]() _ = a.subscribe(onNext: { n in elements.append(n) }) XCTAssertEqual(elements, []) observer(.next(0)) XCTAssertEqual(elements, [0]) observer(.completed) observer(.next(1)) XCTAssertEqual(elements, [0]) } } extension InfallibleTest { func testAsInfallible_never() { let scheduler = TestScheduler(initialClock: 0) let xs: Infallible<Int> = Infallible.never() let res = scheduler.start { xs } let correct: [Recorded<Event<Int>>] = [] XCTAssertEqual(res.events, correct) } #if TRACE_RESOURCES func testAsInfallibleReleasesResourcesOnComplete() { _ = Observable<Int>.empty().asInfallible(onErrorJustReturn: 0).subscribe() } func testAsInfallibleReleasesResourcesOnError() { _ = Observable<Int>.empty().asInfallible(onErrorJustReturn: 0).subscribe() } #endif } // MARK: - Subscribe with object extension InfallibleTest { func testSubscribeWithNext() { var testObject: TestObject! = TestObject() let scheduler = TestScheduler(initialClock: 0) var values = [String]() var disposed: UUID? var completed: UUID? let observable = scheduler.createColdObservable([ .next(10, 0), .next(20, 1), .next(30, 2), .next(40, 3), .completed(50) ]) let inf = observable.asInfallible(onErrorJustReturn: -1) _ = inf .subscribe( with: testObject, onNext: { object, value in values.append(object.id.uuidString + "\(value)") }, onCompleted: { completed = $0.id }, onDisposed: { disposed = $0.id } ) scheduler.start() let uuid = testObject.id XCTAssertEqual(values, [ uuid.uuidString + "0", uuid.uuidString + "1", uuid.uuidString + "2", uuid.uuidString + "3" ]) XCTAssertEqual(completed, uuid) XCTAssertEqual(disposed, uuid) XCTAssertNotNil(testObject) testObject = nil XCTAssertNil(testObject) } func testSubscribeWithError() { var testObject: TestObject! = TestObject() let scheduler = TestScheduler(initialClock: 0) var values = [String]() var disposed: UUID? var completed: UUID? let observable = scheduler.createColdObservable([ .next(10, 0), .next(20, 1), .error(30, testError), .next(40, 3), ]) let inf = observable.asInfallible(onErrorJustReturn: -1) _ = inf .subscribe( with: testObject, onNext: { object, value in values.append(object.id.uuidString + "\(value)") }, onCompleted: { completed = $0.id }, onDisposed: { disposed = $0.id } ) scheduler.start() let uuid = testObject.id XCTAssertEqual(values, [ uuid.uuidString + "0", uuid.uuidString + "1", uuid.uuidString + "-1" ]) XCTAssertEqual(completed, uuid) XCTAssertEqual(disposed, uuid) XCTAssertNotNil(testObject) testObject = nil XCTAssertNil(testObject) } } private class TestObject: NSObject { var id = UUID() }
25.979228
98
0.52964
1646434524dbc8cab18dcffd598562c0aee6c48c
1,812
// // BeNilSpec.swift // Sleipnir // // Created by Artur Termenji on 7/16/14. // Copyright (c) 2014 railsware. All rights reserved. // import Foundation class BeNilSpec : SleipnirSpec { var beNilSpec : () = describe("BeNil matcher") { context("value") { var value: Int? describe("which is nil") { beforeEach { value = nil } describe("positive match") { it("should pass") { expect(value).to(beNil()) } } describe("negative match") { it("should fail with a sensible failure message") { let failureMessage = "Expected <nil> to not be nil" expectFailureWithMessage(failureMessage) { expect(value).toNot(beNil()) } } } } describe("which is not nil") { beforeEach { value = 3 } describe("positive match") { it("should fail with a sensible failure message") { let failureMessage = "Expected <3> to be nil" expectFailureWithMessage(failureMessage) { expect(value).to(beNil()) } } } describe("negative match") { it("should pass") { expect(value).toNot(beNil()) } } } } } }
28.761905
75
0.370861
7521f8bab56026d86480f1aba131e9eb2070f02c
7,660
// // LogViewHelper.swift // TTBaseUIKit // // Created by Tuan Truong Quang on 9/11/19. // Copyright © 2019 Truong Quang Tuan. All rights reserved. // import Foundation import UIKit open class LogViewHelper { fileprivate var viewModel:LogTrackingViewModel = LogTrackingViewModel() public static let share = LogViewHelper() private let concurrentQueue = DispatchQueue(label: "ConcurrentQueue", attributes: .concurrent, target: nil) private init(){} public var didTouchLogButtonHandle:( () -> ())? public var didTouchReportlHandle:( () -> ())? public var didTouchSettinglHandle:( () -> ())? public var didSendCurrentRequest:( (_ request:String) -> ())? public var didSendCurrentResponse:( (_ response:String) -> ())? public func config(withDes des:String, isStartAppToShow:Bool) -> LogViewHelper { self.viewModel.displayString = des self.viewModel.isStartAppToShow = isStartAppToShow return self } } //MARK:// For Base Funcs extension LogViewHelper { public func getLogs() -> [LogViewModel] { var logs: [LogViewModel] = [] self.concurrentQueue.sync { // reading always has to be sync! logs = self.viewModel.logs.reversed() } return logs } public func add(withLog log:LogViewModel) { self.concurrentQueue.async(flags: .barrier) { if self.viewModel.logs.count >= 70 { self.viewModel.logs = [] } self.viewModel.logs.append(log) } } public func resetLogs() { self.viewModel.logs = [] } } //MARK:// For Base View extension LogViewHelper { public func onShow() { DispatchQueue.main.async { if let windown = UIApplication.shared.keyWindow { let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(self.addAccountLongPressGesture(_:))) windown.addGestureRecognizer(longPressRecognizer) } } } @objc fileprivate func addAccountLongPressGesture(_ sender: UILongPressGestureRecognizer) { if sender.state == .ended { if self.viewModel.isShow { return } DispatchQueue.main.async { [weak self] in guard let strongSelf = self else { return } let showLogVC = OptionLogPresentViewController(with: "IS DEV MODE", subTitle: strongSelf.viewModel.displayString) if !strongSelf.viewModel.isShow { strongSelf.viewModel.isShow = true UIApplication.topViewController()?.present(showLogVC, animated: true, completion: { strongSelf.viewModel.isShow = true }) } showLogVC.didLoad? = { [weak self] in guard let strongSelf = self else { return } strongSelf.viewModel.isShow = true } showLogVC.onDissmissViewHandler = { [weak self] in guard let strongSelf = self else { return } strongSelf.viewModel.isShow = false } showLogVC.showLogButton.onTouchHandler = { [weak self] _ in guard let strongSelf = self else { return } showLogVC.dismiss(animated: true, completion: { strongSelf.didTouchLogButtonHandle?() strongSelf.viewModel.isShow = false DispatchQueue.main.async { let logVC:LogTrackingTableViewController = LogTrackingTableViewController() UIApplication.topViewController()?.presentDef(vc: logVC, type: .overFullScreen) logVC.didTouchTitleLabelHandle = { request in strongSelf.didSendCurrentRequest?(request) } logVC.didTouchSubLabelHandle = { response in strongSelf.didSendCurrentResponse?(response) } } }) } showLogVC.showReportBugButton.onTouchHandler = { [weak self] _ in guard let strongSelf = self else { return } showLogVC.dismiss(animated: true, completion: { strongSelf.didTouchReportlHandle?() strongSelf.viewModel.isShow = false }) } showLogVC.showSettingButton.onTouchHandler = { [weak self] _ in guard let strongSelf = self else { return } showLogVC.dismiss(animated: true, completion: { strongSelf.didTouchSettinglHandle?() strongSelf.viewModel.isShow = false }) } } } } } class OptionLogPresentViewController: TTCoverVerticalViewController { let label:TTBaseUILabel = TTBaseUILabel(withType: .TITLE, text: "IS DEV MODE", align: .left) let subLabel:TTBaseUILabel = TTBaseUILabel(withType: .SUB_TITLE, text: "View log by json or report bugs", align: .left) let showLogButton:TTBaseUIButton = TTBaseUIButton(textString: "SHOW LOG FILE", type: .DEFAULT, isSetSize: false) let showReportBugButton:TTBaseUIButton = TTBaseUIButton(textString: "REPORT BUG", type: .WARRING, isSetSize: false) let showSettingButton:TTBaseUIButton = TTBaseUIButton(textString: "SETTING", type: .WARRING, isSetSize: false) init(with title:String, subTitle:String) { super.init() self.label.setText(text: title) self.subLabel.setText(text: subTitle) } public var didLoad:( () -> ())? override func viewDidLoad() { super.viewDidLoad() self.didLoad?() } override func updateBaseUI() { super.updateBaseUI() self.bgView = UIColor.black.withAlphaComponent(0.8) self.view.backgroundColor = UIColor.clear self.view.addSubview(self.label) self.view.addSubview(self.subLabel) self.view.addSubview(self.showLogButton) self.view.addSubview(self.showReportBugButton) self.view.addSubview(self.showSettingButton) self.label.setVerticalContentHuggingPriority() .setLeadingAnchor(constant: 8).setTrailingAnchor(constant: 8) .setTopAnchor(constant: 10) self.subLabel.setVerticalContentHuggingPriority() .setLeadingAnchor(constant: 8).setTrailingAnchor(constant: 8) .setTopAnchorWithAboveView(nextToView: self.label, constant: 10) self.showLogButton.setTopAnchorWithAboveView(nextToView: self.subLabel, constant: 30) .setLeadingAnchor(constant: 8).setTrailingAnchor(constant: 8) .setHeightAnchor(constant: 35) self.showReportBugButton.setTopAnchorWithAboveView(nextToView: self.showLogButton, constant: 8) .setLeadingAnchor(constant: 8).setTrailingAnchor(constant: 8) .setHeightAnchor(constant: 35) self.showSettingButton.setTopAnchorWithAboveView(nextToView: self.showReportBugButton, constant: 8) .setLeadingAnchor(constant: 8).setTrailingAnchor(constant: 8) .setHeightAnchor(constant: 35) .setBottomAnchor(constant: 20, isMarginsGuide: true, priority: .defaultHigh) } }
39.282051
144
0.591253
87571fa5b1e094bd1211e9235e4fcee7d69d49f8
1,391
// // UIButton-Extension.swift // YoungWeibo // // Created by Young on 2016/12/10. // Copyright © 2016年 杨羽. All rights reserved. // import UIKit extension UIButton { class func creatButton(_ iamgeName : String , bgImageName : String) -> UIButton { let btn = UIButton() btn.setImage(UIImage.init(named: iamgeName), for: .normal) btn.setImage(UIImage.init(named: iamgeName + "_highlighted"), for: .highlighted) btn.setBackgroundImage(UIImage.init(named: bgImageName), for: .normal) btn.setBackgroundImage(UIImage.init(named: bgImageName + "_highlighted"), for: .highlighted) btn.sizeToFit() return btn } /** 构造函数 */ convenience init(iamgeName : String , bgImageName : String) { self.init() setImage(UIImage.init(named: iamgeName), for: .normal) setImage(UIImage.init(named: iamgeName + "_highlighted"), for: .highlighted) setBackgroundImage(UIImage.init(named: bgImageName), for: .normal) setBackgroundImage(UIImage.init(named: bgImageName + "_highlighted"), for: .highlighted) sizeToFit() } convenience init(bgColor : UIColor , fontNum : CGFloat , title : String) { self.init() backgroundColor = bgColor titleLabel?.font = UIFont.systemFont(ofSize: fontNum) setTitle(title, for: .normal) } }
32.348837
100
0.642703

Dataset 1: TheStack - Swift - Cleaned

Description: This dataset is drawn from TheStack Corpus, an open-source code dataset with over 3TB of GitHub data covering 48 programming languages. We selected a small portion of this dataset to optimize smaller language models for Swift, a popular statically typed language.

Target Language: Swift

Dataset Size:

  • Training: 900,000 files
  • Validation: 50,000 files
  • Test: 50,000 files

Preprocessing:

  1. Selected Swift as the target language due to its popularity on GitHub.
  2. Filtered out files with average line length > 100 characters, maximum line length > 1000 characters, and alphabet ratio < 25%.
  3. Split files into 90% training, 5% validation, and 5% test sets.

Tokenizer: Byte Pair Encoding (BPE) tokenizer with tab and whitespace tokens. GPT-2 vocabulary extended with special tokens.

Training Sequences: Sequences constructed by joining training data text to reach a context length of 2048 tokens (1024 tokens for full fine-tuning).

Downloads last month
0
Edit dataset card

Models trained or fine-tuned on ammarnasr/the-stack-swift-clean