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
3a4571a16a85ae4f78acd9efa9f4de639048b908
445
import Cocoa import FlutterMacOS import hottie class MainFlutterWindow: NSWindow { override func awakeFromNib() { let flutterViewController = FlutterViewController.init() let windowFrame = self.frame self.contentViewController = flutterViewController self.setFrame(windowFrame, display: true) RegisterGeneratedPlugins(registry: flutterViewController) HottiePlugin.instance.setRoot(); super.awakeFromNib() } }
23.421053
61
0.773034
486bfd84addfcb8b033cd80065e5204851cd5471
652
// // ColorExtension.swift // List // // Created by Michael Kilgore on 9/9/21. // import SwiftUI extension Int { func ff(_ shift: Int) -> Double { return Double((self >> shift) & 0xff) / 255 } } extension Color { init(hex: Int) { self.init(red: hex.ff(16), green: hex.ff(08), blue: hex.ff(00)) } } extension Double { func interpolate(to: Double, in fraction: Double, min: Double = 0, max: Double = 1) -> Double { if fraction <= min { return self } else if fraction >= max { return to } return self + (to - self) * (fraction - min) / (max - min) } }
20.375
99
0.539877
8a47cc5dae6c8266576060ee3c813a3a7b89b280
2,166
// // AppDelegate.swift // RRuleSwiftExample // // Created by 洪鑫 on 16/3/28. // Copyright © 2016年 Teambition. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
49.227273
285
0.755771
3841724af80a4f38ab25fb31443c1b0900825a50
994
// // UILabel.swift // Mini02 // // Created by Rogerio Lucon on 07/04/20. // Copyright © 2020 Rogerio Lucon. All rights reserved. // import UIKit class TextLabel: UILabel { var texto = "" {didSet { counter = 0 text = "" typeWriter() }} var counter = 0 var timer: Timer? var humamMode: Bool = true var speed: Double = 20 {didSet {speed = speed * 10}} @objc func typeWriter(){ var interval = speed * 0.006 if counter < texto.count { let array = Array(texto) self.text = self.text! + String(array[counter]) if humamMode { interval = Double.random(in: 1...8) / (speed * 2) } timer?.invalidate() timer = Timer.scheduledTimer(timeInterval: TimeInterval(interval), target: self, selector: #selector(typeWriter), userInfo: nil, repeats: true) } else { timer?.invalidate() } counter += 1 } }
26.157895
155
0.544266
e8e2c84a185c19066a6bc2e96b3a4e01c00611b5
6,394
// // CommentsViewController.swift // Parsetagram // // Created by Pedro Sandoval Segura on 6/23/16. // Copyright © 2016 Pedro Sandoval Segura. All rights reserved. // import UIKit import Parse import MBProgressHUD class CommentsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { var post: PFObject! @IBOutlet weak var usernameLabel: UILabel! @IBOutlet weak var captionLabel: UILabel! @IBOutlet weak var profilePictureView: UIImageView! @IBOutlet weak var commentTextField: UITextField! @IBOutlet weak var tableView: UITableView! var usernames: [String]! var timestamps: [String]! var comments: [String]! var commenterPFFiles: [PFFile]! override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self tableView.delegate = self // Create circular profile picture view self.profilePictureView.layer.cornerRadius = self.profilePictureView.frame.size.width / 2 profilePictureView.clipsToBounds = true loadControllerData() // Do any additional setup after loading the view. } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.comments.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "commentCell", for: indexPath) as! CommentTableViewCell //Fill labels cell.usernameLabel.text = self.usernames[indexPath.row] cell.commentLabel.text = self.comments[indexPath.row] cell.timeAgoLabel.text = TimeAid.getTimeDifferencePhrase(self.timestamps[indexPath.row]) //Set profile pictures let file = self.commenterPFFiles[indexPath.row] file.getDataInBackground { (imageData, error) in if error == nil { if let imageData = imageData { let image = UIImage(data:imageData) cell.commenterProfileView.image = image } } } //print("By: CommentsViewController.swift \n --------> index path.row = \(indexPath.row) and the comment is = \(self.comments[indexPath.row])") //Allow for profile picture in comments -- UPGRADE return cell } @IBAction func onSend(_ sender: AnyObject) { //Start progress HUD MBProgressHUD.showAdded(to: self.view, animated: true) if self.commentTextField.text != nil && self.commentTextField.text != "" { //Update the users, comments, timestamps before packing self.usernames.append(UserInstance.USERNAME) self.timestamps.append(TimeAid.getFormattedDate()) self.comments.append(self.commentTextField.text!) //Put the commenter profile image (as PFFile) in the commenter profile pictures storage of the Post object var commenterProfilePFFiles = self.post["commenterProfilePictures"] as! [PFFile] commenterProfilePFFiles.append(UserInstance.PROFILE_PICTURE_PFFILE) self.post["commenterProfilePictures"] = commenterProfilePFFiles //Clear the text field and stop editing self.commentTextField.text = "" self.view.endEditing(true) //Send to Parse Servers let updatedStorage = CommentAid.repackCommentArray(self.usernames, timestamps: self.timestamps, comments: self.comments) self.post["comments"] = updatedStorage self.post.incrementKey("commentsCount") self.post.saveInBackground(block: { (success, error) in self.loadControllerData() self.tableView.reloadData() MBProgressHUD.hide(for: self.view, animated: true) }) } } func loadControllerData() { //Get profile picture of post and other attributes if let postImage = post["associatedProfilePicture"] { let postImagePFFile = postImage as! PFFile postImagePFFile.getDataInBackground(block: { (imageData, error) in if error == nil { if let imageData = imageData { let image = UIImage(data:imageData) self.profilePictureView.image = image } } }) //Get commenter PFFiles to recreate images self.commenterPFFiles = post["commenterProfilePictures"] as! [PFFile] //Get the caption self.captionLabel.text = post["caption"] as? String //Get the author self.usernameLabel.text = post["username"] as? String //Get first comment if one exists let storage = post["comments"] as! [[String]] if !storage.isEmpty { let restructuredStorage = CommentAid.unpackCommentArray(storage) self.usernames = restructuredStorage.usernames self.timestamps = restructuredStorage.timestamps self.comments = restructuredStorage.comments } else { // No comments on this post self.comments = [String]() self.usernames = [String]() self.timestamps = [String]() } } if let user = post["username"] { let usernameString = user as! String //Get the author usernameLabel.text = "@ \(usernameString)" } else { usernameLabel.text = "Error..." } } @IBAction func onTap(_ sender: AnyObject) { self.view.endEditing(true) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
36.959538
151
0.597122
5bba9556ceeb8a0bb0c3ed4ae297d817f62f4e93
238
// // UserServiceType.swift // Papr // // Created by Joan Disho on 14.03.18. // Copyright © 2018 Joan Disho. All rights reserved. // import Foundation import RxSwift protocol UserServiceType { func getMe() -> Observable<User> }
15.866667
53
0.689076
231ec45fa159ba15b72ae7b126416f21bd7b0afa
833
// // AppDelegate.swift // UrlSessionLesson // // Created by Константин Богданов on 06/11/2019. // Copyright © 2019 Константин Богданов. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { window = UIWindow(frame: UIScreen.main.bounds) let service = NetworkService(session: SessionFactory().createDefaultSession()) let interactor = Interactor(networkService: service) let viewController = ViewController(interactor: interactor) window?.rootViewController = viewController window?.makeKeyAndVisible() // let url = API.searchPath(text: "test", extras: "url_s") return true } }
25.242424
142
0.761104
9085d742ef92d5d32e44e8ac52dd7037a65c27e4
2,390
// // EVEAllianceList.swift // EVEAPI // // Created by Artem Shimanski on 30.11.16. // Copyright © 2016 Artem Shimanski. All rights reserved. // import UIKit public class EVEAllianceListItem: EVEObject { public var name: String = "" public var shortName: String = "" public var allianceID: Int64 = 0 public var executorCorpID: Int64 = 0 public var memberCount: Int = 0 public var startDate: Date = Date.distantPast public var memberCorporations: [EVEAllianceListMemberCorporation] = [] public required init?(dictionary:[String:Any]) { super.init(dictionary: dictionary) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override public func scheme() -> [String:EVESchemeElementType] { return [ "name":EVESchemeElementType.String(elementName:nil, transformer:nil), "shortName":EVESchemeElementType.String(elementName:nil, transformer:nil), "allianceID":EVESchemeElementType.Int64(elementName:nil, transformer:nil), "executorCorpID":EVESchemeElementType.Int64(elementName:nil, transformer:nil), "memberCount":EVESchemeElementType.Int(elementName:nil, transformer:nil), "startDate":EVESchemeElementType.Date(elementName:nil, transformer:nil), "memberCorporations":EVESchemeElementType.Rowset(elementName: nil, type: EVEAllianceListMemberCorporation.self, transformer: nil) ] } } public class EVEAllianceListMemberCorporation: EVEObject { public var corporationID: Int64 = 0 public var startDate: Date = Date.distantPast public required init?(dictionary:[String:Any]) { super.init(dictionary: dictionary) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override public func scheme() -> [String:EVESchemeElementType] { return [ "corporationID":EVESchemeElementType.Int64(elementName:nil, transformer:nil), "startDate":EVESchemeElementType.Date(elementName:nil, transformer:nil), ] } } public class EVEAllianceList: EVEResult { public var alliances: [EVEAllianceListItem] = [] public required init?(dictionary:[String:Any]) { super.init(dictionary: dictionary) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override public func scheme() -> [String:EVESchemeElementType] { return [ "alliances":EVESchemeElementType.Rowset(elementName: nil, type: EVEAllianceListItem.self, transformer: nil) ] } }
30.253165
131
0.755649
f983361d6e280500a4fcb802798875f39e2d8d6c
6,988
// // ChartBarHighlighter.swift // Charts // // Created by Daniel Cohen Gindi on 26/7/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics internal class BarChartHighlighter: ChartHighlighter { internal init(chart: BarChartView) { super.init(chart: chart) } internal override func getHighlight(x x: Double, y: Double) -> ChartHighlight? { let h = super.getHighlight(x: x, y: y) if h === nil { return h } else { if let set = _chart?.data?.getDataSetByIndex(h!.dataSetIndex) as? BarChartDataSet { if set.isStacked { // create an array of the touch-point var pt = CGPoint() pt.y = CGFloat(y) // take any transformer to determine the x-axis value _chart?.getTransformer(set.axisDependency).pixelToValue(&pt) return getStackedHighlight(old: h, set: set, xIndex: h!.xIndex, dataSetIndex: h!.dataSetIndex, yValue: Double(pt.y)) } } return h } } internal override func getXIndex(x: Double) -> Int { if let barChartData = _chart?.data as? BarChartData { if !barChartData.isGrouped { return super.getXIndex(x) } else { let baseNoSpace = getBase(x) let setCount = barChartData.dataSetCount var xIndex = Int(baseNoSpace) / setCount let valCount = barChartData.xValCount if xIndex < 0 { xIndex = 0 } else if xIndex >= valCount { xIndex = valCount - 1 } return xIndex } } else { return 0 } } internal override func getDataSetIndex(xIndex xIndex: Int, x: Double, y: Double) -> Int { if let barChartData = _chart?.data as? BarChartData { if !barChartData.isGrouped { return 0 } else { let baseNoSpace = getBase(x) let setCount = barChartData.dataSetCount var dataSetIndex = Int(baseNoSpace) % setCount if dataSetIndex < 0 { dataSetIndex = 0 } else if dataSetIndex >= setCount { dataSetIndex = setCount - 1 } return dataSetIndex } } else { return 0 } } /// This method creates the Highlight object that also indicates which value of a stacked BarEntry has been selected. /// - parameter old: the old highlight object before looking for stacked values /// - parameter set: /// - parameter xIndex: /// - parameter dataSetIndex: /// - parameter yValue: /// - returns: internal func getStackedHighlight(old old: ChartHighlight?, set: BarChartDataSet, xIndex: Int, dataSetIndex: Int, yValue: Double) -> ChartHighlight? { let entry = set.entryForXIndex(xIndex) as? BarChartDataEntry if entry?.values === nil { return old } if let ranges = getRanges(entry: entry!) { let stackIndex = getClosestStackIndex(ranges: ranges, value: yValue) let h = ChartHighlight(xIndex: xIndex, dataSetIndex: dataSetIndex, stackIndex: stackIndex, range: ranges[stackIndex]) return h } return nil } /// Returns the index of the closest value inside the values array / ranges (stacked barchart) to the value given as a parameter. /// - parameter entry: /// - parameter value: /// - returns: internal func getClosestStackIndex(ranges ranges: [ChartRange]?, value: Double) -> Int { if ranges == nil { return 0 } var stackIndex = 0 for range in ranges! { if range.contains(value) { return stackIndex } else { stackIndex++ } } let length = max(ranges!.count - 1, 0) return (value > ranges![length].to) ? length : 0 } /// Returns the base x-value to the corresponding x-touch value in pixels. /// - parameter x: /// - returns: internal func getBase(x: Double) -> Double { if let barChartData = _chart?.data as? BarChartData { // create an array of the touch-point var pt = CGPoint() pt.x = CGFloat(x) // take any transformer to determine the x-axis value _chart?.getTransformer(ChartYAxis.AxisDependency.Left).pixelToValue(&pt) let xVal = Double(pt.x) let setCount = barChartData.dataSetCount ?? 0 // calculate how often the group-space appears let steps = Int(xVal / (Double(setCount) + Double(barChartData.groupSpace))) let groupSpaceSum = Double(barChartData.groupSpace) * Double(steps) let baseNoSpace = xVal - groupSpaceSum return baseNoSpace } else { return 0.0 } } /// Splits up the stack-values of the given bar-entry into Range objects. /// - parameter entry: /// - returns: internal func getRanges(entry entry: BarChartDataEntry) -> [ChartRange]? { let values = entry.values if (values == nil) { return nil } var negRemain = -entry.negativeSum var posRemain: Double = 0.0 var ranges = [ChartRange]() ranges.reserveCapacity(values!.count) for (var i = 0, count = values!.count; i < count; i++) { let value = values![i] if value < 0 { ranges.append(ChartRange(from: negRemain, to: negRemain + abs(value))) negRemain += abs(value) } else { ranges.append(ChartRange(from: posRemain, to: posRemain+value)) posRemain += value } } return ranges } }
28.522449
152
0.490126
03604b39b812c929e6577e0b4844095c6a38ee7c
453
// // MockCustomerService.swift // HeartRateMonitor // // Created by Key Hui on 10/30/21. // class MockCustomerService: CustomerService { override func login(request: LoginRequest) async -> LoginResponse? { return MockData.loginResponse } override func logout() async -> VoidResponse? { return VoidResponse() } override func user(id: Int64) async -> UserResponse? { return MockData.userResponse } }
21.571429
72
0.666667
d909b532e6526a967930ba087267013e0dc31585
1,675
// // MovieTableViewCell.swift // Moviest // // Created by Bilal Arslan on 19.05.2018. // Copyright © 2018 Bilal Arslan. All rights reserved. // import UIKit import Kingfisher class MovieRowCell: BaseTableViewCell, NibLoadable, Instantiatable { @IBOutlet fileprivate weak var titleLabel: UILabel! @IBOutlet fileprivate weak var releaseDateLabel: UILabel! @IBOutlet fileprivate weak var overviewLabel: UILabel! @IBOutlet fileprivate weak var posterImageView: UIImageView! { didSet { if let imageView = posterImageView { imageView.kf.indicatorType = .activity } } } override var viewBindableModel: ViewBindable? { didSet { guard let bindable = viewBindableModel else { return } titleLabel.text = bindable.getTitle() releaseDateLabel.text = bindable.getSubtitle() overviewLabel.text = bindable.getSubText() if let url = bindable.getImageURL() { posterImageView.kf.setImage(with: url) } } } override func awakeFromNib() { super.awakeFromNib() styleSetup() selectionStyle = .none } override func prepareForReuse() { super.prepareForReuse() titleLabel.text = nil releaseDateLabel.text = nil overviewLabel.text = nil posterImageView.image = nil posterImageView.kf.cancelDownloadTask() } } extension MovieRowCell { func styleSetup() { posterImageView.layer.borderWidth = 0.3 posterImageView.layer.borderColor = UIColor.lightGray.cgColor } }
26.171875
69
0.62806
9b49030a89f678cea28857aed259edefa2a19565
2,823
import Cocoa import Dwifft final class StuffCollectionViewController: NSViewController { @IBOutlet weak var collectionView: NSCollectionView! let itemIdentifier: NSUserInterfaceItemIdentifier = NSUserInterfaceItemIdentifier("emojiItem") let headerIdentifier: NSUserInterfaceItemIdentifier = NSUserInterfaceItemIdentifier("sectionHeader") var diffCalculator: CollectionViewDiffCalculator<String, String>? var stuff: SectionedValues<String, String> = Stuff.emojiStuff() { // So, whenever your datasource's array of things changes, just let the diffCalculator know and it'll do the rest. didSet { self.diffCalculator?.sectionedValues = stuff } } override func viewDidLoad() { super.viewDidLoad() collectionView.dataSource = self diffCalculator = CollectionViewDiffCalculator(collectionView: collectionView, initialSectionedValues: stuff) let itemNib = NSNib(nibNamed: NSNib.Name("StuffCollectionViewItem"), bundle: nil) collectionView.register(itemNib, forItemWithIdentifier: itemIdentifier) let headerNib = NSNib(nibNamed: NSNib.Name("StuffCollectionHeaderView"), bundle: nil) collectionView.register(headerNib, forSupplementaryViewOfKind: NSCollectionView.elementKindSectionHeader, withIdentifier: headerIdentifier) } @IBAction func shuffle(_ sender: NSButton) { self.stuff = Stuff.emojiStuff() } } extension StuffCollectionViewController: NSCollectionViewDataSource { func numberOfSections(in collectionView: NSCollectionView) -> Int { return diffCalculator?.numberOfSections() ?? 0 } func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int { return diffCalculator?.numberOfObjects(inSection: section) ?? 0 } func collectionView(_ collectionView: NSCollectionView, viewForSupplementaryElementOfKind kind: NSCollectionView.SupplementaryElementKind, at indexPath: IndexPath) -> NSView { let header = collectionView.makeSupplementaryView(ofKind: NSCollectionView.elementKindSectionHeader, withIdentifier: headerIdentifier, for: indexPath) if let dc = diffCalculator, let stuffHeader = header as? StuffCollectionHeaderView { stuffHeader.title.stringValue = dc.value(forSection: indexPath.section) } return header } func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem { let item = collectionView.makeItem(withIdentifier: itemIdentifier, for: indexPath) if let dc = diffCalculator, let emojiItem = item as? StuffCollectionViewItem { emojiItem.textField?.stringValue = dc.value(atIndexPath: indexPath) } return item } } final class StuffCollectionHeaderView: NSView { @IBOutlet weak var title: NSTextField! }
40.328571
154
0.772228
18b3a15efb415686c73a424143b0de8b30ca8da3
16,998
//===--- StringCharacterView.swift - String's Collection of Characters ----===// // // 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 // //===----------------------------------------------------------------------===// // // String is-not-a Sequence or Collection, but it exposes a // collection of characters. // //===----------------------------------------------------------------------===// // FIXME(ABI)#70 : The character string view should have a custom iterator type to // allow performance optimizations of linear traversals. extension String { /// A view of a string's contents as a collection of characters. /// /// In Swift, every string provides a view of its contents as characters. In /// this view, many individual characters---for example, "é", "김", and /// "🇮🇳"---can be made up of multiple Unicode code points. These code points /// are combined by Unicode's boundary algorithms into *extended grapheme /// clusters*, represented by the `Character` type. Each element of a /// `CharacterView` collection is a `Character` instance. /// /// let flowers = "Flowers 💐" /// for c in flowers.characters { /// print(c) /// } /// // F /// // l /// // o /// // w /// // e /// // r /// // s /// // /// // 💐 /// /// You can convert a `String.CharacterView` instance back into a string /// using the `String` type's `init(_:)` initializer. /// /// let name = "Marie Curie" /// if let firstSpace = name.characters.index(of: " ") { /// let firstName = String(name.characters.prefix(upTo: firstSpace)) /// print(firstName) /// } /// // Prints "Marie" public struct CharacterView { internal var _core: _StringCore /// The offset of this view's `_core` from an original core. This works /// around the fact that `_StringCore` is always zero-indexed. /// `_coreOffset` should be subtracted from `UnicodeScalarIndex._position` /// before that value is used as a `_core` index. internal var _coreOffset: Int /// Creates a view of the given string. public init(_ text: String) { self._core = text._core self._coreOffset = 0 } public // @testable init(_ _core: _StringCore, coreOffset: Int = 0) { self._core = _core self._coreOffset = coreOffset } } /// A view of the string's contents as a collection of characters. public var characters: CharacterView { get { return CharacterView(self) } set { self = String(newValue) } } /// Applies the given closure to a mutable view of the string's characters. /// /// Do not use the string that is the target of this method inside the /// closure passed to `body`, as it may not have its correct value. Instead, /// use the closure's `CharacterView` argument. /// /// This example below uses the `withMutableCharacters(_:)` method to /// truncate the string `str` at the first space and to return the remainder /// of the string. /// /// var str = "All this happened, more or less." /// let afterSpace = str.withMutableCharacters { chars -> String.CharacterView in /// if let i = chars.index(of: " ") { /// let result = chars.suffix(from: chars.index(after: i)) /// chars.removeSubrange(i..<chars.endIndex) /// return result /// } /// return String.CharacterView() /// } /// /// print(str) /// // Prints "All" /// print(String(afterSpace)) /// // Prints "this happened, more or less." /// /// - Parameter body: A closure that takes a character view as its argument. /// The `CharacterView` argument is valid only for the duration of the /// closure's execution. /// - Returns: The return value of the `body` closure, if any, is the return /// value of this method. public mutating func withMutableCharacters<R>( _ body: (inout CharacterView) -> R ) -> R { // Naively mutating self.characters forces multiple references to // exist at the point of mutation. Instead, temporarily move the // core of this string into a CharacterView. var tmp = CharacterView("") swap(&_core, &tmp._core) let r = body(&tmp) swap(&_core, &tmp._core) return r } /// Creates a string from the given character view. /// /// Use this initializer to recover a string after performing a collection /// slicing operation on a string's character view. /// /// let poem = "'Twas brillig, and the slithy toves / " + /// "Did gyre and gimbal in the wabe: / " + /// "All mimsy were the borogoves / " + /// "And the mome raths outgrabe." /// let excerpt = String(poem.characters.prefix(22)) + "..." /// print(excerpt) /// // Prints "'Twas brillig, and the..." /// /// - Parameter characters: A character view to convert to a string. public init(_ characters: CharacterView) { self.init(characters._core) } } /// `String.CharacterView` is a collection of `Character`. extension String.CharacterView : BidirectionalCollection { internal typealias UnicodeScalarView = String.UnicodeScalarView internal var unicodeScalars: UnicodeScalarView { return UnicodeScalarView(_core, coreOffset: _coreOffset) } /// A position in a string's `CharacterView` instance. /// /// You can convert between indices of the different string views by using /// conversion initializers and the `samePosition(in:)` method overloads. /// The following example finds the index of the first space in the string's /// character view and then converts that to the same position in the UTF-8 /// view: /// /// let hearts = "Hearts <3 ♥︎ 💘" /// if let i = hearts.characters.index(of: " ") { /// let j = i.samePosition(in: hearts.utf8) /// print(Array(hearts.utf8.prefix(upTo: j))) /// } /// // Prints "[72, 101, 97, 114, 116, 115]" public struct Index : Comparable, CustomPlaygroundQuickLookable { public // SPI(Foundation) init(_base: String.UnicodeScalarView.Index, in c: String.CharacterView) { self._base = _base self._countUTF16 = c._measureExtendedGraphemeClusterForward(from: _base) } internal init(_base: UnicodeScalarView.Index, _countUTF16: Int) { self._base = _base self._countUTF16 = _countUTF16 } internal let _base: UnicodeScalarView.Index /// The count of this extended grapheme cluster in UTF-16 code units. internal let _countUTF16: Int /// The integer offset of this index in UTF-16 code units. public // SPI(Foundation) var _utf16Index: Int { return _base._position } /// The one past end index for this extended grapheme cluster in Unicode /// scalars. internal var _endBase: UnicodeScalarView.Index { return UnicodeScalarView.Index(_position: _utf16Index + _countUTF16) } public var customPlaygroundQuickLook: PlaygroundQuickLook { return .int(Int64(_utf16Index)) } } public typealias IndexDistance = Int /// The position of the first character in a nonempty character view. /// /// In an empty character view, `startIndex` is equal to `endIndex`. public var startIndex: Index { return Index(_base: unicodeScalars.startIndex, in: self) } /// A character view's "past the end" position---that is, the position one /// greater than the last valid subscript argument. /// /// In an empty character view, `endIndex` is equal to `startIndex`. public var endIndex: Index { return Index(_base: unicodeScalars.endIndex, in: self) } /// Returns the next consecutive position after `i`. /// /// - Precondition: The next position is valid. public func index(after i: Index) -> Index { _precondition(i._base < unicodeScalars.endIndex, "cannot increment beyond endIndex") _precondition(i._base >= unicodeScalars.startIndex, "cannot increment invalid index") return Index(_base: i._endBase, in: self) } /// Returns the previous consecutive position before `i`. /// /// - Precondition: The previous position is valid. public func index(before i: Index) -> Index { _precondition(i._base > unicodeScalars.startIndex, "cannot decrement before startIndex") _precondition(i._base <= unicodeScalars.endIndex, "cannot decrement invalid index") let predecessorLengthUTF16 = _measureExtendedGraphemeClusterBackward(from: i._base) return Index( _base: UnicodeScalarView.Index( _position: i._utf16Index - predecessorLengthUTF16 ), in: self ) } // NOTE: don't make this function inlineable. Grapheme cluster // segmentation uses a completely different algorithm in Unicode 9.0. // /// Returns the length of the first extended grapheme cluster in UTF-16 /// code units. @inline(never) // Don't remove, see above. internal func _measureExtendedGraphemeClusterForward( from start: UnicodeScalarView.Index ) -> Int { var start = start let end = unicodeScalars.endIndex if start == end { return 0 } let startIndexUTF16 = start._position let graphemeClusterBreakProperty = _UnicodeGraphemeClusterBreakPropertyTrie() let segmenter = _UnicodeExtendedGraphemeClusterSegmenter() var gcb0 = graphemeClusterBreakProperty.getPropertyRawValue( unicodeScalars[start].value) unicodeScalars.formIndex(after: &start) while start != end { // FIXME(performance): consider removing this "fast path". A branch // that is hard to predict could be worse for performance than a few // loads from cache to fetch the property 'gcb1'. if segmenter.isBoundaryAfter(gcb0) { break } let gcb1 = graphemeClusterBreakProperty.getPropertyRawValue( unicodeScalars[start].value) if segmenter.isBoundary(gcb0, gcb1) { break } gcb0 = gcb1 unicodeScalars.formIndex(after: &start) } return start._position - startIndexUTF16 } // NOTE: don't make this function inlineable. Grapheme cluster // segmentation uses a completely different algorithm in Unicode 9.0. // /// Returns the length of the previous extended grapheme cluster in UTF-16 /// code units. @inline(never) // Don't remove, see above. internal func _measureExtendedGraphemeClusterBackward( from end: UnicodeScalarView.Index ) -> Int { let start = unicodeScalars.startIndex if start == end { return 0 } let endIndexUTF16 = end._position let graphemeClusterBreakProperty = _UnicodeGraphemeClusterBreakPropertyTrie() let segmenter = _UnicodeExtendedGraphemeClusterSegmenter() var graphemeClusterStart = end unicodeScalars.formIndex(before: &graphemeClusterStart) var gcb0 = graphemeClusterBreakProperty.getPropertyRawValue( unicodeScalars[graphemeClusterStart].value) var graphemeClusterStartUTF16 = graphemeClusterStart._position while graphemeClusterStart != start { unicodeScalars.formIndex(before: &graphemeClusterStart) let gcb1 = graphemeClusterBreakProperty.getPropertyRawValue( unicodeScalars[graphemeClusterStart].value) if segmenter.isBoundary(gcb1, gcb0) { break } gcb0 = gcb1 graphemeClusterStartUTF16 = graphemeClusterStart._position } return endIndexUTF16 - graphemeClusterStartUTF16 } /// Accesses the character at the given position. /// /// The following example searches a string's character view for a capital /// letter and then prints the character at the found index: /// /// let greeting = "Hello, friend!" /// if let i = greeting.characters.index(where: { "A"..."Z" ~= $0 }) { /// print("First capital letter: \(greeting.characters[i])") /// } /// // Prints "First capital letter: H" /// /// - Parameter position: A valid index of the character view. `position` /// must be less than the view's end index. public subscript(i: Index) -> Character { return Character(String(unicodeScalars[i._base..<i._endBase])) } } extension String.CharacterView : RangeReplaceableCollection { /// Creates an empty character view. public init() { self.init("") } /// Replaces the characters within the specified bounds with the given /// characters. /// /// Invalidates all indices with respect to the string. /// /// - Parameters: /// - bounds: The range of characters to replace. The bounds of the range /// must be valid indices of the character view. /// - newElements: The new characters to add to the view. /// /// - Complexity: O(*m*), where *m* is the combined length of the character /// view and `newElements`. If the call to `replaceSubrange(_:with:)` /// simply removes characters at the end of the view, the complexity is /// O(*n*), where *n* is equal to `bounds.count`. public mutating func replaceSubrange<C>( _ bounds: Range<Index>, with newElements: C ) where C : Collection, C.Iterator.Element == Character { let rawSubRange: Range<Int> = bounds.lowerBound._base._position - _coreOffset ..< bounds.upperBound._base._position - _coreOffset let lazyUTF16 = newElements.lazy.flatMap { $0.utf16 } _core.replaceSubrange(rawSubRange, with: lazyUTF16) } /// Reserves enough space in the character view's underlying storage to store /// the specified number of ASCII characters. /// /// Because each element of a character view can require more than a single /// ASCII character's worth of storage, additional allocation may be /// necessary when adding characters to the character view after a call to /// `reserveCapacity(_:)`. /// /// - Parameter n: The minimum number of ASCII character's worth of storage /// to allocate. /// /// - Complexity: O(*n*), where *n* is the capacity being reserved. public mutating func reserveCapacity(_ n: Int) { _core.reserveCapacity(n) } /// Appends the given character to the character view. /// /// - Parameter c: The character to append to the character view. public mutating func append(_ c: Character) { switch c._representation { case .small(let _63bits): let bytes = Character._smallValue(_63bits) _core.append(contentsOf: Character._SmallUTF16(bytes)) case .large(_): _core.append(String(c)._core) } } /// Appends the characters in the given sequence to the character view. /// /// - Parameter newElements: A sequence of characters. public mutating func append<S : Sequence>(contentsOf newElements: S) where S.Iterator.Element == Character { reserveCapacity(_core.count + newElements.underestimatedCount) for c in newElements { self.append(c) } } /// Creates a new character view containing the characters in the given /// sequence. /// /// - Parameter characters: A sequence of characters. public init<S : Sequence>(_ characters: S) where S.Iterator.Element == Character { self = String.CharacterView() self.append(contentsOf: characters) } } // Algorithms extension String.CharacterView { /// Accesses the characters in the given range. /// /// The example below uses this subscript to access the characters up to, but /// not including, the first comma (`","`) in the string. /// /// let str = "All this happened, more or less." /// let i = str.characters.index(of: ",")! /// let substring = str.characters[str.characters.startIndex ..< i] /// print(String(substring)) /// // Prints "All this happened" /// /// - Complexity: O(*n*) if the underlying string is bridged from /// Objective-C, where *n* is the length of the string; otherwise, O(1). public subscript(bounds: Range<Index>) -> String.CharacterView { let unicodeScalarRange = bounds.lowerBound._base..<bounds.upperBound._base return String.CharacterView(unicodeScalars[unicodeScalarRange]._core, coreOffset: unicodeScalarRange.lowerBound._position) } } extension String.CharacterView { @available(*, unavailable, renamed: "replaceSubrange") public mutating func replaceRange<C>( _ subRange: Range<Index>, with newElements: C ) where C : Collection, C.Iterator.Element == Character { Builtin.unreachable() } @available(*, unavailable, renamed: "append(contentsOf:)") public mutating func appendContentsOf<S : Sequence>(_ newElements: S) where S.Iterator.Element == Character { Builtin.unreachable() } }
36.165957
87
0.658607
f5ef8e07baefe755f1d2ef03ae5556b7738a140d
19,429
// // YPLibraryVC.swift // YPImagePicker // // Created by Sacha Durand Saint Omer on 27/10/16. // Copyright © 2016 Yummypets. All rights reserved. // import UIKit import Photos public class YPLibraryVC: UIViewController, YPPermissionCheckable { internal weak var delegate: YPLibraryViewDelegate? internal var v: YPLibraryView! internal var isProcessing = false // true if video or image is in processing state internal var multipleSelectionEnabled = false internal var initialized = false internal var selection = [YPLibrarySelection]() internal var currentlySelectedIndex: Int = 0 internal let mediaManager = LibraryMediaManager() internal var latestImageTapped = "" internal let panGestureHelper = PanGestureHelper() // MARK: - Init public required init() { super.init(nibName: nil, bundle: nil) title = YPConfig.wordings.libraryTitle } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } var cropType = YPCropType.none { didSet { guard isViewLoaded else { return } v.cropType = cropType } } func setAlbum(_ album: YPAlbum) { title = album.title mediaManager.collection = album.collection currentlySelectedIndex = 0 if !multipleSelectionEnabled { selection.removeAll() } refreshMediaRequest() } func initialize() { mediaManager.initialize() mediaManager.v = v if mediaManager.fetchResult != nil { return } setupCollectionView() registerForLibraryChanges() panGestureHelper.registerForPanGesture(on: v) registerForTapOnPreview() refreshMediaRequest() if YPConfig.library.defaultMultipleSelection { multipleSelectionButtonTapped() } v.assetViewContainer.multipleSelectionButton.isHidden = !(YPConfig.library.maxNumberOfItems > 1) v.maxNumberWarningLabel.text = String(format: YPConfig.wordings.warningMaxItemsLimit, YPConfig.library.maxNumberOfItems) } // MARK: - View Lifecycle public override func loadView() { v = YPLibraryView.xibView() v.cropType = cropType view = v } public override func viewDidLoad() { super.viewDidLoad() // When crop area changes in multiple selection mode, // we need to update the scrollView values in order to restore // them when user selects a previously selected item. v.assetZoomableView.cropAreaDidChange = { [weak self] in guard let strongSelf = self else { return } strongSelf.updateCropInfo() } } public override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) v.assetViewContainer.squareCropButton .addTarget(self, action: #selector(squareCropButtonTapped), for: .touchUpInside) v.assetViewContainer.multipleSelectionButton .addTarget(self, action: #selector(multipleSelectionButtonTapped), for: .touchUpInside) // Forces assetZoomableView to have a contentSize. // otherwise 0 in first selection triggering the bug : "invalid image size 0x0" // Also fits the first element to the square if the onlySquareFromLibrary = true if !YPConfig.library.onlySquare && v.assetZoomableView.contentSize == CGSize(width: 0, height: 0) { v.assetZoomableView.setZoomScale(1, animated: false) } // Activate multiple selection when using `minNumberOfItems` if YPConfig.library.minNumberOfItems > 1 { multipleSelectionButtonTapped() } } public override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) pausePlayer() NotificationCenter.default.removeObserver(self) PHPhotoLibrary.shared().unregisterChangeObserver(self) } // MARK: - Crop control @objc func squareCropButtonTapped() { doAfterPermissionCheck { [weak self] in self?.v.assetViewContainer.squareCropButtonTapped() } } // MARK: - Multiple Selection @objc func multipleSelectionButtonTapped() { if !multipleSelectionEnabled { selection.removeAll() } // Prevent desactivating multiple selection when using `minNumberOfItems` if YPConfig.library.minNumberOfItems > 1 && multipleSelectionEnabled { return } multipleSelectionEnabled = !multipleSelectionEnabled if multipleSelectionEnabled { if selection.isEmpty { let asset = mediaManager.fetchResult[currentlySelectedIndex] selection = [ YPLibrarySelection(index: currentlySelectedIndex, cropRect: v.currentCropRect(), scrollViewContentOffset: v.assetZoomableView!.contentOffset, scrollViewZoomScale: v.assetZoomableView!.zoomScale, assetIdentifier: asset.localIdentifier) ] } } else { selection.removeAll() addToSelection(indexPath: IndexPath(row: currentlySelectedIndex, section: 0)) } v.assetViewContainer.setMultipleSelectionMode(on: multipleSelectionEnabled) v.collectionView.reloadData() checkLimit() delegate?.libraryViewDidToggleMultipleSelection(enabled: multipleSelectionEnabled) } // MARK: - Tap Preview func registerForTapOnPreview() { let tapImageGesture = UITapGestureRecognizer(target: self, action: #selector(tappedImage)) v.assetViewContainer.addGestureRecognizer(tapImageGesture) } @objc func tappedImage() { if !panGestureHelper.isImageShown { panGestureHelper.resetToOriginalState() // no dragup? needed? dragDirection = .up v.refreshImageCurtainAlpha() } } // MARK: - Permissions func doAfterPermissionCheck(block:@escaping () -> Void) { checkPermissionToAccessPhotoLibrary { hasPermission in if hasPermission { block() } } } func checkPermission() { checkPermissionToAccessPhotoLibrary { [weak self] hasPermission in guard let strongSelf = self else { return } if hasPermission && !strongSelf.initialized { strongSelf.initialize() strongSelf.initialized = true } } } // Async beacause will prompt permission if .notDetermined // and ask custom popup if denied. func checkPermissionToAccessPhotoLibrary(block: @escaping (Bool) -> Void) { // Only intilialize picker if photo permission is Allowed by user. let status = PHPhotoLibrary.authorizationStatus() switch status { case .authorized: block(true) case .restricted, .denied: let popup = YPPermissionDeniedPopup() let alert = popup.popup(cancelBlock: { block(false) }) present(alert, animated: true, completion: nil) case .notDetermined: // Show permission popup and get new status PHPhotoLibrary.requestAuthorization { s in DispatchQueue.main.async { block(s == .authorized) } } default: block(true) } } func refreshMediaRequest() { let options = buildPHFetchOptions() if let collection = mediaManager.collection { mediaManager.fetchResult = PHAsset.fetchAssets(in: collection, options: options) } else { mediaManager.fetchResult = PHAsset.fetchAssets(with: options) } if mediaManager.fetchResult.count > 0 { changeAsset(mediaManager.fetchResult[0]) v.collectionView.reloadData() v.collectionView.selectItem(at: IndexPath(row: 0, section: 0), animated: false, scrollPosition: UICollectionView.ScrollPosition()) if !multipleSelectionEnabled { addToSelection(indexPath: IndexPath(row: 0, section: 0)) } } else { delegate?.noPhotosForOptions() } scrollToTop() } func buildPHFetchOptions() -> PHFetchOptions { // Sorting condition if let userOpt = YPConfig.library.options { return userOpt } let options = PHFetchOptions() options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)] options.predicate = YPConfig.library.mediaType.predicate() return options } func scrollToTop() { tappedImage() v.collectionView.contentOffset = CGPoint.zero } // MARK: - ScrollViewDelegate public func scrollViewDidScroll(_ scrollView: UIScrollView) { if scrollView == v.collectionView { mediaManager.updateCachedAssets(in: self.v.collectionView) } } func changeAsset(_ asset: PHAsset) { latestImageTapped = asset.localIdentifier delegate?.libraryViewStartedLoading() let completion = { self.v.hideLoader() self.v.hideGrid() self.delegate?.libraryViewFinishedLoading() self.v.assetViewContainer.refreshSquareCropButton() self.updateCropInfo() } DispatchQueue.global(qos: .userInitiated).async { switch asset.mediaType { case .image: self.v.assetZoomableView.setImage(asset, mediaManager: self.mediaManager, storedCropPosition: self.fetchStoredCrop(), completion: completion) case .video: self.v.assetZoomableView.setVideo(asset, mediaManager: self.mediaManager, storedCropPosition: self.fetchStoredCrop(), completion: completion) case .audio, .unknown: () } } } // MARK: - Verification private func fitsVideoLengthLimits(asset: PHAsset) -> Bool { guard asset.mediaType == .video else { return true } let tooLong = asset.duration > YPConfig.video.libraryTimeLimit let tooShort = asset.duration < YPConfig.video.minimumTimeLimit if tooLong || tooShort { DispatchQueue.main.async { let alert = tooLong ? YPAlert.videoTooLongAlert(self.view) : YPAlert.videoTooShortAlert(self.view) self.present(alert, animated: true, completion: nil) } return false } return true } // MARK: - Stored Crop Position internal func updateCropInfo(shouldUpdateOnlyIfNil: Bool = false) { guard let selectedAssetIndex = selection.firstIndex(where: { $0.index == currentlySelectedIndex }) else { return } if shouldUpdateOnlyIfNil && selection[selectedAssetIndex].scrollViewContentOffset != nil { return } // Fill new values var selectedAsset = selection[selectedAssetIndex] selectedAsset.scrollViewContentOffset = v.assetZoomableView.contentOffset selectedAsset.scrollViewZoomScale = v.assetZoomableView.zoomScale selectedAsset.cropRect = v.currentCropRect() // Replace selection.remove(at: selectedAssetIndex) selection.insert(selectedAsset, at: selectedAssetIndex) } internal func fetchStoredCrop() -> YPLibrarySelection? { if self.multipleSelectionEnabled, self.selection.contains(where: { $0.index == self.currentlySelectedIndex }) { guard let selectedAssetIndex = self.selection .firstIndex(where: { $0.index == self.currentlySelectedIndex }) else { return nil } return self.selection[selectedAssetIndex] } return nil } internal func hasStoredCrop(index: Int) -> Bool { return self.selection.contains(where: { $0.index == index }) } // MARK: - Fetching Media private func fetchImageAndCrop(for asset: PHAsset, withCropRect: CGRect? = nil, callback: @escaping (_ photo: UIImage, _ exif: [String : Any]) -> Void) { delegate?.libraryViewStartedLoading() let cropRect = withCropRect ?? DispatchQueue.main.sync { v.currentCropRect() } let ts = targetSize(for: asset, cropRect: cropRect) mediaManager.imageManager?.fetchImage(for: asset, cropRect: cropRect, targetSize: ts, callback: callback) } private func checkVideoLengthAndCrop(for asset: PHAsset, withCropRect: CGRect? = nil, callback: @escaping (_ videoURL: URL) -> Void) { if fitsVideoLengthLimits(asset: asset) == true { delegate?.libraryViewStartedLoading() let normalizedCropRect = withCropRect ?? DispatchQueue.main.sync { v.currentCropRect() } let ts = targetSize(for: asset, cropRect: normalizedCropRect) let xCrop: CGFloat = normalizedCropRect.origin.x * CGFloat(asset.pixelWidth) let yCrop: CGFloat = normalizedCropRect.origin.y * CGFloat(asset.pixelHeight) let resultCropRect = CGRect(x: xCrop, y: yCrop, width: ts.width, height: ts.height) mediaManager.fetchVideoUrlAndCrop(for: asset, cropRect: resultCropRect, callback: callback) } } public func selectedMedia(photoCallback: @escaping (_ photo: YPMediaPhoto) -> Void, videoCallback: @escaping (_ videoURL: YPMediaVideo) -> Void, multipleItemsCallback: @escaping (_ items: [YPMediaItem]) -> Void) { DispatchQueue.global(qos: .userInitiated).async { let selectedAssets: [(asset: PHAsset, cropRect: CGRect?)] = self.selection.map { guard let asset = PHAsset.fetchAssets(withLocalIdentifiers: [$0.assetIdentifier], options: PHFetchOptions()).firstObject else { fatalError() } return (asset, $0.cropRect) } // Multiple selection if self.multipleSelectionEnabled && self.selection.count > 1 { // Check video length for asset in selectedAssets { if self.fitsVideoLengthLimits(asset: asset.asset) == false { return } } // Fill result media items array var resultMediaItems: [YPMediaItem] = [] let asyncGroup = DispatchGroup() for asset in selectedAssets { asyncGroup.enter() switch asset.asset.mediaType { case .image: self.fetchImageAndCrop(for: asset.asset, withCropRect: asset.cropRect) { image, exifMeta in let photo = YPMediaPhoto(image: image.resizedImageIfNeeded(), exifMeta: exifMeta, asset: asset.asset) resultMediaItems.append(YPMediaItem.photo(p: photo)) asyncGroup.leave() } case .video: self.checkVideoLengthAndCrop(for: asset.asset, withCropRect: asset.cropRect) { videoURL in let videoItem = YPMediaVideo(thumbnail: thumbnailFromVideoPath(videoURL), videoURL: videoURL, asset: asset.asset) resultMediaItems.append(YPMediaItem.video(v: videoItem)) asyncGroup.leave() } default: break } } asyncGroup.notify(queue: .main) { multipleItemsCallback(resultMediaItems) self.delegate?.libraryViewFinishedLoading() } } else { let asset = selectedAssets.first!.asset switch asset.mediaType { case .video: self.checkVideoLengthAndCrop(for: asset, callback: { videoURL in DispatchQueue.main.async { self.delegate?.libraryViewFinishedLoading() let video = YPMediaVideo(thumbnail: thumbnailFromVideoPath(videoURL), videoURL: videoURL, asset: asset) videoCallback(video) } }) case .image: self.fetchImageAndCrop(for: asset) { image, exifMeta in DispatchQueue.main.async { self.delegate?.libraryViewFinishedLoading() let photo = YPMediaPhoto(image: image.resizedImageIfNeeded(), exifMeta: exifMeta, asset: asset) photoCallback(photo) } } case .audio, .unknown: return } } } } // MARK: - TargetSize private func targetSize(for asset: PHAsset, cropRect: CGRect) -> CGSize { var width = (CGFloat(asset.pixelWidth) * cropRect.width).rounded(.toNearestOrEven) var height = (CGFloat(asset.pixelHeight) * cropRect.height).rounded(.toNearestOrEven) // round to lowest even number width = (width.truncatingRemainder(dividingBy: 2) == 0) ? width : width - 1 height = (height.truncatingRemainder(dividingBy: 2) == 0) ? height : height - 1 return CGSize(width: width, height: height) } // MARK: - Player func pausePlayer() { v.assetZoomableView.videoView.pause() } // MARK: - Deinit deinit { PHPhotoLibrary.shared().unregisterChangeObserver(self) } }
38.096078
158
0.558341
5680618bb2e09f2ca281e477d56a37fa583c03f0
7,027
// Copyright © 2021 Saleem Abdulrasool <[email protected]> // SPDX-License-Identifier: BSD-3-Clause import XCTest @testable import SwiftWin32 final class ViewTests: XCTestCase { func testConvertSameParent() { let window = View(frame: Rect(x: 0.0, y: 0.0, width: 1000, height: 1000)) let textfield: View = View(frame: Rect(x: 4.0, y: 92.0, width: 254.0, height: 17.0)) let password: View = View(frame: Rect(x: 4.0, y: 113.0, width: 254.0, height: 17.0)) window.addSubview(password) window.addSubview(textfield) let boundsRect = Rect(x: 0, y: 0, width: 254.0, height: 17.0) let convertRect = textfield.convert(boundsRect, to: password) let convertPoint = textfield.convert(textfield.bounds.origin, to: password) XCTAssertEqual(convertRect, Rect(x: 0.0, y: -21.0, width: 254.0, height: 17.0)) XCTAssertEqual(convertPoint, Point(x: 0.0, y: -21.0)) } func testConvertWithRotationsAndBounds() { let root = View(frame: Rect(x: 0.0, y: 0.0, width: 1000, height: 1000)) let childA = View(frame: Rect(x: 4.0, y: 92.0, width: 254.0, height: 17.0)) childA.transform = AffineTransform(rotationAngle: 110) childA.bounds = Rect(x: 144.0, y: 23.0, width: 20, height: 15) let childB = View(frame: Rect(x: 12.0, y: 150.0, width: 400.0, height: 400.0)) childB.transform = AffineTransform(rotationAngle: -30) let grandChild = View(frame: Rect(x: 40.0, y: 113.0, width: 10, height: 10)) grandChild.transform = AffineTransform(rotationAngle: 42) grandChild.bounds = Rect(x: 4.0, y: 3.0, width: 20, height: 15) root.addSubview(childA) root.addSubview(childB) childB.addSubview(grandChild) // Test data comes from the UIKit implementation, running on an iPhone, // and so deviation is expected. let accuracy = 0.00000000001 let inputPoint = Point(x: 45, y: 115) var point = grandChild.convert(inputPoint, to: childA) XCTAssertEqual(point.x, -72.9941233911901, accuracy: accuracy) XCTAssertEqual(point.y, -114.85495931677, accuracy: accuracy) point = grandChild.convert(inputPoint, from: childA) XCTAssertEqual(point.x, 80.12346855145998, accuracy: accuracy) XCTAssertEqual(point.y, -140.97315764408575, accuracy: accuracy) let inputRect = Rect(origin: Point(x: 45, y: 115), size: Size(width: 13, height: 14)) var rect = grandChild.convert(inputRect, to: childB) XCTAssertEqual(rect.origin.x, 123.17714789769627, accuracy: accuracy) XCTAssertEqual(rect.origin.y, 30.274792065592464, accuracy: accuracy) XCTAssertEqual(rect.size.width, 18.031110765667435, accuracy: accuracy) XCTAssertEqual(rect.size.height, 17.514574532740156, accuracy: accuracy) rect = grandChild.convert(inputRect, to: childA) XCTAssertEqual(rect.origin.x, -91.9808292852884, accuracy: accuracy) XCTAssertEqual(rect.origin.y, -126.65734667117412, accuracy: accuracy) XCTAssertEqual(rect.size.width, 19.295318391541684, accuracy: accuracy) XCTAssertEqual(rect.size.height, 19.58870361060326, accuracy: accuracy) rect = grandChild.convert(inputRect, from: childA) XCTAssertEqual(rect.origin.x, 69.16410886522763, accuracy: accuracy) XCTAssertEqual(rect.origin.y, -160.22950933436533, accuracy: accuracy) XCTAssertEqual(rect.size.width, 19.295318391541684, accuracy: accuracy) XCTAssertEqual(rect.size.height, 19.58870361060326, accuracy: accuracy) } func testConvertWithAllTransformsAndBounds() { let root = View(frame: Rect(x: 0.0, y: 0.0, width: 1000, height: 1000)) let childA = View(frame: Rect(x: 4.0, y: 92.0, width: 254.0, height: 17.0)) childA.transform = AffineTransform(translationX: 68, y: 419) childA.bounds = Rect(x: 144.0, y: 23.0, width: 20, height: 15) let childB = View(frame: Rect(x: 12.0, y: 150.0, width: 400.0, height: 400.0)) childB.transform = AffineTransform(scaleX: 7, y: 18) let grandChild = View(frame: Rect(x: 40.0, y: 113.0, width: 10, height: 10)) grandChild.transform = AffineTransform(rotationAngle: 42) grandChild.bounds = Rect(x: 4.0, y: 3.0, width: 20, height: 15) root.addSubview(childA) root.addSubview(childB) childB.addSubview(grandChild) // Test data comes from the UIKit implementation, running on an iPhone, // and so deviation is expected. let accuracy = 0.00000000001 let inputPoint = Point(x: 45, y: 115) var point = grandChild.convert(inputPoint, to: childA) XCTAssertEqual(point.x, -334.36130105218615, accuracy: accuracy) XCTAssertEqual(point.y, -2878.791401230013, accuracy: accuracy) point = grandChild.convert(inputPoint, from: childA) XCTAssertEqual(point.x, -129.11445551798738, accuracy: accuracy) XCTAssertEqual(point.y, 98.14414561159256, accuracy: accuracy) let inputRect = Rect(origin: Point(x: 45, y: 115), size: Size(width: 13, height: 14)) var rect = grandChild.convert(inputRect, to: childB) XCTAssertEqual(rect.origin.x, 123.17714789769627, accuracy: accuracy) XCTAssertEqual(rect.origin.y, 30.274792065592464, accuracy: accuracy) XCTAssertEqual(rect.size.width, 18.031110765667435, accuracy: accuracy) XCTAssertEqual(rect.size.height, 17.514574532740156, accuracy: accuracy) rect = grandChild.convert(inputRect, to: childA) XCTAssertEqual(rect.origin.x, -370.7599647161262, accuracy: accuracy) XCTAssertEqual(rect.origin.y, -3194.0537428193356, accuracy: accuracy) XCTAssertEqual(rect.size.width, 126.21777535967215, accuracy: accuracy) XCTAssertEqual(rect.size.height, 315.26234158932266, accuracy: accuracy) rect = grandChild.convert(inputRect, from: childA) XCTAssertEqual(rect.origin.x, -130.5701354815033, accuracy: accuracy) XCTAssertEqual(rect.origin.y, 97.83304592215717, accuracy: accuracy) XCTAssertEqual(rect.size.width, 1.4556799635159337, accuracy: accuracy) XCTAssertEqual(rect.size.height, 2.0132111355644327, accuracy: accuracy) } func testViewTraitCollection() { let window: Window = Window(frame: Rect(x: 0.0, y: 0.0, width: 640, height: 480)) let view: View = View(frame: .zero) XCTAssertTrue(view.traitCollection === TraitCollection.current) window.addSubview(view) XCTAssertTrue(view.traitCollection === TraitCollection.current) let session: SceneSession = SceneSession(identifier: UUID().uuidString, role: .windowApplication) let scene: WindowScene = WindowScene(session: session, connectionOptions: Scene.ConnectionOptions()) window.windowScene = scene // FIXME(compnerd) the view.window is not setup properly // XCTAssertTrue(view.traitCollection === scene.screen.traitCollection) } static var allTests = [ ("testConvertSameParent", testConvertSameParent), ("testConvertWithRotationsAndBounds", testConvertWithRotationsAndBounds), ("testConvertWithAllTransformsAndBounds", testConvertWithAllTransformsAndBounds), ("testViewTraitCollection", testViewTraitCollection), ] }
42.847561
89
0.71453
760968423764c203fb2125a0d89b57e5720ee657
1,637
// // Date.swift // Gotcha // // Created by Don Miller on 3/8/18. // Copyright © 2018 GroundSpeed. All rights reserved. // import UIKit extension Date { func minDate() -> Date { let gregorian: NSCalendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)! let currentDate: Date = Date() let components: NSDateComponents = NSDateComponents() components.year = -150 return gregorian.date(byAdding: components as DateComponents, to: currentDate, options: NSCalendar.Options(rawValue: 0))! } func maxDate() -> Date { let gregorian: NSCalendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)! let currentDate: Date = Date() let components: NSDateComponents = NSDateComponents() components.year = 150 return gregorian.date(byAdding: components as DateComponents, to: currentDate, options: NSCalendar.Options(rawValue: 0))! } func toString(format:String) -> String { let formatter = DateFormatter() formatter.dateFormat = format let result = formatter.string(from: self) return result } func toLongString() -> String? { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "EEEE, MMM d" return dateFormatter.string(from: self).capitalized } var toUTC:String { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss" let result = formatter.string(from: self) return result } }
29.232143
129
0.626145
4be259afa741751585310a7e0ec076c8d1a54199
8,244
// // GameModel.swift // myTicTacToe // // Created by 郑虎 on 15 年 3. 11.. // Copyright (c) 2015年 郑虎. All rights reserved. // import UIKit protocol GameModelProtocol : class { func placeAPiece(location : (Int, Int), side : Side) func sideChanged(side : Side) func win(side : Side, point : (Int, Int), direction: Direction) } class GameModel : NSObject { let dimension : Int let threshold : Int var finished = false var side : Side { didSet { delegate.sideChanged(side) } } var gameboard : SquareGameboard<PieceObject> let delegate : GameModelProtocol var queue : [PlaceCommand] var timer : NSTimer let maxCommands = 5 let queueDelay = 0.1 init(dimension d: Int, threshold t: Int, delegate: GameModelProtocol) { dimension = d threshold = t side = Side.Black self.delegate = delegate queue = [PlaceCommand]() timer = NSTimer() gameboard = SquareGameboard(dimension: d, initialValue: .Empty) super.init() } func reset() { side = Side.Black gameboard.setAll(.Empty) queue.removeAll(keepCapacity: true) timer.invalidate() } func queueMove(side : Side, location : (Int, Int), completion : (Bool) -> ()) { if queue.count > maxCommands { return } let command = PlaceCommand(s : side, l : location ,c : completion) queue.append(command) if (!timer.valid) { timerFired(timer) } } func timerFired(timer: NSTimer) { if queue.count == 0 { return } // Go through the queue until a valid command is run or the queue is empty var changed = false while queue.count > 0 { let command = queue[0] queue.removeAtIndex(0) changed = performMove(command.location, side: command.side) command.completion(changed) if changed { // If the command doesn't change anything, we immediately run the next one break } } if changed { self.timer = NSTimer.scheduledTimerWithTimeInterval(queueDelay, target: self, selector: Selector("timerFired:"), userInfo: nil, repeats: false) } } func placeAPiece(location : (Int, Int), side : Side) { let (x, y) = location switch gameboard[x, y] { case .Empty: gameboard[x, y] = PieceObject.Piece(side) delegate.placeAPiece(location, side : side) default: break } } func insertTileAtRandomLocation(value: Int) { let openSpots = gameboardEmptySpots() if openSpots.count == 0 { // No more open spots; don't even bother return } // Randomly select an open spot, and put a new tile there let idx = Int(arc4random_uniform(UInt32(openSpots.count-1))) let (x, y) = openSpots[idx] placeAPiece((x, y), side: side) } func gameboardEmptySpots() -> [(Int, Int)] { var buffer = Array<(Int, Int)>() for i in 0..<dimension { for j in 0..<dimension { switch gameboard[i, j] { case .Empty: buffer += [(i, j)] default: break } } } return buffer } func performMove(location : (Int, Int), side : Side) -> Bool { if !finished { let (x, y) = location switch gameboard[x, y] { case PieceObject.Empty: gameboard[x, y] = PieceObject.Piece(side) delegate.placeAPiece(location, side: side) self.side.alt() switch self.side { case Side.Black: println("Black!") default: println("White!") } println(sideHasWon(side)) return true default: return false } } return false } // This is the very first, brutal and primitive version // Further versions should contain analysis of the situation // The model should be upgraded. // It's actually KMP isn't it.. // Maybe we should invent a new data structure for this simple and specific problem // The points should record more things I think... // Maybe a new algorithm for updating and inserting.. // Maybe we should put it off func win(side : Side, point : (Int, Int), direction: Direction) { delegate.win(side, point: point, direction: direction) } func sideHasWon(side : Side) -> (result: Bool, point: (Int, Int), direction: Direction) { // for i in 0..<dimension { // We need a scan algorithm... // We need ALGORITHM! var point : (Int ,Int) for i in 0..<dimension - threshold + 1 { for j in 0..<dimension - threshold + 1 { // ba jindu chaoqian gangan caishi weiyi zhengtu... // zhenglu, zhengdao! } } // var result : Bool let a = aPointHasWon(side, point: (0, 0), direction: Direction.Skew) if (a.result) { return a } let b = aPointHasWon(side, point: (dimension - 1, 0), direction: Direction.Subskew) if (b.result) { return b } for i in 0..<dimension { for j in 0..<dimension - threshold + 1 { let a = aPointHasWon(side, point: (i, j), direction: Direction.Horizontal) if (a.result) { return a } } } for i in 0..<dimension - threshold + 1 { for j in 0..<dimension { let a = aPointHasWon(side, point: (i, j), direction: Direction.Vertical) if (a.result) { return a } } } // Scan vertically return (false, (-1, -1), Direction.Skew) } func aPointHasWon(side: Side, point: (x: Int, y: Int), direction: Direction) -> (result: Bool, point: (Int, Int), direction: Direction) { var (x, y) = point var _result: Bool for i in 0..<threshold { switch(gameboard[x, y]) { case .Piece(Side.Black): if side != Side.Black { return (false, (-1, -1), Direction.Skew) } case .Piece(Side.White): if side != Side.White { return (false, (-1, -1), Direction.Skew) } default: return (false, (-1, -1), Direction.Skew) } switch(direction) { case Direction.Horizontal: y++ case Direction.Vertical: x++ case Direction.Skew: x++ y++ case Direction.Subskew: x-- y++ } } return (true, point, direction) } // How to highlight the pieces leading to victory? // It is more about knowledge and less about intelligence. // Diligence and will // A new function for winning // After a winner is detected, the gameboard is frozen and an action is fired // We need to display the animation for winner, for only once // After the board is frozen, any further moves will be banned. }
26.338658
141
0.477681
4b6ec696636faa17338c0d7ce5172946a136065d
566
import Vapor struct MicrosoftCallbackBody: Content { let code: String let clientId: String let clientSecret: String let redirectURI: String let scope: String let grantType: String = "authorization_code" static var defaultContentType: MediaType = .urlEncodedForm enum CodingKeys: String, CodingKey { case code = "code" case clientId = "client_id" case clientSecret = "client_secret" case redirectURI = "redirect_uri" case grantType = "grant_type" case scope = "scope" } }
25.727273
62
0.655477
907069863a6394f3dfc447ce11b0ea44a1095a75
289
import SwiftUI extension HorizontalAlignment { enum NoteCenter: AlignmentID { static func defaultValue(in context: ViewDimensions) -> CGFloat { context[HorizontalAlignment.center] } } static let noteCenter = HorizontalAlignment(NoteCenter.self) }
24.083333
73
0.698962
46e15bfefef72313d97b7ea6164e688a0827fa30
1,422
// // AppDelegate.swift // loteria // // Created by Henrico Lazuroz on 14/06/20. // Copyright © 2020 Henrico Lazuroz. 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. } }
37.421053
179
0.748242
ebe58e11a42f8c84bde4d5d3b0287083870d1731
6,086
// Copyright (C) 2020 Parrot Drones SAS // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the // distribution. // * Neither the name of the Parrot Company nor the names // of its contributors may be used to endorse or promote products // derived from this software without specific prior written // permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // PARROT COMPANY BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS // OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED // AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT // OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF // SUCH DAMAGE. import Foundation /// Mission manager backend protocol public protocol MissionUpdaterBackend: AnyObject { /// Upload a mission to the server /// /// - Parameters: /// - filePath: Internal id (given by the drone when the mission was installed). /// - overwrite: overwrite the mission if it is present on drone. func upload(filePath: URL, overwrite: Bool) -> CancelableCore? /// Delete a mission /// /// - Parameters: /// - uid:Internal id (given by the drone when the mission was installed). /// - success:true if the delete was successfull, else false func delete(uid: String, success: @escaping (Bool) -> Void) /// Browse all missions. func browse() /// Mandatory to omplete the installation of mission. /// The drone will reboot. func complete() } public class MissionUpdaterCore: PeripheralCore, MissionUpdater { /// Implementation backend private unowned let backend: MissionUpdaterBackend public var missions: [String: Mission] { return _missions } private(set) public var _missions: [String: MissionCore] = [:] private(set) public var state: MissionUpdaterUploadState? private(set) public var currentFilePath: String? private(set) public var currentProgress: Int? /// Constructor /// /// - Parameters: /// - store: store where this peripheral will be stored. /// - backend: mission backend. public init(store: ComponentStoreCore, backend: MissionUpdaterBackend) { self.backend = backend super.init(desc: Peripherals.missionsUpdater, store: store) } /// Upload a mission to the server /// /// - Parameters: /// - filePath: Internal id (given by the drone when the mission was installed). /// - overwrite: override the mission if it is present on drone. public func upload(filePath: URL, overwrite: Bool) -> CancelableCore? { return self.backend.upload(filePath: filePath, overwrite: overwrite) } /// Delete a mission /// /// - Parameters: /// - uid:Internal id (given by the drone when the mission was installed). /// - success:true if the delete was successfull, else false public func delete(uid: String, success: @escaping (Bool) -> Void) { return self.backend.delete(uid: uid, success: success) } /// Browse all missions. public func browse() { self.backend.browse() } /// Mandatory to omplete the installation of mission. /// The drone will reboot. public func complete() { self.backend.complete() } } extension MissionUpdaterCore { /// Updates the upload state. /// /// - Parameter state: new upload state /// - Returns: self to allow call chaining /// - Note: Changes are not notified until notifyUpdated() is called. @discardableResult public func update(state newValue: MissionUpdaterUploadState?) -> MissionUpdaterCore { if self.state != newValue { self.state = newValue markChanged() } return self } /// Updates the upload progress. /// /// - Parameter progress: new update progress /// - Returns: self to allow call chaining /// - Note: Changes are not notified until notifyUpdated() is called. @discardableResult public func update(progress newValue: Int?) -> MissionUpdaterCore { if self.currentProgress != newValue { self.currentProgress = newValue markChanged() } return self } /// Updates the file path. /// /// - Parameter filePath: new file path /// - Returns: self to allow call chaining /// - Note: Changes are not notified until notifyUpdated() is called. @discardableResult public func update(filePath newValue: String?) -> MissionUpdaterCore { if self.currentFilePath != newValue { self.currentFilePath = newValue markChanged() } return self } /// Updates the missions array /// /// - Parameter missions: new missions array /// - Returns: self to allow call chaining /// - Note: Changes are not notified until notifyUpdated() is called. @discardableResult public func update(missions newValue: [String: MissionCore]) -> MissionUpdaterCore { if _missions != newValue { _missions = newValue markChanged() } return self } }
36.443114
109
0.661847
d5b120e2f8fbbe1e24de391a85407ee6a57ee6d8
3,655
// Copyright 2020 Google LLC. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { if let windowScene = scene as? UIWindowScene { let window = UIWindow(windowScene: windowScene) let controller = UIViewController() controller.view = MyView() window.rootViewController = controller window.makeKeyAndVisible() self.window = window } } } extension CGRect { init (center: CGPoint, radius: CGFloat) { self.init(x:center.x - radius, y:center.y - radius, width:radius * 2.0, height:radius * 2.0) } } class MyView: UIView { required init?(coder: NSCoder) { super.init(coder: coder) setup() } override init(frame: CGRect) { super.init(frame: frame) setup() } var angle: Double = 0.0 func setup() { Timer.scheduledTimer(withTimeInterval: 1/60, repeats: true) { [weak self] timer in if (self != nil) { self!.angle += 0.01 self!.setNeedsDisplay() } } } override func draw(_ rect: CGRect) { let context = UIGraphicsGetCurrentContext()! context.setFillColor(UIColor.black.cgColor) context.fill(rect) let timeAtStart: CFAbsoluteTime = CFAbsoluteTimeGetCurrent() srand48(0) for _ in 0..<10000 { switch nextInt(2) { case 0: let radius: Double = nextDouble(min(Double(rect.width), Double(rect.height)) / 8) setColor(context, 0xFF000000 + nextInt(0x00FFFFFF)) let rect: CGRect = CGRect( center: CGPoint(x: nextDouble(Double(rect.width) - radius), y: nextDouble(Double(rect.height) - radius)), radius: CGFloat(radius) ) context.fillEllipse(in: rect) case 1: setColor(context, nextInt(0xFFFFFFFF)) let w: Double = nextDouble(Double(rect.width) / 4) let h: Double = nextDouble(Double(rect.height) / 4) let x: Double = nextDouble(Double(rect.width) - w) let y: Double = nextDouble(Double(rect.height) - h) context.saveGState() context.translateBy(x: CGFloat(x + w / 2), y: CGFloat(y + h / 2)); context.rotate(by: CGFloat(angle * nextDouble(2.0) - 1.0)); context.translateBy(x: CGFloat(-(x + w / 2)), y: CGFloat(-(y + h / 2))); context.fill(CGRect(x: x, y: y, width: w, height: h)) context.restoreGState() default: fatalError("math is hard") } } let timeAtEnd: CFAbsoluteTime = CFAbsoluteTimeGetCurrent() print("total frame time: \(String(format: "%.1f", 1000 * (timeAtEnd - timeAtStart)))ms") print("--") } func nextInt(_ max: Int) -> Int { return Int(drand48() * Double(max)) } func nextDouble(_ max: Double) -> Double { return drand48() * max } func setColor(_ context: CGContext, _ color: Int) { context.setFillColor(CGColor( srgbRed: CGFloat(((color >> 16) & 0xFF)) / 255, green: CGFloat(((color >> 8) & 0xFF)) / 255, blue: CGFloat((color & 0xFF)) / 255, alpha: CGFloat(((color >> 24) & 0xFF)) / 255 )) } }
35.144231
127
0.5658
09b698ecb44e0865031cf5710449718111cd2d43
668
@objcMembers public final class HDKLanguageDistribution: NSObject, NSCoding { public let lang: String public let percentage: Int public init(lang: String, percentage: Int) { self.lang = lang self.percentage = percentage } public init?(coder aDecoder: NSCoder) { guard let lang = aDecoder.decodeObject(forKey: "lang") as? String else { return nil } self.lang = lang percentage = aDecoder.decodeInteger(forKey: "percentage") } public func encode(with aCoder: NSCoder) { aCoder.encode(lang, forKey: "lang") aCoder.encode(percentage, forKey: "percentage") } }
26.72
80
0.636228
2fdacd206a02dfde37900fa5c089b87800f26fd1
1,044
// // AnalyticsManager.swift // RSDemoProject // // Created by Mauricio Cousillas on 6/11/19. // Copyright © 2019 TopTier labs. All rights reserved. // import Foundation /** Base component in charge of logging events on the application. The goal of this class is to act as a proxy between the app and all the analytics services that are integrated. Broadcast every event to all of it associated services. */ class AnalyticsManager: AnalyticsService { /** List of services that will be notified. You can either customize this class and add new ones, or subclass it and override the variable. */ open var services = [FirebaseAnalyticsService()] static let shared = AnalyticsManager() public func setup() { services.forEach { $0.setup() } } public func identifyUser(with userId: String) { services.forEach { $0.identifyUser(with: userId) } } public func log(event: AnalyticsEvent) { services.forEach { $0.log(event: event) } } func reset() { services.forEach { $0.reset() } } }
24.857143
68
0.699234
67cc433be3c15f35501b04be69e36448ca0c5725
5,356
// // PageCollectionView.swift // CTPageSegmentView // // Created by Todd Cheng on 16/10/25. // Copyright © 2016年 Todd Cheng. All rights reserved. // import UIKit protocol PageCollectionViewDelegate: class { func pageCollectionView(_ pageCollectionView: PageCollectionView, progress: CGFloat, fromIndex: Int, toIndex: Int) } private let kPageCollectionViewCellIdentifier = "kPageCollectionViewCellIdentifier" class PageCollectionView: UIView { // MARK: Properties fileprivate var titles: [String] fileprivate var titleLabels: [UILabel] = [UILabel]() fileprivate var isDragging: Bool = true internal weak var delegate: PageCollectionViewDelegate? fileprivate lazy var containerCollectionView: UICollectionView = { [unowned self] in let layout = UICollectionViewFlowLayout() layout.itemSize = self.bounds.size layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.scrollDirection = .horizontal let collectionView = UICollectionView(frame: self.bounds, collectionViewLayout: layout) collectionView.bounces = false collectionView.isPagingEnabled = true collectionView.showsVerticalScrollIndicator = false collectionView.showsHorizontalScrollIndicator = false collectionView.dataSource = self // public protocol UICollectionViewDelegate : UIScrollViewDelegate collectionView.delegate = self collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: kPageCollectionViewCellIdentifier) return collectionView }() // MARK: Init Constructed Function init(frame: CGRect, titles: [String]) { self.titles = titles super.init(frame: frame) setupSubviews() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK:- Setup Subviews extension PageCollectionView { fileprivate func setupSubviews() { addSubview(containerCollectionView) } } // MARK:- UICollectionViewDataSource extension PageCollectionView: UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.titles.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kPageCollectionViewCellIdentifier, for: indexPath) for subview in cell.contentView.subviews { subview.removeFromSuperview() } let colorBackgroundView = UIView() colorBackgroundView.frame = cell.bounds colorBackgroundView.backgroundColor = UIColor(red: CGFloat(arc4random_uniform(256)) / 255.0, green: CGFloat(arc4random_uniform(256)) / 255.0, blue: CGFloat(arc4random_uniform(256)) / 255.0, alpha: 1.0) cell.contentView.addSubview(colorBackgroundView) let titleLabel = UILabel() titleLabel.frame = CGRect(x: 0, y: 0, width: colorBackgroundView.frame.width, height: 30) titleLabel.center = colorBackgroundView.center titleLabel.text = titles[indexPath.row] titleLabel.numberOfLines = 1 titleLabel.textAlignment = .center titleLabel.textColor = UIColor.black titleLabel.font = UIFont.systemFont(ofSize: 30) titleLabel.backgroundColor = UIColor.clear colorBackgroundView.addSubview(titleLabel) return cell } } // MARK:- UICollectionViewDelegate extension PageCollectionView: UICollectionViewDelegate { func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { isDragging = true } func scrollViewDidScroll(_ scrollView: UIScrollView) { if isDragging == false { return } if (scrollView.contentOffset.x.truncatingRemainder(dividingBy: scrollView.frame.width) == 0.0) { return } var progress: CGFloat = 0.0 let firstIndex = Int(scrollView.contentOffset.x / scrollView.frame.width) let secondIndex = firstIndex + 1 progress = scrollView.contentOffset.x / scrollView.frame.width - CGFloat(Int(scrollView.contentOffset.x / scrollView.frame.width)) delegate?.pageCollectionView(self, progress: progress, fromIndex: firstIndex, toIndex: secondIndex) } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { let scrollViewDidEndDeceleratingAtIndex = Int(scrollView.contentOffset.x / scrollView.frame.width) delegate?.pageCollectionView(self, progress: 1.0, fromIndex: scrollViewDidEndDeceleratingAtIndex, toIndex: scrollViewDidEndDeceleratingAtIndex) } } // MARK:- Open Functions extension PageCollectionView { internal func scrollToView(atIndex index: Int) { isDragging = false containerCollectionView.setContentOffset(CGPoint(x: CGFloat(index) * containerCollectionView.frame.width, y: 0), animated: true) } }
36.937931
151
0.68876
0e10b4d45cf3bf84280d29d477a29c345dc8efc9
2,625
// // Sidebar.swift // Mail Notifr // // Created by James Chen on 2021/06/15. // Copyright © 2021 ashchan.com. All rights reserved. // import SwiftUI struct Sidebar: View { @AppStorage(Accounts.storageKey) var accounts = Accounts() @Binding var selection: String? var body: some View { VStack { List { Text("Accounts") .font(.subheadline) .fontWeight(.semibold) .foregroundColor(.secondary) ForEach($accounts) { $account in NavigationLink( destination: AccountView(account: account), tag: account.email, selection: $selection ) { AvatarView(image: "person", backgroundColor: .green) Text(verbatim: account.email) } .padding(2) } Text("Preferences") .font(.subheadline) .fontWeight(.semibold) .foregroundColor(.secondary) NavigationLink( destination: SettingsView(), tag: "preferences", selection: $selection ) { AvatarView(image: "gearshape", backgroundColor: .blue) Text("General") } .padding(2) } .listStyle(.sidebar) Spacer() HStack { Button(action: { selection = "welcome" }) { Label("Add Account", systemImage: "plus.circle") } .buttonStyle(.plain) .foregroundColor(.primary) .padding(8) Spacer() } } } } struct AvatarView: View { var image: String var backgroundColor: Color var body: some View { Circle() .frame(width: 24, height: 24) .foregroundColor(backgroundColor) .overlay( Image(systemName: image) .resizable() .aspectRatio(contentMode: .fit) .frame(width: 14, height: 14) .foregroundColor(.white) ) } } struct Sidebar_Previews: PreviewProvider { static var previews: some View { Sidebar( accounts: [Account(email: "[email protected]")], selection: .constant("general") ) } }
27.34375
76
0.445714
b91999cda55b34639c2675ea768f4ebfc6aa2393
1,637
// // Error+Swerl.swift // Swerl // // Created by Phil Nash on 11/03/2019. // Copyright © 2019 Two Blue Cubes. All rights reserved. // https://github.com/philsquared/swerl/blob/master/LICENSE import Foundation public struct ResultNotSet: Error, Equatable { let message: String let file: String let line: UInt } public extension Result { // You can already convert from throws-to-Result by using the `catching` initialiser, // and Result-to-throws by using the `get()` method. // We add unwrap, that works like `get()`, but makes a new Error, capturing file/ line of the unwrap line func unwrap(_ file: String = #file, _ line: UInt = #line) throws -> Success { switch self { case .success(let value): return value case .failure(let error): throw ResultNotSet(message: "Result assumed to contain value, but actually held error: \(error)", file: file, line: line) } } // We can convert to an optional, obviously losing any error information func toOptional() -> Success? { switch self { case .success(let value): return value case .failure: return nil // loses information } } // We can assume we have a value - the equivalent of suffix `operator !` on Optional // - gives a hard error otherwise func assume() -> Success { switch self { case .success(let value): return value case .failure(let error): fatalError("Result assumed to contain value, but actually held error: \(error)") } } }
31.480769
133
0.617593
ab944a36b1c9455274c0b664633bd594199b0e31
714
// ˅ import Foundation // ˄ public class Display { // ˅ // ˄ // Column width public func getColumns() -> Int { // ˅ fatalError("An abstract method has been executed.") // ˄ } // Number of rows public func getRows() -> Int { // ˅ fatalError("An abstract method has been executed.") // ˄ } public func getLineText(row: Int) -> String { // ˅ fatalError("An abstract method has been executed.") // ˄ } // Show all public func show() { // ˅ for i in 0..<getRows() { print(getLineText(row: i)) } // ˄ } // ˅ // ˄ } // ˅ // ˄
14.875
59
0.435574
8f99d7de16bd1eb1be8552d15f14cba4a0a16d02
958
// // UIView.swift // ComposableStyling // // Created by Fujiki Takeshi on 2018/12/20. // Copyright © 2018 takecian. All rights reserved. // import UIKit public func styleViewBackgroundColor(_ color: UIColor) -> (UIView) -> Void { return { $0.backgroundColor = color } } public func styleViewBorder(color: UIColor, width: CGFloat) -> (UIView) -> Void { return { $0.layer.borderColor = color.cgColor $0.layer.borderWidth = width } } public func styleViewCornerRadius(_ cornerRadius: CGFloat) -> (UIView) -> Void { return { $0.layer.cornerRadius = cornerRadius $0.layer.masksToBounds = true } } public func styleViewShadow(color: CGColor, opacity: Float, offset: CGSize, radius: CGFloat) -> (UIView) -> Void { return { $0.layer.shadowColor = color $0.layer.shadowRadius = radius $0.layer.shadowOffset = offset $0.layer.shadowOpacity = opacity } }
24.564103
114
0.641962
91a2d98d343b468f562bd75547b8c83fd448dc73
1,086
// // DataAPI.swift // SwiftyPress // // Created by Basem Emara on 2018-06-12. // Copyright © 2019 Zamzam Inc. All rights reserved. // import Foundation.NSDate // MARK: - Services public protocol DataService { func fetchModified(after date: Date?, with request: DataAPI.ModifiedRequest, completion: @escaping (Result<SeedPayload, SwiftyPressError>) -> Void) } // MARK: - Cache public protocol DataCache { var lastFetchedAt: Date? { get } func configure() func createOrUpdate(with request: DataAPI.CacheRequest, completion: @escaping (Result<SeedPayload, SwiftyPressError>) -> Void) func delete(for userID: Int) } // MARK: - Seed public protocol DataSeed { func configure() func fetch(completion: (Result<SeedPayload, SwiftyPressError>) -> Void) } // MARK: - Namespace public enum DataAPI { public struct ModifiedRequest { let taxonomies: [String] let postMetaKeys: [String] let limit: Int? } public struct CacheRequest { let payload: SeedPayload let lastFetchedAt: Date } }
22.163265
151
0.674954
561da80b57b1cc5204d4f7508befdd24ba86249d
4,036
/// This playground illustrates a few of the things we discussed during the T3 in Saudi Arabia (virtually) in July 2020. /// /// Illustrating the scope of the variable inside a switch case let temperature = 70 switch temperature { case Int.min..<65: /// `tmpValue` is only accessible here in this case let tmpValue = Int.min print(tmpValue) default: print("hello") /// tmpValue is not available here /// Uncomment this line and //print(tmpValue) } /// This illustrates the Swift type inference. /// With no type annotation specified, character is initialized as a String /// The "a", "e", &c. cases are all determined to be String types. //let character = "z" /// If we specify that the `character` constant is a `Character`, Swift infers /// the "a", "e", &c. cases in our switch to be `Character`s. let character:Character = "z" switch character { case "a", "e", "i", "o", "u" : print("I'm a vowel.") default: print("\(character) is not a vowel.") } /// 2-01 Strings Lesson /// The `isEmpty` property on a string is to test if the string exists but has no characters, like this: let myString: String = "" if myString.isEmpty { print("This string exists (it is initialized) but has no characters in it.") } /// 2-03 Structures /// Naming a struct `Struct` /// Not recommended, but possible. /// You cannot name a struct `struct`, with a lowercase 's', as that's a reserved keyword. struct Struct { var testVar: String } let myStruct = Struct(testVar: "hello") /// If you have optional properties, you get a default empty initializer for your struct struct MyStruct { var name: String? } let myOptionalStruct = MyStruct() func returnSomething() -> Int { var counter = 0 for i in 1...99 { counter = i } /// We need a return statement here because we have multiple lines in our function return counter } /// If you uncomment these next few lines, you'll get a feel for the scope of variables /// If you keep the `import Foundation` line commented out, where we print out `index` we'll get a /// complile error because the only `index` symbol we have defined here is in our for loop's local scope. /// If you un-comment it there is a public global symbol deep down called `index`, so it'll print that this is a Function //import Foundation //let name = "Richard" //func printTenNames() { // for index in 1...4 { // print( // } //} /// //print(index) /// For the Unit 2, Lesson 3 Collections lesson /// This will show that using the '+' symbol with arrays will combine their contents into one bigger array. var newArray = [1,2,3] + [4,5,6] print(newArray) /// This illustrates the behavior of the `updateValue` method on dictionaries (it returns the old value, if any, for that key) var dict = ["Bob": 30, "Karen": 19, "Josephine": 11] let oldValue = dict.updateValue(3, forKey: "Kevin") print(dict) /// The `defer` statement /// This code snippet, something you might show off during the Unit 3, Lesson 3 - guard lesson /// shows you how the deferred code gets run and when. Follow the prints in the console to see /// how the deferred code is always called last before func deferMe(name: String?) { defer { print("This item was deferred. [00]\n\n") } /// Another defer block. Note when it gets executed in the console. defer { print("This item was deferred. [01]") } guard let name = name else { print("The name parameter was not provided with a value, so we're exiting.") return } print("This item was not deferred. [02]") for i in 3...9 { defer { print("This item, inside the loop [pass \(i)] was deferred.") } print("This is us, inside the loop. [0\(i)]") } print("Say my name: \"\(name)\"") } /// This call of the deferMe function will show you what happens when you exit with a guard statement deferMe(name:nil) /// This call will show you the whole execution of the function's code. deferMe(name:"Gerald")
31.779528
126
0.670466
fcba83585a14c4e00b6faa989a95ca0792537f84
330
// // ErrorCodes.swift // apous // // Created by David Owens on 7/5/15. // Copyright © 2015 owensd.io. All rights reserved. // enum ErrorCode: Int, ErrorType { case InvalidUsage = 1 case PathNotFound case CarthageNotInstalled case CocoaPodsNotInstalled case SwiftNotInstalled case PTYCreationFailed }
19.411765
52
0.70303
d63f35458de3320c0654b91ac1ed1b72885baad8
1,562
/******************************************************************************* * * Copyright 2019, Manufactura de Ingenios Tecnológicos S.L. * <http://www.mintforpeople.com> * * Redistribution, modification and use of this software are permitted under * terms of the Apache 2.0 License. * * This software is distributed in the hope that it will be useful, * but WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * Apache 2.0 License for more details. * * You should have received a copy of the Apache 2.0 License along with * this software. If not, see <http://www.apache.org/licenses/>. * ******************************************************************************/ // // SpeechProductionDelegateManager.swift // robobo-speech // // Created by Luis Felipe Llamas Luaces on 15/03/2019. // Copyright © 2019 mintforpeople. All rights reserved. // import robobo_framework_ios_pod import robobo_remote_control_ios public class SpeechProductionDelegateManager: DelegateManager { var remote: IRemoteControlModule! init(_ remote:IRemoteControlModule) { super.init() self.remote = remote } func notifyEndOfSpeech(){ for delegate in delegates{ if let del = delegate as? ISpeechProductionDelegate{ del.onEndOfSpeech() } } let s:Status = Status("UNLOCK-TALK") remote.postStatus(s) } }
31.877551
80
0.603073
2886611272dc6529b5f04dd8c3381c0e349b4f93
6,225
import XCTest @testable import ComposableArchitecture @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *) final class IdentifiedArrayTests: XCTestCase { func testIdSubscript() { struct User: Equatable, Identifiable { let id: Int var name: String } let array: IdentifiedArray = [User(id: 1, name: "Blob")] XCTAssertEqual(array[id: 1], .some(User(id: 1, name: "Blob"))) } func testRemoveId() { struct User: Equatable, Identifiable { let id: Int var name: String } var array: IdentifiedArray = [User(id: 1, name: "Blob")] XCTAssertEqual(array.remove(id: 1), User(id: 1, name: "Blob")) XCTAssertEqual(array, []) } func testInsert() { struct User: Equatable, Identifiable { let id: Int var name: String } var array: IdentifiedArray = [User(id: 1, name: "Blob")] array.insert(User(id: 2, name: "Blob Jr."), at: 0) XCTAssertEqual(array, [User(id: 2, name: "Blob Jr."), User(id: 1, name: "Blob")]) } func testInsertContentsOf() { struct User: Equatable, Identifiable { let id: Int var name: String } var array: IdentifiedArray = [User(id: 1, name: "Blob")] array.insert( contentsOf: [User(id: 3, name: "Blob Sr."), User(id: 2, name: "Blob Jr.")], at: 0) XCTAssertEqual( array, [User(id: 3, name: "Blob Sr."), User(id: 2, name: "Blob Jr."), User(id: 1, name: "Blob")] ) } func testRemoveAt() { struct User: Equatable, Identifiable { let id: Int var name: String } var array: IdentifiedArray = [ User(id: 3, name: "Blob Sr."), User(id: 2, name: "Blob Jr."), User(id: 1, name: "Blob"), ] array.remove(at: 1) XCTAssertEqual(array, [User(id: 3, name: "Blob Sr."), User(id: 1, name: "Blob")]) } func testRemoveAllWhere() { struct User: Equatable, Identifiable { let id: Int var name: String } var array: IdentifiedArray = [ User(id: 3, name: "Blob Sr."), User(id: 2, name: "Blob Jr."), User(id: 1, name: "Blob"), ] array.removeAll(where: { $0.name.starts(with: "Blob ") }) XCTAssertEqual(array, [User(id: 1, name: "Blob")]) } func testRemoveAtOffsets() { struct User: Equatable, Identifiable { let id: Int var name: String } var array: IdentifiedArray = [ User(id: 3, name: "Blob Sr."), User(id: 2, name: "Blob Jr."), User(id: 1, name: "Blob"), ] array.remove(atOffsets: [0, 2]) XCTAssertEqual(array, [User(id: 2, name: "Blob Jr.")]) } #if canImport(SwiftUI) func testMoveFromOffsets() { struct User: Equatable, Identifiable { let id: Int var name: String } var array: IdentifiedArray = [ User(id: 3, name: "Blob Sr."), User(id: 2, name: "Blob Jr."), User(id: 1, name: "Blob"), ] array.move(fromOffsets: [0], toOffset: 2) XCTAssertEqual( array, [User(id: 2, name: "Blob Jr."), User(id: 3, name: "Blob Sr."), User(id: 1, name: "Blob")] ) } #endif func testReplaceSubrange() { struct User: Equatable, Identifiable { let id: Int var name: String } var array: IdentifiedArray = [ User(id: 3, name: "Blob Sr."), User(id: 2, name: "Blob Jr."), User(id: 1, name: "Blob"), User(id: 2, name: "Blob Jr."), ] array.replaceSubrange( 0...1, with: [ User(id: 4, name: "Flob IV"), User(id: 5, name: "Flob V"), ] ) XCTAssertEqual( array, [ User(id: 4, name: "Flob IV"), User(id: 5, name: "Flob V"), User(id: 1, name: "Blob"), User(id: 2, name: "Blob Jr."), ] ) } struct ComparableValue: Comparable, Identifiable { let id: Int let value: Int static func < (lhs: ComparableValue, rhs: ComparableValue) -> Bool { return lhs.value < rhs.value } } func testSortBy() { var array: IdentifiedArray = [ ComparableValue(id: 1, value: 100), ComparableValue(id: 2, value: 50), ComparableValue(id: 3, value: 75), ] array.sort { $0.value < $1.value } XCTAssertEqual([2, 3, 1], array.ids) XCTAssertEqual( [ ComparableValue(id: 2, value: 50), ComparableValue(id: 3, value: 75), ComparableValue(id: 1, value: 100), ], array) } func testSort() { var array: IdentifiedArray = [ ComparableValue(id: 1, value: 100), ComparableValue(id: 2, value: 50), ComparableValue(id: 3, value: 75), ] array.sort() XCTAssertEqual([2, 3, 1], array.ids) XCTAssertEqual( [ ComparableValue(id: 2, value: 50), ComparableValue(id: 3, value: 75), ComparableValue(id: 1, value: 100), ], array) } // Account for randomness API changes in Swift 5.3 (https://twitter.com/mbrandonw/status/1262388756847505410) // TODO: Try swapping out the LCRNG for a Xoshiro generator #if swift(>=5.3) func testShuffle() { struct User: Equatable, Identifiable { let id: Int var name: String } var array: IdentifiedArray = [ User(id: 1, name: "Blob"), User(id: 2, name: "Blob Jr."), User(id: 3, name: "Blob Sr."), User(id: 4, name: "Foo Jr."), User(id: 5, name: "Bar Jr."), ] var lcrng = LCRNG(seed: 0) array.shuffle(using: &lcrng) XCTAssertEqual( [ User(id: 1, name: "Blob"), User(id: 3, name: "Blob Sr."), User(id: 5, name: "Bar Jr."), User(id: 4, name: "Foo Jr."), User(id: 2, name: "Blob Jr."), ], array.elements ) XCTAssertEqual([1, 3, 5, 4, 2], array.ids) } #endif func testReverse() { var array: IdentifiedArray = [ ComparableValue(id: 1, value: 100), ComparableValue(id: 2, value: 50), ComparableValue(id: 3, value: 75), ] array.reverse() XCTAssertEqual([3, 2, 1], array.ids) XCTAssertEqual( [ ComparableValue(id: 3, value: 75), ComparableValue(id: 2, value: 50), ComparableValue(id: 1, value: 100), ], array) } }
24.604743
111
0.552771
e4a9d9da2108f83f7fa10ee13f4e309909cd18c8
957
import Foundation public enum AddressType: UInt8 { case pubKeyHash = 0, scriptHash = 8 } public protocol Address: class { var type: AddressType { get } var scriptType: ScriptType { get } var keyHash: Data { get } var stringValue: String { get } } extension Address { var scriptType: ScriptType { switch type { case .pubKeyHash: return .p2pkh case .scriptHash: return .p2sh } } } class LegacyAddress: Address, Equatable { let type: AddressType let keyHash: Data let stringValue: String init(type: AddressType, keyHash: Data, base58: String) { self.type = type self.keyHash = keyHash self.stringValue = base58 } static func ==<T: Address>(lhs: LegacyAddress, rhs: T) -> Bool { guard let rhs = rhs as? LegacyAddress else { return false } return lhs.type == rhs.type && lhs.keyHash == rhs.keyHash } }
23.341463
70
0.61024
50a808362fb930fe42ebc72da17c7f6e280a846d
2,094
// // WalletSummary.swift // AlphaWallet // // Created by Vladyslav Shepitko on 26.05.2021. // import Foundation import BigInt struct WalletSummary: Equatable { private let balances: [WalletBalance] init(balances: [WalletBalance]) { self.balances = balances } var totalAmount: String { if let amount = totalAmountDouble, let value = Formatter.fiat.string(from: amount) { return value } else if let amount = etherTotalAmountDouble, let value = Formatter.shortCrypto.string(from: amount.doubleValue) { return "\(value) \(RPCServer.main.symbol)" } else { return "--" } } var changeDouble: Double? { if let amount = totalAmountDouble, let value = changePercentage { return (amount / 100 * value).nilIfNan } else { return nil } } var changePercentage: Double? { let values = balances.compactMap { $0.changePercentage } if values.isEmpty { return nil } else { return values.reduce(0, +).nilIfNan } } private var totalAmountDouble: Double? { var amount: Double? for each in balances { if let eachTotalAmount = each.totalAmountDouble { if amount == nil { amount = .zero } if let currentAmount = amount { amount = currentAmount + eachTotalAmount } } } return amount?.nilIfNan } private var etherTotalAmountDouble: NSDecimalNumber? { var amount: NSDecimalNumber? for each in balances { if let eachEtherAmount = each.etherTokenObject?.valueDecimal { if amount == nil { amount = .zero } if let currentAmount = amount { amount = currentAmount.adding(eachEtherAmount) } } } return amount } } extension Double { var nilIfNan: Double? { guard !isNaN else { return nil } return self } }
24.635294
123
0.558739
8a1e6870cbe8cd1c29057680418496ec97f6f6f0
3,449
// // ViewController.swift // TrendingMovies // // Created by Nabil Kazi on 27/02/19. // import UIKit import CoreData class MovieListVC : UITableViewController { private var movieDataManager: MovieDataManager! private var moviesApiController: MoviesAPIController! private var movieListViewModel: MovieListViewModel! private var dataSource: TableViewDataSource<MovieTableViewCell,MovieViewModel>! private var displayMessage = Constants.noMoviesMessage lazy var refresh: UIRefreshControl = { let refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: #selector(self.handleRefresh(_:)), for: .valueChanged) refreshControl.tintColor = Color.lightText return refreshControl }() override func viewDidLoad() { super.viewDidLoad() self.movieDataManager = MovieDataManager() self.moviesApiController = MoviesAPIController() setupUI() setupVM() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if #available(iOS 11.0, *) { self.navigationController?.navigationBar.prefersLargeTitles = true } } private func setupUI(){ self.tableView.register(UINib(nibName: Views.movieTableViewCell, bundle: nil), forCellReuseIdentifier: Cells.movie) self.tableView.refreshControl = refresh } private func setupVM() { self.movieListViewModel = MovieListViewModel(apiController: moviesApiController, movieDataManager: movieDataManager) self.movieListViewModel.bindToSourceViewModels = { self.updateDataSource() } self.movieListViewModel.showMessageClosure = { if let message = self.movieListViewModel.displayMessage { self.displayMessage = message self.updateDataSource() } } movieListViewModel.updateLoadingStatus = { let isLoading = self.movieListViewModel.isLoading if isLoading { self.refresh.beginRefreshing() }else { self.refresh.endRefreshing() } } } private func updateDataSource() { self.dataSource = TableViewDataSource(cellIdentifier: Cells.movie, items: self.movieListViewModel.movieViewModels, displayMessage: displayMessage) { cell, vm in cell.movieViewModel = vm } self.tableView.dataSource = self.dataSource self.tableView.reloadData() } @objc func handleRefresh(_ refreshControl: UIRefreshControl) { movieListViewModel.fetchMoviesFromAPI() } } extension MovieListVC { override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let height = UIScreen.main.bounds.height * 0.25 return height } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let indexPath = self.tableView.indexPathForSelectedRow else { fatalError("indexPath not found") } let movie = self.movieListViewModel.movie(at: indexPath.row) let movieDetailsVC = MovieDetailsVC.storyboardInstance()! movieDetailsVC.movieViewModel = movie self.navigationController?.pushViewController(movieDetailsVC, animated: true) } }
33.813725
168
0.663961
d7eb78fdd40dd360cc8650d331102289b604bfc6
2,133
// // Permissions.swift // PermissionScope // // Updated by Artur Kashapov on 4/01/18. // Copyright © 2018 That Thing in Swift. All rights reserved. // import Foundation import CoreLocation import AddressBook import AVFoundation import Photos import EventKit import CoreBluetooth import CoreMotion import CloudKit import Accounts import UserNotifications /** * Protocol for permission configurations. */ @objc public protocol Permission { /// Permission type var type: PermissionType { get } } @objc public class NotificationsPermission: NSObject, Permission { public let type: PermissionType = .notifications public let notificationCategories: Set<UNNotificationCategory>? public init(notificationCategories: Set<UNNotificationCategory>? = nil) { self.notificationCategories = notificationCategories } } @objc public class LocationWhileInUsePermission: NSObject, Permission { public let type: PermissionType = .locationInUse } @objc public class LocationAlwaysPermission: NSObject, Permission { public let type: PermissionType = .locationAlways } @objc public class ContactsPermission: NSObject, Permission { public let type: PermissionType = .contacts } public typealias requestPermissionUnknownResult = () -> Void public typealias requestPermissionShowAlert = (PermissionType) -> Void @objc public class EventsPermission: NSObject, Permission { public let type: PermissionType = .events } @objc public class MicrophonePermission: NSObject, Permission { public let type: PermissionType = .microphone } @objc public class CameraPermission: NSObject, Permission { public let type: PermissionType = .camera } @objc public class PhotosPermission: NSObject, Permission { public let type: PermissionType = .photos } @objc public class RemindersPermission: NSObject, Permission { public let type: PermissionType = .reminders } @objc public class BluetoothPermission: NSObject, Permission { public let type: PermissionType = .bluetooth } @objc public class MotionPermission: NSObject, Permission { public let type: PermissionType = .motion }
27
77
0.766526
3a48de4dd9f61cabf865deee741e9f3d3ef068dd
1,454
// // EdamamAPIClient.swift // CoreData-Recipes // // Created by Alex Paul on 2/25/19. // Copyright © 2019 Alex Paul. All rights reserved. // import Foundation final class EdamamAPIClient { static func searchRecipes(keyword: String, completion: @escaping (AppError?, [RecipeInfo]?) -> Void) { let endpointURLString = "https://api.edamam.com/search?q=\(keyword)&app_id=\(SecretKeys.AppId)&app_key=\(SecretKeys.APIKey)&from=0&to=50" guard let url = URL(string: endpointURLString) else { print("bad url: \(endpointURLString)") return } let request = URLRequest(url: url) let task = URLSession.shared.dataTask(with: request) { (data, response, error) in if let error = error { completion(AppError.networkError(error), nil) } guard let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) else { let statusCode = (response as? HTTPURLResponse)?.statusCode ?? -999 print("bad status code") completion(AppError.badStatusCode(statusCode.description), nil) return } if let data = data { do { let recipeSearch = try JSONDecoder().decode(RecipeSearch.self, from: data) let recipes = recipeSearch.hits.map { $0.recipe } completion(nil, recipes) } catch { completion(AppError.jsonDecodingError(error), nil) } } } task.resume() } }
33.813953
141
0.643741
c1beafcb1293f78ddcfe0fd42c7984d4c785a8db
19,854
// RUN: %target-typecheck-verify-swift protocol P1 { typealias DependentInConcreteConformance = Self } class Base<T> : P1 { typealias DependentClass = T required init(classInit: ()) {} func classSelfReturn() -> Self {} } protocol P2 { typealias FullyConcrete = Int typealias DependentProtocol = Self init(protocolInit: ()) func protocolSelfReturn() -> Self } typealias BaseAndP2<T> = Base<T> & P2 typealias BaseIntAndP2 = BaseAndP2<Int> class Derived : Base<Int>, P2 { required init(protocolInit: ()) { super.init(classInit: ()) } required init(classInit: ()) { super.init(classInit: ()) } func protocolSelfReturn() -> Self {} } class Other : Base<Int> {} typealias OtherAndP2 = Other & P2 protocol P3 : class {} struct Unrelated {} // // If a class conforms to a protocol concretely, the resulting protocol // composition type should be equivalent to the class type. // // FIXME: Not implemented yet. // func alreadyConforms<T>(_: Base<T>) {} // expected-note {{'alreadyConforms' previously declared here}} func alreadyConforms<T>(_: Base<T> & P1) {} // expected-note {{'alreadyConforms' previously declared here}} func alreadyConforms<T>(_: Base<T> & AnyObject) {} // expected-error {{invalid redeclaration of 'alreadyConforms'}} func alreadyConforms<T>(_: Base<T> & P1 & AnyObject) {} // expected-error {{invalid redeclaration of 'alreadyConforms'}} func alreadyConforms(_: P3) {} func alreadyConforms(_: P3 & AnyObject) {} // SE-0156 stipulates that a composition can contain multiple classes, as long // as they are all the same. func basicDiagnostics( _: Base<Int> & Base<Int>, _: Base<Int> & Derived, // expected-error{{protocol-constrained type cannot contain class 'Derived' because it already contains class 'Base<Int>'}} // Invalid typealias case _: Derived & OtherAndP2, // expected-error{{protocol-constrained type cannot contain class 'Other' because it already contains class 'Derived'}} // Valid typealias case _: OtherAndP2 & P3) {} // A composition containing only a single class is actually identical to // the class type itself. struct Box<T : Base<Int>> {} func takesBox(_: Box<Base<Int>>) {} func passesBox(_ b: Box<Base<Int> & Base<Int>>) { takesBox(b) } // Test that subtyping behaves as you would expect. func basicSubtyping( base: Base<Int>, baseAndP1: Base<Int> & P1, baseAndP2: Base<Int> & P2, baseAndP2AndAnyObject: Base<Int> & P2 & AnyObject, baseAndAnyObject: Base<Int> & AnyObject, derived: Derived, derivedAndP2: Derived & P2, derivedAndP3: Derived & P3, derivedAndAnyObject: Derived & AnyObject, p1AndAnyObject: P1 & AnyObject, p2AndAnyObject: P2 & AnyObject, anyObject: AnyObject) { // Errors let _: Base & P2 = base // expected-error {{value of type 'Base<Int>' does not conform to specified type 'Base & P2'}} let _: Base<Int> & P2 = base // expected-error {{value of type 'Base<Int>' does not conform to specified type 'Base<Int> & P2'}} let _: P3 = baseAndP1 // expected-error {{value of type 'Base<Int> & P1' does not conform to specified type 'P3'}} let _: P3 = baseAndP2 // expected-error {{value of type 'Base<Int> & P2' does not conform to specified type 'P3'}} let _: Derived = baseAndP1 // expected-error {{cannot convert value of type 'Base<Int> & P1' to specified type 'Derived'}} let _: Derived = baseAndP2 // expected-error {{cannot convert value of type 'Base<Int> & P2' to specified type 'Derived'}} let _: Derived & P2 = baseAndP2 // expected-error {{value of type 'Base<Int> & P2' does not conform to specified type 'Derived & P2'}} let _ = Unrelated() as Derived & P2 // expected-error {{value of type 'Unrelated' does not conform to 'Derived & P2' in coercion}} let _ = Unrelated() as? Derived & P2 // expected-warning {{always fails}} let _ = baseAndP2 as Unrelated // expected-error {{cannot convert value of type 'Base<Int> & P2' to type 'Unrelated' in coercion}} let _ = baseAndP2 as? Unrelated // expected-warning {{always fails}} // Different behavior on Linux vs Darwin because of id-as-Any. // let _ = Unrelated() as AnyObject // let _ = Unrelated() as? AnyObject let _ = anyObject as Unrelated // expected-error {{'AnyObject' is not convertible to 'Unrelated'; did you mean to use 'as!' to force downcast?}} let _ = anyObject as? Unrelated // No-ops let _: Base & P1 = base let _: Base<Int> & P1 = base let _: Base & AnyObject = base let _: Base<Int> & AnyObject = base let _: Derived & AnyObject = derived let _ = base as Base<Int> & P1 let _ = base as Base<Int> & AnyObject let _ = derived as Derived & AnyObject let _ = base as? Base<Int> & P1 // expected-warning {{always succeeds}} let _ = base as? Base<Int> & AnyObject // expected-warning {{always succeeds}} let _ = derived as? Derived & AnyObject // expected-warning {{always succeeds}} // Erasing superclass constraint let _: P1 = baseAndP1 let _: P1 & AnyObject = baseAndP1 let _: P1 = derived let _: P1 & AnyObject = derived let _: AnyObject = baseAndP1 let _: AnyObject = baseAndP2 let _: AnyObject = derived let _: AnyObject = derivedAndP2 let _: AnyObject = derivedAndP3 let _: AnyObject = derivedAndAnyObject let _ = baseAndP1 as P1 let _ = baseAndP1 as P1 & AnyObject let _ = derived as P1 let _ = derived as P1 & AnyObject let _ = baseAndP1 as AnyObject let _ = derivedAndAnyObject as AnyObject let _ = baseAndP1 as? P1 // expected-warning {{always succeeds}} let _ = baseAndP1 as? P1 & AnyObject // expected-warning {{always succeeds}} let _ = derived as? P1 // expected-warning {{always succeeds}} let _ = derived as? P1 & AnyObject // expected-warning {{always succeeds}} let _ = baseAndP1 as? AnyObject // expected-warning {{always succeeds}} let _ = derivedAndAnyObject as? AnyObject // expected-warning {{always succeeds}} // Erasing conformance constraint let _: Base = baseAndP1 let _: Base<Int> = baseAndP1 let _: Base = derivedAndP3 let _: Base<Int> = derivedAndP3 let _: Derived = derivedAndP2 let _: Derived = derivedAndAnyObject let _ = baseAndP1 as Base<Int> let _ = derivedAndP3 as Base<Int> let _ = derivedAndP2 as Derived let _ = derivedAndAnyObject as Derived let _ = baseAndP1 as? Base<Int> // expected-warning {{always succeeds}} let _ = derivedAndP3 as? Base<Int> // expected-warning {{always succeeds}} let _ = derivedAndP2 as? Derived // expected-warning {{always succeeds}} let _ = derivedAndAnyObject as? Derived // expected-warning {{always succeeds}} // Upcasts let _: Base & P2 = derived let _: Base<Int> & P2 = derived let _: Base & P2 & AnyObject = derived let _: Base<Int> & P2 & AnyObject = derived let _: Base & P3 = derivedAndP3 let _: Base<Int> & P3 = derivedAndP3 let _ = derived as Base<Int> & P2 let _ = derived as Base<Int> & P2 & AnyObject let _ = derivedAndP3 as Base<Int> & P3 let _ = derived as? Base<Int> & P2 // expected-warning {{always succeeds}} let _ = derived as? Base<Int> & P2 & AnyObject // expected-warning {{always succeeds}} let _ = derivedAndP3 as? Base<Int> & P3 // expected-warning {{always succeeds}} // Calling methods with Self return let _: Base & P2 = baseAndP2.classSelfReturn() let _: Base<Int> & P2 = baseAndP2.classSelfReturn() let _: Base & P2 = baseAndP2.protocolSelfReturn() let _: Base<Int> & P2 = baseAndP2.protocolSelfReturn() // Downcasts let _ = baseAndP2 as Derived // expected-error {{did you mean to use 'as!' to force downcast?}} let _ = baseAndP2 as? Derived let _ = baseAndP2 as Derived & P3 // expected-error {{did you mean to use 'as!' to force downcast?}} let _ = baseAndP2 as? Derived & P3 let _ = base as Derived & P2 // expected-error {{did you mean to use 'as!' to force downcast?}} let _ = base as? Derived & P2 // Invalid cases let _ = derived as Other & P2 // expected-error {{value of type 'Derived' does not conform to 'Other & P2' in coercion}} let _ = derived as? Other & P2 // expected-warning {{always fails}} let _ = derivedAndP3 as Other // expected-error {{cannot convert value of type 'Derived & P3' to type 'Other' in coercion}} let _ = derivedAndP3 as? Other // expected-warning {{always fails}} let _ = derivedAndP3 as Other & P3 // expected-error {{value of type 'Derived & P3' does not conform to 'Other & P3' in coercion}} let _ = derivedAndP3 as? Other & P3 // expected-warning {{always fails}} let _ = derived as Other // expected-error {{cannot convert value of type 'Derived' to type 'Other' in coercion}} let _ = derived as? Other // expected-warning {{always fails}} } // Test conversions in return statements func eraseProtocolInReturn(baseAndP2: Base<Int> & P2) -> Base<Int> { return baseAndP2 } func eraseProtocolInReturn(baseAndP2: (Base<Int> & P2)!) -> Base<Int> { return baseAndP2 } func eraseProtocolInReturn(baseAndP2: Base<Int> & P2) -> Base<Int>? { return baseAndP2 } func eraseClassInReturn(baseAndP2: Base<Int> & P2) -> P2 { return baseAndP2 } func eraseClassInReturn(baseAndP2: (Base<Int> & P2)!) -> P2 { return baseAndP2 } func eraseClassInReturn(baseAndP2: Base<Int> & P2) -> P2? { return baseAndP2 } func upcastToExistentialInReturn(derived: Derived) -> Base<Int> & P2 { return derived } func upcastToExistentialInReturn(derived: Derived!) -> Base<Int> & P2 { return derived } func upcastToExistentialInReturn(derived: Derived) -> (Base<Int> & P2)? { return derived } func takesBase<T>(_: Base<T>) {} func takesP2(_: P2) {} func takesBaseMetatype<T>(_: Base<T>.Type) {} func takesP2Metatype(_: P2.Type) {} func takesBaseIntAndP2(_ x: Base<Int> & P2) { takesBase(x) takesP2(x) } func takesBaseIntAndP2Metatype(_ x: (Base<Int> & P2).Type) { takesBaseMetatype(x) takesP2Metatype(x) } func takesDerived(x: Derived) { takesBaseIntAndP2(x) } func takesDerivedMetatype(x: Derived.Type) { takesBaseIntAndP2Metatype(x) } // // Looking up member types of subclass existentials. // func dependentMemberTypes<T : BaseIntAndP2>( _: T.DependentInConcreteConformance, _: T.DependentProtocol, _: T.DependentClass, _: T.FullyConcrete, _: BaseIntAndP2.DependentInConcreteConformance, // FIXME expected-error {{}} _: BaseIntAndP2.DependentProtocol, // expected-error {{type alias 'DependentProtocol' can only be used with a concrete type or generic parameter base}} _: BaseIntAndP2.DependentClass, _: BaseIntAndP2.FullyConcrete) {} func conformsToAnyObject<T : AnyObject>(_: T) {} func conformsToP1<T : P1>(_: T) {} func conformsToP2<T : P2>(_: T) {} func conformsToBaseIntAndP2<T : Base<Int> & P2>(_: T) {} // expected-note@-1 4 {{in call to function 'conformsToBaseIntAndP2'}} func conformsToBaseIntAndP2WithWhereClause<T>(_: T) where T : Base<Int> & P2 {} // expected-note@-1 2 {{in call to function 'conformsToBaseIntAndP2WithWhereClause'}} class FakeDerived : Base<String>, P2 { required init(classInit: ()) { super.init(classInit: ()) } required init(protocolInit: ()) { super.init(classInit: ()) } func protocolSelfReturn() -> Self { return self } } // // Metatype subtyping. // func metatypeSubtyping( base: Base<Int>.Type, derived: Derived.Type, derivedAndAnyObject: (Derived & AnyObject).Type, baseIntAndP2: (Base<Int> & P2).Type, baseIntAndP2AndAnyObject: (Base<Int> & P2 & AnyObject).Type) { // Erasing conformance constraint let _: Base<Int>.Type = baseIntAndP2 let _: Base<Int>.Type = baseIntAndP2AndAnyObject let _: Derived.Type = derivedAndAnyObject let _: BaseAndP2<Int>.Type = baseIntAndP2AndAnyObject let _ = baseIntAndP2 as Base<Int>.Type let _ = baseIntAndP2AndAnyObject as Base<Int>.Type let _ = derivedAndAnyObject as Derived.Type let _ = baseIntAndP2AndAnyObject as BaseAndP2<Int>.Type let _ = baseIntAndP2 as? Base<Int>.Type // expected-warning {{always succeeds}} let _ = baseIntAndP2AndAnyObject as? Base<Int>.Type // expected-warning {{always succeeds}} let _ = derivedAndAnyObject as? Derived.Type // expected-warning {{always succeeds}} let _ = baseIntAndP2AndAnyObject as? BaseAndP2<Int>.Type // expected-warning {{always succeeds}} // Upcast let _: BaseAndP2<Int>.Type = derived let _: BaseAndP2<Int>.Type = derivedAndAnyObject let _ = derived as BaseAndP2<Int>.Type let _ = derivedAndAnyObject as BaseAndP2<Int>.Type let _ = derived as? BaseAndP2<Int>.Type // expected-warning {{always succeeds}} let _ = derivedAndAnyObject as? BaseAndP2<Int>.Type // expected-warning {{always succeeds}} // Erasing superclass constraint let _: P2.Type = baseIntAndP2 let _: P2.Type = derived let _: P2.Type = derivedAndAnyObject let _: (P2 & AnyObject).Type = derived let _: (P2 & AnyObject).Type = derivedAndAnyObject let _ = baseIntAndP2 as P2.Type let _ = derived as P2.Type let _ = derivedAndAnyObject as P2.Type let _ = derived as (P2 & AnyObject).Type let _ = derivedAndAnyObject as (P2 & AnyObject).Type let _ = baseIntAndP2 as? P2.Type // expected-warning {{always succeeds}} let _ = derived as? P2.Type // expected-warning {{always succeeds}} let _ = derivedAndAnyObject as? P2.Type // expected-warning {{always succeeds}} let _ = derived as? (P2 & AnyObject).Type // expected-warning {{always succeeds}} let _ = derivedAndAnyObject as? (P2 & AnyObject).Type // expected-warning {{always succeeds}} // Initializers let _: Base<Int> & P2 = baseIntAndP2.init(classInit: ()) let _: Base<Int> & P2 = baseIntAndP2.init(protocolInit: ()) let _: Base<Int> & P2 & AnyObject = baseIntAndP2AndAnyObject.init(classInit: ()) let _: Base<Int> & P2 & AnyObject = baseIntAndP2AndAnyObject.init(protocolInit: ()) let _: Derived = derived.init(classInit: ()) let _: Derived = derived.init(protocolInit: ()) let _: Derived & AnyObject = derivedAndAnyObject.init(classInit: ()) let _: Derived & AnyObject = derivedAndAnyObject.init(protocolInit: ()) } // // Conformance relation. // func conformsTo<T1 : P2, T2 : Base<Int> & P2>( anyObject: AnyObject, p1: P1, p2: P2, p3: P3, base: Base<Int>, badBase: Base<String>, derived: Derived, fakeDerived: FakeDerived, p2Archetype: T1, baseAndP2Archetype: T2) { // FIXME: Uninformative diagnostics // Errors conformsToAnyObject(p1) // expected-error@-1 {{cannot invoke 'conformsToAnyObject' with an argument list of type '(P1)'}} // expected-note@-2 {{expected an argument list of type '(T)'}} conformsToP1(p1) // expected-error@-1 {{cannot invoke 'conformsToP1' with an argument list of type '(P1)'}} // expected-note@-2 {{expected an argument list of type '(T)'}} conformsToBaseIntAndP2(base) // expected-error@-1 {{generic parameter 'T' could not be inferred}} conformsToBaseIntAndP2(badBase) // expected-error@-1 {{generic parameter 'T' could not be inferred}} conformsToBaseIntAndP2(fakeDerived) // expected-error@-1 {{generic parameter 'T' could not be inferred}} conformsToBaseIntAndP2WithWhereClause(fakeDerived) // expected-error@-1 {{generic parameter 'T' could not be inferred}} conformsToBaseIntAndP2(p2Archetype) // expected-error@-1 {{generic parameter 'T' could not be inferred}} conformsToBaseIntAndP2WithWhereClause(p2Archetype) // expected-error@-1 {{generic parameter 'T' could not be inferred}} // Good conformsToAnyObject(anyObject) conformsToAnyObject(baseAndP2Archetype) conformsToP1(derived) conformsToP1(baseAndP2Archetype) conformsToP2(derived) conformsToP2(baseAndP2Archetype) conformsToBaseIntAndP2(derived) conformsToBaseIntAndP2(baseAndP2Archetype) conformsToBaseIntAndP2WithWhereClause(derived) conformsToBaseIntAndP2WithWhereClause(baseAndP2Archetype) } // // Protocols with superclass-constrained Self -- not supported yet. // protocol ProtoConstraintsSelfToClass where Self : Base<Int> {} protocol ProtoRefinesClass : Base<Int> {} // FIXME expected-error {{}} protocol ProtoRefinesClassAndProtocolAlias : BaseIntAndP2 {} protocol ProtoRefinesClassAndProtocolDirect : Base<Int> & P2 {} protocol ProtoRefinesClassAndProtocolExpanded : Base<Int>, P2 {} // FIXME expected-error {{}} class ClassConformsToClassProtocolBad1 : ProtoConstraintsSelfToClass {} // expected-error@-1 {{'ProtoConstraintsSelfToClass' requires that 'ClassConformsToClassProtocolBad1' inherit from 'Base<Int>'}} // expected-note@-2 {{requirement specified as 'Self' : 'Base<Int>' [with Self = ClassConformsToClassProtocolBad1]}} class ClassConformsToClassProtocolGood1 : Derived, ProtoConstraintsSelfToClass {} class ClassConformsToClassProtocolBad2 : ProtoRefinesClass {} // expected-error@-1 {{'ProtoRefinesClass' requires that 'ClassConformsToClassProtocolBad2' inherit from 'Base<Int>'}} // expected-note@-2 {{requirement specified as 'Self' : 'Base<Int>' [with Self = ClassConformsToClassProtocolBad2]}} class ClassConformsToClassProtocolGood2 : Derived, ProtoRefinesClass {} // Subclass existentials inside inheritance clauses class CompositionInClassInheritanceClauseAlias : BaseIntAndP2 { required init(classInit: ()) { super.init(classInit: ()) } required init(protocolInit: ()) { super.init(classInit: ()) } func protocolSelfReturn() -> Self { return self } func asBase() -> Base<Int> { return self } } class CompositionInClassInheritanceClauseDirect : Base<Int> & P2 { required init(classInit: ()) { super.init(classInit: ()) } required init(protocolInit: ()) { super.init(classInit: ()) } func protocolSelfReturn() -> Self { return self } func asBase() -> Base<Int> { return self } } protocol CompositionInAssociatedTypeInheritanceClause { associatedtype A : BaseIntAndP2 } // Members of metatypes and existential metatypes protocol ProtocolWithStaticMember { static func staticProtocolMember() func instanceProtocolMember() } class ClassWithStaticMember { static func staticClassMember() {} func instanceClassMember() {} } func staticMembers( m1: (ProtocolWithStaticMember & ClassWithStaticMember).Protocol, m2: (ProtocolWithStaticMember & ClassWithStaticMember).Type) { _ = m1.staticProtocolMember() // expected-error {{static member 'staticProtocolMember' cannot be used on protocol metatype '(ClassWithStaticMember & ProtocolWithStaticMember).Protocol'}} _ = m1.staticProtocolMember // expected-error {{static member 'staticProtocolMember' cannot be used on protocol metatype '(ClassWithStaticMember & ProtocolWithStaticMember).Protocol'}} _ = m1.staticClassMember() // expected-error {{static member 'staticClassMember' cannot be used on protocol metatype '(ClassWithStaticMember & ProtocolWithStaticMember).Protocol'}} _ = m1.staticClassMember // expected-error {{static member 'staticClassMember' cannot be used on protocol metatype '(ClassWithStaticMember & ProtocolWithStaticMember).Protocol'}} _ = m1.instanceProtocolMember _ = m1.instanceClassMember _ = m2.staticProtocolMember() _ = m2.staticProtocolMember _ = m2.staticClassMember() _ = m2.staticClassMember _ = m2.instanceProtocolMember // expected-error {{instance member 'instanceProtocolMember' cannot be used on type 'ClassWithStaticMember & ProtocolWithStaticMember'}} _ = m2.instanceClassMember // expected-error {{instance member 'instanceClassMember' cannot be used on type 'ClassWithStaticMember & ProtocolWithStaticMember'}} } // Make sure we correctly form subclass existentials in expression context. func takesBaseIntAndPArray(_: [Base<Int> & P2]) {} func passesBaseIntAndPArray() { takesBaseIntAndPArray([Base<Int> & P2]()) } // // Superclass constrained generic parameters // struct DerivedBox<T : Derived> {} // expected-note@-1 {{requirement specified as 'T' : 'Derived' [with T = Derived & P3]}} func takesBoxWithP3(_: DerivedBox<Derived & P3>) {} // expected-error@-1 {{'DerivedBox' requires that 'Derived & P3' inherit from 'Derived'}}
36.229927
188
0.715221
f493867806aedc96f05e7626ec40f27ea5adfa54
1,477
// swift-tools-version:5.3 import PackageDescription let package = Package( name: "SQLite.swift", products: [ .library( name: "SQLite", targets: ["SQLite"] ) ], targets: [ .target( name: "SQLite", dependencies: ["SQLiteObjc"], exclude: [ "Info.plist" ] ), .target( name: "SQLiteObjc", dependencies: [], exclude: [ "fts3_tokenizer.h" ] ), .testTarget( name: "SQLiteTests", dependencies: [ "SQLite" ], path: "Tests/SQLiteTests", exclude: [ "Info.plist" ], resources: [ .copy("fixtures/encrypted-3.x.sqlite"), .copy("fixtures/encrypted-4.x.sqlite") ] ) ] ) #if os(Linux) package.dependencies = [.package(url: "https://github.com/stephencelis/CSQLite.git", from: "0.0.3")] package.targets = [ .target( name: "SQLite", dependencies: [.product(name: "CSQLite", package: "CSQLite")], exclude: ["Extensions/FTS4.swift", "Extensions/FTS5.swift"] ), .testTarget(name: "SQLiteTests", dependencies: ["SQLite"], path: "Tests/SQLiteTests", exclude: [ "FTSIntegrationTests.swift", "FTS4Tests.swift", "FTS5Tests.swift" ]) ] #endif
25.033898
100
0.474611
236a3b09a0d8c902886b2563aa447a5fae6943ed
1,017
// // FTSideMenuTests.swift // FTSideMenuTests // // Created by liufengting https://github.com/liufengting on 16/8/18. // Copyright © 2016年 liufengting. All rights reserved. // import XCTest @testable import FTSideMenu class FTSideMenuTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func 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.measureBlock { // Put the code you want to measure the time of here. } } }
27.486486
111
0.645034
229ab93f5b68e85f86476c5b2599bc207e5781b1
2,939
/** * BulletinBoard * Copyright (c) 2017 - present Alexis Aubry. Licensed under the MIT license. */ import UIKit /** * A shape layer that animates its path inside a block. */ private class AnimatingShapeLayer: CAShapeLayer { override class func defaultAction(forKey event: String) -> CAAction? { if event == "path" { return CABasicAnimation(keyPath: event) } else { return super.defaultAction(forKey: event) } } } /** * A layer whose corners are rounded with a continuous mask (“squircle“). For the button */ class ContinuousMaskLayerButton: CALayer { /// The corner radius. var continuousCornerRadius: CGFloat = 0 { didSet { refreshMask() } } /// The corners to round. var roundedCorners: UIRectCorner = .allCorners { didSet { refreshMask() } } // MARK: - Initialization override init(layer: Any) { super.init(layer: layer) } override init() { super.init() self.mask = AnimatingShapeLayer() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Layout override func layoutSublayers() { super.layoutSublayers() refreshMask() } private func refreshMask() { guard let mask = mask as? CAShapeLayer else { return } let radii = CGSize(width: continuousCornerRadius, height: continuousCornerRadius) let roundedPath = UIBezierPath(roundedRect: bounds, byRoundingCorners: roundedCorners, cornerRadii: radii) mask.path = roundedPath.cgPath } } /** * A layer whose corners are rounded with a continuous mask (“squircle“). For the main view */ class ContinuousMaskLayerView: CALayer { /// The corner radius. var continuousCornerRadius: CGFloat = 0 { didSet { refreshMask() } } /// The corners to round. var roundedCorners: UIRectCorner = [.topRight, .topLeft] { didSet { refreshMask() } } // MARK: - Initialization override init(layer: Any) { super.init(layer: layer) } override init() { super.init() self.mask = AnimatingShapeLayer() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Layout override func layoutSublayers() { super.layoutSublayers() refreshMask() } private func refreshMask() { guard let mask = mask as? CAShapeLayer else { return } let radii = CGSize(width: continuousCornerRadius, height: continuousCornerRadius) let roundedPath = UIBezierPath(roundedRect: bounds, byRoundingCorners: roundedCorners, cornerRadii: radii) mask.path = roundedPath.cgPath } }
21.143885
114
0.604627
ebb0d121cf92e71aca1717bc80b73568a0dac6f8
2,828
// // JXNavigationController.swift // ShoppingGo-Swift // // Created by 杜进新 on 2017/6/6. // Copyright © 2017年 杜进新. All rights reserved. // import UIKit class JXNavigationController: UINavigationController { lazy var backItem: UIBarButtonItem = { let leftButton = UIButton() leftButton.frame = CGRect(x: 10, y: 7, width: 30, height: 30) leftButton.setImage(UIImage(named: "icon-back")?.withRenderingMode(.alwaysTemplate), for: .normal) leftButton.tintColor = JXMainTextColor //leftButton.imageEdgeInsets = UIEdgeInsetsMake(12, 0, 12, 24) //leftButton.setTitle("up", for: .normal) leftButton.addTarget(self, action: #selector(pop), for: .touchUpInside) let item = UIBarButtonItem(customView: leftButton) return item }() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.navigationBar.isTranslucent = true self.navigationBar.barStyle = .blackTranslucent //状态栏 白色 //self.navigationBar.barStyle = .default //状态栏 黑色 self.navigationBar.barTintColor = UIColor.white//导航条颜色 self.navigationBar.tintColor = UIColor.darkText //item图片文字颜色 self.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor:UIColor.darkText,NSAttributedString.Key.font:UIFont.systemFont(ofSize: 17)]//标题设置 self.navigationBar.isHidden = false } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension JXNavigationController { /// 重写push方法 /// /// - Parameters: /// - viewController: 将要push的viewController /// - animated: 是否使用动画 override func pushViewController(_ viewController: UIViewController, animated: Bool) { super.pushViewController(viewController, animated: true) guard viewControllers.count > 0 else { return } var titleName = ""//"返回" if viewControllers.count == 1 { titleName = viewControllers.first?.title ?? titleName } if let vc = viewController as? BaseViewController { vc.hidesBottomBarWhenPushed = true vc.customNavigationItem.leftBarButtonItem = self.backItem //vc.customNavigationItem.leftBarButtonItem = UIBarButtonItem.init(title: titleName, imageName: "imgBack", target: self, action: #selector(pop)) } else if let vc = viewController as? JSTableViewController { vc.hidesBottomBarWhenPushed = true vc.customNavigationItem.leftBarButtonItem = self.backItem } } /// 自定义导航栏的返回按钮事件 @objc func pop() { popViewController(animated: true) } }
35.797468
170
0.659123
f7b66c7f319207f71004d8648ec3aab378c24d9a
1,262
import DistWorkerModels import Foundation public enum RegisterWorkerResponse: Codable, Equatable { case workerRegisterSuccess(workerConfiguration: WorkerConfiguration) private enum CodingKeys: CodingKey { case caseId case workerConfiguration } private enum CaseId: String, Codable { case workerRegisterSuccess } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let caseId = try container.decode(CaseId.self, forKey: .caseId) switch caseId { case .workerRegisterSuccess: self = .workerRegisterSuccess( workerConfiguration: try container.decode( WorkerConfiguration.self, forKey: .workerConfiguration ) ) } } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) switch self { case .workerRegisterSuccess(let workerConfiguration): try container.encode(CaseId.workerRegisterSuccess, forKey: .caseId) try container.encode(workerConfiguration, forKey: .workerConfiguration) } } }
32.358974
83
0.643423
035f4acdd84825c7df23cea234b42fc6d28af064
5,087
// // MessagesViewController.swift // MessagesExtension // // Created by Mr.H on 2017/7/31. // Copyright © 2017年 王木木. All rights reserved. // import UIKit import Messages class MessagesViewController: MSMessagesAppViewController,MSStickerBrowserViewDataSource { /// 创建数据源 lazy var dataArray: [MSSticker] = { var array:[MSSticker] = [] for i in 1...4 { if let url = Bundle.main.path(forResource: "\(i)", ofType: "png") { do { let temp = URL.init(fileURLWithPath: url) let sticker = try MSSticker(contentsOfFileURL: temp, localizedDescription: "") array.append(sticker) } catch { print(error) } } else if let url = Bundle.main.path(forResource: "\(i)", ofType: "gif") { do { let temp = URL.init(fileURLWithPath: url) let sticker = try MSSticker(contentsOfFileURL: temp, localizedDescription: "") array.append(sticker) } catch { print(error) } }else { print("如果格式不是gif也不是png请自行添加判断") } } return array }() override func viewDidLoad() { super.viewDidLoad() createStickerBrowser() let tab = UITableView() tab.sectionFooterHeight = 0.1 } /// 创建MSStickerBrowserViewController视图 func createStickerBrowser() { let controller = MSStickerBrowserViewController(stickerSize: .large) addChildViewController(controller) view.addSubview(controller.view) controller.stickerBrowserView.backgroundColor = UIColor.white controller.stickerBrowserView.dataSource = self view.topAnchor.constraint(equalTo: controller.view.topAnchor).isActive = true view.bottomAnchor.constraint(equalTo: controller.view.bottomAnchor).isActive = true view.leftAnchor.constraint(equalTo: controller.view.leftAnchor).isActive = true view.rightAnchor.constraint(equalTo: controller.view.rightAnchor).isActive = true } func numberOfStickers(in stickerBrowserView: MSStickerBrowserView) -> Int { return dataArray.count } func stickerBrowserView(_ stickerBrowserView: MSStickerBrowserView, stickerAt index: Int) -> MSSticker { return dataArray[index] } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Conversation Handling override func willBecomeActive(with conversation: MSConversation) { // Called when the extension is about to move from the inactive to active state. // This will happen when the extension is about to present UI. // Use this method to configure the extension and restore previously stored state. } override func didResignActive(with conversation: MSConversation) { // Called when the extension is about to move from the active to inactive state. // This will happen when the user dissmises the extension, changes to a different // conversation or quits Messages. // Use this method to release shared resources, save user data, invalidate timers, // and store enough state information to restore your extension to its current state // in case it is terminated later. } override func didReceive(_ message: MSMessage, conversation: MSConversation) { // Called when a message arrives that was generated by another instance of this // extension on a remote device. // Use this method to trigger UI updates in response to the message. } override func didStartSending(_ message: MSMessage, conversation: MSConversation) { // Called when the user taps the send button. } override func didCancelSending(_ message: MSMessage, conversation: MSConversation) { // Called when the user deletes the message without sending it. // Use this to clean up state related to the deleted message. } override func willTransition(to presentationStyle: MSMessagesAppPresentationStyle) { // Called before the extension transitions to a new presentation style. // Use this method to prepare for the change in presentation style. } override func didTransition(to presentationStyle: MSMessagesAppPresentationStyle) { // Called after the extension transitions to a new presentation style. // Use this method to finalize any behaviors associated with the change in presentation style. } }
33.467105
108
0.60861
bfcde90ae2d119a06e8bb43a29c1db0da048f7bc
82
// Kevin Li - 11:29 PM - 7/16/20 import UIKit let screen = UIScreen.main.bounds
13.666667
33
0.682927
1e556fb6442b67da1972765de9a7af01446c3ad5
2,912
// RUN: %target-typecheck-verify-swift class HasFunc { func HasFunc(_: HasFunc) { } func HasFunc() -> HasFunc { return HasFunc() } func SomethingElse(_: SomethingElse) { // expected-error {{use of undeclared type 'SomethingElse'}} return nil } func SomethingElse() -> SomethingElse? { // expected-error {{use of undeclared type 'SomethingElse'}} return nil } } class HasGenericFunc { func HasGenericFunc<HasGenericFunc : HasGenericFunc>(x: HasGenericFunc) -> HasGenericFunc { // expected-error {{inheritance from non-protocol, non-class type 'HasGenericFunc'}} return x } func SomethingElse<SomethingElse : SomethingElse>(_: SomethingElse) -> SomethingElse? { // expected-error {{inheritance from non-protocol, non-class type 'SomethingElse'}} return nil } } class HasProp { var HasProp: HasProp { return HasProp() // expected-error {{cannot call value of non-function type 'HasProp'}}{{19-21=}} } var SomethingElse: SomethingElse? { // expected-error 2 {{use of undeclared type 'SomethingElse'}} return nil } } protocol SomeProtocol {} protocol ReferenceSomeProtocol { var SomeProtocol: SomeProtocol { get } } func TopLevelFunc(x: TopLevelFunc) -> TopLevelFunc { return x } // expected-error 2 {{use of undeclared type 'TopLevelFunc'}}' func TopLevelGenericFunc<TopLevelGenericFunc : TopLevelGenericFunc>(x: TopLevelGenericFunc) -> TopLevelGenericFunc { return x } // expected-error {{inheritance from non-protocol, non-class type 'TopLevelGenericFunc'}} func TopLevelGenericFunc2<T : TopLevelGenericFunc2>(x: T) -> T { return x} // expected-error {{use of undeclared type 'TopLevelGenericFunc2'}} var TopLevelVar: TopLevelVar? { return nil } // expected-error 2 {{use of undeclared type 'TopLevelVar'}} protocol AProtocol { // FIXME: Should produce an error here, but it's currently causing problems. associatedtype e : e } // <rdar://problem/15604574> Protocol conformance checking needs to be delayed protocol P15604574 { associatedtype FooResult func foo() -> FooResult } class AcceptsP<T : P15604574> { } class X { func foo() -> AcceptsP<X> { } // expected-error {{type 'X' does not conform to protocol 'P15604574'}} } // <rdar://problem/17144076> recursive typealias causes a segfault in the type checker struct SomeStruct<A> { typealias A = A // expected-error {{type alias 'A' references itself}} // expected-note@-1 {{type declared here}} } // <rdar://problem/27680407> Infinite recursion when using fully-qualified associatedtype name that has not been defined with typealias protocol rdar27680407Proto { associatedtype T // expected-note {{protocol requires nested type 'T'; do you want to add it?}} init(value: T) } struct rdar27680407Struct : rdar27680407Proto { // expected-error {{type 'rdar27680407Struct' does not conform to protocol 'rdar27680407Proto'}} init(value: rdar27680407Struct.T) {} }
35.950617
217
0.726648
d63dfa5526adb7b53219e191a3e2b3984e8b0fb8
5,600
// // SwiftRadioSnapshots.swift // SwiftRadioSnapshots // // Created by Joe McMahon on 7/16/18. // Copyright © 2018 matthewfecher.com. All rights reserved. // import XCTest let app = XCUIApplication() class SwiftRadioSnapshots: XCTestCase { let stations = app.cells let hamburgerMenu = app.navigationBars["Swift Radio"].buttons["icon-hamburger"] let pauseButton = app.buttons["btn-stop"] let playButton = app.buttons["btn-play"] let stopButton = app.buttons["btn-stop"] let shareButton = app.buttons["sharing"] let volume = app.sliders.element(boundBy: 0) override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. setupSnapshot(app) app.launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func assertStationsPresent() { let numStations:UInt = 1 XCTAssertEqual(stations.count, Int(numStations)) let texts = stations.staticTexts.count XCTAssertEqual(texts, Int(numStations * 2)) } func assertHamburgerContent() { XCTAssertTrue(app.staticTexts["RadioSpiral"].exists) } func assertAboutContent() { XCTAssertTrue(app.buttons["email us!"].exists) XCTAssertTrue(app.buttons["radiospiral.net"].exists) } func assertPaused() { XCTAssertFalse(pauseButton.isEnabled) XCTAssertTrue(playButton.isEnabled) XCTAssertTrue(app.staticTexts["Station Paused..."].exists); } func assertStopped() { XCTAssertTrue(playButton.isEnabled) XCTAssertTrue(app.staticTexts["Station Stopped..."].exists); } func assertPlaying() { XCTAssertTrue(pauseButton.isEnabled) XCTAssertFalse(app.staticTexts["Station Stopped..."].exists); } func assertStationOnMenu(_ stationName:String) { let button = app.buttons["nowPlaying"] let value:String = button.label XCTAssertTrue(value.contains(stationName)) } func assertStationInfo() { let textView = app.textViews.element(boundBy: 0) if let value = textView.value { XCTAssertGreaterThan((value as AnyObject).length, 10) } else { XCTAssertTrue(false) } } func waitForStationToLoad() { self.expectation( for: NSPredicate(format: "exists == 0"), evaluatedWith: app.staticTexts["Loading Station..."], handler: nil) self.waitForExpectations(timeout: 25.0, handler: nil) sleep(5) } func waitForTitleToAppear() { self.expectation( for: NSPredicate(format: "exists = 0"), evaluatedWith: app.staticTexts["Captivating Electronica"], handler: nil) self.waitForExpectations(timeout: 3600.0, handler: nil) sleep(5) } func waitForStationToRestart() { self.expectation( for: NSPredicate(format: "exists == 0"), evaluatedWith: app.staticTexts["Station Stopped..."], handler:nil) self.waitForExpectations(timeout: 10.0, handler: nil) sleep(5) } func testMainStationsView() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. assertStationsPresent() snapshot("01stations") /* hamburgerMenu.tap() assertHamburgerContent() app.buttons["About"].tap() snapshot("02about") assertAboutContent() app.buttons["Okay"].tap() app.buttons["btn close"].tap() assertStationsPresent() */ let firstStation = stations.element(boundBy: 0) let stationName:String = firstStation.children(matching: .staticText).element(boundBy: 1).label assertStationOnMenu("Choose") firstStation.tap() waitForStationToLoad() waitForTitleToAppear() snapshot("02coverplay") /* stopButton.tap() assertStopped() snapshot("04stop") playButton.tap() waitForStationToRestart() waitForTitleToAppear() assertPlaying() app.navigationBars["Radio Spiral"].buttons["Back"].tap() assertStationOnMenu(stationName) //snapshot("05playonlist") app.navigationBars["Swift Radio"].buttons["btn-nowPlaying"].tap() waitForStationToLoad() volume.adjust(toNormalizedSliderPosition: 0.2) volume.adjust(toNormalizedSliderPosition: 0.8) snapshot("06voladjust") volume.adjust(toNormalizedSliderPosition: 0.5) app.buttons["More Info"].tap() assertStationInfo() snapshot("06info") app.buttons["Okay"].tap() */ app.buttons["sharing"].tap() sleep(2) snapshot("07covershare") } }
33.73494
182
0.620714
de66a9b8883bab465d04e5e31240f2e23eaeebf1
6,926
//===--- TestsUtils.swift -------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// #if os(Linux) import Glibc #else import Darwin #endif public enum BenchmarkCategory : String { // Validation "micro" benchmarks test a specific operation or critical path that // we know is important to measure. case validation // subsystems to validate and their subcategories. case api, Array, String, Dictionary, Codable, Set case sdk case runtime, refcount, metadata // Other general areas of compiled code validation. case abstraction, safetychecks, exceptions, bridging, concurrency // Algorithms are "micro" that test some well-known algorithm in isolation: // sorting, searching, hashing, fibonaci, crypto, etc. case algorithm // Miniapplications are contrived to mimic some subset of application behavior // in a way that can be easily measured. They are larger than micro-benchmarks, // combining multiple APIs, data structures, or algorithms. This includes small // standardized benchmarks, pieces of real applications that have been extracted // into a benchmark, important functionality like JSON parsing, etc. case miniapplication // Regression benchmarks is a catch-all for less important "micro" // benchmarks. This could be a random piece of code that was attached to a bug // report. We want to make sure the optimizer as a whole continues to handle // this case, but don't know how applicable it is to general Swift performance // relative to the other micro-benchmarks. In particular, these aren't weighted // as highly as "validation" benchmarks and likely won't be the subject of // future investigation unless they significantly regress. case regression // Most benchmarks are assumed to be "stable" and will be regularly tracked at // each commit. A handful may be marked unstable if continually tracking them is // counterproductive. case unstable // CPU benchmarks represent instrinsic Swift performance. They are useful for // measuring a fully baked Swift implementation across different platforms and // hardware. The benchmark should also be reasonably applicable to real Swift // code--it should exercise a known performance critical area. Typically these // will be drawn from the validation benchmarks once the language and standard // library implementation of the benchmark meets a reasonable efficiency // baseline. A benchmark should only be tagged "cpubench" after a full // performance investigation of the benchmark has been completed to determine // that it is a good representation of future Swift performance. Benchmarks // should not be tagged if they make use of an API that we plan on // reimplementing or call into code paths that have known opportunities for // significant optimization. case cpubench // Explicit skip marker case skip } public struct BenchmarkInfo { /// The name of the benchmark that should be displayed by the harness. public var name: String /// A function that invokes the specific benchmark routine. public var runFunction: (Int) -> () /// A set of category tags that describe this benchmark. This is used by the /// harness to allow for easy slicing of the set of benchmarks along tag /// boundaries, e.x.: run all string benchmarks or ref count benchmarks, etc. public var tags: [BenchmarkCategory] /// An optional function that if non-null is run before benchmark samples /// are timed. public var setUpFunction: (() -> ())? /// An optional function that if non-null is run immediately after a sample is /// taken. public var tearDownFunction: (() -> ())? public init(name: String, runFunction: @escaping (Int) -> (), tags: [BenchmarkCategory], setUpFunction: (() -> ())? = nil, tearDownFunction: (() -> ())? = nil) { self.name = name self.runFunction = runFunction self.tags = tags self.setUpFunction = setUpFunction self.tearDownFunction = tearDownFunction } } extension BenchmarkInfo : Comparable { public static func < (lhs: BenchmarkInfo, rhs: BenchmarkInfo) -> Bool { return lhs.name < rhs.name } public static func == (lhs: BenchmarkInfo, rhs: BenchmarkInfo) -> Bool { return lhs.name == rhs.name } } extension BenchmarkInfo : Hashable { public var hashValue: Int { return name.hashValue } } // Linear function shift register. // // This is just to drive benchmarks. I don't make any claim about its // strength. According to Wikipedia, it has the maximal period for a // 32-bit register. struct LFSR { // Set the register to some seed that I pulled out of a hat. var lfsr : UInt32 = 0xb78978e7 mutating func shift() { lfsr = (lfsr >> 1) ^ (UInt32(bitPattern: -Int32((lfsr & 1))) & 0xD0000001) } mutating func randInt() -> Int64 { var result : UInt32 = 0 for _ in 0..<32 { result = (result << 1) | (lfsr & 1) shift() } return Int64(bitPattern: UInt64(result)) } } var lfsrRandomGenerator = LFSR() // Start the generator from the beginning public func SRand() { lfsrRandomGenerator = LFSR() } public func Random() -> Int64 { return lfsrRandomGenerator.randInt() } @inline(__always) public func CheckResults( _ resultsMatch: Bool, file: StaticString = #file, function: StaticString = #function, line: Int = #line ) { guard _fastPath(resultsMatch) else { print("Incorrect result in \(function), \(file):\(line)") abort() } } public func False() -> Bool { return false } /// This is a dummy protocol to test the speed of our protocol dispatch. public protocol SomeProtocol { func getValue() -> Int } struct MyStruct : SomeProtocol { init() {} func getValue() -> Int { return 1 } } public func someProtocolFactory() -> SomeProtocol { return MyStruct() } // Just consume the argument. // It's important that this function is in another module than the tests // which are using it. @inline(never) public func blackHole<T>(_ x: T) { } // Return the passed argument without letting the optimizer know that. @inline(never) public func identity<T>(_ x: T) -> T { return x } // Return the passed argument without letting the optimizer know that. // It's important that this function is in another module than the tests // which are using it. @inline(never) public func getInt(_ x: Int) -> Int { return x } // The same for String. @inline(never) public func getString(_ s: String) -> String { return s }
35.15736
90
0.699394
50dc399a04ee5956d202cb2d7a0f354b3c2c0a9b
7,084
// // SocialShare.swift // realreview-iOS // // Created by JungMoon-Mac on 2018. 5. 29.. // Copyright © 2018년 JungMoon. All rights reserved. // import UIKit import KakaoMessageTemplate import KakaoCommon import KakaoLink import FBSDKShareKit let kContentText = "'집합' 공유 글 보기" protocol SocialShare: class { func share(title: String, imageUrl: String, linkUrl: String) func canOpenApp() -> Bool? } class SocialShareKakaoTalk: SocialShare { func share(title: String, imageUrl: String, linkUrl: String) { let template = KMTFeedTemplate { (feedTemplateBuilder) in feedTemplateBuilder.content = KMTContentObject(builderBlock: { (contentBuilder) in contentBuilder.title = title contentBuilder.desc = kContentText if let imageUrl = URL(string: imageUrl) { contentBuilder.imageURL = imageUrl } contentBuilder.link = KMTLinkObject(builderBlock: { (linkBuilder) in linkBuilder.webURL = URL(string: linkUrl) linkBuilder.mobileWebURL = URL(string: linkUrl) }) }) feedTemplateBuilder.addButton(KMTButtonObject(builderBlock: { (buttonBuilder) in buttonBuilder.title = "바로 확인하기" buttonBuilder.link = KMTLinkObject(builderBlock: { (linkBuilder) in linkBuilder.webURL = URL(string: linkUrl) linkBuilder.mobileWebURL = URL(string: linkUrl) }) })) } KLKTalkLinkCenter.shared().sendDefault(with: template, success: { (warningMessage, argumentMessage) in }, failure: { (error) in print("error \(error)") }) } func canOpenApp() -> Bool? { return UIApplication.shared.canOpenURL(URL(string: "kakaolink://")!) } } enum ScrapType: String { case website case video case music case book case article case profile } struct ScrapInfo { var title: String! var desc: String! var imageUrls: [String]! var type: ScrapType! func toJsonString() -> String! { var dictionary = [String: AnyObject]() if title != nil { dictionary["title"] = title as AnyObject? } if desc != nil { dictionary["desc"] = desc as AnyObject? } if let imageUrls = imageUrls, imageUrls.count > 0 { dictionary["imageurl"] = imageUrls as AnyObject? } if type != nil { dictionary["type"] = type.rawValue as AnyObject? } if dictionary.count == 0 { return nil } return SocialShareKakaoStory.convertJsonString(dictionary as AnyObject) } } class SocialShareKakaoStory: SocialShare { let storyLinkURLBaseString = "storylink://posting" func canOpenApp() -> Bool? { return UIApplication.shared.canOpenURL(URL(string: "storylink://")!) } func share(title: String, imageUrl: String, linkUrl: String) { var scrapInfo = ScrapInfo() scrapInfo.title = kContentText scrapInfo.desc = title scrapInfo.imageUrls = [imageUrl] scrapInfo.type = ScrapType.website // let urlString = makeStoryLink("\(kContentText)\n\(title)\n\(linkUrl)", // appBundleId: "com.zuminternet.ios.realreview", // appVersion: "1.0", // appName: "핏뷰", // scrapInfo: scrapInfo)! // let url = URL(string: urlString) // UIApplication.shared.open(url!, options: [:], completionHandler: nil) } func makeStoryLink(_ postingText: String, appBundleId: String, appVersion: String, appName: String, scrapInfo: ScrapInfo!) -> String! { var parameters: [String: String] = [String: String]() parameters["post"] = postingText parameters["apiver"] = "1.0" parameters["appid"] = appBundleId parameters["appver"] = appVersion parameters["appname"] = appName if let scrapInfo = scrapInfo, let infoString = scrapInfo.toJsonString() { parameters["urlinfo"] = infoString } let parameterString = self.HTTPArgumentsStringForParameters(parameters) return "\(storyLinkURLBaseString)?\(parameterString ?? "")" } func canOpenStoryLink() -> Bool { if let url = URL(string: storyLinkURLBaseString) { return UIApplication.shared.canOpenURL(url) } return false } func HTTPArgumentsStringForParameters(_ parameters: [String: String]) -> String! { let arguments: NSMutableArray = NSMutableArray(capacity: parameters.count) for (key, value) in parameters { arguments.add("\(key)=\(encodedURLString(value))") } return arguments.componentsJoined(by: "&") } func encodedURLString(_ string: String) -> String { //let customAllowedSet = CharacterSet(charactersIn: ":/?#[]@!$ &'()*+,;=\"<>%{}|\\^~`").inverted return string.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)! } static func convertJsonString(_ object: AnyObject) -> String! { if let jsonData: Data = try? JSONSerialization.data(withJSONObject: object, options: JSONSerialization.WritingOptions(rawValue: 0)) { if let jsonString = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue) { return String(jsonString) } } return nil } } class SocialShareFacebook: SocialShare { func share(title: String, imageUrl: String, linkUrl: String) { let linkContent = FBSDKShareLinkContent() linkContent.contentURL = URL(string: linkUrl)! let appDelete = UIApplication.shared.delegate guard let viewController = appDelete?.window??.rootViewController else { return } if let viewController = viewController.presentedViewController { FBSDKShareDialog.show(from: viewController, with: linkContent, delegate: nil) } else { FBSDKShareDialog.show(from: viewController, with: linkContent, delegate: nil) } } func canOpenApp() -> Bool? { return nil } } class SocialShareLine: SocialShare { func share(title: String, imageUrl: String, linkUrl: String) { var urlString = "line://msg/text/?\(linkUrl)" urlString = urlString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)! let url = URL(string: urlString) UIApplication.shared.open(url!, options: [:], completionHandler: nil) } func canOpenApp() -> Bool? { return UIApplication.shared.canOpenURL(URL(string: "line://")!) } }
34.222222
141
0.588933
48cd134dbd8a8772eeb3df4d5a2452ff36d2be5e
999
// Copyright © 2020 Mark Moeykens. All rights reserved. | @BigMtnStudio import SwiftUI struct Edges_Landscape_After: View { var body: some View { VStack(spacing: 20) { Text("Ignores Safe Area") .padding() .font(.largeTitle) .frame(maxWidth: .infinity) .foregroundColor(.black) .background(Color.orange) Text("Landscape") .foregroundColor(.gray) Text("You can ignore multiple edges at the same time by using an array.") .padding() .foregroundColor(.black) .frame(maxWidth: .infinity, maxHeight: .infinity) .background(Color.orange) } .font(.title) .ignoresSafeArea(edges: [.horizontal, .bottom]) } } struct Edges_Landscape_After_Previews: PreviewProvider { static var previews: some View { Edges_Landscape_After() } }
29.382353
85
0.546547
0861bc806c20d29b570b07813a4cf5701f1ddc75
469
/// For use with TestSubrouter.swift import Kitura import KituraNet class ExternSubrouter { static func getRouter() -> Router { let externSubrouter = Router() externSubrouter.get("/") { request, response, next in response.status(HttpStatusCode.OK).send("hello from the sub") next() } externSubrouter.get("/sub1") { request, response, next in response.status(HttpStatusCode.OK).send("sub1") next() } return externSubrouter } }
20.391304
67
0.686567
f88ef9dbe2f2acc7fe07efbe846688088c6ab7f7
364
// // ViewController.swift // TableView // // Created by Mitchell Petellin on 4/1/19. // Copyright © 2019 Mitchell Petellin. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } }
17.333333
80
0.675824
f922694cbf3ca93189c88b9df55aa3528658984c
4,130
// // PasswordChangeInteractor.swift // Blogs // // Created by Vyacheslav Pronin on 13.08.2021. // // import Foundation final class PasswordChangeInteractor { weak var output: PasswordChangeInteractorOutput? private var oldPassword = "" private var repeatPassword = "" private var newPassword = "" private func checkNewPassword(pass: String) -> Bool { let text = pass.trimmingCharacters(in: .whitespaces) switch text { case let text where text.isEmpty: output?.transferErrorNewPassword(text: StandartLanguage.newPasswordIsEmptyPasswordChangeScreen) return false case let text where text == oldPassword: output?.transferErrorNewPassword(text: StandartLanguage.newPasswordEqualityPasswordChangeScreen) return false case let text where text.count < 6: output?.transferErrorNewPassword(text: StandartLanguage.newPasswordLittlePasswordChangeScreen) return false case let text where text.count > 40: output?.transferErrorNewPassword(text: StandartLanguage.newPasswordMorePasswordChangeScreen) return false default: newPassword = text output?.transferErrorNewPassword(text: "") return true } } private func checkRepeatPassword(pass: String) -> Bool { let text = pass.trimmingCharacters(in: .whitespaces) switch text { case let text where text.isEmpty: output?.transferErrorRepeatPassword(text: StandartLanguage.repeatPasswordIsEmptyPasswordChangeScreen) return false case let text where text != newPassword: output?.transferErrorRepeatPassword(text: StandartLanguage.repeatPasswordNotEqualityPasswordChangeScreen) return false default: output?.transferErrorRepeatPassword(text: "") return true } } private func resetSignIn(pass: String) { //Повторно авторизируем пользователя, чтобы в дальнейшем изменить его пароль UserManager.resetSignIn(pass: pass, failClosure: { [weak self] in self?.output?.transferErrorOldPassword(text: StandartLanguage.oldPasswordNotCorrectPasswordChangeScreen) }, sucsessClosure: { [weak self] in self?.output?.transferErrorOldPassword(text: "") guard let newPassword = self?.newPassword else { return } guard let repeatPassword = self?.repeatPassword else { return } if self?.checkNewPassword(pass: newPassword) ?? false, self?.checkRepeatPassword(pass: repeatPassword) ?? false { self?.updatePassword(pass: newPassword) } }) } private func updatePassword(pass: String) { UserManager.updatePassword(pass: pass, failClosure: { [weak self] in self?.output?.transferErrorOldPassword(text: StandartLanguage.errorUpdatePasswordPasswordChangeScreen) }, sucsessClosure: { [weak self] in self?.output?.openBackViewController() }) } } extension PasswordChangeInteractor: PasswordChangeInteractorInput { func backController() { output?.openBackViewController() } func giveOldPasswordText(text: String) { oldPassword = text } func newPasswordText(text: String) { newPassword = text } func newRepeatPasswordText(text: String) { repeatPassword = text } func verificationOfEnteredData() { resetSignIn(pass: oldPassword) } }
38.598131
140
0.576029
0892041f8a41a824e0203bf277c3b0d8c152ee81
2,236
// // AddCompetitionViewController.swift // JavaScouting2019 // // Created by Keegan on 2/12/19. // Copyright © 2019 JavaScouts. All rights reserved. // import UIKit import Firebase class AddCompetitionViewController: UIViewController { @IBOutlet var navBar: UINavigationBar! @IBOutlet var nameTextField: UITextField! var db: Firestore! var comp: Competition = Competition(compID: nil, compname: "", path: "", teams: nil) var path = "test-competitions/" override func viewDidLoad() { super.viewDidLoad() db = Firestore.firestore() navBar.topItem?.title = "Add New Competition" } @IBAction func onGoButtonPress(_ sender: Any) { var ref: DocumentReference! ref = db.collection("/test-competitions/").addDocument(data: [ "compname": nameTextField.text as Any, "path": "/test-competitions/" ]) { err in if let err = err { print("Error adding document: \(err)") } else { print("Document added with ID: \(ref!.documentID)") self.comp.compID = ref!.documentID self.comp.compname = self.nameTextField.text! } } path += ref!.documentID + "/" } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let identifier = segue.identifier switch identifier { case "newCompToDetail": let tab = segue.destination as! UITabBarController let vcs = tab.viewControllers! let nav1 = vcs[0] as! UINavigationController let destination1 = nav1.viewControllers.first as! TeamsViewController //destination1.matchPath = comp.path + "matches/" destination1.path = comp.path + "teams/" let nav2 = vcs[1] as! UINavigationController let destination2 = nav2.viewControllers.first as! MatchTableViewController destination2.matchPath = comp.path + "matches/" destination2.teamPath = comp.path + "teams/" let nav3 = vcs[2] as! UINavigationController let destination3 = nav3.viewControllers.first as! AnalysisViewController destination3.matchPath = comp.path + "matches/" destination3.teamPath = comp.path + "teams/" default: print("unknown segue identifier") } } }
29.421053
106
0.702594
0e2e9b2846b20abbb413f4733101f93b5cc9d8f3
8,062
// // TaskQueue.swift // Overdrive // // Created by Said Sikira on 6/19/16. // Copyright © 2016 Said Sikira. All rights reserved. // import class Foundation.Operation import class Foundation.OperationQueue import class Foundation.DispatchQueue import class Foundation.DispatchGroup import enum Foundation.QualityOfService /** Provides interface for `Task<T>` execution and concurrency. ### **Task execution** --- To schedule task for execution, add it to instance of `TaskQueue` by using `addTask(_:)` or `addTasks(_:)` method. ```swift let queue = TaskQueue() queue.add(task: someTask) ``` After the task is added to the `TaskQueue` complex process of task readiness evaluation begins. When the task reaches `ready` state, it is executed until it reaches `finished` state by calling `finish(_:)` method inside task. If task has no conditions or dependencies, it becomes `ready` immediately. If task has dependencies or conditions, dependencies are executed first and conditions are evaluated after that. ### **Running tasks on specific queues** --- `TaskQueue` is queue aware, meaning that you can set up the `TaskQueue` object with specific dispatch queue so that any task execution performs on that defined queue. There are two predefined `TaskQueue` instances already associated with main and background queues. - `TaskQueue.main` - Associated with main UI thread, suitable for execution tasks that application UI is dependent on. - `TaskQueue.background` - Associated with background queue. Any task that is added to this queue will be executed in the background. In addition to the queue specification, you can also create [**Quality Of Service**](https://developer.apple.com/library/content/documentation/Performance/Conceptual/EnergyGuide-iOS/PrioritizeWorkWithQoS.html) aware task queues by passing `NSQualityOfService` object to the initializer. **Quality Of Service** class allows you to categorize type of work that is executed. For example `.UserInteractive` quality of service class is used for the work that is performed by the user and that should be executed immediately. To create `TaskQueue` with specific `QOS` class use designated initializer: ```swift let queue = TaskQueue(qos: .userInteractive) ``` ### **Concurrency** Task queue executes tasks concurrently by default and it's multicore aware meaning that it can use full hardware potential to execute work. Tasks do not execute one after another, rather they are executed concurrently when they reach `ready` state. To specify maximum number of concurrent task executions use `maxConcurrentOperationCount` property. ```swift let queue = TaskQueue() queue.maxConcurrentTaskCount = 3 ``` ### **TaskQueueDelegate** `TaskQueue` has a custom delegate which can be used to monitor certain events in `TaskQueue` lifecycle. See `TaskQueueDelegate` for more information */ open class TaskQueue { /// Underlying `Foundation.OperationQueue` instance used for executing /// `Foundation.Operation` operations internal let operationQueue: OperationQueue = OperationQueue() /** Returns queue associated with application main queue. **Example** ```swift let task = SomeTask() TaskQueue.main.add(task: task) ``` */ open static let main: TaskQueue = { let queue = TaskQueue() queue.operationQueue.underlyingQueue = OperationQueue.main.underlyingQueue return queue }() /** Returns queue associated with application background queue. **Example:** ```swift let task = SomeTask() TaskQueue.background.add(task: task) ``` */ open static let background: TaskQueue = { let queue = TaskQueue() queue.operationQueue.underlyingQueue = DispatchQueue.global(qos: .background) return queue }() /// TaskQueue delegate object weak open var delegate: TaskQueueDelegate? /// Boolean indicating if queue is actively scheduling tasks execution open var isSuspended: Bool { get { return operationQueue.isSuspended } set(suspended) { operationQueue.willChangeValue(forKey: "isSuspended") operationQueue.isSuspended = suspended operationQueue.didChangeValue(forKey: "isSuspended") for task in tasks { task.enqueue(suspended: suspended) } } } /// Returns all active tasks in the queue open var tasks: [Operation] { return operationQueue.operations } /// Specifies service level that is used in executing tasks /// in the current queue. open var qos: QualityOfService { get { return operationQueue.qualityOfService } set(newQos) { operationQueue.qualityOfService = newQos } } /// Queue name identifier open var name: String? /// The maximum number of tasks that can be executed at the same time /// concurrently. open var maxConcurrentTaskCount: Int { get { return operationQueue.maxConcurrentOperationCount } set(newCount) { operationQueue.maxConcurrentOperationCount = newCount } } // MARK: Init methods /// Creates instance of `TaskQueue` public init() { } /** Initilizes TaskQueue with specific `NSQualityOfService` class. Defining quality of service class will later determine how tasks are executed. */ public init(qos: QualityOfService) { operationQueue.qualityOfService = qos } /** Initializes TaskQueue with specific dispatch queue. - note: Setting underlying queue for the TaskQueue will override any Quality Of Service setting on TaskQueue. */ public init(queue: DispatchQueue) { operationQueue.underlyingQueue = queue } //MARK: Task management /** Add task to the TaskQueue and starts execution. Method will call delegate method responsible for adding task. - Parameter task: Task<T> to be added */ open func add<T>(task: Task<T>) { if !task.contains(observer: FinishBlockObserver.self) { task.add(observer: FinishBlockObserver( finishExecutionBlock: { [weak self, unowned task] in if let queue = self { queue.delegate?.didFinish(task: task, in: queue) } }, willFinishExecutionBlock: { [weak self, unowned task] in if let queue = self { queue.delegate?.willFinish(task: task, in: queue) } })) } // Evaluate condition dependencies and add them to the queue task .conditions .flatMap { $0.dependencies(forTask: task) } .forEach { add(dependency: $0, forTask: task) } operationQueue.addOperation(task) delegate?.didAdd(task: task, to: self) task.enqueue(suspended: isSuspended) } /// Adds dependency for specific task /// /// - Parameters: /// - dependency: `Foundation.Operation` subclass /// - task: `Task<T>` to add dependency to fileprivate func add<T>(dependency: Operation, forTask task: Task<T>) { task.add(dependency: dependency) operationQueue.addOperation(dependency) dependency.enqueue(suspended: isSuspended) } func executeSuspendedTasks() { } } // MARK: - CustomStringConvertible extension TaskQueue: CustomStringConvertible { public var description: String { return name ?? operationQueue.description } } // MARK: - CustomDebugStringConvertible extension TaskQueue: CustomDebugStringConvertible { public var debugDescription: String { return "Name: \(String(describing: name)), qos: \(qos), Task count: \(tasks.count)" } }
31.127413
157
0.662739
28d4bb56196b968fb5fa75fc06286211b1250380
5,666
// // LoginSplashViewController.swift // Freetime // // Created by Ryan Nystrom on 7/8/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import UIKit import SafariServices import GitHubAPI import GitHubSession private let loginURL = URL(string: "http://github.com/login/oauth/authorize?client_id=\(Secrets.GitHub.clientId)&scope=user+repo+notifications")! private let callbackURLScheme = "freetime://" final class LoginSplashViewController: UIViewController, GitHubSessionListener { enum State { case idle case fetchingToken } private var client: Client! private var sessionManager: GitHubSessionManager! @IBOutlet weak var splashView: SplashView! @IBOutlet weak var signInButton: UIButton! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! private weak var safariController: SFSafariViewController? @available(iOS 11.0, *) private var authSession: SFAuthenticationSession? { get { return _authSession as? SFAuthenticationSession } set { _authSession = newValue } } private var _authSession: Any? var state: State = .idle { didSet { let hideSpinner: Bool switch state { case .idle: hideSpinner = true case .fetchingToken: hideSpinner = false } signInButton.isEnabled = hideSpinner activityIndicator.isHidden = hideSpinner let title = hideSpinner ? NSLocalizedString("Sign in with GitHub", comment: "") : NSLocalizedString("Signing in...", comment: "") signInButton.setTitle(title, for: .normal) } } override func viewDidLoad() { super.viewDidLoad() state = .idle sessionManager.addListener(listener: self) signInButton.layer.cornerRadius = Styles.Sizes.cardCornerRadius } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) setupSplashView() } // MARK: Public API func config(client: Client, sessionManager: GitHubSessionManager) { self.client = client self.sessionManager = sessionManager } // MARK: Private API @IBAction func onSignInButton(_ sender: Any) { self.authSession = SFAuthenticationSession(url: loginURL, callbackURLScheme: callbackURLScheme, completionHandler: { [weak self] (callbackUrl, error) in guard error == nil, let callbackUrl = callbackUrl else { switch error! { case SFAuthenticationError.canceledLogin: break default: self?.handleError() } return } self?.sessionManager.receivedCodeRedirect(url: callbackUrl) }) self.authSession?.start() } @IBAction func onPersonalAccessTokenButton(_ sender: Any) { let alert = UIAlertController.configured( title: NSLocalizedString("Personal Access Token", comment: ""), message: NSLocalizedString("Sign in with a Personal Access Token with both repo and user scopes.", comment: ""), preferredStyle: .alert ) alert.addTextField { (textField) in textField.placeholder = NSLocalizedString("Personal Access Token", comment: "") } alert.addActions([ AlertAction.cancel(), AlertAction.login({ [weak alert, weak self] _ in alert?.actions.forEach { $0.isEnabled = false } self?.state = .fetchingToken let token = alert?.textFields?.first?.text ?? "" self?.client.send(V3VerifyPersonalAccessTokenRequest(token: token)) { result in switch result { case .failure: self?.handleError() case .success(let user): self?.finishLogin(token: token, authMethod: .pat, username: user.data.login) } } }) ]) present(alert, animated: trueUnlessReduceMotionEnabled) } private func handleError() { state = .idle let alert = UIAlertController.configured( title: NSLocalizedString("Error", comment: ""), message: NSLocalizedString("There was an error signing in to GitHub. Please try again.", comment: ""), preferredStyle: .alert ) alert.addAction(AlertAction.ok()) present(alert, animated: trueUnlessReduceMotionEnabled) } private func finishLogin(token: String, authMethod: GitHubUserSession.AuthMethod, username: String) { sessionManager.focus( GitHubUserSession(token: token, authMethod: authMethod, username: username), dismiss: true ) } private func setupSplashView() { splashView.configureView() } // MARK: GitHubSessionListener func didReceiveRedirect(manager: GitHubSessionManager, code: String) { safariController?.dismiss(animated: trueUnlessReduceMotionEnabled) state = .fetchingToken client.requestAccessToken(code: code) { [weak self] result in switch result { case .error: self?.handleError() case .success(let user): self?.finishLogin(token: user.token, authMethod: .oauth, username: user.username) } } } func didFocus(manager: GitHubSessionManager, userSession: GitHubUserSession, dismiss: Bool) {} func didLogout(manager: GitHubSessionManager) {} }
32.94186
160
0.616131
18d4c38c54e182f354cf0e9c4854e9527006cc40
1,321
// // UIRefreshControl.swift // WaveLabs // // Created by Vlad Gorlov on 06.06.2020. // Copyright © 2020 Vlad Gorlov. All rights reserved. // #if canImport(UIKit) import mcxTypes import UIKit @available(tvOS, unavailable) extension UIRefreshControl { public func endRefreshingIfNeeded() { if isRefreshing { endRefreshing() } } public func beginRefreshingIfNeeded() { if !isRefreshing { beginRefreshing() } } } @available(tvOS, unavailable) extension UIRefreshControl { public typealias Handler = (() -> Void) private enum OBJCAssociationKeys { static var refreshControlHandler = "com.mc.refreshControlHandler" } public convenience init(handler: Handler?) { self.init() addTarget(self, action: #selector(mcRefreshControlValueChanged(_:)), for: .valueChanged) if let handler = handler { ObjCAssociation.setCopyNonAtomic(value: handler, to: self, forKey: &OBJCAssociationKeys.refreshControlHandler) } } @objc private func mcRefreshControlValueChanged(_ sender: UIRefreshControl) { guard sender == self else { return } if let handler: Handler = ObjCAssociation.value(from: self, forKey: &OBJCAssociationKeys.refreshControlHandler) { handler() } } } #endif
23.589286
119
0.676003
fb4988f7e49a7ceab087976ad310f24ce6feacfa
10,966
// // Copyright (c) 2020 Related Code - http://relatedcode.com // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit //------------------------------------------------------------------------------------------------------------------------------------------------- class SearchView: UIViewController { @IBOutlet var labelDescription: UILabel! @IBOutlet var segmentControl: UISegmentedControl! @IBOutlet var labelFrom: UILabel! @IBOutlet var labelTo: UILabel! @IBOutlet var labelWeek: UILabel! @IBOutlet var labelFromDate: UILabel! @IBOutlet var labelToDate: UILabel! @IBOutlet var labelAdults: UILabel! @IBOutlet var labelChildrens: UILabel! let locations = ["New York, USA", "Moscow, Russia", "Palo-Alto, CA", "Moscow, Russia", "Palo-Alto, CA", "Moscow, Russia"] let counts = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"] var isLocations = true //--------------------------------------------------------------------------------------------------------------------------------------------- override func viewDidLoad() { super.viewDidLoad() title = "Search" navigationController?.navigationBar.prefersLargeTitles = true navigationItem.largeTitleDisplayMode = .always segmentControl.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.white], for: .selected) segmentControl.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: AppColor.Theme], for: .normal) updateUI() loadData() } //--------------------------------------------------------------------------------------------------------------------------------------------- override func viewWillDisappear(_ animated: Bool) { navigationController?.navigationBar.prefersLargeTitles = false navigationItem.largeTitleDisplayMode = .automatic } //--------------------------------------------------------------------------------------------------------------------------------------------- override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) updateUI() } // MARK: - Data methods //--------------------------------------------------------------------------------------------------------------------------------------------- func loadData() { labelDescription.text = "Refine your search by places, duration or persons" labelFrom.text = "New York, USA" labelTo.text = "Moscow, Russia" labelWeek.text = "2 weeks" labelFromDate.text = "Apr 28" labelToDate.text = "May 11" labelAdults.text = "2 adults" labelChildrens.text = "3 childrens" } // MARK: - Helper methods //--------------------------------------------------------------------------------------------------------------------------------------------- func updateUI() { let background = UIColor.systemBackground.image(segmentControl.frame.size) let selected = AppColor.Theme.image(segmentControl.frame.size) segmentControl.setTitleTextAttributes([NSAttributedString.Key.foregroundColor : UIColor.white], for: .selected) segmentControl.setTitleTextAttributes([NSAttributedString.Key.foregroundColor : AppColor.Theme], for: .normal) segmentControl.setBackgroundImage(background, for: .normal, barMetrics: .default) segmentControl.setBackgroundImage(selected, for: .selected, barMetrics: .default) segmentControl.setDividerImage(AppColor.Theme.image(), forLeftSegmentState: .normal, rightSegmentState: [.normal, .highlighted, .selected], barMetrics: .default) segmentControl.layer.borderWidth = 1 segmentControl.layer.borderColor = AppColor.Theme.cgColor } // MARK: - User actions //--------------------------------------------------------------------------------------------------------------------------------------------- @IBAction func actionSegment(_ sender: Any) { print(#function) } //--------------------------------------------------------------------------------------------------------------------------------------------- @IBAction func actionFrom(_ sender: Any) { isLocations = true showPickerView(title: "Select from", label: labelFrom, valueIndicator: nil) } //--------------------------------------------------------------------------------------------------------------------------------------------- @IBAction func actionTo(_ sender: Any) { isLocations = true showPickerView(title: "Select to", label: labelTo, valueIndicator: nil) } //--------------------------------------------------------------------------------------------------------------------------------------------- @IBAction func actionFromDate(_ sender: Any) { showDatePickerView(title: "Select from date", label: labelFromDate) } //--------------------------------------------------------------------------------------------------------------------------------------------- @IBAction func actionToDate(_ sender: Any) { showDatePickerView(title: "Select to date", label: labelToDate) } //--------------------------------------------------------------------------------------------------------------------------------------------- @IBAction func actionAdults(_ sender: Any) { isLocations = false showPickerView(title: "Select adults", label: labelAdults, valueIndicator: "adults") } //--------------------------------------------------------------------------------------------------------------------------------------------- @IBAction func actionChildrens(_ sender: Any) { isLocations = false showPickerView(title: "Select childrens", label: labelChildrens, valueIndicator: "childrens") } //--------------------------------------------------------------------------------------------------------------------------------------------- @IBAction func actionSearch(_ sender: Any) { } // MARK: - Picker methods //--------------------------------------------------------------------------------------------------------------------------------------------- func showPickerView(title: String, label: UILabel, valueIndicator: String?) { let alertView = UIAlertController(title: title, message: nil, preferredStyle: .actionSheet) let height:NSLayoutConstraint = NSLayoutConstraint(item: alertView.view!, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: 300) alertView.view.addConstraint(height) let pickerview = UIPickerView(frame: CGRect(x: 0, y: 35, width: alertView.view.frame.size.width - 16, height: 200)) pickerview.delegate = self pickerview.dataSource = self alertView.view.addSubview(pickerview) alertView.addAction(UIAlertAction(title: "OK", style: .cancel, handler: { action in if self.isLocations { label.text = self.locations[pickerview.selectedRow(inComponent: 0)] } else { label.text = self.counts[pickerview.selectedRow(inComponent: 0)] + " " + (valueIndicator ?? "") } })) present(alertView, animated: true, completion: nil) } //--------------------------------------------------------------------------------------------------------------------------------------------- func showDatePickerView(title: String, label: UILabel) { let alertView = UIAlertController(title: title, message: nil, preferredStyle: .actionSheet) let height:NSLayoutConstraint = NSLayoutConstraint(item: alertView.view!, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: 300) alertView.view.addConstraint(height) let datepickerview = UIDatePicker(frame: CGRect(x: 0, y: 35, width: alertView.view.frame.size.width - 16, height: 200)) datepickerview.datePickerMode = .date alertView.view.addSubview(datepickerview) let dateformattor = DateFormatter() dateformattor.dateFormat = "MMM dd" alertView.addAction(UIAlertAction(title: "OK", style: .cancel, handler: { action in label.text = dateformattor.string(from: datepickerview.date) let date1 = dateformattor.date(from: self.labelFromDate.text ?? "Apr 28") let date2 = dateformattor.date(from: self.labelToDate.text ?? "May 11") self.labelWeek.text = "\(date2?.weeks(from: date1 ?? Date()) ?? 2) weeks" })) present(alertView, animated: true, completion: nil) } } // MARK: - UIPickerViewDelegate //------------------------------------------------------------------------------------------------------------------------------------------------- extension SearchView: UIPickerViewDelegate { //--------------------------------------------------------------------------------------------------------------------------------------------- func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { if isLocations { return locations[row] } else { return counts[row] } } } // MARK: - UIPickerViewDataSource //------------------------------------------------------------------------------------------------------------------------------------------------- extension SearchView: UIPickerViewDataSource { //--------------------------------------------------------------------------------------------------------------------------------------------- func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } //--------------------------------------------------------------------------------------------------------------------------------------------- func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { if isLocations { return locations.count } else { return counts.count } } //--------------------------------------------------------------------------------------------------------------------------------------------- func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat { return 30.0 } } // MARK: - UIColor //------------------------------------------------------------------------------------------------------------------------------------------------- fileprivate extension UIColor { //--------------------------------------------------------------------------------------------------------------------------------------------- func image(_ size: CGSize = CGSize(width: 1, height: 1)) -> UIImage { return UIGraphicsImageRenderer(size: size).image { rendererContext in setFill() rendererContext.fill(CGRect(origin: .zero, size: size)) } } }
43.515873
268
0.508846
d52d39f48fb96f142ea32119f545e37fd743826f
4,652
// Copyright 2020 Itty Bitty Apps Pty Ltd import CodableCSV import Foundation import Model import Files import Yams struct TestFlightConfigurationProcessor { let path: String init(path: String) { self.path = path } private static let appYAMLName = "app.yml" private static let betaTestersCSVName = "beta-testers.csv" private static let betaGroupFolderName = "betagroups" func writeConfiguration(_ configuration: TestFlightConfiguration) throws { let appsFolder = try Folder(path: path) try appsFolder.delete() let rowsForTesters: ([BetaTester]) -> [[String]] = { testers in let headers = [BetaTester.CodingKeys.allCases.map(\.rawValue)] let rows = testers.map { [$0.email, $0.firstName, $0.lastName] } return headers + rows } let filenameForBetaGroup: (BetaGroup) -> String = { betaGroup in return betaGroup.groupName .components(separatedBy: CharacterSet(charactersIn: " *?:/\\.")) .joined(separator: "_") + ".yml" } try configuration.appConfigurations.forEach { config in let appFolder = try appsFolder.createSubfolder(named: config.app.bundleId) let appFile = try appFolder.createFile(named: Self.appYAMLName) let appYAML = try YAMLEncoder().encode(config.app) try appFile.write(appYAML) let testersFile = try appFolder.createFile(named: Self.betaTestersCSVName) let testerRows = rowsForTesters(config.betaTesters) let testersCSV = try CSVWriter.encode(rows: testerRows, into: String.self) try testersFile.write(testersCSV) let groupFolder = try appFolder.createSubfolder(named: Self.betaGroupFolderName) let groupFiles: [(fileName: String, yamlData: String)] = try config.betaGroups.map { (filenameForBetaGroup($0), try YAMLEncoder().encode($0)) } try groupFiles.forEach { file in try groupFolder.createFile(named: file.fileName).append(file.yamlData) } } } enum Error: LocalizedError { case testerNotInTestersList(email: String, betaGroup: BetaGroup, app: App) var errorDescription: String? { switch self { case .testerNotInTestersList(let email, let betaGroup, let app): return "Tester with email: \(email) in beta group named: \(betaGroup.groupName) " + "for app: \(app.bundleId) is not included in the \(betaTestersCSVName) file" } } } func readConfiguration() throws -> TestFlightConfiguration { let folder = try Folder(path: path) var configuration = TestFlightConfiguration() let decodeBetaTesters: (Data) throws -> [BetaTester] = { data in var configuration = CSVReader.Configuration() configuration.headerStrategy = .firstLine let csv = try CSVReader.decode(input: data, configuration: configuration) return try csv.records.map { record in try BetaTester( email: record[BetaTester.CodingKeys.email.rawValue], firstName: record[BetaTester.CodingKeys.firstName.rawValue], lastName: record[BetaTester.CodingKeys.lastName.rawValue] ) } } configuration.appConfigurations = try folder.subfolders.map { appFolder in let appYAML = try appFolder.file(named: Self.appYAMLName).readAsString() let app = try YAMLDecoder().decode(from: appYAML) as App var appConfiguration = TestFlightConfiguration.AppConfiguration(app: app) let testersFile = try appFolder.file(named: Self.betaTestersCSVName) let betaTesters = try decodeBetaTesters(try testersFile.read()) appConfiguration.betaTesters = betaTesters let groupsFolder = try appFolder.subfolder(named: Self.betaGroupFolderName) let emails = betaTesters.map(\.email) appConfiguration.betaGroups = try groupsFolder.files.map { groupFile -> BetaGroup in let group: BetaGroup = try YAMLDecoder().decode(from: try groupFile.readAsString()) if let email = group.testers.first(where: { !emails.contains($0) }) { throw Error.testerNotInTestersList(email: email, betaGroup: group, app: app) } return group } return appConfiguration } return configuration } }
38.446281
99
0.625322
e24e3efcc76f873faf45ab1b704d28724925e3fb
381
// // AppUserClass.swift // Saily // // Created by Lakr Aream on 2019/5/29. // Copyright © 2019 Lakr Aream. All rights reserved. // class app_user_class { let user_name = "" let user_pass = "" let user_icon = UIImage(named: "AccountHeadIconPlaceHolder")! func return_user_icon() -> UIImage { // 晚点写 return user_icon } }
17.318182
65
0.593176
382cd7233ac6a4183ab744c914b317b4a08fead9
1,887
// // ViewController.swift // HLBarIndicatorView // // Created by PandaApe on 06/16/2017. // Copyright (c) 2017 PandaApe. All rights reserved. // import UIKit import HLBarIndicatorView class ViewController: UIViewController { @IBOutlet weak var barScaleFromRightView: UIView! @IBOutlet weak var barScaleFromLeftView: UIView! @IBOutlet weak var barScalePulseOutView: UIView! lazy var indicatorView0 = HLBarIndicatorView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 150)) lazy var indicatorView1 = HLBarIndicatorView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 150)) lazy var indicatorView2 = HLBarIndicatorView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 150)) override func viewDidLoad() { super.viewDidLoad() indicatorView0.indicatorType = .barScaleFromRight indicatorView1.barsCount = 7 indicatorView1.animationDuration = 1 indicatorView1.indicatorType = .barScaleFromLeft indicatorView2.animationDuration = 0.6 self.barScaleFromRightView.addSubview(indicatorView0) self.barScaleFromLeftView.addSubview(indicatorView1) self.barScalePulseOutView.addSubview(indicatorView2) indicatorView2.barCornerRadius = 0 indicatorView2.barsGapWidth = 5 } @IBAction func switcherValueChanged(_ sender: UISwitch) { if sender.isOn { indicatorView0.startAnimating() indicatorView1.startAnimating() indicatorView2.startAnimating() }else{ indicatorView1.pauseAnimating() indicatorView0.pauseAnimating() indicatorView2.pauseAnimating() } } }
31.45
123
0.645469
29c7c5eb76d97cb9a60c7a04c963c9dd95d8ec15
339
// // Errors.swift // CombineDemo // // Created by berdil karaçam on 7.11.2019. // Copyright © 2019 berdil karaçam. All rights reserved. // import Foundation enum ServiceError: LocalizedError { case networkException case invalidURL case invalidBody case invalidEndpoint case requestException // case parsing }
17.842105
57
0.710914
ac31df993c4e3bd3b701e13078cf1af5d02abbdc
929
// // TransitionWithViewTests.swift // TransitionWithViewTests // // Created by Michael Mellinger on 4/28/15. // Copyright (c) 2015 h4labs. All rights reserved. // import UIKit import XCTest class TransitionWithViewTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } }
25.108108
111
0.62648
5bf3c93f911882d2c9e6c55afa880bf9c7cb9ecb
6,254
// Copyright (c) 2021 Pedro Almeida // // 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 Down import Inspector import SafariServices import UIKit import WebKit final class ReadMeViewController: UIViewController { // MARK: - Components @IBOutlet var inspectBarButton: CustomButton! private lazy var activityIndicatorView: UIActivityIndicatorView = { let activityIndicatorView = UIActivityIndicatorView(style: .large) activityIndicatorView.color = view.tintColor activityIndicatorView.hidesWhenStopped = true activityIndicatorView.startAnimating() activityIndicatorView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(activityIndicatorView) [ activityIndicatorView.centerYAnchor.constraint(equalTo: view.centerYAnchor), activityIndicatorView.centerXAnchor.constraint(equalTo: view.centerXAnchor) ].forEach { $0.isActive = true } return activityIndicatorView }() private lazy var markdownView: DownView = try! DownView( frame: view.bounds, markdownString: markdown?.markdownString ?? "", openLinksInBrowser: false, templateBundle: nil, writableBundle: false, configuration: nil, options: .smart, didLoadSuccessfully: { [weak self] in guard let self = self else { return } self.activityIndicatorView.stopAnimating() self.markdownView.translatesAutoresizingMaskIntoConstraints = false self.markdownView.alpha = 0 self.markdownView.pageZoom = 1.5 self.markdownView.navigationDelegate = self self.markdownView.backgroundColor = .clear self.markdownView.scrollView.backgroundColor = .clear self.view.insertSubview(self.markdownView, at: 0) [self.markdownView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor), self.markdownView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor), self.markdownView.topAnchor.constraint(equalTo: self.view.topAnchor), self.markdownView.widthAnchor.constraint(equalTo: self.view.widthAnchor), self.markdownView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor)].forEach { $0.isActive = true } UIView.animate(withDuration: 0.5) { self.markdownView.alpha = 1 } } ) private var markdown: Down? { didSet { guard let markdownString = markdown?.markdownString else { return } try? self.markdownView.update(markdownString: markdownString, options: .smart) } } override var keyCommands: [UIKeyCommand]? { Inspector.keyCommands } // MARK: - Life cycle override func viewDidLoad() { super.viewDidLoad() navigationItem.largeTitleDisplayMode = .always navigationController?.navigationBar.prefersLargeTitles = true loadData() } override func didMove(toParent parent: UIViewController?) { super.didMove(toParent: parent) parent?.overrideUserInterfaceStyle = .light } @objc func loadData() { activityIndicatorView.startAnimating() let session = URLSession(configuration: .default) let url = URL(string: "https://raw.githubusercontent.com/ipedro/Inspector/develop/README.md")! let task = session.dataTask(with: url) { [weak self] data, _, _ in guard let self = self else { return } guard let data = data, let markdownString = String(data: data, encoding: String.Encoding.utf8)?.replacingOccurrences(of: "# 🕵🏽‍♂️ Inspector\n", with: "") else { self.activityIndicatorView.stopAnimating() return } DispatchQueue.main.async { [weak self] in guard let self = self else { return } self.markdown = Down(markdownString: markdownString) } } task.resume() } } extension ReadMeViewController: WKNavigationDelegate { public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { guard let url = navigationAction.request.url else { return decisionHandler(.allow) } switch (url.scheme, navigationAction.navigationType) { case ("https", .linkActivated): decisionHandler(.cancel) openInSafariViewController(url) default: decisionHandler(.allow) } } private func openInSafariViewController(_ url: URL?) { guard let url = url else { return } let configuration = SFSafariViewController.Configuration() configuration.barCollapsingEnabled = false let safariController = SFSafariViewController(url: url, configuration: configuration) safariController.preferredControlTintColor = view.tintColor present(safariController, animated: true, completion: nil) } }
36.573099
146
0.666933
f7f8e43578895feb9a08ec3d69dac96f5dc2eddb
741
// // AutoQuery.swift // PracticeProjects // // Created by Michael Ho on 1/16/21. // import UIKit class AutoQuery { private var queryTask: DispatchWorkItem? func performAutoQuery(delay: Double = 0.5, queryBlock: @escaping () -> Void) { if let startQuery = self.queryTask { startQuery.cancel() } self.queryTask = DispatchWorkItem { guard let queryTask = self.queryTask, !queryTask.isCancelled else { return } queryBlock() } getGCDHelperInContext().runOnMainThreadAfter(delay: delay) { self.queryTask?.perform() } } // Test override func getGCDHelperInContext() -> GCDHelper { return GCDHelper.shared } }
24.7
88
0.608637
ab2faa3bb865ce8ccb3329ad4eb3611b82f57a35
742
import XCTest import Dizzy class Tests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } }
25.586207
111
0.598383
db7cf5f571c266470e44a155032fb1785af281ab
2,798
// // ExperienceUser.swift // Model Generated using keith model generator // Created on August 10, 2018 import Foundation class ExperienceUser : NSObject, NSCoding{ var displayName : String! var id : Int! var level : Int! var pictureId : Int! var slug : String! var type : String! /** * Instantiate the instance using the passed dictionary values to set the properties values */ init(fromDictionary dictionary: [String:Any]){ displayName = dictionary["display_name"] as? String id = dictionary["id"] as? Int level = dictionary["level"] as? Int pictureId = dictionary["picture_id"] as? Int slug = dictionary["slug"] as? String type = dictionary["type"] as? String } /** * Returns all the available property values in the form of [String:Any] object where the key is the approperiate json key and the value is the value of the corresponding property */ func toDictionary() -> [String:Any] { var dictionary = [String:Any]() if displayName != nil{ dictionary["display_name"] = displayName } if id != nil{ dictionary["id"] = id } if level != nil{ dictionary["level"] = level } if pictureId != nil{ dictionary["picture_id"] = pictureId } if slug != nil{ dictionary["slug"] = slug } if type != nil{ dictionary["type"] = type } return dictionary } /** * NSCoding required initializer. * Fills the data from the passed decoder */ @objc required init(coder aDecoder: NSCoder) { displayName = aDecoder.decodeObject(forKey: "display_name") as? String id = aDecoder.decodeObject(forKey: "id") as? Int level = aDecoder.decodeObject(forKey: "level") as? Int pictureId = aDecoder.decodeObject(forKey: "picture_id") as? Int slug = aDecoder.decodeObject(forKey: "slug") as? String type = aDecoder.decodeObject(forKey: "type") as? String } /** * NSCoding required method. * Encodes mode properties into the decoder */ @objc func encode(with aCoder: NSCoder) { if displayName != nil{ aCoder.encode(displayName, forKey: "display_name") } if id != nil{ aCoder.encode(id, forKey: "id") } if level != nil{ aCoder.encode(level, forKey: "level") } if pictureId != nil{ aCoder.encode(pictureId, forKey: "picture_id") } if slug != nil{ aCoder.encode(slug, forKey: "slug") } if type != nil{ aCoder.encode(type, forKey: "type") } } }
28.55102
183
0.568978
fe87baa835b4ca81e9500e8150d4b6a868afa60d
1,969
// // XCTFailSwizzler.swift // MockingbirdFramework // // Created by Andrew Chang on 3/11/20. // import Foundation import XCTest /// A type that can handle test failures emitted by Mockingbird. public protocol TestFailer { /// Fail the current test case. /// /// - Parameters: /// - message: A description of the failure. /// - isFatal: If `true`, test case execution should not continue. /// - file: The file where the failure occurred. /// - line: The line in the file where the failure occurred. func fail(message: String, isFatal: Bool, file: StaticString, line: UInt) } /// Change the current global test failer. /// /// - Parameter newTestFailer: A test failer instance to start handling test failures. public func swizzleTestFailer(_ newTestFailer: TestFailer) { if Thread.isMainThread { testFailer = newTestFailer } else { DispatchQueue.main.sync { testFailer = newTestFailer } } } /// Called by Mockingbird on test assertion failures. /// /// - Parameters: /// - message: A description of the failure. /// - isFatal: If `true`, test case execution should not continue. /// - file: The file where the failure occurred. /// - line: The line in the file where the failure occurred. @discardableResult func FailTest(_ message: String, isFatal: Bool = false, file: StaticString = #file, line: UInt = #line) -> String { testFailer.fail(message: message, isFatal: isFatal, file: file, line: line) return message } // MARK: - Internal private class StandardTestFailer: TestFailer { func fail(message: String, isFatal: Bool, file: StaticString, line: UInt) { guard isFatal else { return XCTFail(message, file: file, line: line) } // Raise an Objective-C exception to stop the test runner. MKBStopTest(message) // Test execution should usually be stopped by this point. fatalError(message) } } private var testFailer: TestFailer = StandardTestFailer()
30.292308
86
0.69223
762952fe92d652af51c0d7b5907c2f25e1e61975
2,391
import "stdlib.v2"; assertEqual(string[] a, string[] b) { assertEqual(length(a), length(b), msg = "Array sizes don't match"); foreach i in [0 : length(a) - 1] { assertEqual(a[i], b[i]); } } assertEqual(strcat("left", 1, "right"), "left1right"); assertEqual(strcat("oneArg"), "oneArg"); assertEqual(strcat("two", "Args"), "twoArgs"); assertEqual(length("0123456789"), 10); assertEqual(length(""), 0); string[] expected1 = ["one", "two", "three"]; string[] actual1 = split("one two three", " "); assertEqual(actual1, expected1); string[] expected11 = ["one", "two", "three", "four"]; string[] actual11 = split("one two three four", " "); assertEqual(actual11, expected11); string[] expected2 = ["one", "two three"]; string[] actual2 = split("one two three", " ", 2); assertEqual(actual2, expected2); string[] expected3 = ["one", "two", "three"]; string[] actual3 = splitRe("one two three", "\\s+"); assertEqual(actual3, expected3); string[] expected4 = ["one", "two three"]; string[] actual4 = splitRe("one two three", "\\s+", 2); assertEqual(actual4, expected4); assertEqual(trim(" bla\n"), "bla"); assertEqual(substring("blabla", 3), "bla"); assertEqual(substring("blabla", 3, 5), "bl"); assertEqual(toUpper("blaBla"), "BLABLA"); assertEqual(toLower("BLAbLA"), "blabla"); assertEqual(join(["one", "two", "three"], " "), "one two three"); string[] empty = []; assertEqual(join(empty, ""), ""); assertEqual(replaceAll("one two three two", "two", "four"), "one four three four"); assertEqual(replaceAll("one two three two", "two", "four", 1, 8), "one four three two"); assertEqual(replaceAllRe("one two three two", "([nr]e)", "x$1x"), "oxnex two thxrexe two"); assertEqual(replaceAllRe("one two three two", "t[wh]", "x", 1, 12), "one xo xree two"); assertEqual(indexOf("one two three two", "two", 0), 4); assertEqual(indexOf("one two three two", "four", 0), -1); assertEqual(indexOf("one two three two", "two", 6, 16), 14); assertEqual(indexOf("one two three two", "two", 6, 10), -1); assertEqual(lastIndexOf("one two three two", "two", -1), 14); assertEqual(lastIndexOf("one two three two", "four", -1), -1); assertEqual(lastIndexOf("one two three two", "two", 13, 0), 4); assert(matches("aaabbccdd", "[ab]+[cd]+")); string[] expected5 = ["one", "two", "three"]; string[] actual5 = findAllRe("one two three", "(\\w+)"); assertEqual(actual5, expected5);
33.208333
91
0.640736
87142a63e76e89c54766b08d592af9c0bb09fe7a
7,358
// // Utils.swift // SendBird-iOS // // Created by Jed Gyeong on 10/12/18. // Copyright © 2018 SendBird. All rights reserved. // import UIKit import SendBirdSDK class Utils: NSObject { // static let imageLoaderQueue = DispatchQueue.init(label: "com.sendbird.imageloader", qos: DispatchQoS.background, attributes: DispatchQueue.Attributes., autoreleaseFrequency: <#T##DispatchQueue.AutoreleaseFrequency#>, target: <#T##DispatchQueue?#>) static func getMessageDateStringFromTimestamp(_ timestamp: Int64) -> String? { var messageDateString: String = "" let messageDateFormatter: DateFormatter = DateFormatter() var messageDate: Date? if String(format: "%lld", timestamp).count == 10 { messageDate = Date.init(timeIntervalSince1970: TimeInterval(timestamp)) } else { messageDate = Date.init(timeIntervalSince1970: TimeInterval(Double(timestamp) / 1000.0)) } messageDateFormatter.dateStyle = .none messageDateFormatter.timeStyle = .short messageDateString = messageDateFormatter.string(from: messageDate!) return messageDateString } static func getDateStringForDateSeperatorFromTimestamp(_ timestamp: Int64) -> String { var messageDateString: String = "" let messageDateFormatter: DateFormatter = DateFormatter() var messageDate: Date? if String(format: "%lld", timestamp).count == 10 { messageDate = Date.init(timeIntervalSince1970: TimeInterval(timestamp)) } else { messageDate = Date.init(timeIntervalSince1970: TimeInterval(Double(timestamp) / 1000.0)) } messageDateFormatter.dateStyle = .long messageDateFormatter.timeStyle = .none messageDateString = messageDateFormatter.string(from: messageDate!) return messageDateString } static func checkDayChangeDayBetweenOldTimestamp(oldTimestamp: Int64, newTimestamp: Int64) -> Bool { var oldMessageDate: Date? var newMessageDate: Date? if String(format: "%lld", oldTimestamp).count == 10 { oldMessageDate = Date.init(timeIntervalSince1970: TimeInterval(oldTimestamp)) } else { oldMessageDate = Date.init(timeIntervalSince1970: TimeInterval(Double(oldTimestamp) / 1000.0)) } if String(format: "%lld", newTimestamp).count == 10 { newMessageDate = Date.init(timeIntervalSince1970: TimeInterval(newTimestamp)) } else { newMessageDate = Date.init(timeIntervalSince1970: TimeInterval(Double(newTimestamp) / 1000.0)) } let oldMessageDateComponents = Calendar.current.dateComponents([.day, .month, .year], from: oldMessageDate!) let newMessageDateComponents = Calendar.current.dateComponents([.day, .month, .year], from: newMessageDate!) if oldMessageDateComponents.year != newMessageDateComponents.year || oldMessageDateComponents.month != newMessageDateComponents.month || oldMessageDateComponents.day != newMessageDateComponents.day { return true } else { return false } } static func createGroupChannelName(channel: SBDGroupChannel) -> String { if channel.name.count > 0 { return channel.name } else { return self.createGroupChannelNameFromMembers(channel: channel) } } static func createGroupChannelNameFromMembers(channel: SBDGroupChannel) -> String { var memberNicknames: [String] = [] var count: Int = 0 for member in channel.members as! [SBDUser] { if member.userId == SBDMain.getCurrentUser()?.userId { continue } memberNicknames.append(member.nickname!) count += 1 if count == 4 { break } } var channelName: String? if count == 0 { channelName = "NO MEMBERS" } else { channelName = memberNicknames.joined(separator: ", ") } return channelName! } static func showAlertController(error: SBDError, viewController: UIViewController) { let vc = UIAlertController(title: "Error", message: error.domain, preferredStyle: .alert) let closeAction = UIAlertAction(title: "Close", style: .cancel, handler: nil) vc.addAction(closeAction) DispatchQueue.main.async { viewController.present(vc, animated: true, completion: nil) } } static func showAlertController(title: String?, message: String?, viewController: UIViewController) { let vc = UIAlertController(title: title, message: message, preferredStyle: .alert) let closeAction = UIAlertAction(title: "Close", style: .cancel, handler: nil) vc.addAction(closeAction) DispatchQueue.main.async { viewController.present(vc, animated: true, completion: nil) } } static func buildTypingIndicatorLabel(channel: SBDGroupChannel) -> String { if let typingMembers = channel.getTypingMembers() { if typingMembers.count == 0 { return "" } else { if typingMembers.count == 1 { return String(format: "%@ is typing.", typingMembers[0].nickname!) } else if typingMembers.count == 2 { return String(format: "@% and %@ are typing.", typingMembers[0].nickname!, typingMembers[1].nickname!) } else { return "Several people are typing." } } } else { return "" } } static func transformUserProfileImage(user: SBDUser) -> String { if let profileUrl = user.profileUrl { if profileUrl.hasPrefix("https://sendbird.com/main/img/profiles") { return "" } else { return profileUrl } } return "" } static func getDefaultUserProfileImage(user: SBDUser) -> UIImage? { if let nickname = user.nickname { switch nickname.count % 4 { case 0: return UIImage(named: "img_default_profile_image_1") case 1: return UIImage(named: "img_default_profile_image_2") case 2: return UIImage(named: "img_default_profile_image_3") case 3: return UIImage(named: "img_default_profile_image_4") default: return UIImage(named: "img_default_profile_image_1") } } return UIImage(named: "img_default_profile_image_1") } static func setProfileImage(imageView: UIImageView, user: SBDUser) { let url = Utils.transformUserProfileImage(user: user) if url.count > 0 { imageView.af_setImage(withURL: URL(string: url)!, placeholderImage: Utils.getDefaultUserProfileImage(user: user)) } else { imageView.image = Utils.getDefaultUserProfileImage(user: user) } } }
37.540816
253
0.600707
22a5a3e3a4fa3f6150e83ac328df21c08b6f8929
1,765
// // ATTFindInformationRequest.swift // Bluetooth // // Created by Alsey Coleman Miller on 6/13/18. // Copyright © 2018 PureSwift. All rights reserved. // import Foundation /// Find Information Request /// /// The *Find Information Request* is used to obtain the mapping of attribute handles with their associated types. /// This allows a client to discover the list of attributes and their types on a server. @frozen public struct ATTFindInformationRequest: ATTProtocolDataUnit, Equatable { public static var attributeOpcode: ATTOpcode { return .findInformationRequest } public var startHandle: UInt16 public var endHandle: UInt16 public init(startHandle: UInt16, endHandle: UInt16) { self.startHandle = startHandle self.endHandle = endHandle } } public extension ATTFindInformationRequest { internal static var length: Int { return 5 } init?(data: Data) { guard data.count == type(of: self).length, type(of: self).validateOpcode(data) else { return nil } self.startHandle = UInt16(littleEndian: UInt16(bytes: (data[1], data[2]))) self.endHandle = UInt16(littleEndian: UInt16(bytes: (data[3], data[4]))) } var data: Data { return Data(self) } } // MARK: - DataConvertible extension ATTFindInformationRequest: DataConvertible { var dataLength: Int { return type(of: self).length } static func += <T: DataContainer> (data: inout T, value: ATTFindInformationRequest) { data += attributeOpcode.rawValue data += value.startHandle.littleEndian data += value.endHandle.littleEndian } }
25.955882
114
0.641926
d9f76aedaaf0a4b0bfa096b23ebdfb4b610c09db
2,307
// // Canvas+Data.swift // Canvas2 // // Created by Adeola Uthman on 1/31/20. // Copyright © 2020 Adeola Uthman. All rights reserved. // import Foundation import UIKit extension Canvas { /** Exports the canvas as a UIImage. */ public func export(size s: CGSize? = nil) -> UIImage? { guard let drawable = currentDrawable else { return nil } let size = s ?? CGSize(width: drawable.texture.width, height: drawable.texture.height) guard let img = makeImage(for: drawable.texture, size: size) else { return nil }; return UIImage(cgImage: img) } /** Exports the canvas, all of its layers, brush data, etc. into codable data. */ public func exportCanvas() -> Data? { do { let data: Data = try JSONEncoder().encode(self) return data } catch { return nil } } /** Returns all of the layers. */ public func exportLayers() -> [Layer] { return canvasLayers } /** Exports just the drawings from each layer. */ public func exportLayerDrawings() -> [[Element]] { let ret = canvasLayers.map { $0.elements } return ret } /** Exports just the drawing data from a given element. */ public func exportDrawings(from index: Int) -> [Element] { guard index >= 0 && index < canvasLayers.count else { return [] } return canvasLayers[index].elements } /** Sets the canvas layers to the input and repaints the screen. */ public func load(layers: [Layer]) { canvasLayers = layers currentLayer = layers.count > 0 ? 0 : -1 setNeedsDisplay() } /** Loads the drawings from each layer. */ public func load(layerElements: [[Element]]) { for i in 0..<canvasLayers.count { let copy = layerElements[i].map { $0.copy() } canvasLayers[i].elements = copy } setNeedsDisplay() } /** Loads canvas elements onto a particular layer. */ public func load(elements: [Element], onto layer: Int) { guard layer >= 0 && layer < canvasLayers.count else { return } let copy = elements.map { $0.copy() } canvasLayers[layer].elements = copy setNeedsDisplay() } }
30.355263
94
0.583875
3848502927e82f9a9f9d360a6a250800383a6436
19,953
// // Generated by SwagGen // https://github.com/yonaskolb/SwagGen // import Foundation extension TFL.Journey { /** Perform a Journey Planner search from the parameters specified in simple types */ public enum JourneyJourneyResults { public static let service = APIService<Response>(id: "Journey_JourneyResults", tag: "Journey", method: "GET", path: "/Journey/JourneyResults/{from}/to/{to}", hasBody: false, securityRequirements: []) /** Does the time given relate to arrival or leaving time? Possible options: "departing" | "arriving" */ public enum TimeIs: String, Codable, Equatable, CaseIterable { case arriving = "Arriving" case departing = "Departing" } /** The journey preference eg possible options: "leastinterchange" | "leasttime" | "leastwalking" */ public enum JourneyPreference: String, Codable, Equatable, CaseIterable { case leastInterchange = "LeastInterchange" case leastTime = "LeastTime" case leastWalking = "LeastWalking" } /** The accessibility preference must be a comma separated list eg. "noSolidStairs,noEscalators,noElevators,stepFreeToVehicle,stepFreeToPlatform" */ public enum AccessibilityPreference: String, Codable, Equatable, CaseIterable { case noRequirements = "NoRequirements" case noSolidStairs = "NoSolidStairs" case noEscalators = "NoEscalators" case noElevators = "NoElevators" case stepFreeToVehicle = "StepFreeToVehicle" case stepFreeToPlatform = "StepFreeToPlatform" } /** The walking speed. eg possible options: "slow" | "average" | "fast". */ public enum WalkingSpeed: String, Codable, Equatable, CaseIterable { case slow = "Slow" case average = "Average" case fast = "Fast" } /** The cycle preference. eg possible options: "allTheWay" | "leaveAtStation" | "takeOnTransport" | "cycleHire" */ public enum CyclePreference: String, Codable, Equatable, CaseIterable { case none = "None" case leaveAtStation = "LeaveAtStation" case takeOnTransport = "TakeOnTransport" case allTheWay = "AllTheWay" case cycleHire = "CycleHire" } /** A comma separated list of cycling proficiency levels. eg possible options: "easy,moderate,fast" */ public enum BikeProficiency: String, Codable, Equatable, CaseIterable { case easy = "Easy" case moderate = "Moderate" case fast = "Fast" } public final class Request: APIRequest<Response> { public struct Options { /** Origin of the journey. Can be WGS84 coordinates expressed as "lat,long", a UK postcode, a Naptan (StopPoint) id, an ICS StopId, or a free-text string (will cause disambiguation unless it exactly matches a point of interest name). */ public var from: String /** Destination of the journey. Can be WGS84 coordinates expressed as "lat,long", a UK postcode, a Naptan (StopPoint) id, an ICS StopId, or a free-text string (will cause disambiguation unless it exactly matches a point of interest name). */ public var to: String /** Travel through point on the journey. Can be WGS84 coordinates expressed as "lat,long", a UK postcode, a Naptan (StopPoint) id, an ICS StopId, or a free-text string (will cause disambiguation unless it exactly matches a point of interest name). */ public var via: String? /** Does the journey cover stops outside London? eg. "nationalSearch=true" */ public var nationalSearch: Bool? /** The date must be in yyyyMMdd format */ public var date: String? /** The time must be in HHmm format */ public var time: String? /** Does the time given relate to arrival or leaving time? Possible options: "departing" | "arriving" */ public var timeIs: TimeIs? /** The journey preference eg possible options: "leastinterchange" | "leasttime" | "leastwalking" */ public var journeyPreference: JourneyPreference? /** The mode must be a comma separated list of modes. eg possible options: "public-bus,overground,train,tube,coach,dlr,cablecar,tram,river,walking,cycle" */ public var mode: [String]? /** The accessibility preference must be a comma separated list eg. "noSolidStairs,noEscalators,noElevators,stepFreeToVehicle,stepFreeToPlatform" */ public var accessibilityPreference: [AccessibilityPreference]? /** An optional name to associate with the origin of the journey in the results. */ public var fromName: String? /** An optional name to associate with the destination of the journey in the results. */ public var toName: String? /** An optional name to associate with the via point of the journey in the results. */ public var viaName: String? /** The max walking time in minutes for transfer eg. "120" */ public var maxTransferMinutes: String? /** The max walking time in minutes for journeys eg. "120" */ public var maxWalkingMinutes: String? /** The walking speed. eg possible options: "slow" | "average" | "fast". */ public var walkingSpeed: WalkingSpeed? /** The cycle preference. eg possible options: "allTheWay" | "leaveAtStation" | "takeOnTransport" | "cycleHire" */ public var cyclePreference: CyclePreference? /** Time adjustment command. eg possible options: "TripFirst" | "TripLast" */ public var adjustment: String? /** A comma separated list of cycling proficiency levels. eg possible options: "easy,moderate,fast" */ public var bikeProficiency: [BikeProficiency]? /** Option to determine whether to return alternative cycling journey */ public var alternativeCycle: Bool? /** Option to determine whether to return alternative walking journey */ public var alternativeWalking: Bool? /** Flag to determine whether certain text (e.g. walking instructions) should be output with HTML tags or not. */ public var applyHtmlMarkup: Bool? /** A boolean to indicate whether or not to return 3 public transport journeys, a bus journey, a cycle hire journey, a personal cycle journey and a walking journey */ public var useMultiModalCall: Bool? /** A boolean to indicate whether to optimize journeys using walking */ public var walkingOptimization: Bool? public init(from: String, to: String, via: String? = nil, nationalSearch: Bool? = nil, date: String? = nil, time: String? = nil, timeIs: TimeIs? = nil, journeyPreference: JourneyPreference? = nil, mode: [String]? = nil, accessibilityPreference: [AccessibilityPreference]? = nil, fromName: String? = nil, toName: String? = nil, viaName: String? = nil, maxTransferMinutes: String? = nil, maxWalkingMinutes: String? = nil, walkingSpeed: WalkingSpeed? = nil, cyclePreference: CyclePreference? = nil, adjustment: String? = nil, bikeProficiency: [BikeProficiency]? = nil, alternativeCycle: Bool? = nil, alternativeWalking: Bool? = nil, applyHtmlMarkup: Bool? = nil, useMultiModalCall: Bool? = nil, walkingOptimization: Bool? = nil) { self.from = from self.to = to self.via = via self.nationalSearch = nationalSearch self.date = date self.time = time self.timeIs = timeIs self.journeyPreference = journeyPreference self.mode = mode self.accessibilityPreference = accessibilityPreference self.fromName = fromName self.toName = toName self.viaName = viaName self.maxTransferMinutes = maxTransferMinutes self.maxWalkingMinutes = maxWalkingMinutes self.walkingSpeed = walkingSpeed self.cyclePreference = cyclePreference self.adjustment = adjustment self.bikeProficiency = bikeProficiency self.alternativeCycle = alternativeCycle self.alternativeWalking = alternativeWalking self.applyHtmlMarkup = applyHtmlMarkup self.useMultiModalCall = useMultiModalCall self.walkingOptimization = walkingOptimization } } public var options: Options public init(options: Options) { self.options = options super.init(service: JourneyJourneyResults.service) } /// convenience initialiser so an Option doesn't have to be created public convenience init(from: String, to: String, via: String? = nil, nationalSearch: Bool? = nil, date: String? = nil, time: String? = nil, timeIs: TimeIs? = nil, journeyPreference: JourneyPreference? = nil, mode: [String]? = nil, accessibilityPreference: [AccessibilityPreference]? = nil, fromName: String? = nil, toName: String? = nil, viaName: String? = nil, maxTransferMinutes: String? = nil, maxWalkingMinutes: String? = nil, walkingSpeed: WalkingSpeed? = nil, cyclePreference: CyclePreference? = nil, adjustment: String? = nil, bikeProficiency: [BikeProficiency]? = nil, alternativeCycle: Bool? = nil, alternativeWalking: Bool? = nil, applyHtmlMarkup: Bool? = nil, useMultiModalCall: Bool? = nil, walkingOptimization: Bool? = nil) { let options = Options(from: from, to: to, via: via, nationalSearch: nationalSearch, date: date, time: time, timeIs: timeIs, journeyPreference: journeyPreference, mode: mode, accessibilityPreference: accessibilityPreference, fromName: fromName, toName: toName, viaName: viaName, maxTransferMinutes: maxTransferMinutes, maxWalkingMinutes: maxWalkingMinutes, walkingSpeed: walkingSpeed, cyclePreference: cyclePreference, adjustment: adjustment, bikeProficiency: bikeProficiency, alternativeCycle: alternativeCycle, alternativeWalking: alternativeWalking, applyHtmlMarkup: applyHtmlMarkup, useMultiModalCall: useMultiModalCall, walkingOptimization: walkingOptimization) self.init(options: options) } public override var path: String { return super.path.replacingOccurrences(of: "{" + "from" + "}", with: "\(self.options.from)").replacingOccurrences(of: "{" + "to" + "}", with: "\(self.options.to)") } public override var queryParameters: [String: Any] { var params: [String: Any] = [:] if let via = options.via { params["via"] = via } if let nationalSearch = options.nationalSearch { params["nationalSearch"] = nationalSearch } if let date = options.date { params["date"] = date } if let time = options.time { params["time"] = time } if let timeIs = options.timeIs?.encode() { params["timeIs"] = timeIs } if let journeyPreference = options.journeyPreference?.encode() { params["journeyPreference"] = journeyPreference } if let mode = options.mode?.joined(separator: ",") { params["mode"] = mode } if let accessibilityPreference = options.accessibilityPreference?.encode().map({ String(describing: $0) }).joined(separator: ",") { params["accessibilityPreference"] = accessibilityPreference } if let fromName = options.fromName { params["fromName"] = fromName } if let toName = options.toName { params["toName"] = toName } if let viaName = options.viaName { params["viaName"] = viaName } if let maxTransferMinutes = options.maxTransferMinutes { params["maxTransferMinutes"] = maxTransferMinutes } if let maxWalkingMinutes = options.maxWalkingMinutes { params["maxWalkingMinutes"] = maxWalkingMinutes } if let walkingSpeed = options.walkingSpeed?.encode() { params["walkingSpeed"] = walkingSpeed } if let cyclePreference = options.cyclePreference?.encode() { params["cyclePreference"] = cyclePreference } if let adjustment = options.adjustment { params["adjustment"] = adjustment } if let bikeProficiency = options.bikeProficiency?.encode().map({ String(describing: $0) }).joined(separator: ",") { params["bikeProficiency"] = bikeProficiency } if let alternativeCycle = options.alternativeCycle { params["alternativeCycle"] = alternativeCycle } if let alternativeWalking = options.alternativeWalking { params["alternativeWalking"] = alternativeWalking } if let applyHtmlMarkup = options.applyHtmlMarkup { params["applyHtmlMarkup"] = applyHtmlMarkup } if let useMultiModalCall = options.useMultiModalCall { params["useMultiModalCall"] = useMultiModalCall } if let walkingOptimization = options.walkingOptimization { params["walkingOptimization"] = walkingOptimization } return params } } public enum Response: APIResponseValue, CustomStringConvertible, CustomDebugStringConvertible { /** A DTO representing a list of possible journeys. */ public class Status200: APIModel { public var cycleHireDockingStationData: JourneyPlannerCycleHireDockingStationData? public var journeyVector: JourneyVector? public var journeys: [Journey]? public var lines: [Line]? public var recommendedMaxAgeMinutes: Int? public var searchCriteria: SearchCriteria? public var stopMessages: [String]? public init(cycleHireDockingStationData: JourneyPlannerCycleHireDockingStationData? = nil, journeyVector: JourneyVector? = nil, journeys: [Journey]? = nil, lines: [Line]? = nil, recommendedMaxAgeMinutes: Int? = nil, searchCriteria: SearchCriteria? = nil, stopMessages: [String]? = nil) { self.cycleHireDockingStationData = cycleHireDockingStationData self.journeyVector = journeyVector self.journeys = journeys self.lines = lines self.recommendedMaxAgeMinutes = recommendedMaxAgeMinutes self.searchCriteria = searchCriteria self.stopMessages = stopMessages } public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) cycleHireDockingStationData = try container.decodeIfPresent("cycleHireDockingStationData") journeyVector = try container.decodeIfPresent("journeyVector") journeys = try container.decodeArrayIfPresent("journeys") lines = try container.decodeArrayIfPresent("lines") recommendedMaxAgeMinutes = try container.decodeIfPresent("recommendedMaxAgeMinutes") searchCriteria = try container.decodeIfPresent("searchCriteria") stopMessages = try container.decodeArrayIfPresent("stopMessages") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encodeIfPresent(cycleHireDockingStationData, forKey: "cycleHireDockingStationData") try container.encodeIfPresent(journeyVector, forKey: "journeyVector") try container.encodeIfPresent(journeys, forKey: "journeys") try container.encodeIfPresent(lines, forKey: "lines") try container.encodeIfPresent(recommendedMaxAgeMinutes, forKey: "recommendedMaxAgeMinutes") try container.encodeIfPresent(searchCriteria, forKey: "searchCriteria") try container.encodeIfPresent(stopMessages, forKey: "stopMessages") } public func isEqual(to object: Any?) -> Bool { guard let object = object as? Status200 else { return false } guard self.cycleHireDockingStationData == object.cycleHireDockingStationData else { return false } guard self.journeyVector == object.journeyVector else { return false } guard self.journeys == object.journeys else { return false } guard self.lines == object.lines else { return false } guard self.recommendedMaxAgeMinutes == object.recommendedMaxAgeMinutes else { return false } guard self.searchCriteria == object.searchCriteria else { return false } guard self.stopMessages == object.stopMessages else { return false } return true } public static func == (lhs: Status200, rhs: Status200) -> Bool { return lhs.isEqual(to: rhs) } } public typealias SuccessType = Status200 /** OK */ case status200(Status200) public var success: Status200? { switch self { case .status200(let response): return response } } public var response: Any { switch self { case .status200(let response): return response } } public var statusCode: Int { switch self { case .status200: return 200 } } public var successful: Bool { switch self { case .status200: return true } } public init(statusCode: Int, data: Data, decoder: ResponseDecoder) throws { switch statusCode { case 200: self = try .status200(decoder.decode(Status200.self, from: data)) default: throw APIClientError.unexpectedStatusCode(statusCode: statusCode, data: data) } } public var description: String { return "\(statusCode) \(successful ? "success" : "failure")" } public var debugDescription: String { var string = description let responseString = "\(response)" if responseString != "()" { string += "\n\(responseString)" } return string } } } }
53.350267
751
0.593595
91c01a0f006806908a877687bdeb313fa94dc642
490
// // Coordinate.swift // rasgos-geometricos // // Created by Luis Flores on 1/27/15. // Copyright (c) 2015 Luis Flores. All rights reserved. // import Foundation struct Coordinate : Printable { var x: Int = 0; var y: Int = 0; init(x: Int, y: Int) { self.x = x self.y = y } var description: String { return "x:\(x) y:\(y)" } } func ==(lhs: Coordinate, rhs: Coordinate) -> Bool { return lhs.x == rhs.x && lhs.y == rhs.y; }
18.148148
56
0.542857
f8bce635263f95fb35199da071b831cc000c5099
5,059
// // PhotoPicker.swift // MemoryBox // // Created by Gunner Madsen. // import SwiftUI import PhotosUI struct PhotoPicker: UIViewControllerRepresentable { typealias UIViewControllerType = PHPickerViewController @ObservedObject var mediaItems: PickedMediaItems var albumName: String var didFinishPicking: (_ didSelectItems: Bool) -> Void func makeUIViewController(context: Context) -> PHPickerViewController { var config = PHPickerConfiguration() config.filter = .any(of: [.images, .videos, .livePhotos]) config.selectionLimit = 0 config.preferredAssetRepresentationMode = .current let controller = PHPickerViewController(configuration: config) controller.delegate = context.coordinator return controller } func updateUIViewController(_ uiViewController: PHPickerViewController, context: Context) { } func makeCoordinator() -> Coordinator { Coordinator(with: self) } class Coordinator: PHPickerViewControllerDelegate { var photoPicker: PhotoPicker let fileSystemManager = FileSystemManager() init(with photoPicker: PhotoPicker) { self.photoPicker = photoPicker } func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) { photoPicker.didFinishPicking(!results.isEmpty) guard !results.isEmpty else { return } for result in results { let itemProvider = result.itemProvider guard let typeIdentifier = itemProvider.registeredTypeIdentifiers.first, let utType = UTType(typeIdentifier) else { continue } if utType.conforms(to: .image) { getPhoto(from: itemProvider, isLivePhoto: false) } else if utType.conforms(to: .movie) { getVideo(from: itemProvider, typeIdentifier: typeIdentifier) } else { getPhoto(from: itemProvider, isLivePhoto: true) } } // self.printListOfImagesInFolder() } private func getPhoto(from itemProvider: NSItemProvider, isLivePhoto: Bool) { let objectType: NSItemProviderReading.Type = !isLivePhoto ? UIImage.self : PHLivePhoto.self if itemProvider.canLoadObject(ofClass: objectType) { itemProvider.loadObject(ofClass: objectType) { object, error in if let error = error { print(error.localizedDescription) } if !isLivePhoto { if let image = object as? UIImage { DispatchQueue.main.async { let photoPickerModel = PhotoModel(with: image) self.fileSystemManager.writeImageToFileSystem(photoPickerModel.photo!, photoPickerModel.id, albumName: self.photoPicker.albumName) self.photoPicker.mediaItems.append(item: photoPickerModel) } } } else { if let livePhoto = object as? PHLivePhoto { DispatchQueue.main.async { let photoPickerModel = PhotoModel(with: livePhoto) self.photoPicker.mediaItems.append(item: photoPickerModel) } } } } } } private func getVideo(from itemProvider: NSItemProvider, typeIdentifier: String) { itemProvider.loadFileRepresentation(forTypeIdentifier: typeIdentifier) { url, error in if let error = error { print(error.localizedDescription) } guard let url = url else { return } let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first guard let targetURL = documentsDirectory?.appendingPathComponent(url.lastPathComponent) else { return } do { if FileManager.default.fileExists(atPath: targetURL.path) { try FileManager.default.removeItem(at: targetURL) } try FileManager.default.copyItem(at: url, to: targetURL) DispatchQueue.main.async { self.photoPicker.mediaItems.append(item: PhotoModel(with: targetURL)) } } catch { print(error.localizedDescription) } } } } }
38.618321
162
0.536667
f59d6bfea7feb2ed10ba1cfc5a778368f580a8d8
1,584
// // MovieDetailsModel.swift // InCinema // // Created by Vladimir Abramichev on 24/10/2018. // Copyright © 2018 Vladimir Abramichev. All rights reserved. // import Foundation import MDBProvider protocol MovieModel { var movie: Movie { get } func loadDetails(than handler: @escaping (MovieDetails?, Error?) -> Void) func loadImage(_ type: ImageType, than handler: @escaping (UIImage?, Error?) -> Void) } enum ImageType { case poster case backdrop } enum MovieImageError: Error { case imageNotAvailable } class InCinemaMovieModel: MovieModel { typealias Dependency = HasMDB & HasLocale & HasImageService private let dependency: Dependency var movie: Movie init(movie: Movie, dependency: Dependency) { self.dependency = dependency self.movie = movie } func loadDetails(than handler: @escaping (MovieDetails?, Error?) -> Void) { let locale = self.dependency.currentLocale self.dependency.moviesService.getMovie(id: movie.id, language: locale, than: handler) } func loadImage(_ type: ImageType, than handler: @escaping (UIImage?, Error?) -> Void) { let path: String? switch type { case .poster: path = movie.posterPath case .backdrop: path = movie.backdropPath } guard let moviePath = path else { handler(nil, MovieImageError.imageNotAvailable) return } self.dependency.load(path: moviePath, than: handler) } }
25.142857
93
0.630051
e8c97abc3adb799a86c20ed83be7451a9434e545
5,094
// // DownloadProgressNode.swift // RelistenShared // // Created by Jacob Farkas on 8/10/18. // Copyright © 2018 Alec Gorge. All rights reserved. // import Foundation import AsyncDisplayKit import UIKit import DownloadButton public protocol DownloadProgressActions { var state : Track.DownloadState { get set } func updateProgress(_ progress : Float) } public protocol DownloadProgressDelegate : class { func downloadButtonTapped() } func resizeImage(image: UIImage, newWidth: CGFloat) -> UIImage { let scale = newWidth / image.size.width let newHeight = image.size.height * scale UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight)) image.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage! } public class DownloadProgressNode : ASDisplayNode { private static let buttonSize: CGFloat = 16 private static var buttonImage = { return resizeImage(image: #imageLiteral(resourceName: "download-complete"), newWidth: DownloadProgressNode.buttonSize * 3.0) }() public let downloadProgressNode: ASDisplayNode public weak var delegate : DownloadProgressDelegate? = nil public var state : Track.DownloadState = .none { didSet { if let button = downloadProgressNode.view as? PKDownloadButton { let blockState = state DispatchQueue.main.async { switch blockState { case .none: button.state = .startDownload case .queued: button.state = .pending case .downloading: button.state = .downloading case .downloaded: button.state = .downloaded } } } } } public override init() { downloadProgressNode = ASDisplayNode(viewBlock: { PKDownloadButton(frame: CGRect(x: 0, y: 0, width: DownloadProgressNode.buttonSize, height: DownloadProgressNode.buttonSize)) }) super.init() automaticallyManagesSubnodes = true } public convenience init(delegate: DownloadProgressDelegate) { self.init() self.delegate = delegate } public override func didLoad() { super.didLoad() if let button = downloadProgressNode.view as? PKDownloadButton { button.delegate = self button.backgroundColor = UIColor.clear button.downloadedButton.cleanDefaultAppearance() button.downloadedButton.tintColor = AppColors.primary button.downloadedButton.setImage(DownloadProgressNode.buttonImage, for: .normal) button.downloadedButton.setTitleColor(AppColors.primary, for: .normal) button.downloadedButton.setTitleColor(AppColors.highlight, for: .highlighted) button.downloadedButton.lineWidth = 0 button.stopDownloadButton.tintColor = AppColors.primary button.stopDownloadButton.filledLineStyleOuter = true button.pendingView.tintColor = AppColors.primary button.pendingView.radius = (CGFloat(DownloadProgressNode.buttonSize) - (2.0 * button.pendingView.lineWidth)) / 2.0 button.startDownloadButton.cleanDefaultAppearance() button.startDownloadButton.setImage(#imageLiteral(resourceName: "download-outline"), for: .normal) button.startDownloadButton.tintColor = AppColors.primary button.stopDownloadButton.radius = (CGFloat(DownloadProgressNode.buttonSize) - (2.0 * button.pendingView.lineWidth)) / 2.0 button.stopDownloadButton.stopButtonWidth = 4.0 button.stopDownloadButton.filledLineWidth = 1.5 } } public override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec { downloadProgressNode.style.layoutPosition = CGPoint(x: 0, y: 0) downloadProgressNode.style.preferredSize = CGSize(width: DownloadProgressNode.buttonSize, height: DownloadProgressNode.buttonSize) return ASAbsoluteLayoutSpec( sizing: ASAbsoluteLayoutSpecSizing.sizeToFit, children: [ downloadProgressNode ] ) } } extension DownloadProgressNode : DownloadProgressActions { // MARK: DownloadProgressActions public func updateProgress(_ progress : Float) { if let button = downloadProgressNode.view as? PKDownloadButton { DispatchQueue.main.async { button.stopDownloadButton.progress = CGFloat(progress) } } } } extension DownloadProgressNode : PKDownloadButtonDelegate { // MARK: PKDownloadButtonDelegate public func downloadButtonTapped(_ downloadButton: PKDownloadButton!, currentState state: PKDownloadButtonState) { self.delegate?.downloadButtonTapped() } }
38.014925
185
0.657833
5b3704d5b5823726b7a30d345c67c570af2e25ab
1,010
// // MainViewController.swift // Galileo // // Created by Javier Aznar de los Rios on 08/11/2018. // Copyright © 2018 The Clash Soft. All rights reserved. // import UIKit class GalileoMainViewController: UITabBarController { init(plugins: [GalileoPlugin]) { let defaultIcon = UIImage(named: "103-doubt", in: Galileo.bundle, compatibleWith: nil) let views: [UIViewController] = plugins.map { (plugin) in let view = plugin as! UIViewController view.tabBarItem = UITabBarItem(title: plugin.pluginName, image: plugin.pluginIcon ?? defaultIcon, selectedImage: nil) return view } print("asdsadasd") super.init(nibName: nil, bundle: nil) self.viewControllers = views } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() title = "Galileo" } }
25.897436
129
0.620792
dd863c70f6c14102f4b04e830b0972c2cd0e64f8
903
// // clip2getherTests.swift // clip2getherTests // // Created by Ali on 30.07.15. // Copyright (c) 2015 Remanence. All rights reserved. // import UIKit import XCTest class clip2getherTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
24.405405
111
0.616833
6203daa55d3f91ef1064829faacbd3f349bc127f
3,611
// // Extensions.swift // Spiral // // Created by 杨萧玉 on 15/6/5. // Copyright (c) 2015年 杨萧玉. All rights reserved. // import SpriteKit extension UIImage { class fileprivate func imageWithView(_ view:UIView)->UIImage{ UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.isOpaque, 0.0); view.drawHierarchy(in: view.bounds,afterScreenUpdates:true) let img = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return img!; } class func imageFromNode(_ node:SKNode)->UIImage{ if let tex = ((UIApplication.shared.delegate as! AppDelegate).window?.rootViewController?.view as! SKView).texture(from: node) { let view = SKView(frame: CGRect(x: 0, y: 0, width: tex.size().width, height: tex.size().height)) let scene = SKScene(size: tex.size()) let sprite = SKSpriteNode(texture: tex) sprite.position = CGPoint( x: view.frame.midX, y: view.frame.midY ); scene.addChild(sprite) view.presentScene(scene) return imageWithView(view) } return UIImage() } } extension SKScene { class func unarchiveFromFile(_ file:String) -> SKNode? { if let path = Bundle.main.path(forResource: file, ofType: "sks") { let sceneData = try! Foundation.Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe) let archiver = NSKeyedUnarchiver(forReadingWith: sceneData) archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene") let scene = archiver.decodeObject(forKey: NSKeyedArchiveRootObjectKey) as! SKScene archiver.finishDecoding() for child in scene.children { if let sprite = child as? SKSpriteNode { sprite.texture?.preload(completionHandler: { }) } } return scene } else { return nil } } } extension SKLabelNode { func setDefaultFont(){ self.fontName = NSLocalizedString("HelveticaNeue-Thin", comment: "") } } extension SKNode { class func yxy_swizzleAddChild() { let cls = SKNode.self let originalSelector = #selector(SKNode.addChild(_:)) let swizzledSelector = #selector(SKNode.yxy_addChild(_:)) let originalMethod = class_getInstanceMethod(cls, originalSelector) let swizzledMethod = class_getInstanceMethod(cls, swizzledSelector) method_exchangeImplementations(originalMethod!, swizzledMethod!) } class func yxy_swizzleRemoveFromParent() { let cls = SKNode.self let originalSelector = #selector(SKNode.removeFromParent) let swizzledSelector = #selector(SKNode.yxy_removeFromParent) let originalMethod = class_getInstanceMethod(cls, originalSelector) let swizzledMethod = class_getInstanceMethod(cls, swizzledSelector) method_exchangeImplementations(originalMethod!, swizzledMethod!) } @objc func yxy_addChild(_ node: SKNode) { if node.parent == nil { self.yxy_addChild(node) } else { print("This node has already a parent!\(String(describing: node.name))") } } @objc func yxy_removeFromParent() { if parent != nil { DispatchQueue.main.async(execute: { () -> Void in self.yxy_removeFromParent() }) } else { print("This node has no parent!\(String(describing: name))") } } }
35.058252
136
0.625312
0aae425c7efd6143707b4e57b3a91758f9794ef7
2,067
// // AppDelegate.swift // Sample // // Created by FromAtom on 2018/11/26. // Copyright © FromAtom 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:. } }
44.934783
279
0.78955
758a174ff4f491f564889538bd75e74a9374b3b5
562
// // Saber.swift // Application // // Created by Andrey Pleshkov on 20.03.2019. // import Foundation import Kitura class Saber: RouterMiddleware { private unowned let appContainer: AppContainer init(appContainer: AppContainer) { self.appContainer = appContainer } func handle(request: RouterRequest, response: RouterResponse, next: @escaping () -> Void) throws { request.container = RequestContainer( appContainer: appContainer, routerRequest: request ) next() } }
20.814815
102
0.63879
294084ce71ee38d9d5960fcfdfc5a3b95ebff273
7,338
//// // 🦠 Corona-Warn-App // import Foundation import UIKit final class DiaryOverviewDayCellModel { // MARK: - Init init( diaryDay: DiaryDay, historyExposure: HistoryExposure, minimumDistinctEncountersWithHighRisk: Int, checkinsWithRisk: [CheckinWithRisk], // only needed for UI Testing purposes accessibilityIdentifierIndex: Int = 0 ) { self.diaryDay = diaryDay self.historyExposure = historyExposure self.minimumDistinctEncountersWithHighRisk = minimumDistinctEncountersWithHighRisk self.checkinsWithRisk = checkinsWithRisk self.accessibilityIdentifierIndex = accessibilityIdentifierIndex } // MARK: - Internal let historyExposure: HistoryExposure let checkinsWithRisk: [CheckinWithRisk] let accessibilityIdentifierIndex: Int func entryDetailTextFor(personEncounter: ContactPersonEncounter) -> String { var detailComponents = [String]() detailComponents.append(personEncounter.duration.description) detailComponents.append(personEncounter.maskSituation.description) detailComponents.append(personEncounter.setting.description) // Filter empty strings. detailComponents = detailComponents.filter { $0 != "" } return detailComponents.joined(separator: ", ") } func entryDetailTextFor(locationVisit: LocationVisit) -> String { guard locationVisit.durationInMinutes > 0 else { return "" } let dateComponents = DateComponents(minute: locationVisit.durationInMinutes) let timeString = dateComponentsFormatter.string(from: dateComponents) ?? "" return timeString + " \(AppStrings.ContactDiary.Overview.LocationVisit.abbreviationHours)" } var hideExposureHistory: Bool { switch historyExposure { case .none: return true case .encounter: return false } } var exposureHistoryAccessibilityIdentifier: String? { switch historyExposure { case let .encounter(risk): switch risk { case .low: return AccessibilityIdentifiers.ContactDiaryInformation.Overview.riskLevelLow case .high: return AccessibilityIdentifiers.ContactDiaryInformation.Overview.riskLevelHigh } case .none: return nil } } var exposureHistoryImage: UIImage? { switch historyExposure { case let .encounter(risk): switch risk { case .low: return UIImage(imageLiteralResourceName: "Icons_Attention_low") case .high: return UIImage(imageLiteralResourceName: "Icons_Attention_high") } case .none: return nil } } var exposureHistoryTitle: String? { switch historyExposure { case let .encounter(risk): switch risk { case .low: return AppStrings.ContactDiary.Overview.lowRiskTitle case .high: return AppStrings.ContactDiary.Overview.increasedRiskTitle } case .none: return nil } } var exposureHistoryDetail: String? { switch historyExposure { case let .encounter(risk): switch risk { case .low: return selectedEntries.isEmpty ? AppStrings.ContactDiary.Overview.riskTextStandardCause : [AppStrings.ContactDiary.Overview.riskTextStandardCause, AppStrings.ContactDiary.Overview.riskTextDisclaimer].joined(separator: "\n") case .high where minimumDistinctEncountersWithHighRisk > 0: return selectedEntries.isEmpty ? AppStrings.ContactDiary.Overview.riskTextStandardCause : [AppStrings.ContactDiary.Overview.riskTextStandardCause, AppStrings.ContactDiary.Overview.riskTextDisclaimer].joined(separator: "\n") // for other possible values of minimumDistinctEncountersWithHighRisk such as 0 and -1 case .high: return selectedEntries.isEmpty ? AppStrings.ContactDiary.Overview.riskTextLowRiskEncountersCause : [AppStrings.ContactDiary.Overview.riskTextLowRiskEncountersCause, AppStrings.ContactDiary.Overview.riskTextDisclaimer].joined(separator: "\n") } case .none: return nil } } var hideCheckinRisk: Bool { return checkinsWithRisk.isEmpty } var checkinImage: UIImage? { if checkinsWithRisk.isEmpty { return nil } else { return checkinsWithRisk.contains(where: { $0.risk == .high }) ? UIImage(imageLiteralResourceName: "Icons_Attention_high") : UIImage(imageLiteralResourceName: "Icons_Attention_low") } } var checkinTitleHeadlineText: String? { if checkinsWithRisk.isEmpty { return nil } else { return checkinsWithRisk.contains(where: { $0.risk == .high }) ? AppStrings.ContactDiary.Overview.CheckinEncounter.titleHighRisk : AppStrings.ContactDiary.Overview.CheckinEncounter.titleLowRisk } } var checkinTitleAccessibilityIdentifier: String? { if checkinsWithRisk.isEmpty { return nil } else { return checkinsWithRisk.contains(where: { $0.risk == .high }) ? AccessibilityIdentifiers.ContactDiaryInformation.Overview.checkinRiskLevelHigh : AccessibilityIdentifiers.ContactDiaryInformation.Overview.checkinRiskLevelLow } } var checkinDetailDescription: String? { return checkinsWithRisk.isEmpty ? nil: AppStrings.ContactDiary.Overview.CheckinEncounter.titleSubheadline } var isSinlgeRiskyCheckin: Bool { return checkinsWithRisk.count <= 1 } var selectedEntries: [DiaryEntry] { diaryDay.selectedEntries } var formattedDate: String { diaryDay.formattedDate } var dateAccessibilityIdentifier: String { return AccessibilityIdentifiers.ContactDiaryInformation.Overview.cellDateHeader } var diaryDayTests: [DiaryDayTest] { return diaryDay.tests } func checkInDespription(checkinWithRisk: CheckinWithRisk) -> String { let checkinName = checkinWithRisk.checkIn.traceLocationDescription let riskLevel = checkinWithRisk.risk var suffix = "" switch riskLevel { case .low: suffix = AppStrings.ContactDiary.Overview.CheckinEncounter.lowRisk case .high: suffix = AppStrings.ContactDiary.Overview.CheckinEncounter.highRisk } return isSinlgeRiskyCheckin ? checkinName : checkinName + " \(suffix)" } func colorFor(riskLevel: RiskLevel) -> UIColor { return riskLevel == .high ? .enaColor(for: .riskHigh) : .enaColor(for: .textPrimary2) } // MARK: - Private private let diaryDay: DiaryDay private let minimumDistinctEncountersWithHighRisk: Int private var dateComponentsFormatter: DateComponentsFormatter = { let formatter = DateComponentsFormatter() formatter.unitsStyle = .positional formatter.zeroFormattingBehavior = .pad formatter.allowedUnits = [.hour, .minute] return formatter }() } private extension ContactPersonEncounter.Duration { var description: String { switch self { case .none: return "" case .lessThan10Minutes: return AppStrings.ContactDiary.Overview.PersonEncounter.durationLessThan10Minutes case .moreThan10Minutes: return AppStrings.ContactDiary.Overview.PersonEncounter.durationMoreThan10Minutes } } } private extension ContactPersonEncounter.MaskSituation { var description: String { switch self { case .none: return "" case .withMask: return AppStrings.ContactDiary.Overview.PersonEncounter.maskSituationWithMask case .withoutMask: return AppStrings.ContactDiary.Overview.PersonEncounter.maskSituationWithoutMask } } } private extension ContactPersonEncounter.Setting { var description: String { switch self { case .none: return "" case .outside: return AppStrings.ContactDiary.Overview.PersonEncounter.settingOutside case .inside: return AppStrings.ContactDiary.Overview.PersonEncounter.settingInside } } }
29.23506
245
0.769011
eba1d8fcbb2e13ef0fb12df12add2ee05714a96b
2,152
// // AppDelegate.swift // MOAspectsSwiftExapmple // // Created by 3ign0n on 2015/04/02. // Copyright (c) 2015年 3ign0n. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
45.787234
285
0.755112
16bf21b9df4d61b6da42f341199be4756bc466d2
540
// // Array+Tools.swift // Menuator // // Created by Vlad Radu & Ondrej Rafaj on 14/12/2017. // Copyright © 2017 manGoweb UK. All rights reserved. // import Foundation extension Array { func safe(index: Int) -> Int? { guard !isEmpty, index >= 0, index < count else { return nil } return index } func guaranteed(index: Int) -> Int { if index < 0 { return 0 } else if index >= count { return endIndex - 1 } return index } }
17.419355
56
0.525926
03f0a40e091f1b2cbb3dcabd7756d467e71d7a15
2,115
//: [Previous](@previous) import Foundation //:# 旋转数组 //: 给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。 //: 说明: //: - 尽可能相处更多的解决方案,至少有三种不同的方法可以解决这个问题; //: - 要求使用空间复杂度为 O(1) 的原地算法 //: 思路一 //:如果不考虑空间复杂度这快,最简单的方式是直接创建一个新的 copy ,然后通过数组下标的 % 运算进行替换 var numbers = [1,2,3,4,5,6,7] var k = 3 var numberCopy = numbers for i in 0 ..< numbers.count { numberCopy[(k + i) % numbers.count] = numbers[i] } numberCopy //:思路二: //:按照交换的顺序,一个一个的进行交换,空间复杂度达到要求,但是时间复杂度太大了 /*: ``` k = 1 ,进行交换 1,2,3,4,5,6,7 0 7,2,3,4,5,6,1 6 0 1 7,2,3,4,5,1,6 6 5 2 7,2,3,4,1,5,6 5 4 3 7,2,3,1,4,5,6 4 3 4 7,2,1,3,4,5,6 3 2 5 7,1,2,3,4,5,6 2 1 6,1,2,3,4,5,7 ``` */ var a = 10 var b = 20 a = a ^ b b = b ^ a a = a ^ b var count = numbers.count var start = 0 k = k % count for _ in 0 ..< k { for i in 0 ..< count - 1 { numbers[count - i - 1] = numbers[count - i-1] ^ numbers[(count - i) % count] numbers[(count - i) % count] = numbers[(count - i) % count] ^ numbers[count - i-1] numbers[count - i - 1] = numbers[count - i-1] ^ numbers[(count - i) % count] } } //: 思路三 //numbers = [1,2] // //var count1 = numbers.count //k = 1 //k = k % numbers.count // func swapNumbers<T>(_ nums: inout Array<T>, _ p: Int, _ q: Int) { (nums[p], nums[q]) = (nums[q], nums[p]) } // //for i in 0 ..< numbers.count - k + 1 { // print(i) // print(numbers.count - (k - i % k)) // swapNumbers(&numbers, i, numbers.count - (k - (i % k)) ) // print(numbers) //} // //numbers func rotate(_ nums: inout [Int], _ k: Int) { var count = nums.count var start = 0 var vk = k vk = vk % count while count > 0 && vk > 0{ for i in 0 ..< vk { // i + start count - vk + i + start // swapNumbers(&nums, i + start, count-vk+i + start) nums.swapAt(i + start, count-vk+i + start) } count = count - vk start = start + vk vk = vk % count } } numbers = [1,2,3,4,5,6,7] rotate(&numbers, 3 ) numbers //: 思路三 优化 //使用 swapAt 代替自己实现的数组元素交换函数 //: [Next](@next)
19.766355
91
0.516312
ddf8ed83af16138fbc00be8744bdd56589fb188e
378
// // KeyboardAutoLayoutTests.swift // KeyboardAutoLayoutTests // // Created by ky1vstar on 23 янв. 2021 г.. // Copyright © 2021 ky1vstar. All rights reserved. // @testable import KeyboardAutoLayout import XCTest class KeyboardAutoLayoutTests: XCTestCase { static var allTests = [ ("testExample", testExample), ] func testExample() {} }
18
51
0.671958
29ad0a4f552f134bcfb91530bbddaa08712e1513
517
// // Model.swift // InstagramFeedNativeDemo // // Created by Emil Atanasov on 10.01.18. // Copyright © 2018 SwiftFMI. All rights reserved. // import Foundation //TODO: image dimentions MUST be in the model class FeedItem: Codable { var avatar:Avatar? var image:String? var imageWidth: Int? var imageHeight: Int? var likes:Int? var comments:[Comment]? } class Avatar: Codable { var name:String? var url:String? } class Comment: Codable { var id:Int? var text:String? }
17.233333
51
0.667311
effddaeef15997e663384eace34358de85d9b297
482
// 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 func i: ExtensibleCollectionType>? func a: C { protocol P { func c] typealias d : d
34.428571
79
0.748963
e507ea2931f75e00c194947057ae8778b4c56ed7
1,040
// // UISearchBarExtensions.swift // YYSwift // // Created by Phoenix on 2018/1/8. // Copyright © 2018年 Phoenix. All rights reserved. // #if canImport(UIKit) import UIKit // MARK: - Properties public extension UISearchBar { /// YYSwift: Text field inside search bar (if applicable). var textField: UITextField? { let subViews = subviews.flatMap { $0.subviews } guard let textField = (subViews.filter { $0 is UITextField }).first as? UITextField else { return nil } return textField } /// YYSwift: Text with no spaces or new lines in beginning and end (if applicable). var trimmedText: String? { return text?.trimmingCharacters(in: .whitespacesAndNewlines) } } // MARK: - Methods public extension UISearchBar { /// YYSwift: Clear text. func clear() { text = "" } /// YYSwift: Set text with no spaces or new lines in beginning and end (if applicable). func trimmed() { text = trimmedText } } #endif
23.636364
98
0.625
115a937c0c1cc98e74a75f7f14e4c3ed18a37eb2
455
// 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 class func g<T { class b: a { class a { } } return ""[1)
30.333333
79
0.72967
7a6583413f5fb05977c4ccec22126cbb9df2cae3
2,309
// // Copyright (c) 2021 Adyen N.V. // // This file is open source and available under the MIT license. See the LICENSE file for more info. // import Foundation import UIKit /// Describes any entity that is UI localizable. public protocol Localizable { /// Indicates the localization parameters, leave it nil to use the default parameters. var localizationParameters: LocalizationParameters? { get set } } /// :nodoc: /// Represents any object than can handle a cancel event. public protocol Cancellable: AnyObject { /// :nodoc: /// Called when the user cancels the component. func didCancel() } /// :nodoc: /// Pepresents navigation bar on top of presentable components. public protocol AnyNavigationBar: UIView { var onCancelHandler: (() -> Void)? { get set } } /// :nodoc: public enum NavigationBarType { case regular case custom(AnyNavigationBar) } /// A component that provides a view controller for the shopper to fill payment details. public protocol PresentableComponent: Component { /// Indicates whether `viewController` expected to be presented modally, /// hence it can not handle its own presentation and dismissal. var requiresModalPresentation: Bool { get } /// Returns a view controller that presents the payment details for the shopper to fill. var viewController: UIViewController { get } /// Indicates whether Component implements a custom Navigation bar. var navBarType: NavigationBarType { get } } /// :nodoc: public extension PresentableComponent { /// :nodoc: var requiresModalPresentation: Bool { false } /// :nodoc: var navBarType: NavigationBarType { .regular } } /// :nodoc: public protocol TrackableComponent: Component, PaymentMethodAware, ViewControllerDelegate {} /// :nodoc: extension TrackableComponent { /// :nodoc: public func viewDidLoad(viewController: UIViewController) { Analytics.sendEvent(component: paymentMethod.type, flavor: _isDropIn ? .dropin : .components, context: apiContext) } /// :nodoc: public func viewDidAppear(viewController: UIViewController) { /* Empty Implementation */ } /// :nodoc: public func viewWillAppear(viewController: UIViewController) { /* Empty Implementation */ } }
28.506173
122
0.705933
38962a991ae5d9512ed83d1fb5d39453e34ac793
1,657
/* * Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of MaterialKit nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit public enum ContentImageFormatType { case PNG case JPEG }
46.027778
86
0.782136
8f67e24047993fc642f1f47edae63dd7ae9c6ca0
4,708
// // ChatControllerShortcutUtils.swift // Rocket.Chat // // Created by Matheus Cardoso on 8/3/18. // Copyright © 2018 Rocket.Chat. All rights reserved. // // MARK: Utils extension UIViewController { var isPresenting: Bool { return presentedViewController != nil } func doAfterDismissingPresented(completion: @escaping () -> Void) { let (chatPresented, subsPresented) = (presentedViewController, MainSplitViewController.subscriptionsViewController?.presentedViewController) switch (chatPresented, subsPresented) { case let (chatPresented?, _): chatPresented.dismiss(animated: true) { completion() } case let (nil, subsPresented?): subsPresented.dismiss(animated: true) { completion() } case(nil, nil): completion() } } } // MARK: New Room Screen extension SubscriptionsViewController { var isNewRoomOpen: Bool { return (presentedViewController as? UINavigationController)?.viewControllers.first as? NewRoomViewController != nil } func toggleNewRoom() { if isNewRoomOpen { closeNewRoom() } else { openNewRoom() } } func openNewRoom() { doAfterDismissingPresented { [weak self] in self?.performSegue(withIdentifier: "toNewRoom", sender: nil) } } func closeNewRoom() { if isNewRoomOpen { presentedViewController?.dismiss(animated: true, completion: nil) } } } // MARK: Preferences extension SubscriptionsViewController { var isPreferencesOpen: Bool { return presentedViewController as? PreferencesNavigationController != nil } func togglePreferences() { if isPreferencesOpen { closePreferences() } else { openPreferences() } } func openPreferences() { doAfterDismissingPresented { [weak self] in self?.performSegue(withIdentifier: "Preferences", sender: nil) } } func closePreferences() { if isPreferencesOpen { presentedViewController?.dismiss(animated: true, completion: nil) } } } // MARK: Upload extension MessagesViewController { private var controller: UIViewController? { return composerView.window?.rootViewController } private var alertController: UIAlertController? { return controller?.presentedViewController as? UIAlertController } var isUploadOpen: Bool { return alertController?.popoverPresentationController?.sourceView == composerView.leftButton } func toggleUpload() { if isUploadOpen { closeUpload() } else { openUpload() } } func openUpload() { controller?.doAfterDismissingPresented { [weak self] in guard let self = self else { return } self.composerView(self.composerView, didPressUploadButton: self.composerView.leftButton) } } func closeUpload() { if isUploadOpen { alertController?.dismiss(animated: true, completion: nil) } } } // MARK: Room Actions extension MessagesViewController { var isActionsOpen: Bool { let controller = (presentedViewController as? UINavigationController)?.viewControllers.first return controller as? ChannelActionsViewController != nil } func toggleActions() { if isActionsOpen { closeActions() } else { openActions() } } func openActions() { doAfterDismissingPresented { [weak self] in self?.performSegue(withIdentifier: "Channel Actions", sender: nil) } } func closeActions() { if isActionsOpen { presentedViewController?.dismiss(animated: true, completion: nil) } } } // MARK: Message Searching extension MessagesViewController { var isSearchMessagesOpen: Bool { let controller = presentedViewController?.children.first as? MessagesListViewController return controller?.data.isSearchingMessages == true } func toggleSearchMessages() { if isSearchMessagesOpen { closeSearchMessages() } else { openSearchMessages() } } func openSearchMessages() { doAfterDismissingPresented { [weak self] in self?.showSearchMessages() } } func closeSearchMessages() { if isSearchMessagesOpen { presentedViewController?.dismiss(animated: true, completion: nil) } } }
25.176471
148
0.61746
e6092991305819d5ef84e73f8ccad62d4e8fa6dc
896
// // JLExtension+UIImage.swift // JLReader // // Created by JasonLiu on 2018/9/5. // Copyright © 2018年 JasonLiu. All rights reserved. // import UIKit extension UIImage { } func JLGradientImage(size: CGSize, cgColors: [Any], locations: [NSNumber]! = nil, startPoint: CGPoint = CGPoint(x: 0.5, y: 0), endPoint: CGPoint = CGPoint(x: 0.5, y: 1)) -> UIImage? { let frame = CGRect(origin: CGPoint(x: 0, y: 0), size: size) let layer = CAGradientLayer(cgColors: cgColors, locations: locations, startPoint: startPoint, endPoint: endPoint) layer.frame = frame return JLGradientImage(layer: layer) } func JLGradientImage(layer: CALayer) -> UIImage { UIGraphicsBeginImageContext(layer.frame.size) layer.render(in: UIGraphicsGetCurrentContext()!) let outputImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return outputImage! }
30.896552
183
0.71317
642b8deb7c0ecb50a37a53be99abc5e0098ac557
1,343
// The MIT License (MIT) // Copyright © 2021 Ivan Vorobei ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit public enum SPPageControllerSystem { case page case scroll } public enum SPPageControllerNavigationOrientation { case vertical case horizontal }
38.371429
81
0.758004
fe839fd4ef19f9c8fc3e61f3610738e771d1b23c
1,113
// Copyright (c) 2019-2020 XMLCoder contributors // // This software is released under the MIT License. // https://opensource.org/licenses/MIT // // Created by Benjamin Wetherfield on 11/24/19. // import XMLCoder internal enum IntOrString: Equatable { case int(Int) case string(String) } extension IntOrString: Codable { enum CodingKeys: String, CodingKey { case int case string } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) switch self { case let .int(value): try container.encode(value, forKey: .int) case let .string(value): try container.encode(value, forKey: .string) } } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) do { self = .int(try container.decode(Int.self, forKey: .int)) } catch { self = .string(try container.decode(String.self, forKey: .string)) } } } extension IntOrString.CodingKeys: XMLChoiceCodingKey {}
25.883721
78
0.633423
3354134256642c7b85ccfe865d839b02fd9f569f
1,035
// // ProfileViewController.swift // Tinder // // Created by Trustin Harris on 4/30/18. // Copyright © 2018 Trustin Harris. All rights reserved. // import UIKit class ProfileViewController: UIViewController { @IBOutlet weak var ProfilePic: UIImageView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func Button(_ sender: Any) { performSegue(withIdentifier: "ToCards", sender: nil) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
25.875
106
0.670531