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
d9ddf9613b1b81f7b500d46e63496d28ce10a9a0
293
// // MarkdownOutput.swift // PlistMapper // // Created by Grzegorz Maciak on 23/03/2019. // Copyright ยฉ 2019 kodelit. All rights reserved. // import Foundation struct MarkdownOutput: OutputType { static let outputDirName = "" static let outputFileExt = Markdown.fileExtension }
19.533333
53
0.720137
11a906a38a4f8a373f470ebb046130e63c4225da
2,213
// // AppDelegate.swift // KCSForm-iOS // // Created by Matthew Patience on 02/24/2019. // Copyright (c) 2019 Matthew Patience. All rights reserved. // import UIKit import IQKeyboardManager @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { IQKeyboardManager.shared().isEnabled = true 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:. } }
44.26
285
0.749661
eb140c9cfd86a68005ac06c52f6b1985156fc8d2
523
// // RouteDetailViewModel.swift // GoodServiceIO-Simple (iOS) // // Created by Christopher Sanders on 12/19/21. // import SwiftUI final class RouteDetailViewModel: ObservableObject { private var route: RouteDetailResponse var serviceChangeSummaries: [String: [String]] { route.serviceChangeSummaries } var serviceIrregularitySummaries: [String: String] { route.serviceIrregularitySummaries } init(route: RouteDetailResponse) { self.route = route } }
20.92
56
0.6826
183c1fdd75d092535bdc8c23190033577824c2b0
5,009
// // DDYZDAPI.swift // DDYZD_V2 // // Created by ๊น€์ˆ˜์™„ on 2021/01/17. // import Foundation import Alamofire enum DDYZDAPI { //Auth case getToken(_ DSMAuthToken: String) // ํ† ํฐ ๋ฐœ๊ธ‰ case postDeviceToken(_ DeviceToken: String) // ๋””๋ฐ”์ด์Šค ํ† ํฐ ์ž…๋ ฅ case getGCN // ํ•™๋ฒˆ ๋ฐœ๊ธ‰ case refreshToken // ํ† ํฐ ์žฌ๋ฐœ๊ธ‰ case userInfo(_ gcn: String) // ์œ ์ € ์ •๋ณด case modifyGithubID // ๊นƒํ—ˆ๋ธŒ ์•„์ด๋”” ๋ณ€๊ฒฝ case modifyBio // ์œ ์ € ์†Œ๊ฐœ ๋ณ€๊ฒฝ //feed case feedList(_ page: Int) // ๋ชจ๋“  ๋™์•„๋ฆฌ์˜ ํ”ผ๋“œ๋ฆฌ์ŠคํŠธ case clubFeedList(_ clubID: Int, _ page: Int) // ํŠน์ • ๋™์•„๋ฆฌ์˜ ํ”ผ๋“œ๋ฆฌ์ŠคํŠธ case flagIt(_ feedID: Int) // ํ”ผ๋“œ flag๋‹ฌ๊ธฐ case uploadFeed(_ clubID: Int) // ํ”ผ๋“œ ์˜ฌ๋ฆฌ๊ธฐ case modifyFeed(_ feedID: Int) // ํ”ผ๋“œ ์ˆ˜์ • case uploadFeedFile(_ feedID: Int) // ํ”ผ๋“œ ํŒŒ์ผ ์—…๋กœ๋“œ case deleteFeed(_ feedID: Int) // ํ”ผ๋“œ ์‚ญ์ œ case pinFeed(_ feedID: Int) // ํ”ผ๋“œ ๊ณ ์ • case reportFeed // ํ”ผ๋“œ ์‹ ๊ณ  //club case clubList // ๋™์•„๋ฆฌ ๋ฆฌ์ŠคํŠธ ๋ฐ˜ํ™˜ case clubDetailInfo(_ clubID: Int) // ๋™์•„๋ฆฌ ์ƒ์„ธ ์ •๋ณด case getRecruitment(_ clubID: Int) // ๋ชจ์ง‘ ๊ณต๊ณ  ์ •๋ณด ๋ฐ˜ํ™˜ case getClubMember(_ clubID: Int) // ๋™์•„๋ฆฌ ๋ฉค๋ฒ„ case cancelFollow(_ clubID: Int) // ๋™์•„๋ฆฌ ํŒ”๋กœ์šฐ ์ทจ์†Œ case exitClub(_ clubID: Int) // ์†Œ์† ๋™์•„๋ฆฌ ๋‚˜๊ฐ€๊ธฐ case followClub(_ clubID: Int) // ๋™์•„๋ฆฌ ํŒ”๋กœ์šฐ/ ํŒ”๋กœ์šฐ ์ทจ์†Œ //Chat case chatList // ์ฑ„ํŒ… ๋ฆฌ์ŠคํŠธ case createChatRoom(_ clubID: Int) // ์ฑ„ํŒ… ๋ฃธ ์ƒ์„ฑ case deleteChatRoom(_ roomID: Int) // ์ฑ„ํŒ… ๋ฃธ ์‚ญ์ œ case getRoomToken(_ roomID: Int) // ์ฑ„ํŒ…๋ฐฉ ํ† ํฐ ๋ฐœ๊ธ‰ case chatRoomInfo(_ roomID: Int) // ์ฑ„ํŒ… ๋ฃธ ์ •๋ณด case chatBreakdown(_ roomID: Int) // ์ฑ„ํŒ… ๋‚ด์—ญ func path() -> String { switch self { case .getToken(_): return "/users/token" case .postDeviceToken(_): return "/users/device_token" case .getGCN: return "/users/profile" case .refreshToken: return "/users/refresh" case .userInfo(let gcn): return "/users/\(gcn)" case .modifyGithubID: return "/users/profile/git" case .modifyBio: return "/users/profile/bio" case .feedList(let page): return "/feed/list?page=\(page)&" case .clubFeedList(let clubID, let page): return "/feed/\(clubID)/list?page=\(page)&" case .flagIt(let feedID): return "/feed/\(feedID)/flag" case .uploadFeed(let clubID): return "/feed/\(clubID)" case .modifyFeed(let feedID): return "/feed/\(feedID)" case .uploadFeedFile(let feedID): return "/feed/\(feedID)/medium" case .deleteFeed(let feedID): return "/feed/\(feedID)" case .pinFeed(let feedID): return "/feed/\(feedID)/pin" case .reportFeed: return "/report" case .clubList: return "/club/list" case .clubDetailInfo(let clubID): return "/club/\(clubID)/info" case .getRecruitment(let clubID): return "/club/\(clubID)/recruitment" case .getClubMember(let clubID): return "/club/\(clubID)/member" case .cancelFollow(let clubID): return "/club/\(clubID)/follow" case .exitClub(let clubID): return "/club/\(clubID)" case .followClub(let clubID): return "/club/\(clubID)/follow" case .chatList: return "/chat/list" case .createChatRoom(let clubID): return "/chat/\(clubID)/room" case .deleteChatRoom(let roomID): return "/room/\(roomID)" case .getRoomToken(let roomID): return "/room/\(roomID)/token" case .chatRoomInfo(let roomID): return "/room/\(roomID)/info" case .chatBreakdown(let roomID): return "/chat/\(roomID)/breakdown" } } func header() -> HTTPHeaders? { switch self { case .clubList, .getClubMember(_), .reportFeed: return nil case .getToken(let DSMAuthToken) : return ["access-token": "Bearer \(DSMAuthToken)"] case .refreshToken : guard let refresh_token = Token.refresh_token else { return nil } return ["refresh-token": "Bearer \(refresh_token)"] case .postDeviceToken(let DeviceToekn): return ["device-token": "Bearer \(DeviceToekn)", "Authorization": "Bearer \(Token.access_token)"] case .clubDetailInfo(_): if Token.access_token == "" { return nil } return ["Authorization": "Bearer \(Token.access_token)"] default: return ["Authorization": "Bearer \(Token.access_token)"] } } }
36.830882
77
0.526053
720b5e00efe9dd7a733ab19349dda99ac7041d56
744
// // STPEmptyStripeResponse.swift // StripeiOS // // Created by Cameron Sabol on 6/11/19. // Copyright ยฉ 2019 Stripe, Inc. All rights reserved. // import Foundation /// An STPAPIResponseDecodable implementation to use for endpoints that don't /// actually return objects, like /v1/3ds2/challenge_completed class STPEmptyStripeResponse: NSObject, STPAPIResponseDecodable { private(set) var allResponseFields: [AnyHashable: Any] = [:] required internal override init() { super.init() } class func decodedObject(fromAPIResponse response: [AnyHashable: Any]?) -> Self? { let emptyResponse = self.init() if let response = response { emptyResponse.allResponseFields = response } return emptyResponse } }
25.655172
84
0.721774
3af23334e545a1a9e67f82d0285ee701981c1717
12,315
// // PostTableViewController.swift // Pods // // Created by Le Dinh on 19/10/16. // // import UIKit public class PostTableViewController: UITableViewController, UIPopoverPresentationControllerDelegate { var postlist = [PostItem]() var postReading: ((Int)->())? var loadMore: (()->())? var editTap: ((Int)->())? var commentTap: ((Int, Bool)->())? //Social network tap var shareTap: ((Int)->())? var copyLinkTap: ((Int)->())? var approveTap: ((Int)->())? var deleteTap: ((Int)->())? var wechatTap: ((Int)->())? var viadeoTap: ((Int)->())? var instagramTap: ((Int)->())? var isAdmin: Bool = false var currentTab: String = "published" override public func viewDidLoad() { super.viewDidLoad() tableView.frame.size.width = 0 let podBundle = NSBundle(path: NSBundle(forClass: PostTableViewController.self).pathForResource("SGSnackBar", ofType: "bundle")!) let publishedNib = UINib(nibName: "PostCell", bundle:podBundle) let proposedNib = UINib(nibName: "ProposedCell", bundle: podBundle) tableView.registerNib(publishedNib, forCellReuseIdentifier: "publishedItem") tableView.registerNib(proposedNib, forCellReuseIdentifier: "proposedItem") self.tableView.rowHeight = UITableViewAutomaticDimension self.tableView.estimatedRowHeight = 88.0; self.tableView.separatorColor = UIColor.whiteColor() } override public func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override public func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return postlist.count } override public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let item = postlist[indexPath.row] switch currentTab { case "published": let cell = self.tableView.dequeueReusableCellWithIdentifier("publishedItem", forIndexPath: indexPath) as! PostTableViewCell let postTap = UITapGestureRecognizer(target: self, action: Selector("postTapping:")) postTap.numberOfTapsRequired = 1 cell.parentVC = self cell.addHandler(postReading) cell.socnetList = item.socnetList //Post cell.post.userInteractionEnabled = true cell.post.tag = indexPath.row cell.post.addGestureRecognizer(postTap) //Image if item.image == "" { let noImg = UIImage(named: "no_image.jpg") cell.postImage.image = noImg } else { if let url = NSURL(string: item.image) { if let data = NSData(contentsOfURL: url) { if let i = UIImage(data: data) { cell.postImage.image = i } } } } cell.postImage.userInteractionEnabled = true cell.postImage.clipsToBounds = true //Title cell.title.userInteractionEnabled = true cell.title.text = item.title //Body cell.body.text = item.body cell.body.userInteractionEnabled = true //Date cell.date.text = item.date as? String //Edit button cell.editButton.tag = indexPath.row cell.addEditTap(editTap) if self.isAdmin == false { cell.editButton.hidden = true; } //CommentCount label if item.commentEnabled == true { cell.commentCount.text = "\(item.commentCount) comments" let commentCountTap = UITapGestureRecognizer(target: self, action: Selector("commentTapping:")) commentCountTap.numberOfTapsRequired = 1 cell.commentCount.userInteractionEnabled = true cell.commentCount.addGestureRecognizer(commentCountTap) cell.commentCount.tag = indexPath.row } else { cell.commentCount.hidden = true cell.separateDot.hidden = true cell.comment.enabled = false cell.comment.setTitleColor(UIColor.lightGrayColor().colorWithAlphaComponent(0.7), forState: .Normal) } //Comment button cell.addCommentTapping(commentTap) cell.comment.tag = indexPath.row //Share button if cell.socnetList.count == 0 { cell.shareButton.enabled = false; cell.shareButton.setTitleColor(UIColor.lightGrayColor(), forState: .Normal) } cell.shareButton.tag = indexPath.row cell.shareTap = shareTap cell.copyLinkTap = copyLinkTap cell.wechatTap = wechatTap cell.viadeoTap = viadeoTap cell.instagramTap = instagramTap return cell case "proposed": let cell = self.tableView.dequeueReusableCellWithIdentifier("proposedItem", forIndexPath: indexPath) as! ProposedTableViewCell let postTap = UITapGestureRecognizer(target: self, action: Selector("postTapping:")) postTap.numberOfTapsRequired = 1 cell.parentVC = self cell.socnetList = item.socnetList //Post cell.post.userInteractionEnabled = true cell.post.tag = indexPath.row cell.post.addGestureRecognizer(postTap) //Image if item.image == "" { let noImg = UIImage(named: "no_image.jpg") cell.postImage.image = noImg } else { if let url = NSURL(string: item.image) { if let data = NSData(contentsOfURL: url) { if let i = UIImage(data: data) { cell.postImage.image = i } } } } cell.postImage.userInteractionEnabled = true cell.postImage.clipsToBounds = true //Title cell.title.userInteractionEnabled = true cell.title.text = item.title //Body cell.body.text = item.body cell.body.userInteractionEnabled = true //Date cell.date.text = item.date as? String //Edit button cell.editButton.tag = indexPath.row cell.addEditTap(editTap) if self.isAdmin == false { cell.editButton.hidden = true; } //CommentCount label if item.commentEnabled == true { cell.commentCount.text = "\(item.commentCount) comments" let commentCountTap = UITapGestureRecognizer(target: self, action: Selector("commentTapping:")) commentCountTap.numberOfTapsRequired = 1 cell.commentCount.userInteractionEnabled = true cell.commentCount.addGestureRecognizer(commentCountTap) cell.commentCount.tag = indexPath.row } else { cell.commentCount.hidden = true cell.separateDot.hidden = true } //Approve button cell.approveButton.setTitleColor(UIColor.blueColor(), forState: .Normal) cell.approveButton.tag = indexPath.row cell.approveTapping = approveTap //Delete button cell.deleteButton.tag = indexPath.row cell.deleteTapping = deleteTap return cell default: print("Default case defining cell") let cell: UITableViewCell = UITableViewCell() return cell } } override public func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { let lastRow = postlist.count - 1 if indexPath.row == lastRow { loadMore?() } } func postTapping(sender: UITapGestureRecognizer) { postReading?((sender.view?.tag)!) } func commentTapping(sender: UITapGestureRecognizer) { commentTap?((sender.view?.tag)!, false) } public func addHandler(function: (Int)->()){ postReading = function } public func addLoadMore(function: ()->()){ loadMore = function } public func addEditTap(function: (Int)->()) { editTap = function } public func addCommentTap(function:(Int, Bool)->()){ commentTap = function } public func addShareTap(function:(Int) -> ()) { shareTap = function } public func addApproveTap(function: (Int)->()) { approveTap = function } public func addDeleteTap(function: (Int)->()) { deleteTap = function } public func addGenericTap(function: (Int)->()) { copyLinkTap = function } public func addViadeoTap(function: (Int)->()) { viadeoTap = function } public func addWechatTap(function: (Int)->()) { wechatTap = function } public func addInstagramTap(function: (Int)->()) { instagramTap = function } public func generatePostlist(posts: [NSObject]) { postlist = [PostItem]() for item in posts { var p = PostItem() if let title = item.valueForKey("title") as? String { p.title = title } if let imageUrl = item.valueForKey("imageUrl") as? String { p.image = imageUrl } if let body = item.valueForKey("body") as? String { p.body = body } if let date = item.valueForKey("postDate") as? String { p.date = date } else { p.date = "" } if let cmtCount = item.valueForKey("commentCount") as? Int { p.commentCount = cmtCount } if let isCommentEnabled = item.valueForKey("commentEnabled") as? Bool { p.commentEnabled = isCommentEnabled } if let socnetList = item.valueForKey("socnetList") as? [String] { p.socnetList = socnetList } postlist.append(p) } tableView.reloadData() } public func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle { return .None } public func refresh() { postlist = [PostItem]() } public func setAdmin(value: Bool) { self.isAdmin = value } public func setTab(tab: String) { currentTab = tab.lowercaseString } }
36.434911
142
0.521072
754da4e735d4e644f304faf4314f2ab7013f3d12
122
import XCTest import HexasphereTests var tests = [XCTestCaseEntry]() tests += HexasphereTests.allTests() XCTMain(tests)
15.25
35
0.786885
1d20cc77fcf647957b876e8902ea2bdcb99c4db1
1,351
// // AppDelegate.swift // Prework // // Created by Laurent Shumbusha on 7/22/21. // import UIKit @main class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } }
36.513514
179
0.746114
f8f073170a228b185fe132c0b95c17d4813e8cf7
987
import AST /// Type creator. public struct TypeCreator: ASTVisitor, Pass { public let name: String = "type creation" public init() {} public mutating func run(on module: Node, in context: Context) -> [Error] { self.context = context do { try visit(module) return errors } catch { return [error] } } public mutating func visit(_ node: FunDecl) throws { guard let symbol: Symbol = context[node, "symbol"] else { errors.append(UndefinedSymbol(name: node.name, at: node.range)) return } symbol.type = FunctionType(domain: node.parameters.map({ $0.mutability })) // Visit the parameters, in case a function is declared in their default values. try visit(node.parameters) } /// The AST context. private var context: Context! /// An array of the errors detected during the pass. private var errors: [Error] = [] }
26.675676
88
0.597771
18f1af29e239ad5d708b99756e96e314a7d3480f
378
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing A : A { return { self).substringWithRange(c = ")! func b.B(array: T, x in x } class B == { c(#object1, c("foo"")) func f<T) -> { let t: C<T -> U -> S<T where T) { } } } } protocol B : c, AnyObject, x { func c
22.235294
87
0.640212
6460f61630f27df1f67ef93b742ed87af2398e3d
930
// // Data_RepositoryTests.swift // Data.RepositoryTests // // Created by Kensuke Tamura on 2021/04/29. // import XCTest @testable import Data_Repository class Data_RepositoryTests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() throws { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
27.352941
111
0.674194
e9814c8201b53d82466601d20ca1fa48460c6ea4
235
// // UITableViewCell.swift // TemplateSwift3 // // Created by Hipolito Arias on 13/07/2017. // Copyright ยฉ 2017 Hipolito Arias. All rights reserved. // import Foundation import UIKit extension UITableViewCell: ReusableView { }
16.785714
57
0.731915
4867928aa518d547cc5764d61e0d5c1b23cd29c0
531
/// Number of generations to play in the game of life. public enum Generations: Equatable { case infinite case finite(Int) /// Returns `true` if number of generations left is 0. var hasReachedEnd: Bool { switch self { case .infinite: return false case .finite(let number): return number == 0 } } /// Decrements the number of generations left until it reaches 0. mutating func decrement() { switch self { case .infinite: break case .finite(let number): self = .finite(max(0, number - 1)) } } }
20.423077
66
0.6742
0e5161cf31cea55689864016648bfcc630fb474e
1,064
// // TargetType+Base.swift // HRSwiftDemo // // Created by haoran on 2018/10/19. // Copyright ยฉ 2018ๅนด haoran. All rights reserved. // import Foundation import Moya extension TargetType { /// The target's base `URL`. var baseURL: URL { return URL.init(string: "http://localhost:3000")! } /// The path to be appended to `baseURL` to form the full `URL`. // var path: String { get } /// The HTTP method used in the request. var method: Moya.Method { return .post } /// Provides stub data for use in testing. var sampleData: Data { return "".data(using: .utf8)! } /// The type of HTTP task to be performed. var task: Task { return .requestPlain } /// The type of validation to perform on the request. Default is `.none`. var validationType: ValidationType { return .none } /// The headers to be used in the request. var headers: [String: String]? { let header = ["Client-Value": "13"] return header } }
23.130435
77
0.589286
33198ac38a379deba64c7bebb463d7e3451b4848
1,124
extension Authenticatable { /// Basic middleware to redirect unauthenticated requests to the supplied path public static func redirectMiddleware(path: String) -> Middleware { return RedirectMiddleware<Self>(Self.self, path: path) } } /// Basic middleware to redirect unauthenticated requests to the supplied path private final class RedirectMiddleware<A>: Middleware where A: Authenticatable { /// The path to redirect to let path: String /// Initialise the `RedirectMiddleware` /// /// - parameters: /// - authenticatableType: The type to check authentication against /// - path: The path to redirect to if the request is not authenticated init(_ authenticatableType: A.Type = A.self, path: String) { self.path = path } /// See Middleware.respond func respond(to req: Request, chainingTo next: Responder) -> EventLoopFuture<Response> { if req.isAuthenticated(A.self) { return next.respond(to: req) } let redirect = req.redirect(to: path) return req.eventLoop.makeSucceededFuture(redirect) } }
35.125
92
0.679715
ed42a57aa3b6a118e3e4a46996f56966fba7fc36
873
// // GridView.swift // LetSwift // // Created by ์‹ ํ•œ์„ญ on 2020/11/23. // import SwiftUI struct GridView<Content: View>: View { let rows: Int let columns: Int let content: (Int) -> Content var body: some View { VStack(spacing: 10) { ForEach(0 ..< rows, id: \.self) { row in HStack(alignment: .top) { ForEach(0 ..< self.columns, id: \.self) { column in self.content(row * self.columns + column) if column + 1 != self.columns { Spacer() } } } } } } init(rows: Int, columns: Int, @ViewBuilder content: @escaping (Int) -> Content) { self.rows = rows self.columns = columns self.content = content } }
24.25
85
0.451317
fe1d61d81b3edd17d37df79518cf149850ec5586
706
// // Copyright ยฉ 2019 Essential Developer. All rights reserved. // import UIKit final class WeakRefVirtualProxy<T: AnyObject> { private weak var object: T? init(_ object: T) { self.object = object } } extension WeakRefVirtualProxy: FeedLoadingView where T: FeedLoadingView { func display(_ viewModel: FeedLoadingViewModel) { object?.display(viewModel) } } extension WeakRefVirtualProxy: FeedImageView where T: FeedImageView, T.Image == UIImage { func display(_ model: FeedImageViewModel<UIImage>) { object?.display(model) } } extension WeakRefVirtualProxy: FeedErrorView where T: FeedErrorView { func display(_ viewModel: FeedErrorStateViewModel) { object?.display(viewModel) } }
22.0625
89
0.754958
11eb4ae5723df3df29b8e8396dee2dd08dac4357
3,664
// // StackableViewContainer.swift // BingoPhotoViewerDemo // // Created by ็Ž‹ๆ˜ฑๆ–Œ on 2018/1/2. // Copyright ยฉ 2018ๅนด Qtin. All rights reserved. // import UIKit @objc(StackableViewContainerDelegate) protocol StackableViewContainerDelegate : NSObjectProtocol , AnyObject { @objc optional func stackableViewContainer(_ vc: StackableViewContainer, didAddSubview: UIView) -> Void @objc optional func stackableViewContainer(_ vc: StackableViewContainer, willRemoveSubview: UIView) -> Void } @objc(StackableViewContainer) class StackableViewContainer: UIView { @objc(StackableViewContainerAnchorPoint) enum StackableViewContainerAnchorPoint : Int { case top, bottom } weak var delegate: StackableViewContainerDelegate? var contentInset : UIEdgeInsets = .zero @objc fileprivate(set) var anchorPoint: StackableViewContainerAnchorPoint init(views: [UIView], anchoredAt point: StackableViewContainerAnchorPoint) { anchorPoint = point super.init(frame: .zero) for view in views { addSubview(view) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() computeSize(for: frame.size, applySizingLayout: true) } override func sizeThatFits(_ size: CGSize) -> CGSize { return computeSize(for: size, applySizingLayout: false) } override func didAddSubview(_ subview: UIView) { super.didAddSubview(subview) guard let delegate = delegate , let function = delegate.stackableViewContainer(_:didAddSubview:) else { return } function(self, subview) } override func willRemoveSubview(_ subview: UIView) { super.willRemoveSubview(subview) guard let delegate = delegate , let function = delegate.stackableViewContainer(_:willRemoveSubview:) else { return } function(self, subview) } } extension StackableViewContainer{ @discardableResult fileprivate func computeSize(for constrainedSize: CGSize, applySizingLayout: Bool) -> CGSize { var yOffset: CGFloat = 0 let xOffset: CGFloat = self.contentInset.left var constrainedInsetSize = constrainedSize constrainedInsetSize.width -= (self.contentInset.left + self.contentInset.right) let subviews = (self.anchorPoint == .top) ? self.subviews : self.subviews.reversed() for subview in subviews { let size = subview.sizeThatFits(constrainedInsetSize) var frame: CGRect if yOffset == 0 && size.height > 0 { yOffset = self.contentInset.top } if subview is UIToolbar || subview is UINavigationBar { frame = CGRect(x: xOffset, y: yOffset, width: constrainedInsetSize.width, height: size.height) } else { frame = CGRect(origin: CGPoint(x: xOffset, y: yOffset), size: size) } yOffset += frame.size.height if applySizingLayout { subview.frame = frame subview.setNeedsLayout() subview.layoutIfNeeded() } } if (yOffset - self.contentInset.top) > 0 { yOffset += self.contentInset.bottom } return CGSize(width: constrainedSize.width, height: yOffset) } }
30.533333
117
0.615175
e4c09103e5e7a4002ed12f868a5acff77e65c9ef
376
// // NetShearsModfierProtocol.swift // NetShears // // Created by Mehdi Mirzaie on 6/19/21. // import Foundation public protocol RequestEvaluator { func isActionAllowed(urlRequest: URLRequest) -> Bool } public protocol RequestModifier { func modify(request: inout URLRequest) } public protocol RequestEvaluatorModifier : RequestEvaluator, RequestModifier {}
17.904762
79
0.757979
2fb30204004d32ddf3859dff941e40bb0c627616
944
// // AlertControllerTests.swift // AlertControllerTests // // Created by Himanshu Ingole3 on 10/14/18. // Copyright ยฉ 2018 Himanshu Ingole3. All rights reserved. // import XCTest @testable import AlertController class AlertControllerTests: XCTestCase { override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
26.971429
111
0.668432
f4ccaf1ade3157bb981c3675773ca17328325392
4,355
import XCTest import QCloudCOSXML class PictureOperation: XCTestCase,QCloudSignatureProvider,QCloudCredentailFenceQueueDelegate{ var credentialFenceQueue:QCloudCredentailFenceQueue?; override func setUp() { let config = QCloudServiceConfiguration.init(); config.signatureProvider = self; config.appID = "1253653367"; let endpoint = QCloudCOSXMLEndPoint.init(); endpoint.regionName = "ap-guangzhou";//ๆœๅŠกๅœฐๅŸŸๅ็งฐ๏ผŒๅฏ็”จ็š„ๅœฐๅŸŸ่ฏทๅ‚่€ƒๆณจ้‡Š endpoint.useHTTPS = true; config.endpoint = endpoint; QCloudCOSXMLService.registerDefaultCOSXML(with: config); QCloudCOSTransferMangerService.registerDefaultCOSTransferManger(with: config); // ่„šๆ‰‹ๆžถ็”จไบŽ่Žทๅ–ไธดๆ—ถๅฏ†้’ฅ self.credentialFenceQueue = QCloudCredentailFenceQueue(); self.credentialFenceQueue?.delegate = self; } func fenceQueue(_ queue: QCloudCredentailFenceQueue!, requestCreatorWithContinue continueBlock: QCloudCredentailFenceQueueContinue!) { let cre = QCloudCredential.init(); //ๅœจ่ฟ™้‡ŒๅฏไปฅๅŒๆญฅ่ฟ‡็จ‹ไปŽๆœๅŠกๅ™จ่Žทๅ–ไธดๆ—ถ็ญพๅ้œ€่ฆ็š„ secretID๏ผŒsecretKey๏ผŒexpiretionDate ๅ’Œ token ๅ‚ๆ•ฐ cre.secretID = "COS_SECRETID"; cre.secretKey = "COS_SECRETKEY"; cre.token = "COS_TOKEN"; /*ๅผบ็ƒˆๅปบ่ฎฎ่ฟ”ๅ›žๆœๅŠกๅ™จๆ—ถ้—ดไฝœไธบ็ญพๅ็š„ๅผ€ๅง‹ๆ—ถ้—ด๏ผŒ็”จๆฅ้ฟๅ…็”ฑไบŽ็”จๆˆทๆ‰‹ๆœบๆœฌๅœฐๆ—ถ้—ดๅๅทฎ่ฟ‡ๅคงๅฏผ่‡ด็š„็ญพๅไธๆญฃ็กฎ */ cre.startDate = DateFormatter().date(from: "startTime"); // ๅ•ไฝๆ˜ฏ็ง’ cre.experationDate = DateFormatter().date(from: "expiredTime"); let auth = QCloudAuthentationV5Creator.init(credential: cre); continueBlock(auth,nil); } func signature(with fileds: QCloudSignatureFields!, request: QCloudBizHTTPRequest!, urlRequest urlRequst: NSMutableURLRequest!, compelete continueBlock: QCloudHTTPAuthentationContinueBlock!) { self.credentialFenceQueue?.performAction({ (creator, error) in if error != nil { continueBlock(nil,error!); }else{ let signature = creator?.signature(forData: urlRequst); continueBlock(signature,nil); } }) } // ไธŠไผ ๆ—ถๅ›พ็‰‡ๅค„็† func uploadWithPicOperation() { //.cssg-snippet-body-start:[swift-upload-with-pic-operation] let put = QCloudPutObjectWatermarkRequest<AnyObject>(); // ๅฏน่ฑก้”ฎ๏ผŒๆ˜ฏๅฏน่ฑกๅœจ COS ไธŠ็š„ๅฎŒๆ•ด่ทฏๅพ„๏ผŒๅฆ‚ๆžœๅธฆ็›ฎๅฝ•็š„่ฏ๏ผŒๆ ผๅผไธบ "dir1/object1" put.object = "exampleobject"; // ๅญ˜ๅ‚จๆกถๅ็งฐ๏ผŒๆ ผๅผไธบ BucketName-APPID put.bucket = "examplebucket-1250000000"; put.body = "123456789".data(using: .utf8)! as NSData; let op = QCloudPicOperations.init(); // ๆ˜ฏๅฆ่ฟ”ๅ›žๅŽŸๅ›พไฟกๆฏใ€‚0่กจ็คบไธ่ฟ”ๅ›žๅŽŸๅ›พไฟกๆฏ๏ผŒ1่กจ็คบ่ฟ”ๅ›žๅŽŸๅ›พไฟกๆฏ๏ผŒ้ป˜่ฎคไธบ0 op.is_pic_info = false; let rule = QCloudPicOperationRule.init(); // ๅค„็†็ป“ๆžœ็š„ๆ–‡ไปถ่ทฏๅพ„ๅ็งฐ๏ผŒๅฆ‚ไปฅ/ๅผ€ๅคด๏ผŒๅˆ™ๅญ˜ๅ…ฅๆŒ‡ๅฎšๆ–‡ไปถๅคนไธญ๏ผŒๅฆๅˆ™๏ผŒๅญ˜ๅ…ฅๅŽŸๅ›พๆ–‡ไปถๅญ˜ๅ‚จ็š„ๅŒ็›ฎๅฝ• rule.fileid = "test"; // ็›ฒๆฐดๅฐๆ–‡ๅญ—๏ผŒ้œ€่ฆ็ป่ฟ‡ URL ๅฎ‰ๅ…จ็š„ Base64 ็ผ–็ ใ€‚ๅฝ“ type ไธบ3ๆ—ถๅฟ…ๅกซ๏ผŒtype ไธบ1ๆˆ–2ๆ—ถๆ— ๆ•ˆใ€‚ rule.text = "123"; // ็›ฒๆฐดๅฐ็ฑปๅž‹๏ผŒๆœ‰ๆ•ˆๅ€ผ๏ผš1 ๅŠ็›ฒ๏ผ›2 ๅ…จ็›ฒ๏ผ›3 ๆ–‡ๅญ— rule.type = .text; op.rule = [rule]; put.picOperations = op; put.setFinish { (outoutObject, error) in }; QCloudCOSXMLService.defaultCOSXML().putWatermarkObject(put); //.cssg-snippet-body-end } // ๅฏนไบ‘ไธŠๆ•ฐๆฎ่ฟ›่กŒๅ›พ็‰‡ๅค„็† func processWithPicOperation() { //ไธๆ”ฏๆŒ //.cssg-snippet-body-start:[swift-process-with-pic-operation] //.cssg-snippet-body-end } // ไธŠไผ ๆ—ถๆทปๅŠ ็›ฒๆฐดๅฐ func putObjectWithWatermark() { //ไธๆ”ฏๆŒ //.cssg-snippet-body-start:[swift-put-object-with-watermark] //.cssg-snippet-body-end } // ไธ‹่ฝฝๆ—ถๆทปๅŠ ็›ฒๆฐดๅฐ func downloadObjectWithWatermark() { //ไธๆ”ฏๆŒ //.cssg-snippet-body-start:[swift-download-object-with-watermark] //.cssg-snippet-body-end } // ๅ›พ็‰‡ๅฎกๆ ธ func sensitiveContentRecognition() { //ไธๆ”ฏๆŒ //.cssg-snippet-body-start:[swift-sensitive-content-recognition] //.cssg-snippet-body-end } // .cssg-methods-pragma func testPictureOperation() { // ไธŠไผ ๆ—ถๅ›พ็‰‡ๅค„็† self.uploadWithPicOperation(); // ๅฏนไบ‘ไธŠๆ•ฐๆฎ่ฟ›่กŒๅ›พ็‰‡ๅค„็† self.processWithPicOperation(); // ไธŠไผ ๆ—ถๆทปๅŠ ็›ฒๆฐดๅฐ self.putObjectWithWatermark(); // ไธ‹่ฝฝๆ—ถๆทปๅŠ ็›ฒๆฐดๅฐ self.downloadObjectWithWatermark(); // ๅ›พ็‰‡ๅฎกๆ ธ self.sensitiveContentRecognition(); // .cssg-methods-pragma } }
31.788321
196
0.628014
e5209bea21c34c2a304e37e6981b7580ee91ac7c
534
// 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 struct B<T where B : U -> ((g<T.e == { return self.h : X.C<T where Optional<T where f, d>(n: A> T>(") struct A { switch x { } var b = B
35.6
79
0.70412
e8c6adeda207584e32ae7e8d0fc9f9efbb15239c
4,368
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/noppoMan/aws-sdk-swift/blob/master/Sources/CodeGenerator/main.swift. DO NOT EDIT. import AWSSDKSwiftCore /// Error enum for DirectoryService public enum DirectoryServiceErrorType: AWSErrorType { case entityDoesNotExistException(message: String?) case directoryUnavailableException(message: String?) case invalidParameterException(message: String?) case unsupportedOperationException(message: String?) case clientException(message: String?) case serviceException(message: String?) case invalidNextTokenException(message: String?) case entityAlreadyExistsException(message: String?) case tagLimitExceededException(message: String?) case invalidTargetException(message: String?) case directoryNotSharedException(message: String?) case ipRouteLimitExceededException(message: String?) case snapshotLimitExceededException(message: String?) case insufficientPermissionsException(message: String?) case authenticationFailedException(message: String?) case userDoesNotExistException(message: String?) case invalidPasswordException(message: String?) case directoryAlreadySharedException(message: String?) case shareLimitExceededException(message: String?) case organizationsException(message: String?) case accessDeniedException(message: String?) case directoryLimitExceededException(message: String?) case domainControllerLimitExceededException(message: String?) } extension DirectoryServiceErrorType { public init?(errorCode: String, message: String?){ var errorCode = errorCode if let index = errorCode.index(of: "#") { errorCode = String(errorCode[errorCode.index(index, offsetBy: 1)...]) } switch errorCode { case "EntityDoesNotExistException": self = .entityDoesNotExistException(message: message) case "DirectoryUnavailableException": self = .directoryUnavailableException(message: message) case "InvalidParameterException": self = .invalidParameterException(message: message) case "UnsupportedOperationException": self = .unsupportedOperationException(message: message) case "ClientException": self = .clientException(message: message) case "ServiceException": self = .serviceException(message: message) case "InvalidNextTokenException": self = .invalidNextTokenException(message: message) case "EntityAlreadyExistsException": self = .entityAlreadyExistsException(message: message) case "TagLimitExceededException": self = .tagLimitExceededException(message: message) case "InvalidTargetException": self = .invalidTargetException(message: message) case "DirectoryNotSharedException": self = .directoryNotSharedException(message: message) case "IpRouteLimitExceededException": self = .ipRouteLimitExceededException(message: message) case "SnapshotLimitExceededException": self = .snapshotLimitExceededException(message: message) case "InsufficientPermissionsException": self = .insufficientPermissionsException(message: message) case "AuthenticationFailedException": self = .authenticationFailedException(message: message) case "UserDoesNotExistException": self = .userDoesNotExistException(message: message) case "InvalidPasswordException": self = .invalidPasswordException(message: message) case "DirectoryAlreadySharedException": self = .directoryAlreadySharedException(message: message) case "ShareLimitExceededException": self = .shareLimitExceededException(message: message) case "OrganizationsException": self = .organizationsException(message: message) case "AccessDeniedException": self = .accessDeniedException(message: message) case "DirectoryLimitExceededException": self = .directoryLimitExceededException(message: message) case "DomainControllerLimitExceededException": self = .domainControllerLimitExceededException(message: message) default: return nil } } }
49.078652
143
0.716804
c1bc445fb95631022ad83c7a8d275fefb8a5dda5
360
// // CurrentDataObj.swift // UD Open Lora // // Created by Khoa Bao on 1/7/19. // Copyright ยฉ 2019 Khoa Bao. All rights reserved. // import Foundation import SwiftyJSON final class CurrentData { var id: String? var status: Bool? init(id: String, data: JSON) { self.id = id self.status = data["status"].bool } }
16.363636
51
0.602778
713a698dee8c2d9f5d1a668b07cdcb12acc5e32f
18,044
// // GLTaskDetailViewController.swift // Yihaodar // // Created by ๅผ ๅ›ฝๆข on 2018/2/7. // Copyright ยฉ 2018ๅนด Yihaodar. All rights reserved. // import Spring import SwiftyJSON import SKPhotoBrowser import SnapKit import HandyJSON /* // ๆž้€Ÿ { "custId": "YHD-BD-CD-20171214-0001", "custRequestId": "", "vehicles": [ { "fileTitle": "่ฝฆ่พ†้ฉพ้ฉถ่ฏ/ๆœบๅŠจ่ฝฆ็™ป่ฎฐ่ฏไนฆ", "fileName": "4b0f0de323d84f5d801a60ee89871728.jpg", "uuid": "01201712141304073900", "fileUrl": "http://www.duanhan.ren/staticgfs/4b0f0de323d84f5d801a60ee89871728.jpg" }, { "fileTitle": "ๅ…ถไป–้™„ไปถ", "fileName": "d929b94352a74e11bdc69a8297856c68.jpg", "uuid": "01201712141304073912", "fileUrl": "http://www.duanhan.ren/staticgfs/d929b94352a74e11bdc69a8297856c68.jpg" } ], "others": "[{"fileUrl":"http: //www.duanhan.ren/staticgfs/d929b94352a74e11bdc69a8297856c68.jpg","fileName":"d929b94352a74e11bdc69a8297856c68.jpg"}]", "bDType": "2", "createdDate": "2017ๅนด12ๆœˆ14ๆ—ฅ 17:29:54", "quotesId": "yhd_wap000022" } // ๆ‰‹ๅŠจ { "custId": "YHD-BD-CD-20171214-0002", "custRequestId": "", "isBj": "0", "goodsSeries": "23562", "brandName": "117", "registerTime": "2012", "quotesId": "yhd_wap000022", "goodsSeriesName": "2015ๆฌพ ACS3 sport", "runNumber": "", "parValue": "", "brandNameCN": "AC Schnitzer", "brandSeriesName": "AC Schnitzer M3", "bDType": "1", "createdDate": "2017ๅนด12ๆœˆ14ๆ—ฅ 17:30:17", "carColor": "", "brandSeries": "3895" } */ /// ่ฏ„ไผฐไฟกๆฏๆจกๅž‹ struct GLEstimateMsgModel: HandyJSON { var worth_id: String? var org_name: String? var created_date_long: String? var last_update_date_long: String? var evaluat_status: String? var cust_request_id: String? var party_id: String? var created_date: String? var party_name: String? var process_id: String? var last_update_date: String? var org_id: String? var store_id: String? var store_name: String? var dep_id: String? var dep_name: String? var confirmed_date: String? var confirmed_money: String? var car_info: String? var remarks: String? } /// ๆž้€Ÿไฟๅ•ๅ›พ็‰‡ๆจกๅž‹ struct GLTaskDetailPictureModel: HandyJSON { var fileTitle: String? var fileName: String? var uuid: String? var fileUrl: String? } /// ๆŠฅๅ•่ฏฆๆƒ…ๆจกๅž‹ struct GLTaskDetailModel: HandyJSON { var custId: String? var custRequestId: String? var isBj: String? var goodsSeries: String? var brandName: String? var registerTime: String? var quotesId: String? var goodsSeriesName: String? var runNumber: String? var parValue: String? var brandNameCN: String? var brandSeriesName: String? var bDType: String? var createdDate: String? var carColor: String? var brandSeries: String? var vehicles: [GLTaskDetailPictureModel]? var others: GLTaskDetailPictureModel? } class GLTaskDetailViewController: UIViewController { /// ๆŠฅๅ•ไฟกๆฏ -------------------- @IBOutlet weak var contentView: UIView! @IBOutlet weak var orderNumberLabel: UILabel! @IBOutlet weak var orderPersonLabel: UILabel! @IBOutlet weak var orderSubmitDateLabel: UILabel! // ๆ‰‹ๅŠจไฟๅ•่ง†ๅ›พ @IBOutlet weak var manualView: UIView! @IBOutlet weak var orderCarBrandlabel: UILabel! @IBOutlet weak var orderCarYearLabel: UILabel! @IBOutlet weak var orderMileageLabel: UILabel! @IBOutlet weak var orderBigMoneyLabel: UILabel! @IBOutlet weak var orderCarColorLabel: UILabel! @IBOutlet weak var orderIsBeiJingNumberLabel: UILabel! // ๆž้€Ÿไฟๅ• @IBOutlet weak var speedView: UIView! @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var collectionViewHeight: NSLayoutConstraint! /// ่ฏ„ไผฐไฟกๆฏ --------------------- @IBOutlet weak var estimateMsgView: DesignableView! @IBOutlet weak var estimateMsgViewTop: NSLayoutConstraint! @IBOutlet weak var estimateDateLabel: UILabel! @IBOutlet weak var estimatePriceLabel: UILabel! @IBOutlet weak var estimateCarDetailMsgLabel: UILabel! @IBOutlet weak var estimateMemoLabel: UILabel! /// ่ฟ‡ๆœŸๅคฑๆ•ˆ่ง†ๅ›พ @IBOutlet weak var invalidView: UIView! @IBOutlet weak var invalidDateLabel: UILabel! /// ๅบ•้ƒจ่ฏ„ไผฐ่ง†ๅ›พ @IBOutlet weak var bottomView: UIView! @IBOutlet weak var estimateButton: DesignableButton! @IBOutlet weak var bottomViewBottom: NSLayoutConstraint! /// ๅˆ—่กจcellๆจกๅž‹ var model: GLWorkTableModel? /// ่ฏฆๆƒ…ๆจกๅž‹ var detailModel: GLTaskDetailModel? { didSet{ orderNumberLabel.text = detailModel?.custId orderPersonLabel.text = detailModel?.quotesId orderSubmitDateLabel.text = detailModel?.createdDate if detailModel?.bDType == "1" { // ๆ‰‹ๅŠจๆŠฅๅ• speedView.isHidden = true manualView.isHidden = false speedView.snp.remakeConstraints({ (make) in make.height.equalTo(0) }) manualView.snp.removeConstraints() orderCarBrandlabel.text = (detailModel?.brandNameCN)! + " " + (detailModel?.brandSeriesName)! + " " + (detailModel?.goodsSeriesName)! if detailModel?.registerTime?.isEmpty == false { orderCarYearLabel.text = (detailModel?.registerTime)! + "ๅนด" } else { orderCarYearLabel.text = "ๆœชๅกซๅ†™" orderCarYearLabel.textColor = YiUnselectedTitleColor } if detailModel?.runNumber?.isEmpty == false { orderMileageLabel.text = (detailModel?.runNumber)! + "ๅ…ฌ้‡Œ" } else { orderMileageLabel.text = "ๆœชๅกซๅ†™" orderMileageLabel.textColor = YiUnselectedTitleColor } if detailModel?.parValue?.isEmpty == false { orderBigMoneyLabel.text = (detailModel?.parValue)!.decimalString() + "ๅ…ƒ" } else { orderBigMoneyLabel.text = "ๆœชๅกซๅ†™" orderBigMoneyLabel.textColor = YiUnselectedTitleColor } if detailModel?.carColor?.isEmpty == false { orderCarColorLabel.text = detailModel?.carColor } else { orderCarColorLabel.text = "ๆœชๅกซๅ†™" orderCarColorLabel.textColor = YiUnselectedTitleColor } if detailModel?.isBj?.isEmpty == false { orderIsBeiJingNumberLabel.text = detailModel?.isBj == "0" ? "ๆ˜ฏ" : "ๅฆ" } else { orderIsBeiJingNumberLabel.text = "ๆœชๅกซๅ†™" orderIsBeiJingNumberLabel.textColor = YiUnselectedTitleColor } } else if detailModel?.bDType == "2" { // ๆž้€ŸๆŠฅๅ• speedView.isHidden = false manualView.isHidden = true speedView.snp.removeConstraints() manualView.snp.remakeConstraints({ (make) in make.height.equalTo(0) }) detailModel?.vehicles?.enumerated().forEach({ (index, value) in var photo = SKPhoto.photoWithImageURL((value.fileUrl)!) if let image = SKCache.sharedCache.imageForKey((value.fileUrl)!) { photo = SKPhoto.photoWithImage(image) } photo.checkCache() photo.index = index photo.shouldCachePhotoURLImage = true photo.loadUnderlyingImageAndNotify() imagesss.append(photo) }) observer = NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: SKPHOTO_LOADING_DID_END_NOTIFICATION), object: nil, queue: OperationQueue.main, using: {[weak self] (noti) in guard let photo = noti.object as? SKPhoto else {return} let indexPath = IndexPath(item: photo.index, section: 0) self?.collectionView.reloadItems(at: [indexPath]) }) let count = (detailModel?.vehicles?.count)! - 1 let constant = CGFloat((Int(count)/3)+1) * 100.0 - 10 collectionViewHeight.constant = constant collectionView.reloadData() } } } /// ่ฏ„ไผฐไฟกๆฏๆจกๅž‹ var estimateMsgModel: GLEstimateMsgModel? { didSet{ guard let estimateMsgModel = estimateMsgModel else { return } guard let evaluat_status = estimateMsgModel.evaluat_status else { return } if evaluat_status == "1" || evaluat_status == "2" { // ๅทฒ่ฏ„ไผฐ if evaluat_status == "2" { // ๅทฒๅคฑๆ•ˆ invalidView.isHidden = false if let str = estimateMsgModel.last_update_date { invalidDateLabel.text = str.substring(to: str.index(str.startIndex, offsetBy: 10)) } } else { // ๆœชๅคฑๆ•ˆ invalidView.isHidden = true } bottomView.isHidden = true bottomViewBottom.constant = 64 estimateMsgView.isHidden = false estimateMsgView.snp.removeConstraints() estimateDateLabel.text = estimateMsgModel.confirmed_date estimatePriceLabel.text = (estimateMsgModel.confirmed_money)!.decimalString() + "ไธ‡ๅ…ƒ" if estimateMsgModel.car_info?.isEmpty == false { estimateCarDetailMsgLabel.text = estimateMsgModel.car_info } else { estimateCarDetailMsgLabel.text = "ๆœชๅกซๅ†™" estimateCarDetailMsgLabel.textColor = YiUnselectedTitleColor } if estimateMsgModel.remarks?.isEmpty == false { estimateMemoLabel.text = estimateMsgModel.remarks } else { estimateMemoLabel.text = "ๆœชๅกซๅ†™" estimateMemoLabel.textColor = YiUnselectedTitleColor } } else { // ๆœช่ฏ„ไผฐ bottomView.isHidden = false bottomViewBottom.constant = 0 estimateMsgView.isHidden = true estimateMsgView.snp.remakeConstraints({ (make) in make.height.equalTo(0) }) } } } var imagesss = [SKPhoto]() var observer: NSObjectProtocol? override func viewDidLoad() { super.viewDidLoad() navigationItem.title = "ไปปๅŠก่ฏฆๆƒ…" loadData() } func loadData() -> Void { guard let model = model else { return } GLProvider.request(GLService.estimateDetail(custRequestId: model.executionId!, takeStatus: model.takeStatus!, partyId: GLUser.partyId!, processExampleId: model.processId!, processTaskId: model.processTaskId!)) {[weak self] (result) in if case let .success(respon) = result { print(JSON(respon.data)) if JSON(respon.data)["type"] == "E" { NotificationCenter.default.post(name: YiRefreshNotificationName, object: nil) self?.navigationController?.popViewController(animated: true) return } let jsonStr = JSON(respon.data).rawString() self?.detailModel = GLTaskDetailModel.deserialize(from: jsonStr, designatedPath: "results.dataDJ") self?.estimateMsgModel = GLEstimateMsgModel.deserialize(from: jsonStr, designatedPath: "results.dataPG") } } } lazy var tabBarVc = tabBarController as! GLTabBarController lazy var submitMessageView: GLSubmitMessageView = { let accessoryView = GLSubmitMessageView() let width = view.bounds.width let height = width * 238.0/375.0 accessoryView.frame.size = CGSize(width: width, height: height) accessoryView.frame.origin.x = 0 return accessoryView }() func showSubmitMessageView() -> GLSubmitMessageView { let mask = tabBarVc.showMaskView() guard let maskView = mask else { return submitMessageView } submitMessageView.frame.origin.y = maskView.frame.size.height maskView.addSubview(submitMessageView) UIView.animate(withDuration: 0.25, animations: { self.submitMessageView.frame.origin.y = maskView.frame.size.height - self.submitMessageView.frame.size.height }) { (b) in print(b) self.submitMessageView.priceTextField.becomeFirstResponder() } return submitMessageView } /// ๆไบค่ฏ„ไผฐ @IBAction func estimateBtnClick(_ sender: DesignableButton) { let showMsgView = showSubmitMessageView() weak var weakShowMsgView = showMsgView showMsgView.submitBtnClosure = { [weak self] in // ๅˆคๆ–ญ่ฟ‡ๆปค let priceText = weakShowMsgView?.priceTextField.text ?? "" let carMsgText = weakShowMsgView?.carMsgTextField.text ?? "" let remarksText = weakShowMsgView?.memoTextField.text ?? "" if priceText.count < 1 { weakShowMsgView?.makeToast("่ฏท่พ“ๅ…ฅไปทๆ ผ") return } self?.tabBarVc.dismissCover(btn: nil) self?.tabBarVc.showLoadingView(img: #imageLiteral(resourceName: "taskdetail_submit_loading"), title: "ๆไบคไธญ...") let brand = self?.detailModel?.brandSeriesName ?? "" let series = self?.detailModel?.goodsSeriesName ?? "" let carBrandSeries = brand + series GLProvider.request(GLService.submitTaskDetail(partyId: GLUser.partyId!, processId: (self?.model?.processId)!, processTaskId: (self?.model?.processTaskId)!, executionId: (self?.model?.executionId)!, confirmedMoney: priceText, remarks: remarksText, carInfo: carMsgText, carType: carBrandSeries), completion: { (result) in if case let .success(respon) = result { print(JSON(respon.data)) if JSON(respon.data)["type"] == "S" { self?.tabBarVc.showLoadingView(img: #imageLiteral(resourceName: "taskdetail_submit_success"), title: "ๆไบคๆˆๅŠŸ") NotificationCenter.default.post(name: YiRefreshNotificationName, object: nil) DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: { self?.tabBarVc.dismissCover(btn: nil) self?.navigationController?.popViewController(animated: true) }) } else { self?.tabBarVc.showLoadingView(img: #imageLiteral(resourceName: "taskdetail_submit_failure"), title: "ๆไบคๅคฑ่ดฅ") DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: { self?.tabBarVc.dismissCover(btn: nil) }) } } else { self?.tabBarVc.dismissCover(btn: nil) } }) } } deinit { guard let observer = observer else { return } NotificationCenter.default.removeObserver(observer) } } class GLTaskDetailPictureCell: UICollectionViewCell { @IBOutlet weak var deleteBtn: UIButton! var deleteClosure: ((GLTaskDetailPictureCell)->())? @IBOutlet weak var imageView: UIImageView! override func awakeFromNib() { super.awakeFromNib() } @IBAction func deleteBtnClick(_ sender: UIButton) { if let deleteClosure = deleteClosure { deleteClosure(self) } } } fileprivate let identifier = "GLTaskDetailPictureCell" extension GLTaskDetailViewController: UICollectionViewDataSource, UICollectionViewDelegate { public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return imagesss.count } // The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath: @available(iOS 6.0, *) public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) guard let pictureCell = cell as? GLTaskDetailPictureCell else { return UICollectionViewCell() } pictureCell.imageView.image = imagesss[indexPath.item].underlyingImage return pictureCell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { guard let cell = collectionView.cellForItem(at: indexPath) as? GLTaskDetailPictureCell else { return } guard let originImage = cell.imageView.image else { return } // some image for baseImage let browser = SKPhotoBrowser(originImage: originImage, photos: imagesss, animatedFromView: cell) browser.initializePageIndex(indexPath.item) present(browser, animated: true, completion: nil) } }
36.088
331
0.581412
cc271ac942ce188d7677d934404d7f79f1f1ed0d
1,062
// // Genres.swift // TraktKit // // Created by Maximilian Litteral on 11/15/15. // Copyright ยฉ 2015 Maximilian Litteral. All rights reserved. // import Foundation extension TraktManager { /** Get a list of all genres, including names and slugs. */ @discardableResult public func listGenres(type: WatchedType, completion: @escaping ObjectsCompletionHandler<Genres>) -> URLSessionDataTaskProtocol? { guard let request = mutableRequest(forPath: "genres/\(type)", withQuery: [:], isAuthorized: false, withHTTPMethod: .GET) else { completion(.error(error: nil)) return nil } return performRequest(request: request, expectingStatusCode: StatusCodes.Success, completion: completion) } }
35.4
134
0.491525
622c7b4c7c4f2f43332b11cd1013efa604f621ac
27,494
//===----------------------------------------------------------------------===// // // This source file is part of the AWSSDKSwift open source project // // Copyright (c) 2017-2020 the AWSSDKSwift project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of AWSSDKSwift project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import struct Foundation.Data import struct Foundation.Date import struct Foundation.URL import class Foundation.DateFormatter /// The wrapper class for decoding Codable classes from XMLNodes class XMLDecoder { /// The strategy to use for decoding `Data` values. public enum DataDecodingStrategy { /// Decode the `Data` from a Base64-encoded string. case base64 /// Decode the `Data` as a custom value decoded by the given closure. case custom((_ decoder: Decoder) throws -> Data) } /// The strategy to use for non-JSON-conforming floating-point values (IEEE 754 infinity and NaN). public enum NonConformingFloatDecodingStrategy { /// Throw upon encountering non-conforming values. This is the default strategy. case `throw` /// Decode the values from the given representation strings. case convertFromString(positiveInfinity: String, negativeInfinity: String, nan: String) } /// The strategy to use in decoding binary data. Defaults to `.raw`. open var dataDecodingStrategy: DataDecodingStrategy = .base64 /// The strategy to use in decoding non-conforming numbers. Defaults to `.throw`. open var nonConformingFloatDecodingStrategy: NonConformingFloatDecodingStrategy = .throw /// Contextual user-provided information for use during decoding. open var userInfo: [CodingUserInfoKey : Any] = [:] /// Options set on the top-level encoder to pass down the decoding hierarchy. fileprivate struct _Options { let dataDecodingStrategy: DataDecodingStrategy let nonConformingFloatDecodingStrategy: NonConformingFloatDecodingStrategy let userInfo: [CodingUserInfoKey : Any] } /// The options set on the top-level decoder. fileprivate var options: _Options { return _Options(dataDecodingStrategy: dataDecodingStrategy, nonConformingFloatDecodingStrategy: nonConformingFloatDecodingStrategy, userInfo: userInfo) } public init() {} /// decode a Codable class from XML public func decode<T : Decodable>(_ type: T.Type, from xml: XML.Node) throws -> T { let decoder = _XMLDecoder(xml, options: self.options) let value = try T(from: decoder) return value } } extension XML.Node { func child(for string: String) -> XML.Node? { return (children ?? []).first(where: {$0.name == string}) } func child(for key: CodingKey) -> XML.Node? { return child(for: key.stringValue) } } extension XML.Element { func attribute(for key: CodingKey) -> XML.Node? { return attribute(forName: key.stringValue) } } /// Storage for the XMLDecoder. Stores a stack of XMLNodes struct _XMLDecoderStorage { /// the container stack private var containers : [XML.Node?] = [] /// initializes self with no containers init() {} /// return the container at the top of the storage var topContainer : XML.Node? { return containers.last! } /// push a new container onto the storage mutating func push(container: XML.Node?) { containers.append(container) } /// pop a container from the storage @discardableResult mutating func popContainer() -> XML.Node? { return containers.removeLast() } } /// Internal XMLDecoder class. Does all the heavy lifting fileprivate class _XMLDecoder : Decoder { /// The decoder's storage. var storage : _XMLDecoderStorage /// Options set on the top-level decoder. let options: XMLDecoder._Options /// The path to the current point in encoding. var codingPath: [CodingKey] /// Contextual user-provided information for use during encoding. public var userInfo: [CodingUserInfoKey : Any] { return self.options.userInfo } public init(_ element : XML.Node, at codingPath: [CodingKey] = [], options: XMLDecoder._Options) { self.storage = _XMLDecoderStorage() self.storage.push(container: element) self.codingPath = codingPath self.options = options } public func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> where Key : CodingKey { guard let element = storage.topContainer else { throw DecodingError.keyNotFound(codingPath.last!, DecodingError.Context(codingPath: codingPath, debugDescription: "Key not found")) } return KeyedDecodingContainer(KDC(element, decoder: self)) } struct KDC<Key: CodingKey> : KeyedDecodingContainerProtocol { var codingPath: [CodingKey] { return decoder.codingPath } var allKeys: [Key] = [] let element : XML.Node let decoder : _XMLDecoder public init(_ element : XML.Node, decoder: _XMLDecoder) { self.element = element self.decoder = decoder // all elements directly under the container xml element are considered. THe key is the name of the element and the value is the text attached to the element allKeys = element.children?.compactMap { (element: XML.Node)->Key? in if let name = element.name { return Key(stringValue: name) } return nil } ?? [] } /// return if decoder has a value for a key func contains(_ key: Key) -> Bool { return element.child(for: key) != nil } /// get the XMLElment for a particular key func child(for key: CodingKey) throws -> XML.Node { if let child = element.child(for: key) { return child } else if let attribute = (element as? XML.Element)?.attribute(for: key) { return attribute } throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: codingPath, debugDescription: "Key not found")) } /// get the XMLElment for a particular key func optionalChild(for key: CodingKey) -> XML.Node? { if let child = element.child(for: key) { return child } else if let attribute = (element as? XML.Element)?.attribute(for: key) { return attribute } return nil } func decodeNil(forKey key: Key) throws -> Bool { //let child = try self.child(for: key) return false } func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { let child = try self.child(for: key) return try decoder.unbox(child, as:Bool.self) } func decode(_ type: String.Type, forKey key: Key) throws -> String { let child = try self.child(for: key) return try decoder.unbox(child, as:String.self) } func decode(_ type: Double.Type, forKey key: Key) throws -> Double { let child = try self.child(for: key) return try decoder.unbox(child, as:Double.self) } func decode(_ type: Float.Type, forKey key: Key) throws -> Float { let child = try self.child(for: key) return try decoder.unbox(child, as:Float.self) } func decode(_ type: Int.Type, forKey key: Key) throws -> Int { let child = try self.child(for: key) return try decoder.unbox(child, as:Int.self) } func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { let child = try self.child(for: key) return try decoder.unbox(child, as:Int8.self) } func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { let child = try self.child(for: key) return try decoder.unbox(child, as:Int16.self) } func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { let child = try self.child(for: key) return try decoder.unbox(child, as:Int32.self) } func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { let child = try self.child(for: key) return try decoder.unbox(child, as:Int64.self) } func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { let child = try self.child(for: key) return try decoder.unbox(child, as:UInt.self) } func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { let child = try self.child(for: key) return try decoder.unbox(child, as:UInt8.self) } func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { let child = try self.child(for: key) return try decoder.unbox(child, as:UInt16.self) } func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { let child = try self.child(for: key) return try decoder.unbox(child, as:UInt32.self) } func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { let child = try self.child(for: key) return try decoder.unbox(child, as:UInt64.self) } func decode<T>(_ type: T.Type, forKey key: Key) throws -> T where T : Decodable { self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } let element = self.optionalChild(for:key) return try decoder.unbox(element, as:T.self) } func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> where NestedKey : CodingKey { self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } let child = try self.child(for: key) let container = KDC<NestedKey>(child, decoder:self.decoder) return KeyedDecodingContainer(container) } func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer { self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } return UKDC(element, decoder: self.decoder) } private func _superDecoder(forKey key: __owned CodingKey) throws -> Decoder { self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } let child = try self.child(for: key) return _XMLDecoder(child, at: self.decoder.codingPath, options: self.decoder.options) } func superDecoder() throws -> Decoder { return try _superDecoder(forKey: _XMLKey.super) } func superDecoder(forKey key: Key) throws -> Decoder { return try _superDecoder(forKey: key) } } public func unkeyedContainer() throws -> UnkeyedDecodingContainer { let top = storage.popContainer() defer { storage.push(container: top) } guard let element = storage.topContainer else { throw DecodingError.keyNotFound(codingPath.last!, DecodingError.Context(codingPath: codingPath, debugDescription: "Key not found")) } return UKDC(element, decoder: self) } struct UKDC : UnkeyedDecodingContainer { var codingPath: [CodingKey] { return decoder.codingPath } var currentIndex: Int = 0 let elements : [XML.Node] let decoder : _XMLDecoder init(_ element: XML.Node, decoder: _XMLDecoder) { self.elements = (element as? XML.Element)?.elements(forName: decoder.codingPath.last!.stringValue) ?? [] self.decoder = decoder } var count: Int? { return elements.count } var isAtEnd : Bool { return currentIndex >= count! } mutating func decodeNil() throws -> Bool { fatalError() } mutating func decode(_ type: Bool.Type) throws -> Bool { let value = try decoder.unbox(elements[currentIndex], as: Bool.self) currentIndex += 1 return value } mutating func decode(_ type: String.Type) throws -> String { let value = try decoder.unbox(elements[currentIndex], as: String.self) currentIndex += 1 return value } mutating func decode(_ type: Double.Type) throws -> Double { let value = try decoder.unbox(elements[currentIndex], as: Double.self) currentIndex += 1 return value } mutating func decode(_ type: Float.Type) throws -> Float { let value = try decoder.unbox(elements[currentIndex], as: Float.self) currentIndex += 1 return value } mutating func decode(_ type: Int.Type) throws -> Int { let value = try decoder.unbox(elements[currentIndex], as: Int.self) currentIndex += 1 return value } mutating func decode(_ type: Int8.Type) throws -> Int8 { let value = try decoder.unbox(elements[currentIndex], as: Int8.self) currentIndex += 1 return value } mutating func decode(_ type: Int16.Type) throws -> Int16 { let value = try decoder.unbox(elements[currentIndex], as: Int16.self) currentIndex += 1 return value } mutating func decode(_ type: Int32.Type) throws -> Int32 { let value = try decoder.unbox(elements[currentIndex], as: Int32.self) currentIndex += 1 return value } mutating func decode(_ type: Int64.Type) throws -> Int64 { let value = try decoder.unbox(elements[currentIndex], as: Int64.self) currentIndex += 1 return value } mutating func decode(_ type: UInt.Type) throws -> UInt { let value = try decoder.unbox(elements[currentIndex], as: UInt.self) currentIndex += 1 return value } mutating func decode(_ type: UInt8.Type) throws -> UInt8 { let value = try decoder.unbox(elements[currentIndex], as: UInt8.self) currentIndex += 1 return value } mutating func decode(_ type: UInt16.Type) throws -> UInt16 { let value = try decoder.unbox(elements[currentIndex], as: UInt16.self) currentIndex += 1 return value } mutating func decode(_ type: UInt32.Type) throws -> UInt32 { let value = try decoder.unbox(elements[currentIndex], as: UInt32.self) currentIndex += 1 return value } mutating func decode(_ type: UInt64.Type) throws -> UInt64 { let value = try decoder.unbox(elements[currentIndex], as: UInt64.self) currentIndex += 1 return value } mutating func decode<T>(_ type: T.Type) throws -> T where T : Decodable { let value = try decoder.unbox(elements[currentIndex], as:T.self) currentIndex += 1 return value } mutating func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer<NestedKey> where NestedKey : CodingKey { self.decoder.codingPath.append(_XMLKey(index: currentIndex)) defer { self.decoder.codingPath.removeLast() } let child = elements[currentIndex] currentIndex += 1 let container = KDC<NestedKey>(child, decoder:self.decoder) return KeyedDecodingContainer(container) } mutating func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer { self.decoder.codingPath.append(_XMLKey(index: currentIndex)) defer { self.decoder.codingPath.removeLast() } currentIndex += 1 return UKDC(elements[currentIndex], decoder: self.decoder) } mutating func superDecoder() throws -> Decoder { self.decoder.codingPath.append(_XMLKey(index: currentIndex)) defer { self.decoder.codingPath.removeLast() } let child = elements[currentIndex] currentIndex += 1 return _XMLDecoder(child, at: self.decoder.codingPath, options: self.decoder.options) } } public func singleValueContainer() throws -> SingleValueDecodingContainer { guard let element = storage.topContainer else { throw DecodingError.keyNotFound(codingPath.last!, DecodingError.Context(codingPath: codingPath, debugDescription: "Key not found")) } return SVDC(element, decoder:self) } struct SVDC : SingleValueDecodingContainer { var codingPath: [CodingKey] { return decoder.codingPath } let element : XML.Node let decoder : _XMLDecoder init(_ element : XML.Node, decoder: _XMLDecoder) { self.element = element self.decoder = decoder } func decodeNil() -> Bool { fatalError() } func decode(_ type: Bool.Type) throws -> Bool { return try decoder.unbox(element, as: Bool.self) } func decode(_ type: String.Type) throws -> String { return try decoder.unbox(element, as: String.self) } func decode(_ type: Double.Type) throws -> Double { return try decoder.unbox(element, as: Double.self) } func decode(_ type: Float.Type) throws -> Float { return try decoder.unbox(element, as: Float.self) } func decode(_ type: Int.Type) throws -> Int { return try decoder.unbox(element, as: Int.self) } func decode(_ type: Int8.Type) throws -> Int8 { return try decoder.unbox(element, as: Int8.self) } func decode(_ type: Int16.Type) throws -> Int16 { return try decoder.unbox(element, as: Int16.self) } func decode(_ type: Int32.Type) throws -> Int32 { return try decoder.unbox(element, as: Int32.self) } func decode(_ type: Int64.Type) throws -> Int64 { return try decoder.unbox(element, as: Int64.self) } func decode(_ type: UInt.Type) throws -> UInt { return try decoder.unbox(element, as: UInt.self) } func decode(_ type: UInt8.Type) throws -> UInt8 { return try decoder.unbox(element, as: UInt8.self) } func decode(_ type: UInt16.Type) throws -> UInt16 { return try decoder.unbox(element, as: UInt16.self) } func decode(_ type: UInt32.Type) throws -> UInt32 { return try decoder.unbox(element, as: UInt32.self) } func decode(_ type: UInt64.Type) throws -> UInt64 { return try decoder.unbox(element, as: UInt64.self) } func decode<T>(_ type: T.Type) throws -> T where T : Decodable { return try decoder.unbox(element, as: T.self) } } func unbox(_ element : XML.Node, as type: Bool.Type) throws -> Bool { guard let value = element.stringValue, let unboxValue = Bool(value) else { throw DecodingError._typeMismatch(at: codingPath, expectation: Bool.self, reality: element.stringValue ?? "nil") } return unboxValue } func unbox(_ element : XML.Node, as type: String.Type) throws -> String { guard let unboxValue = element.stringValue else { throw DecodingError._typeMismatch(at: codingPath, expectation: String.self, reality: element.stringValue ?? "nil") } return unboxValue } func unbox(_ element : XML.Node, as type: Int.Type) throws -> Int { guard let value = element.stringValue, let unboxValue = Int(value) else { throw DecodingError._typeMismatch(at: codingPath, expectation: Int.self, reality: element.stringValue ?? "nil") } return unboxValue } func unbox(_ element : XML.Node, as type: Int8.Type) throws -> Int8 { guard let value = element.stringValue, let unboxValue = Int8(value) else { throw DecodingError._typeMismatch(at: codingPath, expectation: Int8.self, reality: element.stringValue ?? "nil") } return unboxValue } func unbox(_ element : XML.Node, as type: Int16.Type) throws -> Int16 { guard let value = element.stringValue, let unboxValue = Int16(value) else { throw DecodingError._typeMismatch(at: codingPath, expectation: Int16.self, reality: element.stringValue ?? "nil") } return unboxValue } func unbox(_ element : XML.Node, as type: Int32.Type) throws -> Int32 { guard let value = element.stringValue, let unboxValue = Int32(value) else { throw DecodingError._typeMismatch(at: codingPath, expectation: Int32.self, reality: element.stringValue ?? "nil") } return unboxValue } func unbox(_ element : XML.Node, as type: Int64.Type) throws -> Int64 { guard let value = element.stringValue, let unboxValue = Int64(value) else { throw DecodingError._typeMismatch(at: codingPath, expectation: Int64.self, reality: element.stringValue ?? "nil") } return unboxValue } func unbox(_ element : XML.Node, as type: UInt.Type) throws -> UInt { guard let value = element.stringValue, let unboxValue = UInt(value) else { throw DecodingError._typeMismatch(at: codingPath, expectation: UInt.self, reality: element.stringValue ?? "nil") } return unboxValue } func unbox(_ element : XML.Node, as type: UInt8.Type) throws -> UInt8 { guard let value = element.stringValue, let unboxValue = UInt8(value) else { throw DecodingError._typeMismatch(at: codingPath, expectation: UInt8.self, reality: element.stringValue ?? "nil") } return unboxValue } func unbox(_ element : XML.Node, as type: UInt16.Type) throws -> UInt16 { guard let value = element.stringValue, let unboxValue = UInt16(value) else { throw DecodingError._typeMismatch(at: codingPath, expectation: UInt16.self, reality: element.stringValue ?? "nil") } return unboxValue } func unbox(_ element : XML.Node, as type: UInt32.Type) throws -> UInt32 { guard let value = element.stringValue, let unboxValue = UInt32(value) else { throw DecodingError._typeMismatch(at: codingPath, expectation: UInt32.self, reality: element.stringValue ?? "nil") } return unboxValue } func unbox(_ element : XML.Node, as type: UInt64.Type) throws -> UInt64 { guard let value = element.stringValue, let unboxValue = UInt64(value) else { throw DecodingError._typeMismatch(at: codingPath, expectation: UInt64.self, reality: element.stringValue ?? "nil") } return unboxValue } func unbox(_ element : XML.Node, as type: Double.Type) throws -> Double { guard let value = element.stringValue, let unboxValue = Double(value) else { throw DecodingError._typeMismatch(at: codingPath, expectation: Double.self, reality: element.stringValue ?? "nil") } return unboxValue } func unbox(_ element : XML.Node, as type: Float.Type) throws -> Float { guard let value = element.stringValue, let unboxValue = Float(value) else { throw DecodingError._typeMismatch(at: codingPath, expectation: Float.self, reality: element.stringValue ?? "nil") } return unboxValue } /// get Data from XML.Node fileprivate func unbox(_ element : XML.Node?, as type: Data.Type) throws -> Data { guard let element = element else { throw DecodingError.keyNotFound(codingPath.last!, DecodingError.Context(codingPath: codingPath, debugDescription: "Key not found")) } switch self.options.dataDecodingStrategy { case .base64: guard let string = element.stringValue else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: element.stringValue ?? "nil") } guard let data = Data(base64Encoded: string) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Encountered Data is not valid Base64.")) } return data case .custom(let closure): self.storage.push(container: element) defer { self.storage.popContainer() } return try closure(self) } } func unbox<T>(_ element : XML.Node?, as type: T.Type) throws -> T where T : Decodable { return try unbox_(element, as: T.self) as! T } func unbox_(_ element : XML.Node?, as type: Decodable.Type) throws -> Any { if type == Data.self { return try self.unbox(element, as: Data.self) } else { self.storage.push(container:element) defer { self.storage.popContainer() } return try type.init(from: self) } } } //===----------------------------------------------------------------------===// // Shared Key Types //===----------------------------------------------------------------------===// fileprivate struct _XMLKey : CodingKey { public var stringValue: String public var intValue: Int? public init?(stringValue: String) { self.stringValue = stringValue self.intValue = nil } public init?(intValue: Int) { self.stringValue = "\(intValue)" self.intValue = intValue } public init(stringValue: String, intValue: Int?) { self.stringValue = stringValue self.intValue = intValue } fileprivate init(index: Int) { self.stringValue = "Index \(index)" self.intValue = index } fileprivate static let `super` = _XMLKey(stringValue: "super")! } //===----------------------------------------------------------------------===// // Error Utilities //===----------------------------------------------------------------------===// extension EncodingError { /// Returns a `.invalidValue` error describing the given invalid floating-point value. /// /// /// - parameter value: The value that was invalid to encode. /// - parameter path: The path of `CodingKey`s taken to encode this value. /// - returns: An `EncodingError` with the appropriate path and debug description. fileprivate static func _invalidFloatingPointValue<T : FloatingPoint>(_ value: T, at codingPath: [CodingKey]) -> EncodingError { let valueDescription: String if value == T.infinity { valueDescription = "\(T.self).infinity" } else if value == -T.infinity { valueDescription = "-\(T.self).infinity" } else { valueDescription = "\(T.self).nan" } let debugDescription = "Unable to encode \(valueDescription) directly. Use DictionaryEncoder.NonConformingFloatEncodingStrategy.convertToString to specify how the value should be encoded." return .invalidValue(value, EncodingError.Context(codingPath: codingPath, debugDescription: debugDescription)) } }
39.053977
201
0.615262
f57fc46dad737c6e6ed7d38b7b6537c89cefd2f2
3,767
// // UpdateCreateNewPINViewControllerTests.swift // CotterIOS_Tests // // Created by Raymond Andrie on 4/24/20. // Copyright ยฉ 2020 CocoaPods. All rights reserved. // import XCTest import Nimble @testable import Cotter @available(iOS 13.0, *) class UpdateCreateNewPINViewControllerTests: XCTestCase { // MARK: - VC Text Definitions let navTitle = CotterStrings.instance.getText(for: UpdateCreateNewPINViewControllerKey.navTitle) let titleText = CotterStrings.instance.getText(for: UpdateCreateNewPINViewControllerKey.title) let showPinText = CotterStrings.instance.getText(for: UpdateCreateNewPINViewControllerKey.showPin) let hidePinText = CotterStrings.instance.getText(for: UpdateCreateNewPINViewControllerKey.hidePin) // MARK: - VC Color Definitions let primaryColor = Config.instance.colors.primary let accentColor = Config.instance.colors.accent let dangerColor = Config.instance.colors.danger let presenter = UpdateCreateNewPINViewPresenterMock() func makeSUT(actualPresenter: Bool = false) -> UpdateCreateNewPINViewController { let storyboard = UIStoryboard(name: "UpdateProfile", bundle: Cotter.resourceBundle) let sut = storyboard.instantiateViewController(identifier: "UpdateCreateNewPINViewController") as! UpdateCreateNewPINViewController if !actualPresenter { sut.presenter = presenter } sut.loadViewIfNeeded() return sut } func setupProps() -> UpdateCreateNewPINViewProps { return UpdateCreateNewPINViewProps( navTitle: navTitle, title: titleText, showPinText: showPinText, hidePinText: hidePinText, primaryColor: primaryColor, accentColor: accentColor, dangerColor: dangerColor ) } func testViewDidLoadCallsPresenter() { let sut = makeSUT() sut.viewDidLoad() expect(self.presenter.onViewLoadCalled).to(beTrue()) } func testOnClickPinVisCallsPresenter() { let sut = makeSUT() sut.onClickPinVis(.init()) expect(self.presenter.onClickPinVisCalled).to(beTrue()) } func testRender() { let props = setupProps() let sut = makeSUT() sut.render(props) // expect(sut.navigationItem.title).to(match(navTitle)) expect(sut.titleLabel.text).to(match(titleText)) expect(sut.pinVisibilityButton.title(for: .normal)).to(match(showPinText)) expect(sut.pinVisibilityButton.titleColor(for: .normal)).to(equal(primaryColor)) expect(sut.errorLabel.textColor).to(equal(dangerColor)) } func testOnClickPinVis() { let props = setupProps() let sut = makeSUT(actualPresenter: true) sut.render(props) // Sets pinVisibilityButton title to be showPinText initially sut.onClickPinVis(sut.pinVisibilityButton) expect(sut.pinVisibilityButton.title(for: .normal)).to(match(hidePinText)) } func testToggleErrorMsg() { let sut = makeSUT(actualPresenter: true) // errorLabel is hidden initially let msg = "Test Error" sut.setError(msg: msg) expect(sut.errorLabel.isHidden).to(beFalse()) expect(sut.errorLabel.text).to(match(msg)) } } class UpdateCreateNewPINViewPresenterMock: UpdateCreateNewPINViewPresenter { private(set) var onViewLoadCalled = false func onViewLoaded() { onViewLoadCalled = true } private(set) var onClickPinVisCalled = false func onClickPinVis(button: UIButton) { onClickPinVisCalled = true } }
31.655462
139
0.664454
db083bf6f76d412d48c6502fd2eb1f5c784e0839
861
// // Copyright (c) WhatsApp Inc. and its affiliates. // All rights reserved. // // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. // import UIKit struct Limits { static let MaxStaticStickerFileSize: Int = 100 * 1024 static let MaxAnimatedStickerFileSize: Int = 500 * 1024 static let MaxTrayImageFileSize: Int = 50 * 1024 static let MinAnimatedStickerFrameDurationMS: Int = 8 static let MaxAnimatedStickerTotalDurationMS: Int = 10000 static let TrayImageDimensions: CGSize = CGSize(width: 96, height: 96) static let ImageDimensions: CGSize = CGSize(width: 512, height: 512) static let MinStickersPerPack: Int = 3 static let MaxStickersPerPack: Int = 30 static let MaxCharLimit128: Int = 128 static let MaxEmojisCount: Int = 3 }
29.689655
74
0.730546
269d87d62cdef1a9772598246ead667152d5b935
2,854
// FunctionIdentifier.swift /* MIT License Copyright (c) 2019 Davinder 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 struct FunctionIdentifier: Equatable, Hashable { // MARK: - Properties private let identifier: String! // MARK: - Initializers init<ReturnType>(function: String, return: ReturnType.Type) { var normalizedFunction = function if let normalized = normalizedAsProperty(function: function, return: ReturnType.self) { normalizedFunction = normalized } if let normalized = normalizedAsSubscript(function: function, return: ReturnType.self) { normalizedFunction = normalized } identifier = "\(normalizedFunction) -> \(ReturnType.self)" } // MARK: - Methods func callDescription(with parameters: [ParameterType]) -> String { var callDescription: String = "" var currentIndex = 0 let separator = ", " var needSeparator = false for character in identifier { if needSeparator, character != ")" { callDescription.append(separator) } needSeparator = false callDescription.append(character) if character == ":" { callDescription.append(" \(parameters[currentIndex] ?? "nil")") currentIndex += 1 needSeparator = true } } return callDescription } } // MARK: - Private methods private func normalizedAsProperty<ReturnType>(function: String, return: ReturnType.Type) -> String? { guard !function.contains("(") else { return nil } return ReturnType.self == Void.self ? function + "(newValue:)" : function + "()" } private func normalizedAsSubscript<ReturnType>(function: String, return: ReturnType.Type) -> String? { guard function.starts(with: "subscript(") else { return nil } return ReturnType.self == Void.self ? function + "(newValue:)" : function }
31.362637
102
0.716889
fc776dbeda09af1df9fd2b77bb6bc6cd76068245
1,787
// // SuperheroListViewModel.swift // MarvelApp // // Created by Marcelo Vazquez on 28/02/2019. // Copyright ยฉ 2019 Marcelo Vazquez. All rights reserved. // import Foundation import RxSwift class SuperheroListViewModel { let pageSize = 20 let superheroService: SuperheroServiceProtocol let superheroes = Variable<[SuperheroViewModel]>([]) let selectedHero = Variable<SuperheroViewModel?>(nil) var canLoadMore: Bool { return superheroService.remoteSuperheroesCount > superheroService.localSuperheroesCount } private var isFetchInProgress = false init(_ superheroService: SuperheroServiceProtocol) { self.superheroService = superheroService } func refresh() { superheroService.clearLocalData() fetchSuperheroes(true) } func setFavoriteHero(_ superhero: SuperheroViewModel, _ isFavorite: Bool) { superhero.isFavorite.value = isFavorite superheroService.setFavoriteSuperhero(superhero.id , isFavorite) } func selectHero(_ superhero: SuperheroViewModel) { selectedHero.value = superhero } func fetchSuperheroes(_ clear: Bool = false) { guard !isFetchInProgress else { return } isFetchInProgress = true superheroService.fetchSuperheroes(clear ? 0 : superheroes.value.count, pageSize) { (superheroes) in let superheroesViewModels = superheroes.map { SuperheroViewModel($0, self.superheroService.isFavoriteSuperhero($0.id)) } if clear { self.superheroes.value = superheroesViewModels } else { self.superheroes.value += superheroesViewModels } self.isFetchInProgress = false } } }
27.075758
107
0.665361
e282d80448217f74369885d7233fad35ef563c9c
1,176
// // RCTableView.swift // // // Created by Alexander Zaporozhchenko on 6/12/18. // Copyright ยฉ 2018 Alexander Zaporozhchenko. All rights reserved. // import Bond class RCTableView: UITableView { private var _viewModel: RCVMProtocol? required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame: CGRect, style: UITableView.Style) { super.init(frame: frame, style: style) } var viewModel: RCVMProtocol? { get { return _viewModel; } set(newViewModel) { if(_viewModel !== newViewModel) { unadvise(); _viewModel = newViewModel; if _viewModel != nil { advise(); } } } } deinit { viewModel = nil } // called to dispose binds needed for view func unadvise() { bag.dispose() let views = subviews.compactMap { $0 as? RCView } for view in views { view.viewModel = nil } } // called to bind needed for view func advise() { } }
20.275862
67
0.518707
284f79d7475a89feddb06d9877ebdb01db92d200
1,930
// // WebSockets.swift // SolanaDemoApp // // Created by Gene Crucean on 3/14/21. // import Foundation protocol WebSocketsDelegate: AnyObject { func recievedMessage<T: Codable>(message: T) func disconnected() } public class WebSockets { var task: URLSessionWebSocketTask? var delegate: WebSocketsDelegate? public init() {} public func webSocketTask<Req: Codable>(request: URLRequest, payload: Req, decoder: JSONDecoder = JSONDecoder()) -> Void { let task = URLSession.shared.webSocketTask(with: request) self.task = task task.resume() if let jsonData = try? JSONEncoder().encode(payload) { task.send(.data(jsonData)) { (error) in if let error = error { print(error) } } receiveMessage() } } private func receiveMessage() { guard let task = self.task else { return } task.receive { (result) in switch result { case .failure: self.disconnect() self.delegate?.disconnected() case .success(let message): self.processMessage(message: message) self.receiveMessage() } } } private func processMessage(message: URLSessionWebSocketTask.Message) { switch message { case .string(let jsonString): self.delegate?.recievedMessage(message: jsonString) case .data(let data): if let _data = try? JSONDecoder().decode(TestResponse.self, from: data) { // ToDo: Need to make this generic. self.delegate?.recievedMessage(message: _data) } default: break } } public func disconnect() { task?.cancel() task = nil delegate?.disconnected() } }
26.805556
126
0.551813
ac60075c6cecca1c6895c4b216ef5ed7c794d15a
2,183
// // AppDelegate.swift // 08-Optional // // Created by michael on 2017/6/8. // Copyright ยฉ 2017ๅนด MYNavigationController. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.446809
285
0.756757
75564a46b21edebf4e2078fd5f4dd5bd29574ef3
361
// // AppDelegate.swift // Bouncer // // Created by Domenico on 12.04.15. // Copyright (c) 2015 Domenico Solazzo. All rights reserved. // import UIKit import CoreMotion @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? struct Motion { static let Manager = CMMotionManager() } }
14.44
61
0.68144
237b029d6f2dfc1935975b601425fb3968546e98
3,304
// // Motherboard.swift // Boardy // // Created by NGUYEN CHI CONG on 11/1/19. // Copyright ยฉ 2019 NGUYEN CHI CONG. All rights reserved. // import Foundation import UIKit open class Motherboard: Board, MotherboardRepresentable, BoardDelegate, FlowMotherboard, LazyMotherboard { public var flows: [BoardFlow] = [] override public var debugDescription: String { let superDesc = super.debugDescription return superDesc + "\n" + """ โ— [Children] โžค \(String(describing: boards.map { $0.identifier })) โ— [Flows] โžค \(String(describing: flows.count)) โ— [Producer] โžค \(String(describing: boardProducer)) """ } public init(identifier: BoardID = .random(), boards: [ActivatableBoard] = []) { boardProducer = NoBoardProducer() super.init(identifier: identifier) for board in boards { addBoard(board) } registerDefaultFlows() } public init(identifier: BoardID = .random(), boardProducer: ActivableBoardProducer) { self.boardProducer = boardProducer super.init(identifier: identifier) registerDefaultFlows() } public convenience init(identifier: BoardID = .random(), boardProducer: ActivableBoardProducer, boards: [ActivatableBoard]) { self.init(identifier: identifier, boardProducer: boardProducer) for board in boards { addBoard(board) } } func registerDefaultFlows() { // Forward action through chain forwardActionFlow(to: self) // Register Interaction flow registerGeneralFlow { [weak self] in self?.interactWithBoard(command: $0) } // Register activation flow registerGeneralFlow { [weak self] in self?.activateBoard(model: $0) } // Register complete flow registerGeneralFlow { [weak self] (action: CompleteAction) in self?.removeBoard(withIdentifier: action.identifier) } } override open func putIntoContext(_ context: AnyObject) { super.putIntoContext(context) for board in boards { board.putIntoContext(context) } } @discardableResult public func registerFlow(_ flow: BoardFlow) -> Self { flows.append(flow) return self } public func resetFlows() { flows = [] registerDefaultFlows() } // MARK: - MotherboardRepresentable var mainboard: [ActivatableBoard] = [] { didSet { for board in boards { board.delegate = self if board.context == nil, let root = context { board.putIntoContext(root) } } } } // MARK: - LazyMotherboard public private(set) var boardProducer: ActivableBoardProducer } /// A Motherboard is a special board which only accepts a BoardInputModel as input. When activate func is called, the motherboard will activate a Board with identifier in list of boards it manages. extension Motherboard: GuaranteedBoard { public typealias InputType = BoardInputModel open func activate(withGuaranteedInput input: BoardInputModel) { activateBoard(model: input) } }
28.730435
197
0.618644
2f23b627d109a3612204cf3a9cea75f5e8444c8f
22,870
//===--- ManagedBuffer.swift - variable-sized buffer of aligned memory ----===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 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 // //===----------------------------------------------------------------------===// import SwiftShims @inlinable // FIXME(sil-serialize-all) @_silgen_name("swift_bufferAllocate") internal func _swift_bufferAllocate( bufferType type: AnyClass, size: Int, alignmentMask: Int ) -> AnyObject /// A class whose instances contain a property of type `Header` and raw /// storage for an array of `Element`, whose size is determined at /// instance creation. /// /// Note that the `Element` array is suitably-aligned **raw memory**. /// You are expected to construct and---if necessary---destroy objects /// there yourself, using the APIs on `UnsafeMutablePointer<Element>`. /// Typical usage stores a count and capacity in `Header` and destroys /// any live elements in the `deinit` of a subclass. /// - Note: Subclasses must not have any stored properties; any storage /// needed should be included in `Header`. @_fixed_layout // FIXME(sil-serialize-all) open class ManagedBuffer<Header, Element> { /// Create a new instance of the most-derived class, calling /// `factory` on the partially-constructed object to generate /// an initial `Header`. @inlinable // FIXME(sil-serialize-all) public final class func create( minimumCapacity: Int, makingHeaderWith factory: ( ManagedBuffer<Header, Element>) throws -> Header ) rethrows -> ManagedBuffer<Header, Element> { let p = Builtin.allocWithTailElems_1( self, minimumCapacity._builtinWordValue, Element.self) let initHeaderVal = try factory(p) p.headerAddress.initialize(to: initHeaderVal) // The _fixLifetime is not really needed, because p is used afterwards. // But let's be conservative and fix the lifetime after we use the // headerAddress. _fixLifetime(p) return p } /// The actual number of elements that can be stored in this object. /// /// This header may be nontrivial to compute; it is usually a good /// idea to store this information in the "header" area when /// an instance is created. @inlinable // FIXME(sil-serialize-all) public final var capacity: Int { let storageAddr = UnsafeMutableRawPointer(Builtin.bridgeToRawPointer(self)) let endAddr = storageAddr + _stdlib_malloc_size(storageAddr) let realCapacity = endAddr.assumingMemoryBound(to: Element.self) - firstElementAddress return realCapacity } @inlinable // FIXME(sil-serialize-all) internal final var firstElementAddress: UnsafeMutablePointer<Element> { return UnsafeMutablePointer(Builtin.projectTailElems(self, Element.self)) } @inlinable // FIXME(sil-serialize-all) internal final var headerAddress: UnsafeMutablePointer<Header> { return UnsafeMutablePointer<Header>(Builtin.addressof(&header)) } /// Call `body` with an `UnsafeMutablePointer` to the stored /// `Header`. /// /// - Note: This pointer is valid only for the duration of the /// call to `body`. @inlinable // FIXME(sil-serialize-all) public final func withUnsafeMutablePointerToHeader<R>( _ body: (UnsafeMutablePointer<Header>) throws -> R ) rethrows -> R { return try withUnsafeMutablePointers { (v, _) in return try body(v) } } /// Call `body` with an `UnsafeMutablePointer` to the `Element` /// storage. /// /// - Note: This pointer is valid only for the duration of the /// call to `body`. @inlinable // FIXME(sil-serialize-all) public final func withUnsafeMutablePointerToElements<R>( _ body: (UnsafeMutablePointer<Element>) throws -> R ) rethrows -> R { return try withUnsafeMutablePointers { return try body($1) } } /// Call `body` with `UnsafeMutablePointer`s to the stored `Header` /// and raw `Element` storage. /// /// - Note: These pointers are valid only for the duration of the /// call to `body`. @inlinable // FIXME(sil-serialize-all) public final func withUnsafeMutablePointers<R>( _ body: (UnsafeMutablePointer<Header>, UnsafeMutablePointer<Element>) throws -> R ) rethrows -> R { defer { _fixLifetime(self) } return try body(headerAddress, firstElementAddress) } /// The stored `Header` instance. /// /// During instance creation, in particular during /// `ManagedBuffer.create`'s call to initialize, `ManagedBuffer`'s /// `header` property is as-yet uninitialized, and therefore /// reading the `header` property during `ManagedBuffer.create` is undefined. public final var header: Header //===--- internal/private API -------------------------------------------===// /// Make ordinary initialization unavailable @inlinable // FIXME(sil-serialize-all) internal init(_doNotCallMe: ()) { _sanityCheckFailure("Only initialize these by calling create") } } /// Contains a buffer object, and provides access to an instance of /// `Header` and contiguous storage for an arbitrary number of /// `Element` instances stored in that buffer. /// /// For most purposes, the `ManagedBuffer` class works fine for this /// purpose, and can simply be used on its own. However, in cases /// where objects of various different classes must serve as storage, /// `ManagedBufferPointer` is needed. /// /// A valid buffer class is non-`@objc`, with no declared stored /// properties. Its `deinit` must destroy its /// stored `Header` and any constructed `Element`s. /// /// Example Buffer Class /// -------------------- /// /// class MyBuffer<Element> { // non-@objc /// typealias Manager = ManagedBufferPointer<(Int, String), Element> /// deinit { /// Manager(unsafeBufferObject: self).withUnsafeMutablePointers { /// (pointerToHeader, pointerToElements) -> Void in /// pointerToElements.deinitialize(count: self.count) /// pointerToHeader.deinitialize(count: 1) /// } /// } /// /// // All properties are *computed* based on members of the Header /// var count: Int { /// return Manager(unsafeBufferObject: self).header.0 /// } /// var name: String { /// return Manager(unsafeBufferObject: self).header.1 /// } /// } /// @_fixed_layout public struct ManagedBufferPointer<Header, Element> : Equatable { /// Create with new storage containing an initial `Header` and space /// for at least `minimumCapacity` `element`s. /// /// - parameter bufferClass: The class of the object used for storage. /// - parameter minimumCapacity: The minimum number of `Element`s that /// must be able to be stored in the new buffer. /// - parameter factory: A function that produces the initial /// `Header` instance stored in the buffer, given the `buffer` /// object and a function that can be called on it to get the actual /// number of allocated elements. /// /// - Precondition: `minimumCapacity >= 0`, and the type indicated by /// `bufferClass` is a non-`@objc` class with no declared stored /// properties. The `deinit` of `bufferClass` must destroy its /// stored `Header` and any constructed `Element`s. @inlinable // FIXME(sil-serialize-all) public init( bufferClass: AnyClass, minimumCapacity: Int, makingHeaderWith factory: (_ buffer: AnyObject, _ capacity: (AnyObject) -> Int) throws -> Header ) rethrows { self = ManagedBufferPointer( bufferClass: bufferClass, minimumCapacity: minimumCapacity) // initialize the header field try withUnsafeMutablePointerToHeader { $0.initialize(to: try factory( self.buffer, { ManagedBufferPointer(unsafeBufferObject: $0).capacity })) } // FIXME: workaround for <rdar://problem/18619176>. If we don't // access header somewhere, its addressor gets linked away _ = header } /// Manage the given `buffer`. /// /// - Precondition: `buffer` is an instance of a non-`@objc` class whose /// `deinit` destroys its stored `Header` and any constructed `Element`s. @inlinable // FIXME(sil-serialize-all) public init(unsafeBufferObject buffer: AnyObject) { ManagedBufferPointer._checkValidBufferClass(type(of: buffer)) self._nativeBuffer = Builtin.unsafeCastToNativeObject(buffer) } /// Internal version for use by _ContiguousArrayBuffer where we know that we /// have a valid buffer class. /// This version of the init function gets called from /// _ContiguousArrayBuffer's deinit function. Since 'deinit' does not get /// specialized with current versions of the compiler, we can't get rid of the /// _debugPreconditions in _checkValidBufferClass for any array. Since we know /// for the _ContiguousArrayBuffer that this check must always succeed we omit /// it in this specialized constructor. @inlinable // FIXME(sil-serialize-all) internal init(_uncheckedUnsafeBufferObject buffer: AnyObject) { ManagedBufferPointer._sanityCheckValidBufferClass(type(of: buffer)) self._nativeBuffer = Builtin.unsafeCastToNativeObject(buffer) } /// The stored `Header` instance. @inlinable // FIXME(sil-serialize-all) public var header: Header { addressWithNativeOwner { return (UnsafePointer(_headerPointer), _nativeBuffer) } mutableAddressWithNativeOwner { return (_headerPointer, _nativeBuffer) } } /// Returns the object instance being used for storage. @inlinable // FIXME(sil-serialize-all) public var buffer: AnyObject { return Builtin.castFromNativeObject(_nativeBuffer) } /// The actual number of elements that can be stored in this object. /// /// This value may be nontrivial to compute; it is usually a good /// idea to store this information in the "header" area when /// an instance is created. @inlinable // FIXME(sil-serialize-all) public var capacity: Int { return (_capacityInBytes &- _My._elementOffset) / MemoryLayout<Element>.stride } /// Call `body` with an `UnsafeMutablePointer` to the stored /// `Header`. /// /// - Note: This pointer is valid only /// for the duration of the call to `body`. @inlinable // FIXME(sil-serialize-all) public func withUnsafeMutablePointerToHeader<R>( _ body: (UnsafeMutablePointer<Header>) throws -> R ) rethrows -> R { return try withUnsafeMutablePointers { (v, _) in return try body(v) } } /// Call `body` with an `UnsafeMutablePointer` to the `Element` /// storage. /// /// - Note: This pointer is valid only for the duration of the /// call to `body`. @inlinable // FIXME(sil-serialize-all) public func withUnsafeMutablePointerToElements<R>( _ body: (UnsafeMutablePointer<Element>) throws -> R ) rethrows -> R { return try withUnsafeMutablePointers { return try body($1) } } /// Call `body` with `UnsafeMutablePointer`s to the stored `Header` /// and raw `Element` storage. /// /// - Note: These pointers are valid only for the duration of the /// call to `body`. @inlinable // FIXME(sil-serialize-all) public func withUnsafeMutablePointers<R>( _ body: (UnsafeMutablePointer<Header>, UnsafeMutablePointer<Element>) throws -> R ) rethrows -> R { defer { _fixLifetime(_nativeBuffer) } return try body(_headerPointer, _elementPointer) } /// Returns `true` iff `self` holds the only strong reference to its buffer. /// /// See `isUniquelyReferenced` for details. @inlinable // FIXME(sil-serialize-all) public mutating func isUniqueReference() -> Bool { return _isUnique(&_nativeBuffer) } //===--- internal/private API -------------------------------------------===// /// Create with new storage containing space for an initial `Header` /// and at least `minimumCapacity` `element`s. /// /// - parameter bufferClass: The class of the object used for storage. /// - parameter minimumCapacity: The minimum number of `Element`s that /// must be able to be stored in the new buffer. /// /// - Precondition: `minimumCapacity >= 0`, and the type indicated by /// `bufferClass` is a non-`@objc` class with no declared stored /// properties. The `deinit` of `bufferClass` must destroy its /// stored `Header` and any constructed `Element`s. @inlinable // FIXME(sil-serialize-all) internal init( bufferClass: AnyClass, minimumCapacity: Int ) { ManagedBufferPointer._checkValidBufferClass(bufferClass, creating: true) _precondition( minimumCapacity >= 0, "ManagedBufferPointer must have non-negative capacity") self.init( _uncheckedBufferClass: bufferClass, minimumCapacity: minimumCapacity) } /// Internal version for use by _ContiguousArrayBuffer.init where we know that /// we have a valid buffer class and that the capacity is >= 0. @inlinable // FIXME(sil-serialize-all) internal init( _uncheckedBufferClass: AnyClass, minimumCapacity: Int ) { ManagedBufferPointer._sanityCheckValidBufferClass(_uncheckedBufferClass, creating: true) _sanityCheck( minimumCapacity >= 0, "ManagedBufferPointer must have non-negative capacity") let totalSize = _My._elementOffset + minimumCapacity * MemoryLayout<Element>.stride let newBuffer: AnyObject = _swift_bufferAllocate( bufferType: _uncheckedBufferClass, size: totalSize, alignmentMask: _My._alignmentMask) self._nativeBuffer = Builtin.unsafeCastToNativeObject(newBuffer) } /// Manage the given `buffer`. /// /// - Note: It is an error to use the `header` property of the resulting /// instance unless it has been initialized. @inlinable // FIXME(sil-serialize-all) internal init(_ buffer: ManagedBuffer<Header, Element>) { _nativeBuffer = Builtin.unsafeCastToNativeObject(buffer) } internal typealias _My = ManagedBufferPointer @inlinable // FIXME(sil-serialize-all) internal static func _checkValidBufferClass( _ bufferClass: AnyClass, creating: Bool = false ) { _debugPrecondition( _class_getInstancePositiveExtentSize(bufferClass) == MemoryLayout<_HeapObject>.size || ( (!creating || bufferClass is ManagedBuffer<Header, Element>.Type) && _class_getInstancePositiveExtentSize(bufferClass) == _headerOffset + MemoryLayout<Header>.size), "ManagedBufferPointer buffer class has illegal stored properties" ) _debugPrecondition( _usesNativeSwiftReferenceCounting(bufferClass), "ManagedBufferPointer buffer class must be non-@objc" ) } @inlinable // FIXME(sil-serialize-all) internal static func _sanityCheckValidBufferClass( _ bufferClass: AnyClass, creating: Bool = false ) { _sanityCheck( _class_getInstancePositiveExtentSize(bufferClass) == MemoryLayout<_HeapObject>.size || ( (!creating || bufferClass is ManagedBuffer<Header, Element>.Type) && _class_getInstancePositiveExtentSize(bufferClass) == _headerOffset + MemoryLayout<Header>.size), "ManagedBufferPointer buffer class has illegal stored properties" ) _sanityCheck( _usesNativeSwiftReferenceCounting(bufferClass), "ManagedBufferPointer buffer class must be non-@objc" ) } /// The required alignment for allocations of this type, minus 1 @inlinable // FIXME(sil-serialize-all) internal static var _alignmentMask: Int { return max( MemoryLayout<_HeapObject>.alignment, max(MemoryLayout<Header>.alignment, MemoryLayout<Element>.alignment)) &- 1 } /// The actual number of bytes allocated for this object. @inlinable // FIXME(sil-serialize-all) internal var _capacityInBytes: Int { return _stdlib_malloc_size(_address) } /// The address of this instance in a convenient pointer-to-bytes form @inlinable // FIXME(sil-serialize-all) internal var _address: UnsafeMutableRawPointer { return UnsafeMutableRawPointer(Builtin.bridgeToRawPointer(_nativeBuffer)) } /// Offset from the allocated storage for `self` to the stored `Header` @inlinable // FIXME(sil-serialize-all) internal static var _headerOffset: Int { _onFastPath() return _roundUp( MemoryLayout<_HeapObject>.size, toAlignment: MemoryLayout<Header>.alignment) } /// An **unmanaged** pointer to the storage for the `Header` /// instance. Not safe to use without _fixLifetime calls to /// guarantee it doesn't dangle @inlinable // FIXME(sil-serialize-all) internal var _headerPointer: UnsafeMutablePointer<Header> { _onFastPath() return (_address + _My._headerOffset).assumingMemoryBound( to: Header.self) } /// An **unmanaged** pointer to the storage for `Element`s. Not /// safe to use without _fixLifetime calls to guarantee it doesn't /// dangle. @inlinable // FIXME(sil-serialize-all) internal var _elementPointer: UnsafeMutablePointer<Element> { _onFastPath() return (_address + _My._elementOffset).assumingMemoryBound( to: Element.self) } /// Offset from the allocated storage for `self` to the `Element` storage @inlinable // FIXME(sil-serialize-all) internal static var _elementOffset: Int { _onFastPath() return _roundUp( _headerOffset + MemoryLayout<Header>.size, toAlignment: MemoryLayout<Element>.alignment) } @inlinable // FIXME(sil-serialize-all) public static func == ( lhs: ManagedBufferPointer, rhs: ManagedBufferPointer ) -> Bool { return lhs._address == rhs._address } @usableFromInline internal var _nativeBuffer: Builtin.NativeObject } // FIXME: when our calling convention changes to pass self at +0, // inout should be dropped from the arguments to these functions. // FIXME(docs): isKnownUniquelyReferenced should check weak/unowned counts too, // but currently does not. rdar://problem/29341361 /// Returns a Boolean value indicating whether the given object is known to /// have a single strong reference. /// /// The `isKnownUniquelyReferenced(_:)` function is useful for implementing the /// copy-on-write optimization for the deep storage of value types: /// /// mutating func update(withValue value: T) { /// if !isKnownUniquelyReferenced(&myStorage) { /// myStorage = self.copiedStorage() /// } /// myStorage.update(withValue: value) /// } /// /// Use care when calling `isKnownUniquelyReferenced(_:)` from within a Boolean /// expression. In debug builds, an instance in the left-hand side of a `&&` /// or `||` expression may still be referenced when evaluating the right-hand /// side, inflating the instance's reference count. For example, this version /// of the `update(withValue)` method will re-copy `myStorage` on every call: /// /// // Copies too frequently: /// mutating func badUpdate(withValue value: T) { /// if myStorage.shouldCopy || !isKnownUniquelyReferenced(&myStorage) { /// myStorage = self.copiedStorage() /// } /// myStorage.update(withValue: value) /// } /// /// To avoid this behavior, swap the call `isKnownUniquelyReferenced(_:)` to /// the left-hand side or store the result of the first expression in a local /// constant: /// /// mutating func goodUpdate(withValue value: T) { /// let shouldCopy = myStorage.shouldCopy /// if shouldCopy || !isKnownUniquelyReferenced(&myStorage) { /// myStorage = self.copiedStorage() /// } /// myStorage.update(withValue: value) /// } /// /// `isKnownUniquelyReferenced(_:)` checks only for strong references to the /// given object---if `object` has additional weak or unowned references, the /// result may still be `true`. Because weak and unowned references cannot be /// the only reference to an object, passing a weak or unowned reference as /// `object` always results in `false`. /// /// If the instance passed as `object` is being accessed by multiple threads /// simultaneously, this function may still return `true`. Therefore, you must /// only call this function from mutating methods with appropriate thread /// synchronization. That will ensure that `isKnownUniquelyReferenced(_:)` /// only returns `true` when there is really one accessor, or when there is a /// race condition, which is already undefined behavior. /// /// - Parameter object: An instance of a class. This function does *not* modify /// `object`; the use of `inout` is an implementation artifact. /// - Returns: `true` if `object` is known to have a single strong reference; /// otherwise, `false`. @inlinable public func isKnownUniquelyReferenced<T : AnyObject>(_ object: inout T) -> Bool { return _isUnique(&object) } @inlinable internal func _isKnownUniquelyReferencedOrPinned<T : AnyObject>(_ object: inout T) -> Bool { return _isUniqueOrPinned(&object) } /// Returns a Boolean value indicating whether the given object is known to /// have a single strong reference. /// /// The `isKnownUniquelyReferenced(_:)` function is useful for implementing the /// copy-on-write optimization for the deep storage of value types: /// /// mutating func update(withValue value: T) { /// if !isKnownUniquelyReferenced(&myStorage) { /// myStorage = self.copiedStorage() /// } /// myStorage.update(withValue: value) /// } /// /// `isKnownUniquelyReferenced(_:)` checks only for strong references to the /// given object---if `object` has additional weak or unowned references, the /// result may still be `true`. Because weak and unowned references cannot be /// the only reference to an object, passing a weak or unowned reference as /// `object` always results in `false`. /// /// If the instance passed as `object` is being accessed by multiple threads /// simultaneously, this function may still return `true`. Therefore, you must /// only call this function from mutating methods with appropriate thread /// synchronization. That will ensure that `isKnownUniquelyReferenced(_:)` /// only returns `true` when there is really one accessor, or when there is a /// race condition, which is already undefined behavior. /// /// - Parameter object: An instance of a class. This function does *not* modify /// `object`; the use of `inout` is an implementation artifact. /// - Returns: `true` if `object` is known to have a single strong reference; /// otherwise, `false`. If `object` is `nil`, the return value is `false`. @inlinable public func isKnownUniquelyReferenced<T : AnyObject>( _ object: inout T? ) -> Bool { return _isUnique(&object) }
38.960818
92
0.693704
1a03c51cf5eb8dc4fa6ea538faa7fc894e7714ed
1,354
// // See LICENSE folder for this templateโ€™s licensing information. // // Abstract: // Implements the application delegate for LiveViewTestApp with appropriate configuration points. // import UIKit import PlaygroundSupport import LiveViewHost import BookCore @UIApplicationMain class AppDelegate: LiveViewHost.AppDelegate { override func setUpLiveView() -> PlaygroundLiveViewable { // This method should return a fully-configured live view. This method must be implemented. // // The view or view controller returned from this method will be automatically be shown on screen, // as if it were a live view in Swift Playgrounds. You can control how the live view is shown by // changing the implementation of the `liveViewConfiguration` property below. return BookCore.instantiateLiveView() } override var liveViewConfiguration: LiveViewConfiguration { // Make this property return the configuration of the live view which you desire to test. // // Valid values are `.fullScreen`, which simulates when the user has expanded the live // view to fill the full screen in Swift Playgrounds, and `.sideBySide`, which simulates when // the live view is shown next to or above the source code editor in Swift Playgrounds. return .fullScreen } }
41.030303
106
0.725258
fcea4fefc463aa355757eb07dbdd6644fd82da87
1,362
// // UITextField+Tool.swift // Chat33 // // Created by ๅดๆ–‡ๆ‹ผ on 2018/9/19. // Copyright ยฉ 2018ๅนด ๅดๆ–‡ๆ‹ผ. All rights reserved. // import Foundation import UIKit extension UITextField{ func limitText(with limit:Int){ guard let text = self.text else { return } let lang = self.textInputMode?.primaryLanguage if lang == "zh-Hans" { guard let selectedRange = self.markedTextRange,let _ = self.position(from: selectedRange.start, offset: 0) else { if text.count > limit{ self.text = text.substring(to: limit - 1) } return } }else { if text.count > limit { self.text = text.substring(to: limit - 1) } } } @discardableResult func addToolBar(with title: String, target: Any, sel: Selector) -> UIButton { let view = UIView.init(frame: CGRect.init(x: 0, y: 0, width: ScreenWidth, height: 70)) view.backgroundColor = FZM_BackgroundColor let btn = UIButton.getNormalBtn(with: title) btn.frame = CGRect(x: 15, y: 15, width: ScreenWidth - 30, height: 40) btn.addTarget(target, action: sel, for: .touchUpInside) btn.layer.cornerRadius = 20 view.addSubview(btn) self.inputAccessoryView = view return btn } }
31.674419
125
0.582232
2267bca9587ac5e83e9af8a7ad20add1ada6a9af
1,917
// // PulleyViewController+Nested.swift // Pulley // // Created by Ethan Gill on 8/1/17. // import Foundation import UIKit extension PulleyViewController: PulleyDrawerViewControllerDelegate { public func collapsedDrawerHeight() -> CGFloat { if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate { return drawerVCCompliant.collapsedDrawerHeight() } else { return 68.0 } } public func partialRevealDrawerHeight() -> CGFloat { if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate { return drawerVCCompliant.partialRevealDrawerHeight() } else { return 264.0 } } public func supportedDrawerPositions() -> [PulleyPosition] { if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate { return drawerVCCompliant.supportedDrawerPositions() } else { return PulleyPosition.all } } public func drawerPositionDidChange(drawer: PulleyViewController) { if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate { drawerVCCompliant.drawerPositionDidChange?(drawer: drawer) } } public func makeUIAdjustmentsForFullscreen(progress: CGFloat) { if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate { drawerVCCompliant.makeUIAdjustmentsForFullscreen?(progress: progress) } } public func drawerChangedDistanceFromBottom(drawer: PulleyViewController, distance: CGFloat) { if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate { drawerVCCompliant.drawerChangedDistanceFromBottom?(drawer: drawer, distance: distance) } } }
36.169811
103
0.714137
2f3a30728d81037e071a0d4035a35ef4b304abf7
5,219
// // Array+Extensions.swift // // Created by Michael Westbrooks on 8/12/19. // Copyright ยฉ 2019 RedRooster Technologies Inc. All rights reserved. // import Foundation public extension Array where Element: Equatable { var uniqueElementsInOrder: [Element] { var uniqueValues: [Element] = [] forEach { item in if !uniqueValues.contains(item) { uniqueValues += [item] } } return uniqueValues } } public extension Array where Element: Hashable { func uniqueArray() -> Array { return Array(Set(self)) } } public extension Array where Element: Comparable { // MARK: - Swap an item in array with the current if it satisfies the scenario. Do this until complete acension and descension exists. func selectionSort(by areInIncreasingOrder: ((Element, Element) -> Bool) = (<)) -> [Element] { var data = self for i in 0..<(data.count-1) { var key = i // 1 for j in i+1..<data.count where areInIncreasingOrder(data[j], data[key]) { // 2 key = j } guard i != key else { continue } data.swapAt(i, key) // 3 } return data } } extension Array where Element: Comparable { // MARK: - Sort array by moving values 1 x 1 to the end of the array until ascencion or descension exists. func bubbleSort(by areInIncreasingOrder: ((Element, Element) -> Bool) = (<)) -> [Element] { var data = self for i in 0..<(data.count-1) { for j in 0..<(data.count-i-1) where areInIncreasingOrder(data[j+1], data[j]) { data.swapAt(j, j + 1) } } return data } } extension Array where Element: Comparable { // MARK: - Like sorting a deck of cards. Pull card out and order while keeping a reference to the new order, then replace until acension or descension exists. // Best for small itemsets func insertionSort(by areInIncreasingOrder: ((Element, Element) -> Bool) = (<)) -> [Element] { var data = self for i in 1..<data.count { // 1 let key = data[i] // 2 var j = i - 1 while j >= 0 && areInIncreasingOrder(key, data[j]) { // 3 data[j+1] = data[j] // 4 j = j - 1 } data[j + 1] = key // 5 } return data } } extension Array where Element: Comparable { // MARK: - Merge sort is the most efficient by splitting the data into chucnks and performing sorting accordingly until ascension or descension exists. private func merge(left: [Element], right: [Element], by areInIncreasingOrder: ((Element, Element) -> Bool) = (<)) -> [Element] { var output: [Element] = [] var mutableLeft = left var mutableRight = right while mutableLeft.count > 0 && mutableRight.count > 0 { if let firstElement = mutableLeft.first, let secondElement = mutableRight.first { if !areInIncreasingOrder(firstElement, secondElement) { output.append(secondElement) mutableRight.remove(at: 0) } else { output.append(firstElement) mutableLeft.remove(at: 0) } } } output.append(contentsOf: mutableLeft) output.append(contentsOf: mutableRight) return output } private func _emMergeSort(data: [Element], by areInIncreasingOrder: ((Element, Element) -> Bool) = (<)) -> [Element] { if data.count < 2 { return data } let leftArray = Array(data[..<Int(data.count / 2)]) // 1 let rightArray = Array(data[Int(data.count / 2)..<data.count]) // 2 return merge(left: _emMergeSort(data: leftArray, by: areInIncreasingOrder), right: _emMergeSort(data: rightArray, by: areInIncreasingOrder), by: areInIncreasingOrder) // 3 } func emMergeSort(by: ((Element, Element) -> Bool) = (<)) -> [Element] { let data = self return _emMergeSort(data: data, by: by) } } extension Array where Element: Comparable { // MARK: - Similar to the merge sort but uses less space to achieve complete ascension or descension. However its best on small sets of data. private func _quickSort(_ array: [Element], by areInIncreasingOrder: ((Element, Element) -> Bool)) -> [Element] { if array.count < 2 { return array } // 0 var data = array let pivot = data.remove(at: 0) // 1 let left = data.filter { areInIncreasingOrder($0, pivot) } // 2 let right = data.filter { !areInIncreasingOrder($0, pivot) } // 3 let middle = [pivot] return _quickSort(left, by: areInIncreasingOrder) + middle + _quickSort(right, by: areInIncreasingOrder) // 4 } func quickSort(by areInIncreasingOrder: ((Element, Element) -> Bool) = (<)) -> [Element] { return _quickSort(self, by: areInIncreasingOrder) } }
36.243056
179
0.568883
e0a9a5602a1dcc65e9402c7b57c5275bd2dced89
19,311
/// Detects differences between two given values by comparing their mirrors and optionally returns /// a formatted string describing it. /// /// This can be a great tool to use for building debug tools for applications and libraries. For /// example, this library uses ``diff(_:_:format:)`` to implement /// ``XCTAssertNoDifference(_:_:_:file:line:)``, which asserts that two values are equal, and /// if they are not the failure message is a nicely formatted diff showing exactly what part of the /// values are not equal. /// /// Further, the /// [Composable Architecture](https://www.github.com/pointfreeco/swift-composable-architecture) uses /// ``diff(_:_:format:)`` in a couple different ways: /// /// * It is used to implement a tool that prints changes to application state over time as diffs /// between the previous state and the current state whenever an action is sent to the store. /// * It is also used in a testing tool so that when one fails to assert for how state may have /// changed after sending an action, it can display a concise message showing the exact difference /// in state. /// /// - Parameters: /// - lhs: An expression of type `T`. /// - rhs: A second expression of type `T`. /// - format: A format to use for the diff. By default it uses ASCII characters typically /// associated with the "diff" format: "-" for removals, "+" for additions, and " " for /// unchanged lines. /// - Returns: A string describing any difference detected between values, or `nil` if no difference /// is detected. public func diff<T>(_ lhs: T, _ rhs: T, format: DiffFormat = .default) -> String? { var visitedItems: Set<ObjectIdentifier> = [] func diffHelp( _ lhs: Any, _ rhs: Any, lhsName: String?, rhsName: String?, separator: String, indent: Int ) -> String { let rhsName = rhsName ?? lhsName guard !isMirrorEqual(lhs, rhs) else { return _customDump(lhs, name: rhsName, indent: indent, maxDepth: 0) .appending(separator) .indenting(with: format.both + " ") } let lhsMirror = Mirror(customDumpReflecting: lhs) let rhsMirror = Mirror(customDumpReflecting: rhs) var out = "" func diffEverything() { print( _customDump(lhs, name: lhsName, indent: indent, maxDepth: .max) .appending(separator) .indenting(with: format.first + " "), to: &out ) print( _customDump(rhs, name: rhsName, indent: indent, maxDepth: .max) .appending(separator) .indenting(with: format.second + " "), terminator: "", to: &out ) } guard lhsMirror.subjectType == rhsMirror.subjectType else { diffEverything() return out } func diffChildren( _ lhsMirror: Mirror, _ rhsMirror: Mirror, prefix: String, suffix: String, elementIndent: Int, elementSeparator: String, collapseUnchanged: Bool, areEquivalent: (Mirror.Child, Mirror.Child) -> Bool = { $0.label == $1.label }, areInIncreasingOrder: ((Mirror.Child, Mirror.Child) -> Bool)? = nil, _ transform: (inout Mirror.Child, Int) -> Void = { _, _ in } ) { var lhsChildren = Array(lhsMirror.children) var rhsChildren = Array(rhsMirror.children) guard !isMirrorEqual(lhsChildren, rhsChildren) else { print( "// Not equal but no difference detected:" .indenting(by: indent) .indenting(with: format.both + " "), to: &out ) print( _customDump( lhs, name: lhsName, indent: indent, maxDepth: 0 ) .indenting(with: format.first + " "), to: &out ) print( _customDump( rhs, name: rhsName, indent: indent, maxDepth: 0 ) .indenting(with: format.second + " "), terminator: "", to: &out ) return } guard !lhsMirror.isSingleValueContainer && !rhsMirror.isSingleValueContainer else { print( _customDump( lhs, name: lhsName, indent: indent, maxDepth: .max ) .indenting(with: format.first + " "), to: &out ) print( _customDump( rhs, name: rhsName, indent: indent, maxDepth: .max ) .indenting(with: format.second + " "), terminator: "", to: &out ) return } let name = rhsName.map { "\($0): " } ?? "" print( name .appending(prefix) .indenting(by: indent) .indenting(with: format.both + " "), to: &out ) if let areInIncreasingOrder = areInIncreasingOrder { lhsChildren.sort(by: areInIncreasingOrder) rhsChildren.sort(by: areInIncreasingOrder) } let difference = rhsChildren.difference(from: lhsChildren, by: areEquivalent) var lhsOffset = 0 var rhsOffset = 0 var unchangedBuffer: [Mirror.Child] = [] func flushUnchanged() { guard collapseUnchanged else { return } if areInIncreasingOrder == nil && unchangedBuffer.count == 1 { let child = unchangedBuffer[0] print( _customDump( child.value, name: child.label, indent: indent + elementIndent, maxDepth: 0 ) .indenting(with: format.both + " "), terminator: rhsOffset - 1 == rhsChildren.count - 1 ? "\n" : "\(elementSeparator)\n", to: &out ) } else if areInIncreasingOrder != nil && unchangedBuffer.count == 1 || unchangedBuffer.count > 1 { print( "โ€ฆ (\(unchangedBuffer.count) unchanged)" .indenting(by: indent + elementIndent) .indenting(with: format.both + " "), terminator: rhsOffset - 1 == rhsChildren.count - 1 ? "\n" : "\(elementSeparator)\n", to: &out ) } unchangedBuffer.removeAll() } while lhsOffset < lhsChildren.count || rhsOffset < rhsChildren.count { let isRemoval = difference.removals.contains(where: { $0.offset == lhsOffset }) let isInsertion = difference.insertions.contains(where: { $0.offset == rhsOffset }) if collapseUnchanged, !isRemoval, !isInsertion, isMirrorEqual(lhsChildren[lhsOffset], rhsChildren[rhsOffset]) { var child = rhsChildren[rhsOffset] transform(&child, rhsOffset) unchangedBuffer.append(child) lhsOffset += 1 rhsOffset += 1 continue } if areInIncreasingOrder == nil { flushUnchanged() } switch (isRemoval, isInsertion) { case (true, true), (false, false): var lhsChild = lhsChildren[lhsOffset] var rhsChild = rhsChildren[rhsOffset] transform(&lhsChild, isRemoval ? lhsOffset : rhsOffset) transform(&rhsChild, rhsOffset) print( diffHelp( lhsChild.value, rhsChild.value, lhsName: lhsChild.label, rhsName: rhsChild.label, separator: lhsOffset == lhsChildren.count - 1 && rhsOffset == rhsChildren.count - 1 ? "" : elementSeparator, indent: indent + elementIndent ), to: &out ) lhsOffset += 1 rhsOffset += 1 continue case (true, false): var lhsChild = lhsChildren[lhsOffset] transform(&lhsChild, lhsOffset) print( _customDump( lhsChild.value, name: lhsChild.label, indent: indent + elementIndent, maxDepth: .max ) .indenting(with: format.first + " "), terminator: lhsOffset == lhsChildren.count - 1 ? "\n" : "\(elementSeparator)\n", to: &out ) lhsOffset += 1 case (false, true): var rhsChild = rhsChildren[rhsOffset] transform(&rhsChild, rhsOffset) print( _customDump( rhsChild.value, name: rhsChild.label, indent: indent + elementIndent, maxDepth: .max ) .indenting(with: format.second + " "), terminator: rhsOffset == rhsChildren.count - 1 && unchangedBuffer.isEmpty ? "\n" : "\(elementSeparator)\n", to: &out ) rhsOffset += 1 } } flushUnchanged() print( suffix .indenting(by: indent) .indenting(with: format.both + " "), terminator: separator, to: &out ) } switch (lhs, lhsMirror.displayStyle, rhs, rhsMirror.displayStyle) { case (is CustomDumpStringConvertible, _, is CustomDumpStringConvertible, _): diffEverything() case let (lhs as CustomDumpRepresentable, _, rhs as CustomDumpRepresentable, _): out.write( diffHelp( lhs.customDumpValue, rhs.customDumpValue, lhsName: lhsName, rhsName: rhsName, separator: separator, indent: indent ) ) case let (lhs as AnyObject, .class?, rhs as AnyObject, .class?): let lhsItem = ObjectIdentifier(lhs) let rhsItem = ObjectIdentifier(rhs) let subjectType = typeName(lhsMirror.subjectType) if visitedItems.contains(lhsItem) || visitedItems.contains(rhsItem) { print( "\(lhsName.map { "\($0): " } ?? "")\(subjectType)(โ†ฉ๏ธŽ)" .indenting(by: indent) .indenting(with: format.first + " "), to: &out ) print( "\(rhsName.map { "\($0): " } ?? "")\(subjectType)(โ†ฉ๏ธŽ)" .indenting(by: indent) .indenting(with: format.second + " "), terminator: "", to: &out ) } else { let showObjectIdentifiers = lhsItem != rhsItem && isMirrorEqual(Array(lhsMirror.children), Array(rhsMirror.children)) let lhsMirror = showObjectIdentifiers ? Mirror(lhs, children: [("_", lhsItem)] + lhsMirror.children, displayStyle: .class) : lhsMirror let rhsMirror = showObjectIdentifiers ? Mirror(rhs, children: [("_", rhsItem)] + rhsMirror.children, displayStyle: .class) : rhsMirror visitedItems.insert(lhsItem) diffChildren( lhsMirror, rhsMirror, prefix: "\(subjectType)(", suffix: ")", elementIndent: 2, elementSeparator: ",", collapseUnchanged: false ) } case (_, .collection?, _, .collection?): diffChildren( lhsMirror, rhsMirror, prefix: "[", suffix: "]", elementIndent: 2, elementSeparator: ",", collapseUnchanged: true, areEquivalent: { isIdentityEqual($0.value, $1.value) || isMirrorEqual($0.value, $1.value) }, { $0.label = "[\($1)]" } ) case (_, .dictionary?, _, .dictionary?): diffChildren( lhsMirror, rhsMirror, prefix: "[", suffix: "]", elementIndent: 2, elementSeparator: ",", collapseUnchanged: true, areEquivalent: { guard let lhs = $0.value as? (key: AnyHashable, value: Any), let rhs = $1.value as? (key: AnyHashable, value: Any) else { return isMirrorEqual($0.value, $1.value) } return lhs.key == rhs.key }, areInIncreasingOrder: { guard let lhs = $0.value as? (key: AnyHashable, value: Any), let rhs = $1.value as? (key: AnyHashable, value: Any) else { return _customDump($0.value, name: nil, indent: 0, maxDepth: 1) < _customDump($1.value, name: nil, indent: 0, maxDepth: 1) } return _customDump(lhs.key.base, name: nil, indent: 0, maxDepth: 1) < _customDump(rhs.key.base, name: nil, indent: 0, maxDepth: 1) } ) { child, _ in guard let pair = child.value as? (key: AnyHashable, value: Any) else { return } child = ( _customDump(pair.key.base, name: nil, indent: 0, maxDepth: 1), pair.value ) } case (_, .enum?, _, .enum?): guard let lhsChild = lhsMirror.children.first, let rhsChild = rhsMirror.children.first, let caseName = lhsChild.label, caseName == rhsChild.label else { diffEverything() break } let lhsChildMirror = Mirror(customDumpReflecting: lhsChild.value) let rhsChildMirror = Mirror(customDumpReflecting: rhsChild.value) let lhsAssociatedValuesMirror = lhsChildMirror.displayStyle == .tuple ? lhsChildMirror : Mirror(lhs, unlabeledChildren: [lhsChild.value], displayStyle: .tuple) let rhsAssociatedValuesMirror = rhsChildMirror.displayStyle == .tuple ? rhsChildMirror : Mirror(rhs, unlabeledChildren: [rhsChild.value], displayStyle: .tuple) let subjectType = typeName(lhsMirror.subjectType) diffChildren( lhsAssociatedValuesMirror, rhsAssociatedValuesMirror, prefix: "\(subjectType).\(caseName)(", suffix: ")", elementIndent: 2, elementSeparator: ",", collapseUnchanged: false, { child, _ in if child.label?.first == "." { child.label = nil } } ) case (_, .optional?, _, .optional?): guard let lhsValue = lhsMirror.children.first?.value, let rhsValue = rhsMirror.children.first?.value else { diffEverything() break } out.write( diffHelp( lhsValue, rhsValue, lhsName: lhsName, rhsName: rhsName, separator: separator, indent: indent ) ) case (_, .set?, _, .set?): diffChildren( lhsMirror, rhsMirror, prefix: "Set([", suffix: "])", elementIndent: 2, elementSeparator: ",", collapseUnchanged: true, areEquivalent: { isIdentityEqual($0.value, $1.value) || isMirrorEqual($0.value, $1.value) }, areInIncreasingOrder: { _customDump($0.value, name: nil, indent: 0, maxDepth: 1) < _customDump($1.value, name: nil, indent: 0, maxDepth: 1) } ) case (_, .struct?, _, .struct?): diffChildren( lhsMirror, rhsMirror, prefix: "\(typeName(lhsMirror.subjectType))(", suffix: ")", elementIndent: 2, elementSeparator: ",", collapseUnchanged: false ) case (_, .tuple?, _, .tuple?): diffChildren( lhsMirror, rhsMirror, prefix: "(", suffix: ")", elementIndent: 2, elementSeparator: ",", collapseUnchanged: false, { child, _ in if child.label?.first == "." { child.label = nil } } ) default: if let lhs = stringFromStringProtocol(lhs), let rhs = stringFromStringProtocol(rhs), lhs.contains(where: \.isNewline) || rhs.contains(where: \.isNewline) { let lhsMirror = Mirror( customDumpReflecting: lhs.isEmpty ? [] : lhs .split(separator: "\n", omittingEmptySubsequences: false) .map(Line.init(rawValue:)) ) let rhsMirror = Mirror( customDumpReflecting: rhs.isEmpty ? [] : rhs .split(separator: "\n", omittingEmptySubsequences: false) .map(Line.init(rawValue:)) ) let hashes = String(repeating: "#", count: max(lhs.hashCount, rhs.hashCount)) diffChildren( lhsMirror, rhsMirror, prefix: "\(hashes)\"\"\"", suffix: rhsName != nil ? " \"\"\"\(hashes)" : "\"\"\"\(hashes)", elementIndent: rhsName != nil ? 2 : 0, elementSeparator: "", collapseUnchanged: false, areEquivalent: { isIdentityEqual($0.value, $1.value) || isMirrorEqual($0.value, $1.value) } ) } else { diffEverything() } } return out } guard !isMirrorEqual(lhs, rhs) else { return nil } var diff = diffHelp(lhs, rhs, lhsName: nil, rhsName: nil, separator: "", indent: 0) if diff.last == "\n" { diff.removeLast() } return diff } /// Describes how to format a difference between two values when using ``diff(_:_:format:)``. /// /// Typically one simply wants to use "-" to denote removals, "+" to denote additions, and " " for /// spacing. However, in some contexts, such as in `XCTest` failures, messages are displayed in a /// non-monospaced font. In those times the simple "-" and " " characters do not properly line up /// visually, and so you need to use different characters that visually look similar to "-" and " " /// but have the proper widths. /// /// This type comes with two pre-configured formats that you will probably want to use for most /// situations: ``DiffFormat/default`` and ``DiffFormat/proportional``. public struct DiffFormat { /// A string prepended to lines that only appear in the string representation of the first value, /// e.g. a "removal." public var first: String /// A string prepended to lines that only appear in the string representation of the second value, /// e.g. an "insertion." public var second: String /// A string prepended to lines that appear in the string representation of both values, e.g. /// something "unchanged." public var both: String public init( first: String, second: String, both: String ) { self.first = first self.second = second self.both = both } /// The default format for ``diff(_:_:format:)`` output, appropriate for where monospaced fonts /// are used, e.g. console output. /// /// Uses ascii characters for removals (hyphen "-"), insertions (plus "+"), and unchanged (space /// " "). public static let `default` = Self(first: "-", second: "+", both: " ") /// A diff format appropriate for where proportional (non-monospaced) fonts are used, e.g. Xcode's /// failure overlays. /// /// Uses ascii plus ("+") for insertions, unicode minus sign ("โˆ’") for removals, and unicode /// figure space ("โ€‡") for unchanged. These three characters are more likely to render with equal /// widths in proportional fonts. public static let proportional = Self(first: "\u{2212}", second: "+", both: "\u{2007}") } private struct Line: CustomDumpStringConvertible, Identifiable { var rawValue: Substring var id: Substring { self.rawValue } var customDumpDescription: String { .init(self.rawValue) } }
31.866337
100
0.558645
f78cc068e8198129c5484f7d35a767b8b61d9842
652
// // AKHighShelfFilterTests.swift // AudioKitTestSuite // // Created by Aurelius Prochazka, revision history on GitHub. // Copyright ยฉ 2018 AudioKit. All rights reserved. // import AudioKit import XCTest class AKHighShelfFilterTests: AKTestCase { func testDefault() { output = AKHighShelfFilter(input) AKTestNoEffect() } func testGain() { output = AKHighShelfFilter(input, gain: 1) AKTestMD5("a3e0e254d8e615aa7680e6ac21487a0b") } func testParameters() { output = AKHighShelfFilter(input, cutOffFrequency: 400, gain: 1) AKTestMD5("46b3c7449912abb6a5484ad7db9d3e9c") } }
21.733333
72
0.685583
6a955b4bfeeb944a9139e06c632d0600ddc60702
1,642
import Foundation import Redis import TCP import WebSocket fileprivate let subscriberQueue = DispatchQueue(label: "redis_queue") fileprivate let publisher = try? RedisClient.connect(worker: DispatchQueue(label: "redis_publish_queue")) fileprivate let redisChannel = "chat_channel" class WebsocketServer { private static var connections = [String : WebsocketServer]() private let username: String private let websocket: WebSocket private init(username: String, websocket: WebSocket) throws { self.username = username self.websocket = websocket try subscribe() websocket.onText(self.onText(json:)) } static func register(username: String, websocket: WebSocket) throws { connections[username] = try WebsocketServer(username: username, websocket: websocket) } private func onText(json: String) { if let input: MessageInputData = MessageInputData.from(json: json) { let message = RedisMessage(username: self.username, input: input) publish(message) } } private func publish(_ message: RedisMessage) { _ = publisher?.do { client in client.publish(message, to: redisChannel) } } private func subscribe() throws { let _ = try RedisClient.connect(worker: subscriberQueue).do { client in client.subscribe(to: redisChannel).onRedisMessage { message, _ in let output = MessageOutputData(message) if let outputJson = output.toJson() { self.websocket.send(outputJson) } } } } }
30.981132
105
0.65408
0e652b707745c83a18dcd8e67d9bb9cdb87bba00
3,376
// // 3Dify App // // Project website: https://github.com/3dify-app // // Authors: // - It's free real estate 2020, Contact: [email protected] // // Copyright notice: All rights reserved by the authors given above. Do not // remove or change this copyright notice without confirmation of the authors. // import UIKit import Vision import Accelerate class PydnetProcessor: DepthProcessor { let model: Pydnet var description: String { return "Pydnet Neural Processor" } required init() { self.model = Pydnet() } enum ProcessingError: Error { case inputPixelBufferCreationFailed case inferenceFailed case createOutputCGImageFailed case filteringFailed case normalizationFailed } func process( originalImage: UIImage, completion: @escaping (Result<UIImage, Error>) -> Void ) { guard let pixelBuffer = makeInputPixelBuffer( fromOriginalImage: originalImage ) else { completion(.failure(ProcessingError.inputPixelBufferCreationFailed)) return } guard let prediction = try? model .prediction(im0__0: pixelBuffer) .mul__0 else { completion(.failure(ProcessingError.inferenceFailed)) return } let context = CIContext() let outputImage = CIImage(cvPixelBuffer: prediction) guard let outputCGImage = context.createCGImage( outputImage, from: outputImage.extent ) else { completion(.failure(ProcessingError.createOutputCGImageFailed)) return } let filteredImage = UIImage(cgImage: outputCGImage) guard let finalImage = NormalizationFilter(image: filteredImage) .normalize() else { completion(.failure(ProcessingError.normalizationFailed)) return } completion(.success(finalImage)) } private func makeInputPixelBuffer( fromOriginalImage originalImage: UIImage ) -> CVPixelBuffer? { // Resize the original image to 384 x 640 let inputHeight = 384 let inputWidth = 640 let rect = CGRect(x: 0, y: 0, width: inputWidth, height: inputHeight) UIGraphicsBeginImageContext(rect.size) originalImage.draw(in: rect) let drawnImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() guard let inputImage = drawnImage else { return nil } // Create a new pixel buffer with float32 BGRA pixel format var pixelBufferCreationOutput : CVPixelBuffer? let status = CVPixelBufferCreate( kCFAllocatorDefault, Int(inputImage.size.width), Int(inputImage.size.height), kCVPixelFormatType_32BGRA, [ kCVPixelBufferCGImageCompatibilityKey: kCFBooleanTrue, kCVPixelBufferCGBitmapContextCompatibilityKey: kCFBooleanTrue ] as CFDictionary, &pixelBufferCreationOutput ) guard status == kCVReturnSuccess, let createdPixelBuffer = pixelBufferCreationOutput else { return nil } return createdPixelBuffer } }
29.103448
80
0.619372
0357a8dab744323dba22dce0dd3f30c4c09b0899
3,313
// swiftlint:disable file_header // // Reachability.swift // Etcetera // // Copyright ยฉ 2018 Nice Boy LLC. All rights reserved. // import Foundation import SystemConfiguration public protocol Mockable {} // Sourcery // sourcery: name = Reachability public protocol Reachable: Mockable { var isReachable: Bool { get } func setDelegate(_ delegate: ReachabilityDelegate) } public protocol ReachabilityDelegate: AnyObject, Mockable { func reachabilityDidChange(_ reachability: Reachable, isReachable: Bool) } /// A class that reports whether or not the network is currently reachable. public final class Reachability: NSObject, Reachable { /// Synchronous evaluation of the current flags. public var isReachable: Bool { return flags?.isReachable == true } private let reachability: SCNetworkReachability? private weak var delegate: ReachabilityDelegate? // was originally os_unfair_lock_unlock(), however this isn't compatible with macOS 10.10 private let lockQueue = DispatchQueue(label: "com.larromba.Reachability.queue") private var _flags: SCNetworkReachabilityFlags? private var flags: SCNetworkReachabilityFlags? { get { return lockQueue.sync { return _flags } } set { lockQueue.sync { _flags = newValue DispatchQueue.main.async { self.delegate?.reachabilityDidChange(self, isReachable: newValue?.isReachable == true) } } } } public init(host: String = "www.google.com") { guard host.isValid else { assertionFailure("invalid host name") reachability = nil super.init() return } self.reachability = SCNetworkReachabilityCreateWithName(nil, host) super.init() guard let reachability = reachability else { return } // Populate the current flags asap. var flags = SCNetworkReachabilityFlags() SCNetworkReachabilityGetFlags(reachability, &flags) _flags = flags // Then configure the callback. let callback: SCNetworkReachabilityCallBack = { _, flags, infoPtr in guard let info = infoPtr else { return } let this = Unmanaged<Reachability>.fromOpaque(info).takeUnretainedValue() this.flags = flags } let selfPtr = Unmanaged.passUnretained(self).toOpaque() var context = SCNetworkReachabilityContext( version: 0, info: selfPtr, retain: nil, release: nil, copyDescription: nil ) SCNetworkReachabilitySetCallback(reachability, callback, &context) SCNetworkReachabilitySetDispatchQueue(reachability, .global()) } deinit { guard let reachability = reachability else { return } SCNetworkReachabilitySetCallback(reachability, nil, nil) } public func setDelegate(_ delegate: ReachabilityDelegate) { self.delegate = delegate } } // MARK: - String private extension String { var isValid: Bool { return URL(string: self) != nil } } // MARK: - SCNetworkReachabilityFlags private extension SCNetworkReachabilityFlags { var isReachable: Bool { return contains(.reachable) } }
30.394495
106
0.656505
87d8be43c373fe653eba65453a6ddc9a2b455c34
684
import Foundation import ObjectMapper open class ExtensionPermissions: Mappable { /* Admin permission */ open var `admin`: PermissionInfo? /* International Calling permission */ open var `internationalCalling`: PermissionInfo? public init() { } required public init?(map: Map) { } convenience public init(admin: PermissionInfo? = nil, internationalCalling: PermissionInfo? = nil) { self.init() self.admin = `admin` self.internationalCalling = `internationalCalling` } open func mapping(map: Map) { `admin` <- map["admin"] `internationalCalling` <- map["internationalCalling"] } }
26.307692
104
0.643275
debc8177c480f6b88cbc77afe5721633cadf34a1
5,144
// // PasscodePresenter.swift // HumbleNumber // // Created by Yaroslav Stanislavyk on 19.08.2020. // Copyright ยฉ 2020 Yaroslav Stanislavyk. All rights reserved. // import SwiftUI import Combine import os protocol PasscodePresenter: ObservableObject { func loadPasscodeData() func makeProgressBar() -> AnyView func makeInformationMessageLabel() -> AnyView func makeKeypad() -> AnyView func makeCancelButton() -> AnyView func makeDeleteButton() -> AnyView } final class PasscodePresenterReal: PasscodePresenter { private let interactor: PasscodeInteractor private let logger = OSLog.init(subsystem: Bundle.main.bundleIdentifier!, category: "Passcode") private var cancellables = Set<AnyCancellable>() @Published private var passcodeData: PasscodeData @Published private var informationLabelText: String @Published private var passcodeInputProgress: Int @Published private var isPasscodeDataLoading: Bool init(interactor: PasscodeInteractor) { self.passcodeData = PasscodeData() self.informationLabelText = "" self.passcodeInputProgress = 0 self.isPasscodeDataLoading = true self.interactor = interactor self.interactor.passcodeDataPublisher() .receive(on: DispatchQueue.main) .assign(to: \.passcodeData, on: self) .store(in: &cancellables) self.interactor.passcodeInputProgressPublisher() .receive(on: DispatchQueue.main) .assign(to: \.passcodeInputProgress, on: self) .store(in: &cancellables) self.interactor.passcodeDataLoadingFlagPublisher() .receive(on: DispatchQueue.main) .assign(to: \.isPasscodeDataLoading, on: self) .store(in: &cancellables) } func loadPasscodeData() { interactor.loadPasscodeData(completion: { [weak self] result in guard let strongSelf = self else { return } switch result.code { case .success: DispatchQueue.main.async { strongSelf.informationLabelText = "Please enter your 4 digit pin code:" } case .failure(error: let error): DispatchQueue.main.async { strongSelf.informationLabelText = "Oops. Something went wrong. Please try again later" } os_log("An error during the passcode data loading: %@", log: strongSelf.logger, type: .error, error.localizedDescription) } }) } func makeProgressBar() -> AnyView { if isPasscodeDataLoading { return AnyView( DataLoadingIndicator(isLoading: isPasscodeDataLoading, style: .large) .padding(.vertical) ) } else { let maxProgressValue = interactor.maxPasscodeInputProgressValue() let progressPoints = ((maxProgressValue - passcodeInputProgress)..<maxProgressValue) let remainingProgressPoints = (passcodeInputProgress..<maxProgressValue) return AnyView( PasscodeInputProgressBar(progressPoints: progressPoints, remainingProgressPoints: remainingProgressPoints) .foregroundColor(.darkOrange) .padding(.top) .padding(.bottom, 40) ) } } func makeInformationMessageLabel() -> AnyView { if isPasscodeDataLoading { return AnyView( Text("The passcode data is loading. Please wait") .foregroundColor(.darkOrange) ) } return AnyView( Text(informationLabelText) .foregroundColor(.darkOrange) ) } func makeKeypad() -> AnyView { var keypadButtons = [KeypadButton]() for digit in passcodeData.digits { let stringDigit = String(digit) let keypadButton = KeypadButton(action: { self.interactor.appendInput(with: stringDigit) }, number: Text(stringDigit)) keypadButtons.append(keypadButton) } return AnyView( KeypadView(buttons: keypadButtons) .disabled(isPasscodeDataLoading) ) } func makeCancelButton() -> AnyView { return AnyView( Button(action: { self.interactor.clearInput() }) { Text("Cancel") .foregroundColor(.white) } .disabled(isPasscodeDataLoading) ) } func makeDeleteButton() -> AnyView { return AnyView( Button(action: { self.interactor.removeLastInput() }) { Text("Delete") .foregroundColor(.white) } .disabled(isPasscodeDataLoading) ) } }
32.764331
137
0.571151
877370001ca99a772732999a5ab95a5416cadead
2,797
// 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 Cocoa class NewDeviceViewController: NSViewController { @IBOutlet weak var Category: NSTextField! @IBOutlet weak var VendorIdentifier: NSTextField! @IBOutlet weak var ProductIdentifier: NSTextField! @IBOutlet weak var Serial: NSTextField! @IBOutlet weak var Name: NSTextField! @IBOutlet weak var Manufacturer: NSTextField! let hidTypes = [ 1: "Pointer", 2: "Mouse", 4: "Joystick", 5: "Game Pad", 6: "Keyboard", 7: "Keypad", 8: "Multi-axis Controller", ] let vendors = [ 0x05AC: "Apple, Inc.", ] let products = [ 0x030E: "MC380Z/A [Magic Trackpad]" ] override func viewDidLoad() { super.viewDidLoad() } override var representedObject: Any? { didSet { // Update the view, if already loaded. Name.stringValue = (representedObject as! USBDevice).Name let primaryUsageKey = (representedObject as! USBDevice).PrimaryUsage let usageKeyText = hidTypes[primaryUsageKey] ?? "Unknown Device (\(primaryUsageKey))" Category.stringValue = usageKeyText let vendorID = (representedObject as! USBDevice).VendorID VendorIdentifier.stringValue = "\(vendors[vendorID] ?? "Unknown") (\(String(format:"0x%04X", vendorID)))" let productID = (representedObject as! USBDevice).ProductID ProductIdentifier.stringValue = "\(products[productID] ?? "Unknown") (\(String(format:"0x%04X", productID)))" Serial.stringValue = "\((representedObject as! USBDevice).SerialNumber)" Manufacturer.stringValue = "\((representedObject as! USBDevice).Manufacturer)" self.view.window!.title = "USB Detective ๐Ÿ”" } } @IBAction func whitelistButton(_ sender: Any) { let application = NSApplication.shared application.stopModal(withCode: NSApplication.ModalResponse(ModalResult.Whitelist.rawValue)) } @IBAction func dismiss(_ sender: Any) { let application = NSApplication.shared application.stopModal() } }
33.698795
115
0.700393
8fb83a5389551e117020dce36d32f69e8eec3b65
2,677
// // DataExample.swift // Independent Study App // // Created by Malcolm Machesky on 1/3/18. // Copyright ยฉ 2018 Malcolm Machesky. All rights reserved. // import Foundation import KituraKit class DataExample { static let sharedInstance = DataExample() var Users: [User] = [] var Posts : [Post] = [] var currentUser: User? var postForUser: [[Post]]? private init() { Users = { /* let malcolmUser = User(username: "malcolm5858", profilePicture: #imageLiteral(resourceName: "MalcolmProfile"), bio: "TO TEst the bio") let robertUser = User(username: "Robert", profilePicture: #imageLiteral(resourceName: "RobertProfile"), bio: "bio...") let alexUser = User(username: "9Srting", profilePicture: #imageLiteral(resourceName: "AlexProfile"), bio: "9Srting") let joshUser = User(username: "Josh", profilePicture: #imageLiteral(resourceName: "JoshProfile"), bio: "Bio") */ return [] }() Posts = { /* let malcolmPost1 = Post(user: Users[0], caption: "first powerup", postImage: #imageLiteral(resourceName: "Nature1")) let malcolmPost2 = Post(user: Users[0], caption: "first powerup 2", postImage: #imageLiteral(resourceName: "Nature2")) let malcolmPost3 = Post(user: Users[0], caption: "first powerup", postImage: #imageLiteral(resourceName: "Nature3")) let malcolmPost4 = Post(user: Users[0], caption: "first powerup 2", postImage: #imageLiteral(resourceName: "Robert1")) let robertPost1 = Post(user: Users[1], caption: "robert", postImage: #imageLiteral(resourceName: "Robert1")) let alexPost1 = Post(user: Users[2], caption: "Colosseum", postImage: #imageLiteral(resourceName: "Alex1")) let joshPost1 = Post(user: Users[3], caption: "caption", postImage: #imageLiteral(resourceName: "JoshPicture")) */ return [] }() //currentUser = Users[0] /* postForUser = { let malcolmPosts = [Posts[0], Posts[1]] let robertPosts = [Posts[2]] let alexPosts = [Posts[3]] return [malcolmPosts, robertPosts, alexPosts] }() */ } /* func sendTestData(data: String) { let json: [String: Any] = ["title": "TestData", "dict": ["1": data]] let jsonData = try? JSONSerialization.data(withJSONObject: json, options: JSONSerialization.WritingOptions.sortedKeys) } */ }
36.175676
146
0.576018
566c0bdcec9a879fb49029f83fd38c3306898f8b
7,270
// // AccountsEndpointTests.swift // Xpense Server Tests // // Created by Paul Schmiedmayer on 4/9/20. // Copyright ยฉ 2020 TUM LS1. All rights reserved. // @testable import XpenseServer import Corvus import XCTVapor // MARK: AccountsEndpointTests /// The unit tests that concern the `AccountsEndpoint` final class AccountsEndpointTests: XpenseServerTests { override func setUpWithError() throws { try super.setUpWithError() // Create the User let corvusUser = CorvusUser(username: user.username, password: try Bcrypt.hash(user.password)) try corvusUser.save(on: database()).wait() user.id = corvusUser.id // Create the Token let userId = try XCTUnwrap(user.id) let corvusToken = CorvusToken(value: "kt3Lp9Aozk9JAwo13wueCw==", userID: userId) try corvusToken.save(on: database()).wait() user.token = corvusToken.value } /// Tests getting an `Account` at the `api/accounts` endpoint func testGetAccountsOne() throws { let account = Account(name: "Paul's Wallet") user.id.map { account.$user.id = $0 } try account.create(on: database()).wait() try tester() .test(.GET, "/api/accounts", headers: [ "Content-Type": "application/json", "Authorization": user.bearerToken() ]) { response in let content = try response.content.decode([Account].self) XCTAssertEqual(content.count, 1) XCTAssertEqual(content.first, account) } } /// Tests getting an `Account` at the `api/accounts` endpoint func testGetAccountsTwo() throws { let account = Account(name: "Paul's Wallet") user.id.map { account.$user.id = $0 } try account.create(on: database()).wait() let secondAccount = Account(name: "Paul's Wallet") user.id.map { secondAccount.$user.id = $0 } try secondAccount.create(on: database()).wait() try tester() .test(.GET, "/api/accounts", headers: [ "Content-Type": "application/json", "Authorization": user.bearerToken() ]) { response in let content = try response.content.decode([Account].self) XCTAssertEqual(content.count, 2) XCTAssertEqual(content.first, account) XCTAssertEqual(content.last, secondAccount) } } /// Tests the sucessful creation of an `Account` at the `api/accounts` route func testCreateAccount() throws { let account = Account(name: "Paul's Wallet") user.id.map { account.$user.id = $0 } try tester() .test(.POST, "/api/accounts", headers: [ "Content-Type": "application/json", "Authorization": user.bearerToken() ], body: account.encode()) { response in let content = try response.content.decode(Account.self) XCTAssertNotNil(content.id) XCTAssertEqual(content.name, account.name) XCTAssertEqual(content.$user.id, account.$user.id) Account.query(on: try database()).all().whenSuccess { dbAccounts in XCTAssertEqual(dbAccounts.count, 1) XCTAssertEqual(content, dbAccounts.first) } } } /// Tests the sucessful update of an `Account` at the `api/accounts` route func testUpdateAccount() throws { let account = Account(name: "Paul's Wallet") user.id.map { account.$user.id = $0 } try account.create(on: database()).wait() account.name = "Paul's Second Wallet" let accountId = try XCTUnwrap(account.id?.uuidString) try tester() .test(.PUT, "/api/accounts/\(accountId)", headers: [ "Content-Type": "application/json", "Authorization": user.bearerToken() ], body: account.encode()) { response in let content = try response.content.decode(Account.self) XCTAssertNotNil(content.id) XCTAssertEqual(content.name, account.name) XCTAssertEqual(content.$user.id, account.$user.id) Account.query(on: try database()).all().whenSuccess { dbAccounts in XCTAssertEqual(dbAccounts.count, 1) XCTAssertEqual(content, dbAccounts.first) } } } /// Tests the sucessful delete of an `Account` at the `api/accounts` route func testDeleteAccount() throws { let account = Account(name: "Paul's Wallet") user.id.map { account.$user.id = $0 } try account.create(on: database()).wait() let accountId = try XCTUnwrap(account.id?.uuidString) XCTAssertEqual(try Account.query(on: try database()).all().wait().count, 1) try tester() .test(.DELETE, "/api/accounts/\(accountId)", headers: ["Authorization": user.bearerToken()]) { response in XCTAssertEqual(response.status, .ok) XCTAssertEqual(try Account.query(on: try database()).all().wait().count, 0) } } func testAuthentication() throws { let account = Account(name: "Paul's Wallet") user.id.map { account.$user.id = $0 } try account.create(on: database()).wait() let accountId = try XCTUnwrap(account.id?.uuidString) XCTAssertEqual(try Account.query(on: try database()).all().wait().count, 1) try tester() .test(.GET, "/api/accounts/") { response in XCTAssertEqual(response.status, .unauthorized) XCTAssertEqual(try Account.query(on: try database()).all().wait().count, 1) } try tester() .test(.POST, "/api/accounts/", body: account.encode()) { response in XCTAssertEqual(response.status, .unauthorized) XCTAssertEqual(try Account.query(on: try database()).all().wait().count, 1) } try tester() .test(.PUT, "/api/accounts/\(accountId)", body: account.encode()) { response in XCTAssertEqual(response.status, .unauthorized) XCTAssertEqual(try Account.query(on: try database()).all().wait().first, account) } try tester() .test(.DELETE, "/api/accounts/\(accountId)") { response in XCTAssertEqual(response.status, .unauthorized) XCTAssertEqual(try Account.query(on: try database()).all().wait().count, 1) } } }
38.263158
97
0.532325
d9fcdf7baba411b5b39e328a1c1bec6a5011d837
366
// // StoryCounterCell.swift // SurRound // // Created by Kai-Ta Hsieh on 2020/2/10. // Copyright ยฉ 2020 Kai-Ta Hsieh. All rights reserved. // import UIKit class StoryCounterCell: UICollectionViewCell { @IBOutlet weak var timerBar: UIProgressView! override func awakeFromNib() { super.awakeFromNib() timerBar.progress = 0 } }
18.3
55
0.666667
db63ee95b94b0f71b863215d78baa176ee7ba5a9
484
// // ChatListScopeBuilder.swift // SwiftDI-Example // // Created by Andrey Chernoprudov on 01.01.2020. // Copyright ยฉ 2020 LittleStars. All rights reserved. // import SwiftDI struct ChatListScopeBuilder { let injector: Injector func build() -> Injector { let chatListScopeInjector = injector.plus() chatListScopeInjector.bind(ChatListViewModel.self) .with(ChatListViewModel.init(repository:)) return chatListScopeInjector } }
21.043478
58
0.694215
14ed48aa116d71a17e3f9fc4ac3d271fb1bfa2f7
233
import Foundation import WalletCore let kMargin: CGFloat = 20 var hdWallet: HDWallet? var safeAreaInsets: UIEdgeInsets { return UIApplication.shared.windows.first?.safeAreaInsets ?? .init(top: 0, left: 0, bottom: 0, right: 0) }
23.3
108
0.755365
2810d01152d8cdb04b3aa773e601e8c434977800
3,474
import UIKit import ReactiveSwift import ReactiveCocoa import ReactiveTimelane final class ViewController: UIViewController { // MARK: - Properties private let timedValueProducer: SignalProducer<(), Never> = { SignalProducer(value: ()) .delay(5, on: QueueScheduler.main) .lane("Timed value producer") }() fileprivate enum Errors: Error { case somethingWentWrong } private let timedErrorProducer: SignalProducer<(), Errors> = { SignalProducer(value: ()) .delay(5, on: QueueScheduler.main) .flatMap(.latest) { SignalProducer(error: .somethingWentWrong).lane("Inner error producer") } .lane("Timed error producer") }() private var (subscriptionLifetime, subscriptionToken) = Lifetime.make() // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() setUpView() setUpBindings() } private func setUpBindings() { reactive.lifetime += startValueProducerButton.reactive .mapControlEvents(.touchUpInside, { _ in () }) .observeValues { [weak self] in guard let strongSelf = self else { return } strongSelf.subscriptionLifetime += strongSelf.timedValueProducer.start() } reactive.lifetime += startErrorProducerButton.reactive .mapControlEvents(.touchUpInside, { _ in () }) .observeValues { [weak self] in guard let strongSelf = self else { return } strongSelf.subscriptionLifetime += strongSelf.timedErrorProducer.start() } reactive.lifetime += stopButton.reactive .mapControlEvents(.touchUpInside, { _ in () }) .observeValues { [weak self] in guard let strongSelf = self else { return } (strongSelf.subscriptionLifetime, strongSelf.subscriptionToken) = Lifetime.make() } } // MARK: - View private lazy var buttonStack: UIStackView = { let stack = UIStackView(arrangedSubviews: [ startValueProducerButton, startErrorProducerButton, stopButton ]) stack.axis = .vertical stack.spacing = 24 return stack }() private let startValueProducerButton: UIButton = { let button = UIButton(type: .system) button.setTitle("Start value producer", for: .normal) return button }() private let startErrorProducerButton: UIButton = { let button = UIButton(type: .system) button.setTitle("Start error producer", for: .normal) return button }() private let stopButton: UIButton = { let button = UIButton(type: .system) button.setTitle("Stop all", for: .normal) return button }() private func setUpView() { if #available(iOS 13.0, *) { view.backgroundColor = .systemBackground } else { view.backgroundColor = .white } view.addSubview(buttonStack) buttonStack.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ buttonStack.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor), buttonStack.centerYAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerYAnchor), ]) } }
33.085714
105
0.604203
f57fb906de5c584c2fd00ffb173160a21521b9f8
1,897
// // String+ArString.swift // Arumdaun // // Created by Park, Chanick on 9/12/17. // Copyright ยฉ 2017 Chanick Park. All rights reserved. // import UIKit extension String { var stringByRemovingWhitespaceAndNewlineCharacterSet: String { return components(separatedBy: NSCharacterSet.whitespacesAndNewlines).joined(separator: "") } /// trim first and last empty spaces var trim: String { return self.trimmingCharacters(in: .whitespacesAndNewlines) } // get filename only(exclue file extension) func fileName() -> String { if let fileNameWithoutExtension = NSURL(fileURLWithPath: self).deletingPathExtension?.lastPathComponent { return fileNameWithoutExtension } else { return "" } } // get file extension func fileExtension() -> String { if let fileExtension = NSURL(fileURLWithPath: self).pathExtension { return fileExtension } else { return "" } } var count: Int { return self.utf8.count } // MARK: - date /** * @desc format string: ex. "Thu, 04 Sep 2014 10:50:12 +0000" */ func toDate(format: String = "E, dd MMM yyyy HH:mm:ss Z") ->Date? { if self.isEmpty { return nil } let dateFormatter = DateFormatter() dateFormatter.dateFormat = format return dateFormatter.date(from: self) ?? nil } } extension String { // MARK: - URL func removeParametersFromURL()-> String { if var componenets = URLComponents(string: self) { componenets.query = nil return componenets.description } return self } func encodingQueryAllowed() -> String? { return self.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed) } }
25.635135
113
0.606747
625f38c4c20f9010f91a6c4477ab9bc8cf71bfa0
839
import Foundation #if os(iOS) || os(tvOS) import UIKit #elseif os(OSX) import AppKit #endif class SVGView: MacawView { @IBInspectable var fileName: String? { didSet { node = (try? SVGParser.parse(resource: fileName ?? "")) ?? Group() } } init(node: Node, frame: CGRect) { super.init(frame: frame) self.node = node } @objc override init?(node: Node, coder aDecoder: NSCoder) { super.init(node: node, coder: aDecoder) } required convenience init?(coder aDecoder: NSCoder) { self.init(node: Group(), coder: aDecoder) } override init(frame: CGRect) { super.init(frame: frame) } override func initializeView() { super.initializeView() self.contentLayout = ContentLayout.of(contentMode: contentMode) } }
20.975
78
0.606675
db562cd5d36b60dc1e32144a3bb9399b39a4cc45
568
// // Session.swift // MFLHalsa // // Created by Alex Miculescu on 07/07/2017. // Copyright ยฉ 2017 Future Workshops. All rights reserved. // import Foundation public protocol Session { var id : String { get } var title : String { get } var startDate : Date { get } var endDate : Date { get } var teamMemberId : String { get } var teamMemberFirstName : String { get } var teamMemberLastName : String { get } var teamMemberImageUrlString : String { get } var isCancelled : Bool { get } var messageGroupId : String { get } }
24.695652
59
0.649648
e6d3a1c36eabc398e426d8772309a6ad6fc5c8be
2,172
// // AppDelegate.swift // homeWorkGesture // // Created by brian์€์„ on 07/05/2019. // Copyright ยฉ 2019 brian. All rights reserved. // import UIKit @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. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.212766
285
0.755525
ff53c684491f5cdb641798333fe07911dfba7f12
2,326
// swiftlint:disable identifier_name cyclomatic_complexity public struct InsanityMerger: Merger { public init() { } public func canMerge(_ source: Tile, _ target: Tile) -> Bool { switch (source.value, target.value) { case (0, _) where source == .empty: return false case (_, 0) where target == .empty: return true case (.min, _): return false case (_, .min): return false case (-2, -2): return false case (-2, -1): return true case (-1, -2): return true case (-1, -1): return false case (1, 1): return false case (1, 2): return true case (2, 1): return true case (2, 2): return false case (.max, _): return false case (_, .max): return false case let (x, y): return x == y || x + y == 0 } } private let minusOne = Tile(value: -1, score: 0) private let minusTwo = Tile(value: -2, score: 0) private let minusThree = Tile(value: -3, score: 3) private let plusOne = Tile(value: 1, score: 0) private let plusTwo = Tile(value: 2, score: 0) private let plusThree = Tile(value: 3, score: 3) public func merge(_ source: Tile, _ target: Tile) -> Tile { assert(canMerge(source, target), "Cannot merge") switch (source, target) { case (_, .empty): return source case (minusTwo, minusOne): return minusThree case (minusOne, minusTwo): return minusThree case (plusOne, plusTwo): return plusThree case (plusTwo, plusOne): return plusThree case let (x, y) where x.value < 0: return Tile( value: x.value |+ y.value, score: x.score |+ y.score ) case let (x, y) where x.value > 0: return Tile( value: x.value |+ y.value, score: x.score |+ y.score |+ min(x.score, y.score) ) case let (x, y): return Tile( value: 0, score: max(x.score, y.score) ) } } }
28.365854
66
0.477214
ddb333d581c22755465da070d9e90c6f8a50aa61
1,226
// // AppDelegate.swift // MenuBarSampleApp // // Created by isaoeka on 2018/12/17. // Copyright ยฉ 2018 isaoeka. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { private let menuBarItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength) private let popover = NSPopover() func applicationDidFinishLaunching(_ aNotification: Notification) { if let button = self.menuBarItem.button { button.image = NSImage(named: NSImage.Name("MenuBarIcon")) button.action = #selector(togglePopover(_:)) } self.popover.contentViewController = ViewController.freshController() } } extension AppDelegate { @objc func togglePopover(_ sender: Any) { if self.popover.isShown { self.closePopover(sender) } else { self.showPopover(sender) } } func showPopover(_ sender: Any) { guard let button = self.menuBarItem.button else { return } self.popover.show(relativeTo: button.bounds, of: button, preferredEdge: .minY) } func closePopover(_ sender: Any) { self.popover.performClose(sender) } }
28.511628
98
0.662316
64e1a00b1ebfa5b3a12a68839f421a4464eff164
6,472
// // QuickActions.swift // QuickActions // // Created by Ricardo Pereira on 20/02/16. // Copyright ยฉ 2016 Ricardo Pereira. All rights reserved. // import UIKit public enum ShortcutIcon: Int { case compose case play case pause case add case location case search case share case prohibit case contact case home case markLocation case favorite case love case cloud case invitation case confirmation case mail case message case date case time case capturePhoto case captureVideo case task case taskCompleted case alarm case bookmark case shuffle case audio case update case custom @available(iOS 9.0, *) func toApplicationShortcutIcon() -> UIApplicationShortcutIcon? { if self == .custom { NSException(name: NSExceptionName(rawValue: "Invalid option"), reason: "`Custom` type need to be used with `toApplicationShortcutIcon:imageName`", userInfo: nil).raise() return nil } if #available(iOS 9.1, *) { let icon = UIApplicationShortcutIcon.IconType(rawValue: self.rawValue) ?? UIApplicationShortcutIcon.IconType.confirmation return UIApplicationShortcutIcon(type: icon) } else { let icon = UIApplicationShortcutIcon.IconType(rawValue: self.rawValue) ?? UIApplicationShortcutIcon.IconType.add return UIApplicationShortcutIcon(type: icon) } } @available(iOS 9.0, *) func toApplicationShortcutIcon(_ imageName: String) -> UIApplicationShortcutIcon? { if self == .custom { return UIApplicationShortcutIcon(templateImageName: imageName) } else { NSException(name: NSExceptionName(rawValue: "Invalid option"), reason: "Type need to be `Custom`", userInfo: nil).raise() return nil } } } public protocol ShortcutType: RawRepresentable {} public extension RawRepresentable where Self: ShortcutType { init?(type: String) { assert(type is RawValue) // FIXME: try another solution to restrain the RawRepresentable as String self.init(rawValue: type as! RawValue) } var value: String { return self.rawValue as? String ?? "" } } public struct Shortcut { public let type: String public let title: String public let subtitle: String? public let icon: ShortcutIcon? public init<T: ShortcutType>(type: T, title: String, subtitle: String?, icon: ShortcutIcon?) { self.type = type.value self.title = title self.subtitle = subtitle self.icon = icon } } public extension Shortcut { @available(iOS 9.0, *) init(shortcutItem: UIApplicationShortcutItem) { if let range = shortcutItem.type.rangeOfCharacter(from: CharacterSet(charactersIn: "."), options: .backwards) { type = String(shortcutItem.type[range.upperBound...]) } else { type = "unknown" } title = shortcutItem.localizedTitle subtitle = shortcutItem.localizedSubtitle // FIXME: shortcutItem.icon!.type isn't accessible icon = nil } @available(iOS 9.0, *) fileprivate func toApplicationShortcut(_ bundleIdentifier: String) -> UIApplicationShortcutItem { return UIMutableApplicationShortcutItem(type: bundleIdentifier + "." + type, localizedTitle: title, localizedSubtitle: subtitle, icon: icon?.toApplicationShortcutIcon(), userInfo: nil) } } @available(iOS 9.0, *) public extension UIApplicationShortcutItem { var toShortcut: Shortcut { return Shortcut(shortcutItem: self) } } public protocol QuickActionSupport { @available(iOS 9.0, *) func prepareForQuickAction<T: ShortcutType>(_ shortcutType: T) } open class QuickActions<T: ShortcutType> { fileprivate let bundleIdentifier: String public init(_ application: UIApplication, actionHandler: QuickActionSupport?, bundleIdentifier: String, shortcuts: [Shortcut], launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) { self.bundleIdentifier = bundleIdentifier if #available(iOS 9.0, *) { install(shortcuts, toApplication: application) } if #available(iOS 9.0, *), let shortcutItem = launchOptions?[.shortcutItem] as? UIApplicationShortcutItem { handle(actionHandler, shortcutItem: shortcutItem) } } /// Install initial Quick Actions (app shortcuts) @available(iOS 9.0, *) fileprivate func install(_ shortcuts: [Shortcut], toApplication application: UIApplication) { application.shortcutItems = shortcuts.map { $0.toApplicationShortcut(bundleIdentifier) } } @available(iOS 9.0, *) @discardableResult open func handle(_ actionHandler: QuickActionSupport?, shortcutItem: UIApplicationShortcutItem) -> Bool { return handle(actionHandler, shortcut: shortcutItem.toShortcut) } open func handle(_ actionHandler: QuickActionSupport?, shortcut: Shortcut) -> Bool { guard let viewController = actionHandler else { return false } if #available(iOS 9.0, *) { // FIXME: Can't use `shortcutType`: Segmentation fault: 11 //let shortcutType = T.init(type: shortcut.type) viewController.prepareForQuickAction(T.init(type: shortcut.type)!) return true } else { return false } } open func add(_ shortcuts: [Shortcut], toApplication application: UIApplication) { if #available(iOS 9.0, *) { var items = shortcuts.map { $0.toApplicationShortcut(bundleIdentifier) } items.append(contentsOf: application.shortcutItems ?? []) application.shortcutItems = items } } open func add(_ shortcut: Shortcut, toApplication application: UIApplication) { add([shortcut], toApplication: application) } open func remove(_ shortcut: Shortcut, toApplication application: UIApplication) { if #available(iOS 9.0, *) { if let index = application.shortcutItems?.firstIndex(of: shortcut.toApplicationShortcut(bundleIdentifier)) , index > -1 { application.shortcutItems?.remove(at: index) } } } open func clear(_ application: UIApplication) { if #available(iOS 9.0, *) { application.shortcutItems = nil } } }
30.819048
193
0.656211
291714bd6fb67596e8364b176284ff41fd670fe4
599
import SwiftUI import Relay @propertyWrapper public struct Fragment<F: Relay.Fragment>: DynamicProperty { @SwiftUI.Environment(\.fragmentResource) var fragmentResource @StateObject var loader = FragmentLoader<F>() let key: F.Key? public init() { self.key = nil } public init(_ key: F.Key) { self.key = key } public var wrappedValue: F.Data? { guard let key = key else { return nil } // load the data if needed loader.load(from: fragmentResource!, key: key) return loader.data } }
19.966667
65
0.597663
e046aefaed57a31f2e328d468eb471c33c8e6ce9
2,068
// // ForecastedLotteryCell.swift // LotteryForecaster // // Created by Soohan Lee on 2020/05/02. // Copyright ยฉ 2020 Soohan Lee. All rights reserved. // import UIKit class ForecastedLotteryCell: UITableViewCell { // MARK: - Properties enum UI { case width var cgFloat: CGFloat { switch self { case .width: return 30 } } } private let forecastedBallsStackView = UIStackView().then { $0.axis = .horizontal $0.distribution = .fillEqually $0.spacing = 30 $0.addArrangedSubviews([UILabel(), UILabel(), UILabel(), UILabel(), UILabel(), UILabel()]) guard let labels = $0.arrangedSubviews as? [UILabel] else { return } let width = UI.width.cgFloat labels.forEach { $0.do { label in label.textAlignment = .center label.textColor = .white label.clipsToBounds = true label.layer.cornerRadius = width / 2 label.snp.makeConstraints { $0.width.equalTo(width) $0.height.equalTo(label.snp.width) } } } } // MARK: - Life Cycle override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setUpAttribute() addAllSubviews() setUpAutoLayout() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Setup UI private func setUpAttribute() { } private func addAllSubviews() { contentView.addSubview(forecastedBallsStackView) } private func setUpAutoLayout() { forecastedBallsStackView.snp.makeConstraints { $0.center.equalToSuperview() } } // MARK: - Element Control func configure(numbers: [Int]) { for index in numbers.indices { guard let ball = forecastedBallsStackView.arrangedSubviews[index] as? UILabel else { return } let number = numbers[index] ball.text = "\(number)" ball.backgroundColor = Ball.number(number).color } } }
22.725275
99
0.626209
2296b37e29981684e6d1a7c0fca1afeb3ea04f9b
373
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=A | FileCheck %s -check-prefix=A // Make sure we can code complete at EOF. // Don't add any tests at the end of the file! // // A: Begin completions // A-DAG: Pattern/ExprSpecific: ['(']{#Int#})[#Void#]{{; name=.+$}} // A: End completions func f(_ x: Int) {} f(#^A^#
33.909091
123
0.621984
d7bc370c40aab1b9c43dfec0a53150d501abe498
374
// // CCColorExtension.swift // CCLocalLibrary-Swift // // Created by ๅ†ฏๆ˜Žๅบ† on 19/06/2017. // Copyright ยฉ 2017 ๅ†ฏๆ˜Žๅบ†. All rights reserved. // import UIKit extension UIColor { var imageColor : UIImage? { get { return UIImage.ccImage(self); } } func ccImageColor() -> UIImage? { return self.imageColor; } }
15.583333
46
0.566845
db972dec075bca97ad5a6af3ae38010589fb7291
12,793
//===----------------------------------------------------------------------===// // // This source file is part of the MQTTNIO project // // Copyright (c) 2020-2021 Adam Fowler // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// #if canImport(Network) import Foundation import Network #if canImport(NIOSSL) import NIOSSL #endif /// TLS Version enumeration public enum TSTLSVersion { case tlsV10 case tlsV11 case tlsV12 case tlsV13 /// return `SSLProtocol` for iOS12 api var sslProtocol: SSLProtocol { switch self { case .tlsV10: return .tlsProtocol1 case .tlsV11: return .tlsProtocol11 case .tlsV12: return .tlsProtocol12 case .tlsV13: return .tlsProtocol13 } } /// return `tls_protocol_version_t` for iOS13 and later apis @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) var tlsProtocolVersion: tls_protocol_version_t { switch self { case .tlsV10: return .TLSv10 case .tlsV11: return .TLSv11 case .tlsV12: return .TLSv12 case .tlsV13: return .TLSv13 } } } @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) extension tls_protocol_version_t { var tsTLSVersion: TSTLSVersion { switch self { case .TLSv10: return .tlsV10 case .TLSv11: return .tlsV11 case .TLSv12: return .tlsV12 case .TLSv13: return .tlsV13 default: preconditionFailure("Invalid TLS version") } } } /// Certificate verification modes. public enum TSCertificateVerification { /// All certificate verification disabled. case none /// Certificates will be validated against the trust store and checked /// against the hostname of the service we are contacting. case fullVerification } /// TLS configuration for NIO Transport Services public struct TSTLSConfiguration { /// Error loading TLS files public enum Error: Swift.Error { case invalidData } /// Struct defining an array of certificates public struct Certificates { let certificates: [SecCertificate] /// Create certificate array from already loaded SecCertificate array public static func certificates(_ secCertificates: [SecCertificate]) -> Self { .init(certificates: secCertificates) } #if canImport(NIOSSL) /// Create certificate array from PEM file public static func pem(_ filename: String) throws -> Self { let certificates = try NIOSSLCertificate.fromPEMFile(filename) let secCertificates = try certificates.map { certificate -> SecCertificate in guard let certificate = SecCertificateCreateWithData(nil, Data(try certificate.toDERBytes()) as CFData) else { throw TSTLSConfiguration.Error.invalidData } return certificate } return .init(certificates: secCertificates) } #endif /// Create certificate array from DER file public static func der(_ filename: String) throws -> Self { let certificateData = try Data(contentsOf: URL(fileURLWithPath: filename)) guard let secCertificate = SecCertificateCreateWithData(nil, certificateData as CFData) else { throw TSTLSConfiguration.Error.invalidData } return .init(certificates: [secCertificate]) } } /// Struct defining identity public struct Identity { let identity: SecIdentity /// Create Identity from already loaded SecIdentity public static func secIdentity(_ secIdentity: SecIdentity) -> Self { .init(identity: secIdentity) } /// Create Identity from p12 file public static func p12(filename: String, password: String) throws -> Self { let data = try Data(contentsOf: URL(fileURLWithPath: filename)) let options: [String: String] = [kSecImportExportPassphrase as String: password] var rawItems: CFArray? guard SecPKCS12Import(data as CFData, options as CFDictionary, &rawItems) == errSecSuccess else { throw TSTLSConfiguration.Error.invalidData } let items = rawItems! as! [[String: Any]] guard let firstItem = items.first, let secIdentity = firstItem[kSecImportItemIdentity as String] as! SecIdentity? else { throw TSTLSConfiguration.Error.invalidData } return .init(identity: secIdentity) } } /// The minimum TLS version to allow in negotiation. Defaults to tlsv1. public var minimumTLSVersion: TSTLSVersion /// The maximum TLS version to allow in negotiation. If nil, there is no upper limit. Defaults to nil. public var maximumTLSVersion: TSTLSVersion? /// The trust roots to use to validate certificates. This only needs to be provided if you intend to validate /// certificates. public var trustRoots: [SecCertificate]? /// The identity associated with the leaf certificate. public var clientIdentity: SecIdentity? /// The application protocols to use in the connection. public var applicationProtocols: [String] /// Whether to verify remote certificates. public var certificateVerification: TSCertificateVerification /// Initialize TSTLSConfiguration /// - Parameters: /// - minimumTLSVersion: minimum version of TLS supported /// - maximumTLSVersion: maximum version of TLS supported /// - trustRoots: The trust roots to use to validate certificates /// - clientIdentity: Client identity /// - applicationProtocols: The application protocols to use in the connection /// - certificateVerification: Should certificates be verified public init( minimumTLSVersion: TSTLSVersion = .tlsV10, maximumTLSVersion: TSTLSVersion? = nil, trustRoots: [SecCertificate]? = nil, clientIdentity: SecIdentity? = nil, applicationProtocols: [String] = [], certificateVerification: TSCertificateVerification = .fullVerification ) { self.minimumTLSVersion = minimumTLSVersion self.maximumTLSVersion = maximumTLSVersion self.trustRoots = trustRoots self.clientIdentity = clientIdentity self.applicationProtocols = applicationProtocols self.certificateVerification = certificateVerification } /// Initialize TSTLSConfiguration /// - Parameters: /// - minimumTLSVersion: minimum version of TLS supported /// - maximumTLSVersion: maximum version of TLS supported /// - trustRoots: The trust roots to use to validate certificates /// - clientIdentity: Client identity /// - applicationProtocols: The application protocols to use in the connection /// - certificateVerification: Should certificates be verified public init( minimumTLSVersion: TSTLSVersion = .tlsV10, maximumTLSVersion: TSTLSVersion? = nil, trustRoots: Certificates, clientIdentity: Identity, applicationProtocols: [String] = [], certificateVerification: TSCertificateVerification = .fullVerification ) { self.minimumTLSVersion = minimumTLSVersion self.maximumTLSVersion = maximumTLSVersion self.trustRoots = trustRoots.certificates self.clientIdentity = clientIdentity.identity self.applicationProtocols = applicationProtocols self.certificateVerification = certificateVerification } } extension TSTLSConfiguration { func getNWProtocolTLSOptions() throws -> NWProtocolTLS.Options { let options = NWProtocolTLS.Options() // minimum TLS protocol if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { sec_protocol_options_set_min_tls_protocol_version(options.securityProtocolOptions, self.minimumTLSVersion.tlsProtocolVersion) } else { sec_protocol_options_set_tls_min_version(options.securityProtocolOptions, self.minimumTLSVersion.sslProtocol) } // maximum TLS protocol if let maximumTLSVersion = self.maximumTLSVersion { if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { sec_protocol_options_set_max_tls_protocol_version(options.securityProtocolOptions, maximumTLSVersion.tlsProtocolVersion) } else { sec_protocol_options_set_tls_max_version(options.securityProtocolOptions, maximumTLSVersion.sslProtocol) } } if let clientIdentity = self.clientIdentity, let secClientIdentity = sec_identity_create(clientIdentity) { sec_protocol_options_set_local_identity(options.securityProtocolOptions, secClientIdentity) } self.applicationProtocols.forEach { sec_protocol_options_add_tls_application_protocol(options.securityProtocolOptions, $0) } if self.certificateVerification != .fullVerification || self.trustRoots != nil { // add verify block to control certificate verification sec_protocol_options_set_verify_block( options.securityProtocolOptions, { _, sec_trust, sec_protocol_verify_complete in guard self.certificateVerification != .none else { sec_protocol_verify_complete(true) return } let trust = sec_trust_copy_ref(sec_trust).takeRetainedValue() if let trustRootCertificates = trustRoots { SecTrustSetAnchorCertificates(trust, trustRootCertificates as CFArray) } if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { SecTrustEvaluateAsyncWithError(trust, Self.tlsDispatchQueue) { _, result, error in if let error = error { print("Trust failed: \(error.localizedDescription)") } sec_protocol_verify_complete(result) } } else { SecTrustEvaluateAsync(trust, Self.tlsDispatchQueue) { _, result in switch result { case .proceed, .unspecified: sec_protocol_verify_complete(true) default: sec_protocol_verify_complete(false) } } } }, Self.tlsDispatchQueue ) } return options } /// Dispatch queue used by Network framework TLS to control certificate verification static var tlsDispatchQueue = DispatchQueue(label: "TSTLSConfiguration") } /// Deprecated TSTLSConfiguration @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) @available(*, deprecated, message: "Use the init using TSTLSVersion") extension TSTLSConfiguration { /// Initialize TSTLSConfiguration public init( minimumTLSVersion: tls_protocol_version_t, maximumTLSVersion: tls_protocol_version_t? = nil, trustRoots: Certificates, clientIdentity: Identity, applicationProtocols: [String] = [], certificateVerification: TSCertificateVerification = .fullVerification ) { self.minimumTLSVersion = minimumTLSVersion.tsTLSVersion self.maximumTLSVersion = maximumTLSVersion?.tsTLSVersion self.trustRoots = trustRoots.certificates self.clientIdentity = clientIdentity.identity self.applicationProtocols = applicationProtocols self.certificateVerification = certificateVerification } /// Initialize TSTLSConfiguration public init( minimumTLSVersion: tls_protocol_version_t, maximumTLSVersion: tls_protocol_version_t? = nil, trustRoots: [SecCertificate]? = nil, clientIdentity: SecIdentity? = nil, applicationProtocols: [String] = [], certificateVerification: TSCertificateVerification = .fullVerification ) { self.minimumTLSVersion = minimumTLSVersion.tsTLSVersion self.maximumTLSVersion = maximumTLSVersion?.tsTLSVersion self.trustRoots = trustRoots self.clientIdentity = clientIdentity self.applicationProtocols = applicationProtocols self.certificateVerification = certificateVerification } } #endif
39.853583
171
0.645353
e95e9aef3596f23c8f745e02668e046082e87512
1,443
// // IntExtension.swift // GamerSky // // Created by QY on 2018/5/3. // Copyright ยฉ 2018ๅนด QY. All rights reserved. // import Foundation extension Int { public var timeFormat: String { let timeDate = Date(timeIntervalSince1970: TimeInterval(self / 1000)) var timeInterval = timeDate.timeIntervalSinceNow timeInterval = -timeInterval let section = Int(timeInterval) let minute = section / 60 let hour = minute / 60 let day = hour / 24 var result = "" if timeInterval < 60 { result = "ๅˆšๅˆš" } else if minute < 60 { result = "\(minute)ๅˆ†้’Ÿๅ‰" } else if hour < 24 { result = "\(hour)ๅฐๆ—ถๅ‰" } else if day <= 7 { result = "\(day)ๅคฉๅ‰" } else { result = timeDate.string(withFormat: "MM-dd HH:mm") } return result } /// ๆ•ฐ้‡่ถ…่ฟ‡1ไธ‡ไปฅๅŽๆ˜พ็คบ็š„ๅ†…ๅฎน public var countString: String { self / 10000 >= 1 ? "\(self / 10000)ไธ‡" : "\(self)" } /// ่ง†้ข‘ๆ—ถ้•ฟ public var timeDuration: String { let minute = self / 60 let hour = minute / 60 let second = String(format: "%02d", self % 60) if minute < 60 { // ่ง†้ข‘ๆ—ถ้•ฟๅฐไบŽไธ€ๅฐๆ—ถ return "\(String(format: "%02d", minute)):\(second)" } else { // ่ง†้ข‘ๆ—ถ้•ฟ่ถ…่ฟ‡ไธ€ๅฐๆ—ถ return "\(String(format: "%02d", hour)):\(String(format: "%02d", minute)):\(second)" } } }
24.05
96
0.523909
030ce2965760c39b4e130f4bfa129a35ac244db9
2,013
// // Session+Platform.swift // WWDCast // // Created by Maksym Shcheglov on 05/06/2018. // Copyright ยฉ 2018 Maksym Shcheglov. All rights reserved. // import Foundation extension Session { struct Platform: OptionSet { let rawValue: Int static let iOS = Platform(rawValue: 1 << 0) static let macOS = Platform(rawValue: 1 << 1) static let tvOS = Platform(rawValue: 1 << 2) static let watchOS = Platform(rawValue: 1 << 3) static let all: Platform = [.iOS, .macOS, .tvOS, .watchOS] } } extension Session.Platform: Hashable { var hashValue: Int { return self.rawValue.hashValue } } extension Session.Platform: LosslessStringConvertible { init?(_ description: String) { let mapping: [String: Session.Platform] = [ "iOS": .iOS, "macOS": .macOS, "tvOS": .tvOS, "watchOS": .watchOS] guard let value = mapping[description] else { assertionFailure("Failed to find a value for track with description '\(description)'!") return nil } self = value } var description: String { let mapping: [Session.Platform: String] = [.iOS: "iOS", .macOS: "macOS", .tvOS: "tvOS", .watchOS: "watchOS"] return self.map ({ value in return NSLocalizedString(mapping[value] ?? "", comment: "Platform description") }).joined(separator: ", ") } } extension Session.Platform: Sequence { func makeIterator() -> AnyIterator<Session.Platform> { var remainingBits = rawValue var bitMask: RawValue = 1 return AnyIterator { while remainingBits != 0 { defer { bitMask = bitMask &* 2 } if remainingBits & bitMask != 0 { remainingBits = remainingBits & ~bitMask return Session.Platform(rawValue: bitMask) } } return nil } } }
28.757143
99
0.563835
d69b02fa9fb809d739653e7e536e32a493537cfe
3,352
/* * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. * See LICENSE in the project root for license information. */ import UIKit class PersistentStore { init() { if let archivedItems = NSKeyedUnarchiver.unarchiveObjectWithFile(fileRecordsArchiveURL.path!) as? [FileRecord] { fileRecords += archivedItems } else { fileRecords = [FileRecord]() } } // MARK: Sync Token let defaults = NSUserDefaults.standardUserDefaults() var syncToken: String? { get { return defaults.objectForKey("syncToken") as! String? } set(newSyncToken) { if let _ = newSyncToken { defaults.setObject(newSyncToken, forKey: "syncToken") } else { defaults.removeObjectForKey("syncToken") } } } // MARK: File records var fileRecords = [FileRecord]() let fileRecordsArchiveURL: NSURL = { let documentsDirectories = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) let documentDirectory = documentsDirectories.first! return documentDirectory.URLByAppendingPathComponent("fileRecords.archive") }() func processDeltaArrayForFoldeWithId(folderId:String, items: [DeltaItem]?) { for item:FileRecord in fileRecords { item.isNew = false; } if let nonNilItems = items { for item:DeltaItem in nonNilItems { if item.parentId == folderId { if item.isDelete { tryDeleteFile(item.fileId) } else { tryCreateOrUpdateFile(item.fileId, fileName: item.fileName!, isFolder: item.isFolder, lastModified: item.lastModified) } } } } } func tryDeleteFile(fileId: String) { for var index = fileRecords.count - 1; index >= 0 ; index-- { if fileRecords[index].fileId == fileId { fileRecords.removeAtIndex(index) } } } func tryCreateOrUpdateFile(fileId: String, fileName: String, isFolder: Bool, lastModified: String) { // flag to indicate update var updated = false for fileRecord: FileRecord in fileRecords { if fileRecord.fileId == fileId { updated = true fileRecord.fileName = fileName fileRecord.isNew = true fileRecord.dateModified = lastModified } } if updated == false { let newRecord = FileRecord(fileId: fileId, fileName: fileName, dateModified: lastModified, isNew: true, isFolder: isFolder) fileRecords.append(newRecord) } } func createRecord(record: FileRecord) { fileRecords.append(record) } // MARK: Reset func resetStorage() { self.syncToken = nil fileRecords.removeAll() } func saveFileRecordChanges() -> Bool { return NSKeyedArchiver.archiveRootObject(fileRecords, toFile: fileRecordsArchiveURL.path!) } }
28.896552
142
0.563544
d6396177554b3490b6e2bb304b43f0b4a56aeff8
837
// // RestClient+SseAuthenticator.swift // Split // // Created by Javier L. Avrudsky on 13/07/2020. // Copyright ยฉ 2020 Split. All rights reserved. // import Foundation struct SseAuthenticationResponse: Decodable { let pushEnabled: Bool let token: String? } protocol RestClientSseAuthenticator: RestClient { func authenticate(userKey: String, completion: @escaping (DataResult<SseAuthenticationResponse>) -> Void) } extension DefaultRestClient: RestClientSseAuthenticator { var kUserKeyParameter: String { "users" } func authenticate(userKey: String, completion: @escaping (DataResult<SseAuthenticationResponse>) -> Void) { self.execute( endpoint: endpointFactory.sseAuthenticationEndpoint, parameters: [kUserKeyParameter: userKey], completion: completion) } }
28.862069
111
0.72282
61aee913b867b28443204958ddf5a280707fa2fc
224
// // Deck.swift // Citation Share Extension // // Created by Doug Diego on 1/31/19. // Copyright ยฉ 2019 Doug Diego. All rights reserved. // import UIKit final class Deck { var id: String? var title: String? }
14.933333
53
0.647321
186bacd3f2069711fa74922c016c9c09aeaabf65
2,527
import Foundation public struct Route: ExpressibleByStringLiteral { private var components: [Component] public static let asteriks: Route = "*" public init(stringLiteral rawRoute: String) { components = Route.components(from: rawRoute) } internal func matches(_ path: Path, parameters: inout [String: String], partially: Bool = false) -> Bool { guard path.count == components.count || (partially && (path.count > components.count)) else { return false } for idx in 0 ..< components.count { let component = components[idx] let pathComponent = path[idx] if !component.matches(pathComponent, parameters: &parameters) { return false } } return true } /// Returns removed components internal func removeLeading(from path: inout Path) -> [String] { var removedComponents: [String] = [] for component in components { guard !path.isEmpty else { break } var parameters: [String: String] = [:] if component.matches(path[0], parameters: &parameters) { let removedComponent = path.removeFirstComponent() removedComponents.append(removedComponent) } else { break } } return removedComponents } } private extension Route { enum Component { case constant(String) case willcard case parameter(name: String) func matches(_ pathComponent: String, parameters: inout [String: String]) -> Bool { switch self { case .constant(let constant): return constant == pathComponent case .willcard: return true case .parameter(let name): parameters[name] = pathComponent return true } } } static func components(from _rawRoute: String) -> [Component] { let rawRoute: Substring if _rawRoute.hasPrefix(Path.componentSeparator) { rawRoute = _rawRoute.dropFirst() } else { rawRoute = _rawRoute[_rawRoute.startIndex ..< _rawRoute.endIndex] } return rawRoute .exps_components(separatedBy: Path.componentSeparatorChar) .compactMap { (rawComponent: String) -> Component? in if rawComponent == "*" { return .willcard } else if rawComponent.hasPrefix(":") { let parameterName = rawComponent.dropFirst() return .parameter(name: String(parameterName)) } else if rawComponent == "" { return nil } else { return .constant(rawComponent) } } } }
26.322917
108
0.629205
cc6a6b6b5092c03d8ef270000080d96b978e9b2d
2,255
/*: ## App Exercise - Finding Movements >These exercises reinforce Swift concepts in the context of a fitness tracking app. You decide you want your app's users to be able to put in a heart rate range they would like to hit, and then you want the app to suggest movements where historically the user has reached that heart rate range. The dictionary `movementHeartRates` below contains keys corresponding to the movements that the app has tracked, and values corresponding to the average heart rate of the user that your fitness tracker has monitored historically during the given movement. Loop through `movementHeartRates` below and if the heart rate doesn't fall between `lowHR` and `highHR`, continue to the next movement and heart rate. Otherwise, print "You could go <INSERT MOVEMENT HERE>". */ let lowHR = 110 let highHR = 125 var movementHeartRates: [String: Int] = ["Walking": 85, "Running": 120, "Swimming": 130, "Cycling": 128, "Skiing": 114, "Climbing": 129] for (movement, heartRate) in movementHeartRates { if heartRate < lowHR || heartRate > highHR { continue } print("You could go \(movement).") } /*: _Copyright ยฉ 2018 Apple Inc._ _Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:_ _The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software._ _THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE._ */ //: [Previous](@previous) | page 6 of 6
68.333333
467
0.768514
b9a24dfe68c4402bb8afc0db53e34cd84c763308
810
// // GRPullRequestCell.swift // GitReview // // Created by Whitney Foster on 7/16/17. // Copyright ยฉ 2017 Whitney Foster. All rights reserved. // import UIKit class GRPullRequestCell: UITableViewCell { static let identifier = "prCell" @IBOutlet weak var userImageView: UIImageView! @IBOutlet weak var prTitleLabel: UILabel! @IBOutlet weak var prSubtitleLabel: UILabel! func setUp(pullRequest: GRPullRequest) { userImageView.setImageWithCache(urlString: pullRequest.user.profileImageURL, completion: nil) prTitleLabel.text = pullRequest.title let date = pullRequest.dateOpened == nil ? "" : " opened on \(pullRequest.dateOpened!.toString())" prSubtitleLabel.text = "#\(pullRequest.number)" + date + " by \(pullRequest.user.userName)" } }
32.4
106
0.698765
615a9024d30f047c04f81f948bf8782e7b2a9aae
4,773
// // CurrencyFormatterTests.swift // CurrencyTextDemoTests // // Created by Felipe Lefรจvre Marino on 2/11/19. // Copyright ยฉ 2019 Felipe Lefรจvre Marino. All rights reserved. // import XCTest @testable import CurrencyText class CurrencyFormatterTests: XCTestCase { var formatter: CurrencyFormatter! override func setUp() { super.setUp() formatter = CurrencyFormatter() formatter.locale = CurrencyLocale.englishIreland formatter.currency = .euro } override func tearDown() { formatter = nil super.tearDown() } func testComposing() { formatter = CurrencyFormatter { $0.locale = CurrencyLocale.italianItaly $0.currency = .euro $0.hasDecimals = false } XCTAssertEqual(formatter.decimalDigits, 0) XCTAssertEqual(formatter.hasDecimals, false) XCTAssertEqual(formatter.locale.locale, CurrencyLocale.italianItaly.locale) XCTAssertEqual(formatter.currencySymbol, "โ‚ฌ") formatter.decimalSeparator = ";" XCTAssertEqual(formatter.numberFormatter.currencyDecimalSeparator, ";") formatter.currencyCode = "^" XCTAssertEqual(formatter.numberFormatter.currencyCode, "^") formatter.alwaysShowsDecimalSeparator = true XCTAssertEqual(formatter.numberFormatter.alwaysShowsDecimalSeparator, true) formatter.groupingSize = 4 XCTAssertEqual(formatter.numberFormatter.groupingSize, 4) formatter.secondaryGroupingSize = 1 XCTAssertEqual(formatter.numberFormatter.secondaryGroupingSize, 1) formatter.groupingSeparator = "-" XCTAssertEqual(formatter.numberFormatter.currencyGroupingSeparator, "-") formatter.hasGroupingSeparator = false XCTAssertEqual(formatter.numberFormatter.usesGroupingSeparator, false) formatter.currencySymbol = "%" formatter.showCurrencySymbol = false XCTAssertEqual(formatter.showCurrencySymbol, false) XCTAssertEqual(formatter.numberFormatter.currencySymbol, "") formatter.showCurrencySymbol = true formatter.currencySymbol = "%" XCTAssertEqual(formatter.showCurrencySymbol, true) XCTAssertEqual(formatter.numberFormatter.currencySymbol, "%") } func testMinAndMaxValues() { formatter.minValue = nil formatter.maxValue = nil var formattedString = formatter.string(from: 300000.54) XCTAssertEqual(formattedString, "โ‚ฌ300,000.54") formatter.minValue = 10 formatter.maxValue = 100.31 formattedString = formatter.updated(formattedString: "โ‚ฌ300,000.54") XCTAssertEqual(formattedString, "โ‚ฌ100.31") formattedString = formatter.updated(formattedString: "โ‚ฌ2.03") XCTAssertEqual(formattedString, "โ‚ฌ10.00") formattedString = formatter.string(from: 88888888) XCTAssertEqual(formattedString, "โ‚ฌ100.31") formattedString = formatter.string(from: 1) XCTAssertEqual(formattedString, "โ‚ฌ10.00") formatter.minValue = -351 formattedString = formatter.string(from: -24) XCTAssertEqual(formattedString, "-โ‚ฌ24.00") formattedString = formatter.string(from: -400) XCTAssertEqual(formattedString, "-โ‚ฌ351.00") } func testFormatting() { formatter.locale = CurrencyLocale.portugueseBrazil formatter.currency = .euro formatter.hasDecimals = true let formattedString = formatter.string(from: 300000.54) XCTAssertEqual(formattedString, "โ‚ฌย 300.000,54") let unformattedString = formatter.unformatted(string: formattedString!) XCTAssertEqual(unformattedString, "30000054") let doubleValue = formatter.double(from: "30000054") XCTAssertEqual(doubleValue, 30000054.00) } func testDoubleFromStringForDifferentFormatters() { formatter.locale = CurrencyLocale.portugueseBrazil formatter.currency = .euro formatter.hasDecimals = true var doubleValue = formatter.double(from: "00.02") XCTAssertEqual(doubleValue, 0.02) formatter.locale = CurrencyLocale.dutchBelgium formatter.currency = .dollar formatter.hasDecimals = false doubleValue = formatter.double(from: "00.02") XCTAssertEqual(doubleValue, 0.02) formatter.locale = CurrencyLocale.zarma formatter.hasDecimals = false doubleValue = formatter.double(from: "100.12") XCTAssertEqual(doubleValue, 100.12) } }
34.338129
83
0.651163
9ccb4710e69aba40ce4f014ca3295e552ad7f1b7
673
// // HttpLink.swift // ProgrammaticallyExample // // Created by admin on 17.04.2020. // Copyright ยฉ 2020 ahmet. All rights reserved. // import Foundation /// This enum providing all service connection links. /// - Usage Example: HttpLink.photos.value /// - Returns: a string type of link public enum HttpLink: String { /// mainURL is most important case of this enum because it stored main link. case mainURL = "https://gorest.co.in/public-api/" // Photos Url case photos = "photos" /// this variable returning full link when it is get called var UrlValue: String { return HttpLink.mainURL.rawValue + self.rawValue } }
24.925926
80
0.676077
e0a8b90d55f07b6cf51d4b7abf810b6e33fe37ec
3,305
//===--- Match.swift ------------------------------------------------------===// //Copyright (c) 2016 Daniel Leping (dileping) // //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // //http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. //===----------------------------------------------------------------------===// import Foundation public protocol MatchType { var source:String {get} var range:StringRange {get} var ranges:[StringRange?] {get} func range(atIndex:Int) -> StringRange? func range(byName:String) -> StringRange? var matched:String {get} var subgroups:[String?] {get} func group(atIndex:Int) -> String? func group(byName:String) -> String? } public class Match : MatchType { public let source:String let match:CompiledPatternMatch let groupNames:[String] let nameMap:Dictionary<String, Int> init(source:String, match:CompiledPatternMatch, groupNames:[String]) { self.source = source self.match = match self.groupNames = groupNames self.nameMap = groupNames.indexHash } func groupIndex(group:String) -> Int { return nameMap[group]! + 1 } public var range:StringRange { get { //here it never throws, because otherwise it will not match return try! match.range.toStringRange(source) } } public var ranges:[StringRange?] { get { var result = Array<StringRange?>() for i in 0..<match.numberOfRanges { //subrange can be empty let stringRange = try? match.range(at: i).toStringRange(source) result.append(stringRange) } return result } } public func range(atIndex:Int) -> StringRange? { return try? match.range(at: atIndex).toStringRange(source) } public func range(byName:String) -> StringRange? { //subrange can be empty return try? match.range(at: groupIndex(byName)).toStringRange(source) } public var matched:String { get { //zero group is always there, otherwise there is no match return group(0)! } } public var subgroups:[String?] { get { let subRanges = ranges.suffix(from: 1) return subRanges.map { range in range.map { range in source.substring(with: range) } } } } public func group(atIndex:Int) -> String? { let range = self.range(atIndex) return range.map { range in source.substring(with: range) } } public func group(byName:String) -> String? { return self.group(groupIndex(byName)) } }
29.247788
80
0.56944
727352361297e632ead07c783838c7595cbd609b
1,898
// // ResultBuilder.swift // TweaKit // // Created by cokile // import Foundation public protocol TweakBuildable { var constrainKey: String { get } var hasBuilt: Bool { get } } @resultBuilder public struct TweakContainerBuilder<Element: TweakBuildable> { public typealias Expression = Element public typealias Component = [Element] public static func buildExpression(_ expression: Expression) -> Component { _build(component: [expression]) } public static func buildBlock(_ components: Component...) -> Component { _build(component: components.flatMap { $0 }) } public static func buildArray(_ components: [Component]) -> Component { _build(component: components.flatMap { $0 }) } private static func _build(component: Component) -> Component { component .uniqued { $0.constrainKey == $1.constrainKey } .filter { !$0.hasBuilt } .sorted { $0.constrainKey < $1.constrainKey } } } // A Duplication of TweakContainerBuilder for AnyTweak since AnyTweak can not conform to TweakBuildable @resultBuilder public struct AnyTweakBuilder { public typealias Expression = AnyTweak public typealias Component = [AnyTweak] public static func buildExpression(_ expression: Expression) -> Component { _build(component: [expression]) } public static func buildBlock(_ components: Component...) -> Component { _build(component: components.flatMap { $0 }) } public static func buildArray(_ components: [Component]) -> Component { _build(component: components.flatMap { $0 }) } private static func _build(component: Component) -> Component { component .uniqued { $0.name == $1.name } .filter { $0.section == nil } .sorted { $0.name < $1.name } } }
29.2
103
0.643309
ccc02c1cc9e07673923256b404b79316b8bb9531
179
// // CustomImageViewPicker.swift // Triptic // // Created by Valentin COUSIEN on 01/03/2018. // Copyright ยฉ 2018 Valentin COUSIEN. All rights reserved. // import Foundation
17.9
59
0.715084
9c0a1035e559fe8a4a0f38fb414769bebd2d7757
501
// // VGSFormAnanlyticsDetails.swift // VGSCollectSDK // // Created by Dima on 26.11.2020. // Copyright ยฉ 2020 VGS. All rights reserved. // import Foundation ///:nodoc: VGSCollect Form Analytics Details public struct VGSFormAnanlyticsDetails { public let formId: String public let tenantId: String public let environment: String public init(formId: String, tenantId: String, environment: String) { self.formId = formId self.tenantId = tenantId self.environment = environment } }
21.782609
69
0.738523
38071e2ccd6d7f99f8ed6c0524c45ad507ee6c86
35,182
// // OEXRouter+Swift.swift // edX // // Created by Akiva Leffert on 5/7/15. // Copyright (c) 2015 edX. All rights reserved. // import Foundation import WebKit // The router is an indirection point for navigation throw our app. // New router logic should live here so it can be written in Swift. // We should gradually migrate the existing router class here and then // get rid of the objc version public enum CourseHTMLBlockSubkind { case Base case Problem case OpenAssesment case DragAndDrop case WordCloud case LTIConsumer } enum CourseBlockDisplayType { case Unknown case Outline case Unit case Video case HTML(CourseHTMLBlockSubkind) case Discussion(DiscussionModel) var isUnknown : Bool { switch self { case .Unknown: return true default: return false } } } extension CourseBlock { var displayType : CourseBlockDisplayType { switch self.type { case .Unknown(_), .HTML: return multiDevice ? .HTML(.Base) : .Unknown case .Problem: return multiDevice ? .HTML(.Problem) : .Unknown case .OpenAssesment: return multiDevice ? .HTML(.OpenAssesment) : .Unknown case .DragAndDrop: return multiDevice ? .HTML(.DragAndDrop) : .Unknown case .WordCloud: return multiDevice ? .HTML(.WordCloud) : .Unknown case .LTIConsumer: return multiDevice ? .HTML(.LTIConsumer) : .Unknown case .Course: return .Outline case .Chapter: return .Outline case .Section: return .Outline case .Unit: return .Unit case let .Video(summary): return (summary.isSupportedVideo) ? .Video : .Unknown case let .Discussion(discussionModel): return .Discussion(discussionModel) } } } extension OEXRouter { func showCoursewareForCourseWithID(courseID : String, fromController controller : UIViewController) { showContainerForBlockWithID(blockID: nil, type: CourseBlockDisplayType.Outline, parentID: nil, courseID : courseID, fromController: controller) } func unitControllerForCourseID(courseID : String, blockID : CourseBlockID?, initialChildID : CourseBlockID?, forMode mode: CourseOutlineMode? = .full) -> CourseContentPageViewController { let contentPageController = CourseContentPageViewController(environment: environment, courseID: courseID, rootID: blockID, initialChildID: initialChildID, forMode: mode ?? .full) return contentPageController } func navigateToComponentScreen(from controller: UIViewController, courseID: CourseBlockID, componentID: CourseBlockID) { let courseQuerier = environment.dataManager.courseDataManager.querierForCourseWithID(courseID: courseID, environment: environment) guard let childBlock = courseQuerier.blockWithID(id: componentID).firstSuccess().value, let unitBlock = courseQuerier.parentOfBlockWith(id: childBlock.blockID, type: .Unit).firstSuccess().value, let sectionBlock = courseQuerier.parentOfBlockWith(id: childBlock.blockID, type: .Section).firstSuccess().value, let chapterBlock = courseQuerier.parentOfBlockWith(id: childBlock.blockID, type: .Chapter).firstSuccess().value else { Logger.logError("ANALYTICS", "Unable to load block: \(componentID)") return } var outlineViewController: UIViewController if controller is CourseOutlineViewController { outlineViewController = controller } else { guard let dashboardController = controller.navigationController?.viewControllers.first(where: { $0 is CourseDashboardViewController}) as? CourseDashboardViewController else { return } dashboardController.switchTab(with: .courseDashboard) guard let outlineController = dashboardController.currentVisibleController as? CourseOutlineViewController else { return } outlineViewController = outlineController } showContainerForBlockWithID(blockID: sectionBlock.blockID, type: sectionBlock.displayType, parentID: chapterBlock.blockID, courseID: courseID, fromController: outlineViewController) { [weak self] visibleController in self?.showContainerForBlockWithID(blockID: childBlock.blockID, type: childBlock.displayType, parentID: unitBlock.blockID, courseID: courseID, fromController: visibleController, completion: nil) } } func showCourseUnknownBlock(blockID: CourseBlockID?, courseID: CourseBlockID, fromController controller: UIViewController) { let unsupportedController = CourseUnknownBlockViewController(blockID: blockID, courseID : courseID, environment : environment) controller.navigationController?.pushViewController(unsupportedController, animated: true) } func showContainerForBlockWithID(blockID: CourseBlockID?, type: CourseBlockDisplayType, parentID: CourseBlockID?, courseID: CourseBlockID, fromController controller: UIViewController, forMode mode: CourseOutlineMode? = .full, completion: ((UIViewController) -> Void)? = nil) { switch type { case .Outline: fallthrough case .Unit: let outlineController = controllerForBlockWithID(blockID: blockID, type: type, courseID: courseID, forMode: mode) controller.navigationController?.pushViewController(outlineController, animated: true, completion: completion) case .HTML: fallthrough case .Video: fallthrough case .Unknown: let pageController = unitControllerForCourseID(courseID: courseID, blockID: parentID, initialChildID: blockID, forMode: mode) if let delegate = controller as? CourseContentPageViewControllerDelegate { pageController.navigationDelegate = delegate } controller.navigationController?.pushViewController(pageController, animated: true, completion: completion) case .Discussion: let pageController = unitControllerForCourseID(courseID: courseID, blockID: parentID, initialChildID: blockID) if let delegate = controller as? CourseContentPageViewControllerDelegate { pageController.navigationDelegate = delegate } controller.navigationController?.pushViewController(pageController, animated: true, completion: completion) } } func showCelebratoryModal(fromController controller: UIViewController, courseID: String) -> CelebratoryModalViewController { let celebratoryModalView = CelebratoryModalViewController(courseID: courseID, environment: environment) celebratoryModalView.modalPresentationStyle = .overCurrentContext celebratoryModalView.modalTransitionStyle = .crossDissolve controller.present(celebratoryModalView, animated: false, completion: nil) return celebratoryModalView } private func controllerForBlockWithID(blockID: CourseBlockID?, type: CourseBlockDisplayType, courseID: String, forMode mode: CourseOutlineMode? = .full, gated: Bool? = false, shouldCelebrationAppear: Bool = false) -> UIViewController { if gated ?? false { return CourseUnknownBlockViewController(blockID: blockID, courseID : courseID, environment : environment) } switch type { case .Outline: let outlineController = CourseOutlineViewController(environment: self.environment, courseID: courseID, rootID: blockID, forMode: mode) return outlineController case .Unit: return unitControllerForCourseID(courseID: courseID, blockID: blockID, initialChildID: nil, forMode: mode) case .HTML(let subkind): let controller = HTMLBlockViewController(blockID: blockID, courseID: courseID, environment: environment, subkind: subkind) return controller case .Video: let controller = VideoBlockViewController(environment: environment, blockID: blockID, courseID: courseID, shouldCelebrationAppear: shouldCelebrationAppear) return controller case .Unknown: let controller = CourseUnknownBlockViewController(blockID: blockID, courseID : courseID, environment : environment) return controller case let .Discussion(discussionModel): let controller = DiscussionBlockViewController(blockID: blockID, courseID: courseID, topicID: discussionModel.topicID, environment: environment) return controller } } func controllerForBlock(block : CourseBlock, courseID : String, shouldCelebrationAppear: Bool = false) -> UIViewController { return controllerForBlockWithID(blockID: block.blockID, type: block.displayType, courseID: courseID, gated: block.isGated, shouldCelebrationAppear: shouldCelebrationAppear) } @objc(showMyCoursesAnimated:pushingCourseWithID:) func showMyCourses(animated: Bool = true, pushingCourseWithID courseID: String? = nil) { let controller = EnrolledTabBarViewController(environment: environment) showContentStack(withRootController: controller, animated: animated) if let courseID = courseID { showCourseWithID(courseID: courseID, fromController: controller, animated: false) } } @objc func showEnrolledTabBarView() { let controller = EnrolledTabBarViewController(environment: environment) showContentStack(withRootController: controller, animated: false) } func showCourseDates(controller:UIViewController, courseID: String) { let courseDates = CourseDatesViewController(environment: environment, courseID: courseID) controller.navigationController?.pushViewController(courseDates, animated: true) } func showCourseVideos(controller:UIViewController, courseID: String) { showContainerForBlockWithID(blockID: nil, type: CourseBlockDisplayType.Outline, parentID: nil, courseID : courseID, fromController: controller, forMode: .video) } func showDatesTabController(controller: UIViewController) { if let dashboardController = controller as? CourseDashboardViewController { dashboardController.switchTab(with: .courseDates) } else if let dashboardController = controller.navigationController?.viewControllers.first(where: { $0 is CourseDashboardViewController}) as? CourseDashboardViewController { controller.navigationController?.popToViewController(dashboardController, animated: false) dashboardController.switchTab(with: .courseDates) } } // MARK: Deep Linking //Method can be use to navigate on particular tab of course dashboard with deep link type func showCourse(with deeplink: DeepLink, courseID: String, from controller: UIViewController) { var courseDashboardController = controller.navigationController?.viewControllers.compactMap { controller -> UIViewController? in if controller is CourseDashboardViewController { return controller } return nil }.first func switchTab() { if let dashboardController = courseDashboardController as? CourseDashboardViewController { dashboardController.switchTab(with: deeplink.type, componentID: deeplink.componentID) } } if let dashboardController = courseDashboardController as? CourseDashboardViewController, dashboardController.courseID == deeplink.courseId { controller.navigationController?.setToolbarHidden(true, animated: false) controller.navigationController?.popToViewController(dashboardController, animated: true) switchTab() } else { if let controllers = controller.navigationController?.viewControllers, let enrolledTabBarController = controllers.first as? EnrolledTabBarViewController { popToRoot(controller: enrolledTabBarController) { [weak self] in guard let weakSelf = self else { return } enrolledTabBarController.switchTab(with: deeplink.type) let dashboardController = CourseDashboardViewController(environment: weakSelf.environment, courseID: courseID) courseDashboardController = dashboardController enrolledTabBarController.navigationController?.pushViewController(dashboardController, animated: true) { _ in switchTab() } } } } } func showProgram(with type: DeepLinkType, url: URL? = nil, from controller: UIViewController) { var controller = controller if let controllers = controller.navigationController?.viewControllers, let enrolledTabBarView = controllers.first as? EnrolledTabBarViewController { popToRoot(controller: controller) let programView = enrolledTabBarView.switchTab(with: type) controller = programView } else { let enrolledTabBarControler = EnrolledTabBarViewController(environment: environment) controller = enrolledTabBarControler showContentStack(withRootController: enrolledTabBarControler, animated: false) } if let url = url, type == .programDetail { showProgramDetails(with: url, from: controller) } } func showAnnouncment(from controller : UIViewController, courseID : String) { let announcementViewController = CourseAnnouncementsViewController(environment: environment, courseID: courseID) controller.navigationController?.pushViewController(announcementViewController, animated: true) } private func popToRoot(controller: UIViewController, completion: (() -> Void)? = nil) { controller.navigationController?.setToolbarHidden(true, animated: false) controller.navigationController?.popToRootViewController(animated: true, completion: completion) } func showDiscoveryController(from controller: UIViewController, type: DeepLinkType, isUserLoggedIn: Bool, pathID: String?) { let bottomBar = BottomBarView(environment: environment) var discoveryController = discoveryViewController(bottomBar: bottomBar, searchQuery: nil) if isUserLoggedIn { // Pop out all views and switches enrolledCourses tab on the bases of link type if let controllers = controller.navigationController?.viewControllers, let enrolledTabBarView = controllers.first as? EnrolledTabBarViewController { popToRoot(controller: controller) discoveryController = enrolledTabBarView.switchTab(with: type) } else { //Create new stack of views and switch tab let enrolledTabController = EnrolledTabBarViewController(environment: environment) showContentStack(withRootController: enrolledTabController, animated: false) discoveryController = enrolledTabController.switchTab(with: type) } } else { if let controllers = controller.navigationController?.viewControllers, let discoveryView = controllers.first as? DiscoveryViewController { popToRoot(controller: controller) discoveryController = discoveryView } else if let discoveryController = discoveryController { showControllerFromStartupScreen(controller: discoveryController) } } // Switch segment tab on discovery view if let discoveryController = discoveryController as? DiscoveryViewController { discoveryController.switchSegment(with: type) } // If the pathID is given the detail view will open if let pathID = pathID, let discoveryController = discoveryController { showDiscoveryDetail(from: discoveryController, type: type, pathID: pathID, bottomBar: bottomBar) } } func showDiscoveryDetail(from controller: UIViewController, type: DeepLinkType, pathID: String, bottomBar: UIView?) { if type == .courseDetail { showCourseDetails(from: controller, with: pathID, bottomBar: bottomBar) } else if type == .programDiscoveryDetail { showProgramDetail(from: controller, with: pathID, bottomBar: bottomBar) } else if type == .degreeDiscoveryDetail { showProgramDetail(from: controller, with: pathID, bottomBar: bottomBar, type: .degree) } } func showDiscussionResponsesFromViewController(controller: UIViewController, courseID : String, thread : DiscussionThread, isDiscussionBlackedOut: Bool) { let storyboard = UIStoryboard(name: "DiscussionResponses", bundle: nil) let responsesViewController = storyboard.instantiateInitialViewController() as! DiscussionResponsesViewController responsesViewController.environment = environment responsesViewController.courseID = courseID responsesViewController.thread = thread responsesViewController.isDiscussionBlackedOut = isDiscussionBlackedOut controller.navigationController?.pushViewController(responsesViewController, animated: true) } func showDiscussionResponses(from controller: UIViewController, courseID: String, threadID: String, isDiscussionBlackedOut: Bool, completion: (()->Void)?) { let storyboard = UIStoryboard(name: "DiscussionResponses", bundle: nil) let responsesViewController = storyboard.instantiateInitialViewController() as! DiscussionResponsesViewController responsesViewController.environment = environment responsesViewController.courseID = courseID responsesViewController.threadID = threadID responsesViewController.isDiscussionBlackedOut = isDiscussionBlackedOut controller.navigationController?.delegate = self if let completion = completion { controller.navigationController?.pushViewController(viewController: responsesViewController, completion: completion) } else { controller.navigationController?.pushViewController(responsesViewController, animated: true) } } func showDiscussionComments(from controller: UIViewController, courseID: String, commentID: String, threadID: String) { let discussionCommentController = DiscussionCommentsViewController(environment: environment, courseID: courseID, commentID: commentID, threadID: threadID) if let delegate = controller as? DiscussionCommentsViewControllerDelegate { discussionCommentController.delegate = delegate } controller.navigationController?.pushViewController(discussionCommentController, animated: true) } func showDiscussionCommentsFromViewController(controller: UIViewController, courseID : String, response : DiscussionComment, closed : Bool, thread: DiscussionThread, isDiscussionBlackedOut: Bool) { let commentsVC = DiscussionCommentsViewController(environment: environment, courseID : courseID, responseItem: response, closed: closed, thread: thread, isDiscussionBlackedOut: isDiscussionBlackedOut) if let delegate = controller as? DiscussionCommentsViewControllerDelegate { commentsVC.delegate = delegate } controller.navigationController?.pushViewController(commentsVC, animated: true) } func showDiscussionNewCommentFromController(controller: UIViewController, courseID : String, thread:DiscussionThread, context: DiscussionNewCommentViewController.Context) { let newCommentViewController = DiscussionNewCommentViewController(environment: environment, courseID : courseID, thread:thread, context: context) if let delegate = controller as? DiscussionNewCommentViewControllerDelegate { newCommentViewController.delegate = delegate } controller.present(ForwardingNavigationController(rootViewController: newCommentViewController), animated: true, completion: nil) } func showPostsFromController(controller : UIViewController, courseID : String, topic: DiscussionTopic) { let postsController = PostsViewController(environment: environment, courseID: courseID, topic: topic) controller.navigationController?.pushViewController(postsController, animated: true) } func showDiscussionPosts(from controller: UIViewController, courseID: String, topicID: String) { let postsController = PostsViewController(environment: environment, courseID: courseID, topicID: topicID) controller.navigationController?.pushViewController(postsController, animated: true) } func showAllPostsFromController(controller : UIViewController, courseID : String, followedOnly following : Bool) { let postsController = PostsViewController(environment: environment, courseID: courseID, following : following) controller.navigationController?.pushViewController(postsController, animated: true) } func showPostsFromController(controller : UIViewController, courseID : String, queryString : String) { let postsController = PostsViewController(environment: environment, courseID: courseID, queryString : queryString) controller.navigationController?.pushViewController(postsController, animated: true) } func showDiscussionTopicsFromController(controller: UIViewController, courseID : String) { let topicsController = DiscussionTopicsViewController(environment: environment, courseID: courseID) controller.navigationController?.pushViewController(topicsController, animated: true) } func showDiscussionNewPostFromController(controller: UIViewController, courseID : String, selectedTopic : DiscussionTopic?) { let newPostController = DiscussionNewPostViewController(environment: environment, courseID: courseID, selectedTopic: selectedTopic) if let delegate = controller as? DiscussionNewPostViewControllerDelegate { newPostController.delegate = delegate } controller.present(ForwardingNavigationController(rootViewController: newPostController), animated: true, completion: nil) } func showHandoutsFromController(controller : UIViewController, courseID : String) { let handoutsViewController = CourseHandoutsViewController(environment: environment, courseID: courseID) controller.navigationController?.pushViewController(handoutsViewController, animated: true) } func showProfile(controller: UIViewController? = nil, completion: ((_ success: Bool) -> ())? = nil) { let profileViewController = ProfileOptionsViewController(environment: environment) let navigationController = ForwardingNavigationController(rootViewController: profileViewController) navigationController.navigationBar.prefersLargeTitles = true controller?.navigationController?.present(navigationController, animated: true) { completion?(true) } } func showValuePropDetailView(from controller: UIViewController? = nil, type: ValuePropModalType, course: OEXCourse, completion: (() -> Void)? = nil) { let upgradeDetailController = ValuePropDetailViewController(type: type, course: course, environment: environment) controller?.present(ForwardingNavigationController(rootViewController: upgradeDetailController), animated: true, completion: completion) } func showBrowserViewController(from controller: UIViewController, title: String?, url: URL, alwaysRequireAuth: Bool = false, completion: (() -> Void)? = nil) { let browserViewController = BrowserViewController(title: title, url: url, environment: environment, alwaysRequireAuth: alwaysRequireAuth) if let controller = controller as? BrowserViewControllerDelegate { browserViewController.delegate = controller } let navController = ForwardingNavigationController(rootViewController: browserViewController) navController.modalPresentationStyle = .fullScreen controller.present(navController, animated: true, completion: completion) } func showBannerViewController(from controller: UIViewController, url: URL, title: String?, delegate: BannerViewControllerDelegate? = nil, alwaysRequireAuth: Bool = false, modal: Bool = true, showNavbar: Bool = false) { let bannerController = BannerViewController(url: url, title: title, environment: environment, alwaysRequireAuth: alwaysRequireAuth, showNavbar: showNavbar) bannerController.delegate = delegate if modal { let navController = ForwardingNavigationController(rootViewController: bannerController) navController.modalPresentationStyle = .fullScreen controller.present(navController, animated: true, completion: nil) } else { controller.navigationController?.pushViewController(bannerController, animated: true) } } func showProfileForUsername(controller: UIViewController? = nil, username : String, editable: Bool = true, modal: Bool = false) { OEXAnalytics.shared().trackProfileViewed(username: username) let editable = self.environment.session.currentUser?.username == username let profileController = UserProfileViewController(environment: environment, username: username, editable: editable) if modal { controller?.present(ForwardingNavigationController(rootViewController: profileController), animated: true, completion: nil) } else { if let controller = controller { controller.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil) controller.navigationController?.pushViewController(profileController, animated: true) } else { showContentStack(withRootController: profileController, animated: true) } } } func showProfileEditorFromController(controller : UIViewController) { guard let profile = environment.dataManager.userProfileManager.feedForCurrentUser().output.value else { return } let editController = UserProfileEditViewController(profile: profile, environment: environment) controller.navigationController?.pushViewController(editController, animated: true) } func showDownloadVideoQuality(from controller: UIViewController, delegate: VideoDownloadQualityDelegate?, modal: Bool = false) { let videoQualityController = VideoDownloadQualityViewController.init(environment: environment, delegate: delegate) if modal { controller.present(ForwardingNavigationController(rootViewController: videoQualityController), animated: true, completion: nil) } else { controller.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil) controller.navigationController?.pushViewController(videoQualityController, animated: true) } } func showCertificate(url: NSURL, title: String?, fromController controller: UIViewController) { let c = CertificateViewController(environment: environment) c.title = title controller.navigationController?.pushViewController(c, animated: true) c.loadRequest(request: URLRequest(url: url as URL) as NSURLRequest) } func showCourseWithID(courseID : String, fromController: UIViewController, animated: Bool = true) { let controller = CourseDashboardViewController(environment: environment, courseID: courseID) fromController.navigationController?.pushViewController(controller, animated: animated) } func showCourseCatalog(fromController: UIViewController? = nil, bottomBar: UIView? = nil, searchQuery: String? = nil) { guard let controller = discoveryViewController(bottomBar: bottomBar, searchQuery: searchQuery) else { return } if let fromController = fromController { fromController.tabBarController?.selectedIndex = EnrolledTabBarViewController.courseCatalogIndex if let discovery = fromController.tabBarController?.children.first(where: { $0.isKind(of: DiscoveryViewController.self)} ) as? DiscoveryViewController { discovery.switchSegment(with: .courseDiscovery) } } else { showControllerFromStartupScreen(controller: controller) } self.environment.analytics.trackUserFindsCourses() } func showAllSubjects(from controller: UIViewController? = nil, delegate: SubjectsViewControllerDelegate?) { let subjectsVC = SubjectsViewController(environment:environment) subjectsVC.delegate = delegate controller?.navigationController?.pushViewController(subjectsVC, animated: true) } func discoveryViewController(bottomBar: UIView? = nil, searchQuery: String? = nil) -> UIViewController? { let isCourseDiscoveryEnabled = environment.config.discovery.course.isEnabled let isProgramDiscoveryEnabled = environment.config.discovery.program.isEnabled let isDegreeDiscveryEnabled = environment.config.discovery.degree.isEnabled if (isCourseDiscoveryEnabled && (isProgramDiscoveryEnabled || isDegreeDiscveryEnabled)) { return DiscoveryViewController(with: environment, bottomBar: bottomBar, searchQuery: searchQuery) } else if isCourseDiscoveryEnabled { return environment.config.discovery.course.type == .webview ? OEXFindCoursesViewController(environment: environment, showBottomBar: true, bottomBar: bottomBar, searchQuery: searchQuery) : CourseCatalogViewController(environment: environment) } return nil } func showProgramDetail(from controller: UIViewController, with pathId: String, bottomBar: UIView?, type: ProgramDiscoveryScreen? = .program) { let programDetailViewController = ProgramsDiscoveryViewController(with: environment, pathId: pathId, bottomBar: bottomBar?.copy() as? UIView, type: type) pushViewController(controller: programDetailViewController, fromController: controller) } private func showControllerFromStartupScreen(controller: UIViewController) { let backButton = UIBarButtonItem(barButtonSystemItem: .cancel, target: nil, action: nil) backButton.oex_setAction({ controller.dismiss(animated: true, completion: nil) }) controller.navigationItem.leftBarButtonItem = backButton let navController = ForwardingNavigationController(rootViewController: controller) present(navController, from:nil, completion: nil) } func showCourseCatalogDetail(courseID: String, fromController: UIViewController) { let detailController = CourseCatalogDetailViewController(environment: environment, courseID: courseID) fromController.navigationController?.pushViewController(detailController, animated: true) } func showAppReviewIfNeeded(fromController: UIViewController) { if RatingViewController.canShowAppReview(environment: environment){ let reviewController = RatingViewController(environment: environment) reviewController.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext reviewController.providesPresentationContextTransitionStyle = true reviewController.definesPresentationContext = true if let controller = fromController as? RatingViewControllerDelegate { reviewController.delegate = controller } fromController.present(reviewController, animated: false, completion: nil) } } func showWhatsNew(fromController controller : UIViewController) { let whatsNewController = WhatsNewViewController(environment: environment) let navController = ForwardingNavigationController(rootViewController: whatsNewController) navController.setNavigationBarHidden(true, animated: false) controller.present(navController, animated: true, completion: nil) } // MARK: - LOGIN / LOGOUT @objc func showSplash() { removeCurrentContentController() let splashController: UIViewController if !environment.config.isRegistrationEnabled { splashController = loginViewController() } else if environment.config.newLogistrationFlowEnabled { splashController = StartupViewController(environment: environment) } else { splashController = OEXLoginSplashViewController(environment: environment) } makeContentControllerCurrent(splashController) } func pushViewController(controller: UIViewController, fromController: UIViewController) { fromController.navigationController?.pushViewController(controller, animated: true) } @objc public func logout() { invalidateToken() environment.session.closeAndClear() environment.session.removeAllWebData() showLoggedOutScreen() } func invalidateToken() { if let refreshToken = environment.session.token?.refreshToken, let clientID = environment.config.oauthClientID() { let networkRequest = LogoutApi.invalidateToken(refreshToken: refreshToken, clientID: clientID) environment.networkManager.taskForRequest(networkRequest) { result in } } } // MARK: - Debug func showDebugPane() { let debugMenu = DebugMenuViewController(environment: environment) showContentStack(withRootController: debugMenu, animated: true) } public func showProgramDetails(with url: URL, from controller: UIViewController) { let programDetailsController = ProgramsViewController(environment: environment, programsURL: url, viewType: .detail) controller.navigationController?.pushViewController(programDetailsController, animated: true) } @objc public func showCourseDetails(from controller: UIViewController, with coursePathID: String, bottomBar: UIView?) { let courseInfoViewController = OEXCourseInfoViewController(environment: environment, pathID: coursePathID, bottomBar: bottomBar?.copy() as? UIView) controller.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil) controller.navigationController?.pushViewController(courseInfoViewController, animated: true) } } extension OEXRouter: UINavigationControllerDelegate { public func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) { viewController.navigationController?.completionHandler() } }
55.933227
280
0.721591
2136206065c0a3731212281ce5e88135c688e773
2,884
// Copyright (c) 2017-2019 Coinbase Inc. See LICENSE import RxSwift extension HTTP { /// Creates an observable for HTTP Post operation and parses result using the specified Decodable /// /// - Parameters: /// - service: The service for the API call. Used as baseURL /// - path: The relative path for the API call. Appended to the baseURL. /// - credentials: HTTP basic auth credentials /// - parameters: A JSON object, to be sent as the HTTP body data. /// - headers: A [String: String] dictionary mapping HTTP header field names to values. Defaults to nil. /// - timeout: How many seconds before the request times out. Defaults to 15.0 /// - respType: Decodable model used to parse json to given model /// /// - Returns: An instance of Single<T>. public static func post<T>( service: HTTPService, path: String, credentials: Credentials? = nil, parameters: [String: Any]? = nil, headers: [String: String]? = nil, timeout: TimeInterval = HTTP.kDefaultTimeout, for responseType: T.Type ) -> Single<HTTPResponse<T>> where T: Decodable { let request = HTTPRequest<T>( service: service, method: .post, credentials: credentials, path: path, parameters: parameters, headers: headers, timeout: timeout, for: responseType ) return HTTP.makeDecodableRequest(request: request) } /// Creates an observable for HTTP Post operation and parses result using the specified closure /// /// - Parameters: /// - service: The service for the API call. Used as baseURL /// - path: The relative path for the API call. Appended to the baseURL. /// - credentials: HTTP basic auth credentials /// - parameters: A JSON object, to be sent as the HTTP body data. /// - headers: A [String: String] dictionary mapping HTTP header field names to values. Defaults to nil. /// - timeout: How many seconds before the request times out. Defaults to 15.0 /// - parser: Closure called to parse Data to given model /// /// - Returns: An instance of Single<T>. public static func post( service: HTTPService, path: String, credentials: Credentials? = nil, parameters: [String: Any]? = nil, headers: [String: String]? = nil, timeout: TimeInterval = HTTP.kDefaultTimeout ) -> Single<Data> { let request = HTTPRequest<Data>( service: service, method: .post, credentials: credentials, path: path, parameters: parameters, headers: headers, timeout: timeout ) return HTTP.makeDataRequest(request: request) } }
39.506849
114
0.601248
46b9dc44ad804a961bb2b10d3700a440677b69a8
1,833
import Foundation enum MRZFieldType { case documentType, countryCode, names, documentNumber, nationality, birthdate, sex, expiryDate, personalNumber, optionalData, hash } struct MRZField { let value: Any? let rawValue: String let checkDigit: String? let isValid: Bool? init(value: Any?, rawValue: String, checkDigit: String?) { self.value = value self.rawValue = rawValue self.checkDigit = checkDigit self.isValid = (checkDigit == nil) ? nil : MRZField.isValueValid(rawValue, checkDigit: checkDigit!) } // MRZ ์œ ํšจ ์ฒดํฌ์„ฌ static func isValueValid(_ value: String, checkDigit: String) -> Bool { guard let numericCheckDigit = Int(checkDigit) else { if checkDigit == "<" { return value.trimmingFillers().isEmpty } print("mrz ์œ ํšจ ์ฒดํฌ์„ฌ") return false } // 7, 3, 1 ๊ฐ€์ค‘์น˜ ๊ณ„์‚ฐ let uppercaseLetters = CharacterSet.uppercaseLetters let digits = CharacterSet.decimalDigits let weights = [7, 3, 1] var total = 0 for (index, character) in value.enumerated() { let unicodeScalar = character.unicodeScalars.first! let charValue: Int if uppercaseLetters.contains(unicodeScalar) { charValue = Int(10 + unicodeScalar.value) - 65 } else if digits.contains(unicodeScalar) { charValue = Int(String(character))! } else if character == "<" { charValue = 0 } else { print("์—๋Ÿฌ") return false } total += (charValue * weights[index % 3]) } return (total % 10 == numericCheckDigit) } }
30.55
134
0.548282
56042a7e59e3ea3a86ad7c740444706f7e1ab342
958
// // BallNode.swift // Simple Games // // Created by Ricardo Sรกnchez Sotres on 22/10/15. // Copyright ยฉ 2015 Ricardo Sรกnchez Sotres. All rights reserved. // import UIKit import SpriteKit class BallNode:SKShapeNode { let BALL_RADIUS:CGFloat = 10.0 var direction:CGVector = CGVector(dx: 1.0, dy: 1.0) override init() { super.init() speed = 10.0 self.path = CGPathCreateWithEllipseInRect(CGRect(x: -BALL_RADIUS, y: -BALL_RADIUS, width: BALL_RADIUS*2, height: BALL_RADIUS*2), nil) physicsBody = SKPhysicsBody(circleOfRadius:BALL_RADIUS) fillColor = SKColor.whiteColor() strokeColor = SKColor.blackColor() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func update() { position = CGPoint(x: position.x + speed * direction.dx, y: position.y + speed * direction.dy) } }
23.95
141
0.633612
116bb977951b63a6d514d59fba6fe3063f23e903
3,489
// // FullfillmentDescription.swift // Pods // // Created by Martin Eberl on 09.07.17. // // import Foundation public protocol FullfillmentDescription { @discardableResult func this<T>(_ type: T.Type) -> FullfillmentDescription } public protocol DependencyDelegate: class { func didResolve<T>(dependency: Dependency, canProvide type: T.Type) } public protocol Dependency: FullfillmentDescription { var isResolved: Bool { get } var parameters: [FullfillmentParameter]? { get } var module: Module { get } weak var delegate: DependencyDelegate? { get set } @discardableResult func tryToResolve() -> Bool func didProvide<T>(type: T.Type) func conforms<T>(to type: T.Type) -> Bool func requires<T>(_ type: T.Type) -> Bool } extension Dependency { public var isResolved: Bool { return parameters?.isEmpty ?? true } public func conforms<T>(to type: T.Type) -> Bool { return module is T } } public protocol FullfillmentParameter: class { var moduleForFullfillment: Module? { get } func requires<T>(_ type: T.Type) -> Bool } final public class DefaultFullfillmentParameter<H>: FullfillmentParameter { public var moduleForFullfillment: Module? { return Injector.shared.module(for: H.self) } public func requires<T>(_ type: T.Type) -> Bool { return H.self == T.self } } final public class DefaultDependency<H>: Dependency { private(set) public var parameters: [FullfillmentParameter]? private(set) public var module: Module public weak var delegate: DependencyDelegate? init(_ module: Module) { self.module = module } public func didProvide<T>(type: T.Type) { tryToResolve() } @discardableResult public func this<T>(_ type: T.Type) -> FullfillmentDescription { if parameters == nil { parameters = [FullfillmentParameter]() } let parameter = DefaultFullfillmentParameter<T>() if shouldAdd(parameter) { parameters?.append(parameter) } return self } @discardableResult public func tryToResolve() -> Bool { guard let parameters = parameters else { return true } var fullfilledParameters = [FullfillmentParameter]() for parameter in parameters { if let moduleForFullfillment = parameter.moduleForFullfillment { module.injectAndNotify(moduleForFullfillment) fullfilledParameters.append(parameter) } } for parameter in fullfilledParameters { remove(parameter) } if isResolved { delegate?.didResolve(dependency: self, canProvide: H.self) return true } return false } public func requires<T>(_ type: T.Type) -> Bool { return parameters?.first(where: { $0.requires(T.self) }) != nil } private func remove(_ parameter: FullfillmentParameter) { guard let index = parameters?.index(where: { return $0 === parameter } ) else { return } parameters?.remove(at: index) } private func shouldAdd(_ parameter: FullfillmentParameter) -> Bool { guard let moduleForFullfillment = parameter.moduleForFullfillment else { return true } module.inject(inject: moduleForFullfillment) return false } }
28.365854
87
0.627114
d54e627fbf69847e6a949a86ec3426c51e3e4e67
949
// // PufferyTests.swift // PufferyTests // // Created by Valentin Knabel on 13.04.20. // Copyright ยฉ 2020 Valentin Knabel. All rights reserved. // @testable import Puffery import XCTest class PufferyTests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() throws { // This is an example of a performance test case. measure { // Put the code you want to measure the time of here. } } }
28.757576
111
0.669125
aba5f6625b1301fa433d088d85beacba673b36c3
1,877
// // UIAlertController.swift // TVNExtensions // // Created by Tien Nhat Vu on 6/12/18. // import Foundation extension UIAlertController { public var attributedTitle: NSAttributedString? { get { return self.value(forKey: "attributedTitle") as? NSAttributedString } set { self.setValue(newValue, forKey: "attributedTitle") } } public var attributedMessage: NSAttributedString? { get { return self.value(forKey: "attributedMessage") as? NSAttributedString } set { self.setValue(newValue, forKey: "attributedMessage") } } public convenience init(title: String?, message: String?, preferredStyle: UIAlertController.Style, cancelTitle: String, cancelStyle: UIAlertAction.Style = .cancel, cancelHandler: ((UIAlertAction)->())? = nil) { self.init(title: title, message: message, preferredStyle: preferredStyle) self.addCancelAction(title: cancelTitle, cancelStyle: cancelStyle, cancelHandler: cancelHandler) } public func addCancelAction(title: String, cancelStyle: UIAlertAction.Style = .cancel, cancelHandler: ((UIAlertAction)->())? = nil) { self.addAction(UIAlertAction(title: title, style: .cancel, handler: cancelHandler)) } public func show() { if let topVC = UIViewController.getTopViewController() { topVC.present(self, animated: true, completion: nil) } else { let window = UIWindow(frame: UIScreen.main.bounds) window.windowLevel = UIWindow.Level.statusBar window.rootViewController = UIViewController() window.makeKeyAndVisible() window.rootViewController?.present(self, animated: true, completion: nil) } } }
39.104167
137
0.627597
1a21b56656c91512461fb754c403069e654ac783
1,423
// // AppDelegate.swift // SwiftUI-Animations // // Created by Shubham Singh on 05/08/20. // Copyright ยฉ 2020 Shubham Singh. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } }
44.46875
179
0.751933
89894f935dc626a0f009bf8e871c978268afab98
288
// // RepositoriesModuleViewToPresenter.swift // RepositoriesModule // // Created by Mena Yousif on 11/1/19. // Copyright ยฉ 2019 Mena Soft. All rights reserved. // import Entities protocol RepositoriesModuleViewToPresenter { func fetchRepositories() func viewWillAppear() }
19.2
52
0.743056
08fe58c88e17b4980c4dfce62901fbf955546850
2,188
import UIKit import AVFoundation class ViewController: UIViewController { var player: AVAudioPlayer! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var progressLabel: UILabel! @IBOutlet weak var progressBar: UIProgressView! @IBOutlet weak var percentageLabel: UILabel! @IBOutlet weak var cookingTime1: UILabel! @IBOutlet weak var cookingTime2: UILabel! @IBOutlet weak var cookingTime3: UILabel! let eggTimes: [String: Float] = [ "Soft": 270, "Medium": 350, "Hard": 420 ] var cookingTime: Float = 0 var secondsPassed: Float = 0 var progress: Float = 0 var timer = Timer() @IBAction func hardnessSelected(_ sender: UIButton) { playSound(soundName: "Rooster-Crowing") timer.invalidate() let hardness = sender.currentTitle! cookingTime = eggTimes[hardness]! secondsPassed = 0 progress = 0 titleLabel.text = "Cooking time for \(hardness) is \(Int(cookingTime)) seconds..." timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true) } @objc func updateTimer() { progress = secondsPassed / cookingTime progressLabel.text = String("\(Int(secondsPassed)) s") progressBar.progress = progress percentageLabel.text = "\(Int(progress * 100)) %" if secondsPassed < cookingTime { secondsPassed += 1 } else { timer.invalidate() titleLabel.text = "Done !" playSound(soundName: "Rooster-Crowing") } } func initialise() { cookingTime1.text = String("\(eggTimes["Soft"]!) s") cookingTime2.text = String("\(eggTimes["Medium"]!) s") cookingTime3.text = String("\(eggTimes["Hard"]!) s") } func playSound(soundName: String) { let url = Bundle.main.url(forResource: soundName, withExtension: "mp3") player = try! AVAudioPlayer(contentsOf: url!) player.play() } }
28.051282
133
0.58638
8f5039496ece9f7ed948590c72efd6c7f045acca
884
import Bot import Sugar final class HelloBot: SlackMessageService { override func messageEvent(slackBot: SlackBot, webApi: WebAPI, message: MessageDecorator, previous: MessageDecorator?) throws { guard let target = message.target, let sender = message.sender else { return } try message.routeText( to: self.sayHello(to: sender, in: target, with: webApi), matching: Greeting(name: "greeting"), slackBot.me ) } } fileprivate extension HelloBot { func sayHello(to sender: User, in target: SlackTargetType, with webApi: WebAPI) -> (PatternMatchResult) throws -> Void { return { match in let message = SlackMessage(target: target) .text(match.value(named: "greeting")) .user(sender) try webApi.execute(message.apiMethod()) } } }
34
131
0.625566
508cc71848b92f905c4abef3fd7f83013520a5f7
830
import CYices extension Yices.Context { final class Model: SolverModel { private var context: Yices.Context private var model: OpaquePointer init?(context: Yices.Context) { guard context.isSatisfiable, let model = yices_get_model(context.context, 0) else { return nil } self.context = context self.model = model } deinit { yices_free_model(model) } func satisfies(formula: Yices.Context.Term) -> Bool? { switch yices_formula_true_in_model(self.model, formula) { case 1: return true case 0: return false default: return nil } } } }
23.714286
69
0.493976
28f7d02a5a0c62b4bdbceaf0e41002e82b3959e0
2,883
import CoreImage public class PageCurlWithShadowTransition { public var targetImage: CIImage public var angle: NSNumber = 0 public var shadowSize: NSNumber = 0.5 public var shadowExtent: CIVector = CIVector(values: [0.0, 0.0, 0.0, 0.0], count: 4) public var time: NSNumber = 0 public var extent: CIVector = CIVector(values: [0.0, 0.0, 0.0, 0.0], count: 4) public var backsideImage: CIImage public var radius: NSNumber = 100 public var shadowAmount: NSNumber = 0.7 public var image: CIImage required public init(targetImage: CIImage, angle: NSNumber = 0, shadowSize: NSNumber = 0.5, shadowExtent: CIVector = CIVector(values: [0.0, 0.0, 0.0, 0.0], count: 4), time: NSNumber = 0, extent: CIVector = CIVector(values: [0.0, 0.0, 0.0, 0.0], count: 4), backsideImage: CIImage, radius: NSNumber = 100, shadowAmount: NSNumber = 0.7, image: CIImage){ self.targetImage = targetImage self.angle = angle self.shadowSize = shadowSize self.shadowExtent = shadowExtent self.time = time self.extent = extent self.backsideImage = backsideImage self.radius = radius self.shadowAmount = shadowAmount self.image = image } public func filter() -> CIFilter? { guard let filter = CIFilter(name: "CIPageCurlWithShadowTransition") else { return nil } filter.setValue(targetImage, forKey: "inputTargetImage") filter.setValue(angle, forKey: "inputAngle") filter.setValue(shadowSize, forKey: "inputShadowSize") filter.setValue(shadowExtent, forKey: "inputShadowExtent") filter.setValue(time, forKey: "inputTime") filter.setValue(extent, forKey: "inputExtent") filter.setValue(backsideImage, forKey: "inputBacksideImage") filter.setValue(radius, forKey: "inputRadius") filter.setValue(shadowAmount, forKey: "inputShadowAmount") filter.setValue(image, forKey: "inputImage") return filter } } extension CIImage { public func pageCurlWithShadowTransitionFilter(targetImage: CIImage, angle: NSNumber = 0, shadowSize: NSNumber = 0.5, shadowExtent: CIVector = CIVector(values: [0.0, 0.0, 0.0, 0.0], count: 4), time: NSNumber = 0, extent: CIVector = CIVector(values: [0.0, 0.0, 0.0, 0.0], count: 4), backsideImage: CIImage, radius: NSNumber = 100, shadowAmount: NSNumber = 0.7) -> CIImage? { guard let filter = CIFilter(name: "CIPageCurlWithShadowTransition") else { return nil } filter.setValue(self, forKey: "inputImage") filter.setValue(targetImage, forKey: "inputTargetImage") filter.setValue(angle, forKey: "inputAngle") filter.setValue(shadowSize, forKey: "inputShadowSize") filter.setValue(shadowExtent, forKey: "inputShadowExtent") filter.setValue(time, forKey: "inputTime") filter.setValue(extent, forKey: "inputExtent") filter.setValue(backsideImage, forKey: "inputBacksideImage") filter.setValue(radius, forKey: "inputRadius") filter.setValue(shadowAmount, forKey: "inputShadowAmount") return filter.outputImage } }
45.761905
374
0.740548
e0e0d5a771fc8d2493eee283627f3e3ffc5ffe3f
2,098
// // Mailbox.swift // PortalView // // Created by Guido Marucci Blas on 1/27/17. // // import Foundation // This type needs to have reference semantics // due to how container components are rendered. // // All child components' mailboxes of a container component // are forwared to the container's mailbox thus the need to // have a single mailbox reference. Keep in mind that a Mailbox // is a mutable type. Subscribers can be added anytime thus the need // for a reference type because any object that gets a reference to // a mailbox should be able to send a message to all its subscribers // no matter when subscribers where added to the mailbox. // // See how the `forward` method is implemented. public final class Mailbox<MessageType> { fileprivate var subscribers: [(MessageType) -> Void] = [] public func subscribe(subscriber: @escaping (MessageType) -> Void) { subscribers.append(subscriber) } } extension Mailbox { internal func dispatch(message: MessageType) { subscribers.forEach { $0(message) } } internal func forward(to mailbox: Mailbox<MessageType>) { subscribe { mailbox.dispatch(message: $0) } } internal func forwardMap<NewMessageType>( to mailbox: Mailbox<NewMessageType>, _ transform: @escaping (MessageType) -> NewMessageType) { subscribe { mailbox.dispatch(message: transform($0)) } } internal func filterMap<NewMessageType>( _ transform: @escaping (MessageType) -> NewMessageType?) -> Mailbox<NewMessageType> { let mailbox = Mailbox<NewMessageType>() subscribe { message in if let transformedMessage = transform(message) { mailbox.dispatch(message: transformedMessage) } } return mailbox } } extension Mailbox: CustomDebugStringConvertible { public var debugDescription: String { let address = Unmanaged.passUnretained(self).toOpaque() return "<\(type(of: self)): \(address)> - Subscribers \(subscribers.count)" } }
29.971429
93
0.666349
6a0fc9b77856c22b950d95a768dfd5f7144adb39
2,739
/* Copyright 2021 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import AEPServices import Foundation import WebKit class ErrorView: FullscreenMessageDelegate { var error: AssuranceConnectionError var fullscreenMessage: FullscreenPresentable? var fullscreenWebView: WKWebView? /// Initializer init(_ error: AssuranceConnectionError) { self.error = error } func display() { fullscreenMessage = ServiceProvider.shared.uiService.createFullscreenMessage(payload: String(bytes: PinDialogHTML.content, encoding: .utf8) ?? "", listener: self, isLocalImageUsed: false) fullscreenMessage?.show() } func onShow(message: FullscreenMessage) { fullscreenWebView = message.webView as? WKWebView } func onDismiss(message: FullscreenMessage) { fullscreenWebView = nil fullscreenMessage = nil } func overrideUrlLoad(message: FullscreenMessage, url: String?) -> Bool { // no operation if we are unable to find the host of the url // return true, so force core to handle the URL guard let host = URL(string: url ?? "")?.host else { return true } // when the user hits "Cancel" on the iOS pinpad screen. Dismiss the fullscreen message // return false, to indicate that the URL has been handled if host == AssuranceConstants.HTMLURLPath.CANCEL { message.dismiss() return false } return true } func webViewDidFinishInitialLoading(webView: WKWebView) { showErrorDialogToUser() } func onShowFailure() { Log.debug(label: AssuranceConstants.LOG_TAG, "Unable to display Assurance error screen. Assurance session terminated.") } private func showErrorDialogToUser() { Log.debug(label: AssuranceConstants.LOG_TAG, String(format: "Assurance connection establishment failed. Error : %@, Description : %@", error.info.name, error.info.description)) let jsFunctionCall = String(format: "showError('%@','%@', %d);", error.info.name, error.info.description, false) fullscreenWebView?.evaluateJavaScript(jsFunctionCall, completionHandler: nil) } }
37.013514
195
0.702081
9c718d8890ea41c612cc5c943cebc9c08581baf3
1,701
// // WLItemView.swift // HOwner-iOS // // Created by three stone ็Ž‹ on 2019/6/13. // Copyright ยฉ 2019 three stone ็Ž‹. All rights reserved. // import Foundation import UIKit import WLToolsKit public let asmargin: CGFloat = 15 public let sasmargin: CGFloat = 30 open class WLItemView: UICollectionView { public static func createItem(_ itemSize: CGSize ,col: Int ,total: Int) -> Self { let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal layout.sectionInset = UIEdgeInsets(top: col == 4 ? asmargin : 0, left: col == 4 ? asmargin : sasmargin, bottom: col == 4 ? 0 : 15, right: col == 4 ? asmargin : sasmargin) layout.itemSize = itemSize layout.minimumLineSpacing = 1 let space = (WL_SCREEN_WIDTH - (col == 4 ? asmargin : sasmargin) * 2 - CGFloat(col) * itemSize.width) / CGFloat(col - 1) layout.minimumLineSpacing = space return self.init(frame: .zero ,collectionViewLayout: layout) } required override public init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) { super.init(frame: frame, collectionViewLayout: layout) commitInit() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension WLItemView { func commitInit() { showsVerticalScrollIndicator = false showsHorizontalScrollIndicator = false backgroundColor = .white bounces = false isPagingEnabled = true } }
25.014706
178
0.607878
d7fd38c1a7e0eff3d4fe108d62c2ab31649062ee
2,156
// // AppDelegate.swift // exerc4 // // Created by IFCE on 25/05/17. // Copyright ยฉ 2017 IFCE. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
45.87234
285
0.754174
4b8968b1ed2dcb967fd42a7f4b234eb9c8ad4a59
374
// // TipSeeWith.swift // Pods-TipSee_Example // // Created by Farshad on 10/30/19. // import Foundation public protocol TipSeeConfiguration { func with(_ mutations: (inout Self) -> Void) -> Self } extension TipSeeConfiguration { public func with(_ mutations: (inout Self) -> Void) -> Self { var copyOfSelf = self mutations(&copyOfSelf) return copyOfSelf } }
17.809524
62
0.700535
e22ccc18cf427ccb00400b11d6140c049f75a558
1,688
// // MainScreenApi.swift // AdvancedMovieApp // // Created by Gizem Boskan on 1.11.2021. // import Foundation import RxSwift protocol MainScreenApi { } extension MainScreenApi { func getMovieList(pageNumber: Int) -> Observable<MovieResults> { guard let url = URL.getPopularMovies(page: pageNumber) else { return .empty() } return URLRequest.load(resource: Resource<MovieResults>(url: url)) } func searchMovie(movie: String) -> Observable<MovieResults> { guard let url = URL.searchMovie(query: movie) else { return .empty() } return URLRequest.load(resource: Resource<MovieResults>(url: url)) } func searchMovieAndPerson(searchText: String) -> Observable<MultiSearchResult> { guard let url = URL.searchPersonAndMovie(query: searchText) else { return .empty() } return URLRequest.load(resource: Resource<MultiSearchResult>(url: url)) } } // MARK: - FUTURE WORK! // TODO: I WILL SEPERATE ALL THIS PART TO IMPLEMENT A PROPER TEST!!! //protocol MainScreenApiProtocol { // func getMovieList(pageNumber: Int) // func searchMovie(movie: String) //} //final class MainScreenApi: MainScreenApiProtocol { // func getMovieList(pageNumber: Int) -> Observable<MovieResults> { // guard let url = URL.getPopularMovies(page: pageNumber) else { return .empty() } // return URLRequest.load(resource: Resource<MovieResults>(url: url)) // } // // func searchMovie(movie: String) -> Observable<MovieResults> { // guard let url = URL.searchMovie(query: movie) else { return .empty() } // return URLRequest.load(resource: Resource<MovieResults>(url: url)) // } //}
33.76
92
0.680687