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
e8e6bb3cd05fbcf70d2204176a28b315c2ee8e84
2,171
// // AppDelegate.swift // StudioCalc // // Created by Doug Olson on 9/25/16. // Copyright © 2016 Doug Olson. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.191489
285
0.754952
abe82cc5e0b58f1afffcc7fae1724f4b152e3bee
2,713
// // Pencil.swift // Photo Editor // // Created by Mohamed Hamed on 4/26/17. // Copyright © 2017 Mohamed Hamed. All rights reserved. // import UIKit extension PhotoEditorViewController { //MARK: Pencil override public func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?){ if isDrawing { // self.view.bringSubview(toFront: tempImageView) swiped = false if let touch = touches.first { lastPoint = touch.location(in: self.tempImageView) } } //Hide BottomSheet if clicked outside it else if bottomSheetIsVisible == true { if let touch = touches.first { let location = touch.location(in: self.view) if !bottomSheetVC.view.frame.contains(location) { removeBottomSheetView() } } } } override public func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?){ if isDrawing { // 6 swiped = true if let touch = touches.first { let currentPoint = touch.location(in: tempImageView) drawLineFrom(lastPoint, toPoint: currentPoint) // 7 lastPoint = currentPoint } } } override public func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?){ if isDrawing { if !swiped { // draw a single point drawLineFrom(lastPoint, toPoint: lastPoint) } } } func drawLineFrom(_ fromPoint: CGPoint, toPoint: CGPoint) { // 1 UIGraphicsBeginImageContext(imageView.frame.size) if let context = UIGraphicsGetCurrentContext() { tempImageView.image?.draw(in: CGRect(x: 0, y: 0, width: imageView.frame.size.width, height: imageView.frame.size.height)) // 2 context.move(to: CGPoint(x: fromPoint.x, y: fromPoint.y)) context.addLine(to: CGPoint(x: toPoint.x, y: toPoint.y)) // 3 context.setLineCap( CGLineCap.round) context.setLineWidth(5.0) context.setStrokeColor(drawColor.cgColor) context.setBlendMode( CGBlendMode.normal) // 4 context.strokePath() // 5 tempImageView.image = UIGraphicsGetImageFromCurrentImageContext() tempImageView.alpha = opacity UIGraphicsEndImageContext() } } }
32.297619
133
0.525986
d5a5e1fe39bfd57b6e363a84dff867946d2fece0
13,521
import Foundation import JSONUtilities import XcodeProj import Version public struct LegacyTarget: Equatable { public static let passSettingsDefault = false public var toolPath: String public var arguments: String? public var passSettings: Bool public var workingDirectory: String? public init( toolPath: String, passSettings: Bool = passSettingsDefault, arguments: String? = nil, workingDirectory: String? = nil ) { self.toolPath = toolPath self.arguments = arguments self.passSettings = passSettings self.workingDirectory = workingDirectory } } public struct Target: ProjectTarget { public var name: String public var type: PBXProductType public var platform: Platform public var settings: Settings public var sources: [TargetSource] public var dependencies: [Dependency] public var info: Plist? public var entitlements: Plist? public var transitivelyLinkDependencies: Bool? public var directlyEmbedCarthageDependencies: Bool? public var requiresObjCLinking: Bool? public var preBuildScripts: [BuildScript] public var postCompileScripts: [BuildScript] public var postBuildScripts: [BuildScript] public var buildRules: [BuildRule] public var configFiles: [String: String] public var scheme: TargetScheme? public var legacy: LegacyTarget? public var deploymentTarget: Version? public var attributes: [String: Any] public var productName: String public var isLegacy: Bool { legacy != nil } public var filename: String { var filename = productName if let fileExtension = type.fileExtension { filename += ".\(fileExtension)" } return filename } public init( name: String, type: PBXProductType, platform: Platform, productName: String? = nil, deploymentTarget: Version? = nil, settings: Settings = .empty, configFiles: [String: String] = [:], sources: [TargetSource] = [], dependencies: [Dependency] = [], info: Plist? = nil, entitlements: Plist? = nil, transitivelyLinkDependencies: Bool? = nil, directlyEmbedCarthageDependencies: Bool? = nil, requiresObjCLinking: Bool? = nil, preBuildScripts: [BuildScript] = [], postCompileScripts: [BuildScript] = [], postBuildScripts: [BuildScript] = [], buildRules: [BuildRule] = [], scheme: TargetScheme? = nil, legacy: LegacyTarget? = nil, attributes: [String: Any] = [:] ) { self.name = name self.type = type self.platform = platform self.deploymentTarget = deploymentTarget self.productName = productName ?? name self.settings = settings self.configFiles = configFiles self.sources = sources self.dependencies = dependencies self.info = info self.entitlements = entitlements self.transitivelyLinkDependencies = transitivelyLinkDependencies self.directlyEmbedCarthageDependencies = directlyEmbedCarthageDependencies self.requiresObjCLinking = requiresObjCLinking self.preBuildScripts = preBuildScripts self.postCompileScripts = postCompileScripts self.postBuildScripts = postBuildScripts self.buildRules = buildRules self.scheme = scheme self.legacy = legacy self.attributes = attributes } } extension Target: CustomStringConvertible { public var description: String { "\(name): \(platform.rawValue) \(type)" } } extension Target: PathContainer { static var pathProperties: [PathProperty] { [ .dictionary([ .string("sources"), .object("sources", TargetSource.pathProperties), .string("configFiles"), .object("dependencies", Dependency.pathProperties), .object("info", Plist.pathProperties), .object("entitlements", Plist.pathProperties), .object("preBuildScripts", BuildScript.pathProperties), .object("prebuildScripts", BuildScript.pathProperties), .object("postCompileScripts", BuildScript.pathProperties), .object("postBuildScripts", BuildScript.pathProperties), ]), ] } } extension Target { static func resolveMultiplatformTargets(jsonDictionary: JSONDictionary) -> JSONDictionary { guard let targetsDictionary: [String: JSONDictionary] = jsonDictionary["targets"] as? [String: JSONDictionary] else { return jsonDictionary } var crossPlatformTargets: [String: JSONDictionary] = [:] for (targetName, target) in targetsDictionary { if let platforms = target["platform"] as? [String] { for platform in platforms { var platformTarget = target platformTarget = platformTarget.expand(variables: ["platform": platform]) platformTarget["platform"] = platform let platformSuffix = platformTarget["platformSuffix"] as? String ?? "_\(platform)" let platformPrefix = platformTarget["platformPrefix"] as? String ?? "" let newTargetName = platformPrefix + targetName + platformSuffix var settings = platformTarget["settings"] as? JSONDictionary ?? [:] if settings["configs"] != nil || settings["groups"] != nil || settings["base"] != nil { var base = settings["base"] as? JSONDictionary ?? [:] if base["PRODUCT_NAME"] == nil { base["PRODUCT_NAME"] = targetName } settings["base"] = base } else { if settings["PRODUCT_NAME"] == nil { settings["PRODUCT_NAME"] = targetName } } platformTarget["productName"] = targetName platformTarget["settings"] = settings if let deploymentTargets = target["deploymentTarget"] as? [String: Any] { platformTarget["deploymentTarget"] = deploymentTargets[platform] } crossPlatformTargets[newTargetName] = platformTarget } } else { crossPlatformTargets[targetName] = target } } var merged = jsonDictionary merged["targets"] = crossPlatformTargets return merged } } extension Target: Equatable { public static func == (lhs: Target, rhs: Target) -> Bool { lhs.name == rhs.name && lhs.type == rhs.type && lhs.platform == rhs.platform && lhs.deploymentTarget == rhs.deploymentTarget && lhs.transitivelyLinkDependencies == rhs.transitivelyLinkDependencies && lhs.requiresObjCLinking == rhs.requiresObjCLinking && lhs.directlyEmbedCarthageDependencies == rhs.directlyEmbedCarthageDependencies && lhs.settings == rhs.settings && lhs.configFiles == rhs.configFiles && lhs.sources == rhs.sources && lhs.info == rhs.info && lhs.entitlements == rhs.entitlements && lhs.dependencies == rhs.dependencies && lhs.preBuildScripts == rhs.preBuildScripts && lhs.postCompileScripts == rhs.postCompileScripts && lhs.postBuildScripts == rhs.postBuildScripts && lhs.buildRules == rhs.buildRules && lhs.scheme == rhs.scheme && lhs.legacy == rhs.legacy && NSDictionary(dictionary: lhs.attributes).isEqual(to: rhs.attributes) } } extension LegacyTarget: JSONObjectConvertible { public init(jsonDictionary: JSONDictionary) throws { toolPath = try jsonDictionary.json(atKeyPath: "toolPath") arguments = jsonDictionary.json(atKeyPath: "arguments") passSettings = jsonDictionary.json(atKeyPath: "passSettings") ?? LegacyTarget.passSettingsDefault workingDirectory = jsonDictionary.json(atKeyPath: "workingDirectory") } } extension LegacyTarget: JSONEncodable { public func toJSONValue() -> Any { var dict: [String: Any?] = [ "toolPath": toolPath, "arguments": arguments, "workingDirectory": workingDirectory, ] if passSettings != LegacyTarget.passSettingsDefault { dict["passSettings"] = passSettings } return dict } } extension Target: NamedJSONDictionaryConvertible { public init(name: String, jsonDictionary: JSONDictionary) throws { let resolvedName: String = jsonDictionary.json(atKeyPath: "name") ?? name self.name = resolvedName productName = jsonDictionary.json(atKeyPath: "productName") ?? resolvedName let typeString: String = try jsonDictionary.json(atKeyPath: "type") if let type = PBXProductType(string: typeString) { self.type = type } else { throw SpecParsingError.unknownTargetType(typeString) } let platformString: String = try jsonDictionary.json(atKeyPath: "platform") if let platform = Platform(rawValue: platformString) { self.platform = platform } else { throw SpecParsingError.unknownTargetPlatform(platformString) } if let string: String = jsonDictionary.json(atKeyPath: "deploymentTarget") { deploymentTarget = try Version.parse(string) } else if let double: Double = jsonDictionary.json(atKeyPath: "deploymentTarget") { deploymentTarget = try Version.parse(String(double)) } else { deploymentTarget = nil } settings = jsonDictionary.json(atKeyPath: "settings") ?? .empty configFiles = jsonDictionary.json(atKeyPath: "configFiles") ?? [:] if let source: String = jsonDictionary.json(atKeyPath: "sources") { sources = [TargetSource(path: source)] } else if let array = jsonDictionary["sources"] as? [Any] { sources = try array.compactMap { source in if let string = source as? String { return TargetSource(path: string) } else if let dictionary = source as? [String: Any] { return try TargetSource(jsonDictionary: dictionary) } else { return nil } } } else { sources = [] } if jsonDictionary["dependencies"] == nil { dependencies = [] } else { dependencies = try jsonDictionary.json(atKeyPath: "dependencies", invalidItemBehaviour: .fail) } if jsonDictionary["info"] != nil { info = try jsonDictionary.json(atKeyPath: "info") as Plist } if jsonDictionary["entitlements"] != nil { entitlements = try jsonDictionary.json(atKeyPath: "entitlements") as Plist } transitivelyLinkDependencies = jsonDictionary.json(atKeyPath: "transitivelyLinkDependencies") directlyEmbedCarthageDependencies = jsonDictionary.json(atKeyPath: "directlyEmbedCarthageDependencies") requiresObjCLinking = jsonDictionary.json(atKeyPath: "requiresObjCLinking") preBuildScripts = jsonDictionary.json(atKeyPath: "preBuildScripts") ?? jsonDictionary.json(atKeyPath: "prebuildScripts") ?? [] postCompileScripts = jsonDictionary.json(atKeyPath: "postCompileScripts") ?? [] postBuildScripts = jsonDictionary.json(atKeyPath: "postBuildScripts") ?? jsonDictionary.json(atKeyPath: "postbuildScripts") ?? [] buildRules = jsonDictionary.json(atKeyPath: "buildRules") ?? [] scheme = jsonDictionary.json(atKeyPath: "scheme") legacy = jsonDictionary.json(atKeyPath: "legacy") attributes = jsonDictionary.json(atKeyPath: "attributes") ?? [:] } } extension Target: JSONEncodable { public func toJSONValue() -> Any { var dict: [String: Any?] = [ "type": type.name, "platform": platform.rawValue, "settings": settings.toJSONValue(), "configFiles": configFiles, "attributes": attributes, "sources": sources.map { $0.toJSONValue() }, "dependencies": dependencies.map { $0.toJSONValue() }, "postCompileScripts": postCompileScripts.map { $0.toJSONValue() }, "prebuildScripts": preBuildScripts.map { $0.toJSONValue() }, "postbuildScripts": postBuildScripts.map { $0.toJSONValue() }, "buildRules": buildRules.map { $0.toJSONValue() }, "deploymentTarget": deploymentTarget?.deploymentTarget, "info": info?.toJSONValue(), "entitlements": entitlements?.toJSONValue(), "transitivelyLinkDependencies": transitivelyLinkDependencies, "directlyEmbedCarthageDependencies": directlyEmbedCarthageDependencies, "requiresObjCLinking": requiresObjCLinking, "scheme": scheme?.toJSONValue(), "legacy": legacy?.toJSONValue(), ] if productName != name { dict["productName"] = productName } return dict } }
39.419825
137
0.611937
5d1a9e79f6ca13b6e2a0f0c20e48458b58118775
22,031
// // PhotoPreviewViewController.swift // HXPHPickerExample // // Created by Silence on 2020/11/13. // Copyright © 2020 Silence. All rights reserved. // import UIKit import Photos protocol PhotoPreviewViewControllerDelegate: AnyObject { func previewViewController( _ previewController: PhotoPreviewViewController, didOriginalButton isOriginal: Bool ) func previewViewController( _ previewController: PhotoPreviewViewController, didSelectBox photoAsset: PhotoAsset, isSelected: Bool, updateCell: Bool ) func previewViewController( _ previewController: PhotoPreviewViewController, editAssetFinished photoAsset: PhotoAsset ) func previewViewController( _ previewController: PhotoPreviewViewController, networkImagedownloadSuccess photoAsset: PhotoAsset ) func previewViewController( didFinishButton previewController: PhotoPreviewViewController ) func previewViewController( _ previewController: PhotoPreviewViewController, requestSucceed photoAsset: PhotoAsset ) func previewViewController( _ previewController: PhotoPreviewViewController, requestFailed photoAsset: PhotoAsset ) } extension PhotoPreviewViewControllerDelegate { func previewViewController( _ previewController: PhotoPreviewViewController, didOriginalButton isOriginal: Bool ) { } func previewViewController( _ previewController: PhotoPreviewViewController, didSelectBox photoAsset: PhotoAsset, isSelected: Bool, updateCell: Bool ) { } func previewViewController( _ previewController: PhotoPreviewViewController, editAssetFinished photoAsset: PhotoAsset ) { } func previewViewController( _ previewController: PhotoPreviewViewController, networkImagedownloadSuccess photoAsset: PhotoAsset ) { } func previewViewController( didFinishButton previewController: PhotoPreviewViewController ) { } func previewViewController( _ previewController: PhotoPreviewViewController, requestSucceed photoAsset: PhotoAsset ) { } func previewViewController( _ previewController: PhotoPreviewViewController, requestFailed photoAsset: PhotoAsset ) { } } public class PhotoPreviewViewController: BaseViewController { weak var delegate: PhotoPreviewViewControllerDelegate? public let config: PreviewViewConfiguration /// 当前预览的位置索引 public var currentPreviewIndex: Int = 0 /// 预览的资源数组 public var previewAssets: [PhotoAsset] = [] /// 是否是外部预览 public var isExternalPreview: Bool = false var isExternalPickerPreview: Bool = false var orientationDidChange: Bool = false var statusBarShouldBeHidden: Bool = false var videoLoadSingleCell = false var viewDidAppear: Bool = false var firstLayoutSubviews: Bool = true var interactiveTransition: PickerInteractiveTransition? weak var beforeNavDelegate: UINavigationControllerDelegate? lazy var selectBoxControl: SelectBoxView = { let boxControl = SelectBoxView( frame: CGRect( origin: .zero, size: config.selectBox.size ) ) boxControl.backgroundColor = .clear boxControl.config = config.selectBox boxControl.addTarget(self, action: #selector(didSelectBoxControlClick), for: UIControl.Event.touchUpInside) return boxControl }() lazy var collectionViewLayout: UICollectionViewFlowLayout = { let layout = UICollectionViewFlowLayout.init() layout.scrollDirection = .horizontal layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.sectionInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10) return layout }() lazy var collectionView: UICollectionView = { let collectionView = UICollectionView.init(frame: view.bounds, collectionViewLayout: collectionViewLayout) collectionView.backgroundColor = .clear collectionView.dataSource = self collectionView.delegate = self collectionView.isPagingEnabled = true collectionView.showsVerticalScrollIndicator = false collectionView.showsHorizontalScrollIndicator = false if #available(iOS 11.0, *) { collectionView.contentInsetAdjustmentBehavior = .never } else { // Fallback on earlier versions self.automaticallyAdjustsScrollViewInsets = false } collectionView.register( PreviewPhotoViewCell.self, forCellWithReuseIdentifier: NSStringFromClass(PreviewPhotoViewCell.self) ) collectionView.register( PreviewLivePhotoViewCell.self, forCellWithReuseIdentifier: NSStringFromClass(PreviewLivePhotoViewCell.self) ) if let customVideoCell = config.customVideoCellClass { collectionView.register( customVideoCell, forCellWithReuseIdentifier: NSStringFromClass(PreviewVideoViewCell.self) ) }else { collectionView.register( PreviewVideoViewCell.self, forCellWithReuseIdentifier: NSStringFromClass(PreviewVideoViewCell.self) ) } return collectionView }() var isMultipleSelect: Bool = false var allowLoadPhotoLibrary: Bool = true lazy var bottomView: PhotoPickerBottomView = { let bottomView = PhotoPickerBottomView( config: config.bottomView, allowLoadPhotoLibrary: allowLoadPhotoLibrary, isMultipleSelect: isMultipleSelect, isPreview: true, isExternalPreview: isExternalPreview ) bottomView.hx_delegate = self if config.bottomView.showSelectedView && (isMultipleSelect || isExternalPreview) { bottomView.selectedView.reloadData( photoAssets: pickerController!.selectedAssetArray ) } if !isExternalPreview { bottomView.boxControl.isSelected = pickerController!.isOriginal bottomView.requestAssetBytes() } return bottomView }() var requestPreviewTimer: Timer? init(config: PreviewViewConfiguration) { self.config = config super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() let margin: CGFloat = 20 let itemWidth = view.width + margin collectionViewLayout.minimumLineSpacing = margin collectionViewLayout.itemSize = view.size let contentWidth = (view.width + itemWidth) * CGFloat(previewAssets.count) collectionView.frame = CGRect(x: -(margin * 0.5), y: 0, width: itemWidth, height: view.height) collectionView.contentSize = CGSize(width: contentWidth, height: view.height) collectionView.setContentOffset(CGPoint(x: CGFloat(currentPreviewIndex) * itemWidth, y: 0), animated: false) DispatchQueue.main.async { if self.orientationDidChange { let cell = self.getCell(for: self.currentPreviewIndex) cell?.setupScrollViewContentSize() self.orientationDidChange = false } } configBottomViewFrame() if firstLayoutSubviews { if !previewAssets.isEmpty && config.bottomView.showSelectedView && (isMultipleSelect || isExternalPreview) && config.showBottomView { DispatchQueue.main.async { self.bottomView.selectedView.scrollTo( photoAsset: self.previewAssets[self.currentPreviewIndex], isAnimated: false ) } } firstLayoutSubviews = false } } public override func viewDidLoad() { super.viewDidLoad() title = "" isMultipleSelect = pickerController?.config.selectMode == .multiple allowLoadPhotoLibrary = pickerController?.config.allowLoadPhotoLibrary ?? true extendedLayoutIncludesOpaqueBars = true edgesForExtendedLayout = .all view.clipsToBounds = true initView() } public override func deviceOrientationDidChanged(notify: Notification) { orientationDidChange = true let cell = getCell(for: currentPreviewIndex) if cell?.photoAsset.mediaSubType == .livePhoto { if #available(iOS 9.1, *) { cell?.scrollContentView.livePhotoView.stopPlayback() } } if config.bottomView.showSelectedView && (isMultipleSelect || isExternalPreview) && config.showBottomView { bottomView.selectedView.reloadSectionInset() } } public override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) pickerController?.viewControllersWillAppear(self) } public override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) viewDidAppear = true DispatchQueue.main.async { let cell = self.getCell(for: self.currentPreviewIndex) cell?.requestPreviewAsset() } pickerController?.viewControllersDidAppear(self) guard let picker = pickerController else { return } if (picker.modalPresentationStyle == .fullScreen && interactiveTransition == nil) || (!UIDevice.isPortrait && !UIDevice.isPad) && !isExternalPreview { interactiveTransition = PickerInteractiveTransition( panGestureRecognizerFor: self, type: .pop ) } } public override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) pickerController?.viewControllersWillDisappear(self) } public override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) pickerController?.viewControllersDidDisappear(self) } public override var prefersStatusBarHidden: Bool { return statusBarShouldBeHidden } public override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation { return .fade } public override var preferredStatusBarStyle: UIStatusBarStyle { if PhotoManager.isDark { return .lightContent } return pickerController?.config.statusBarStyle ?? .default } public override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) if #available(iOS 13.0, *) { if traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection) && viewDidAppear { configColor() } } } deinit { NotificationCenter.default.removeObserver(self) } } // MARK: Function extension PhotoPreviewViewController { private func initView() { view.addSubview(collectionView) if config.showBottomView { view.addSubview(bottomView) bottomView.updateFinishButtonTitle() } if let pickerController = pickerController, (isExternalPreview || isExternalPickerPreview) { // statusBarShouldBeHidden = pickerController.config.prefersStatusBarHidden if pickerController.modalPresentationStyle != .custom { configColor() } } if isMultipleSelect || isExternalPreview { videoLoadSingleCell = pickerController!.singleVideo if !isExternalPreview { if isExternalPickerPreview { let cancelItem = UIBarButtonItem( image: "hx_picker_photolist_cancel".image, style: .done, target: self, action: #selector(didCancelItemClick) ) navigationItem.leftBarButtonItem = cancelItem } navigationItem.rightBarButtonItem = UIBarButtonItem.init(customView: selectBoxControl) }else { var cancelItem: UIBarButtonItem if config.cancelType == .image { let isDark = PhotoManager.isDark cancelItem = UIBarButtonItem( image: UIImage.image( for: isDark ? config.cancelDarkImageName : config.cancelImageName ), style: .done, target: self, action: #selector(didCancelItemClick) ) }else { cancelItem = UIBarButtonItem( title: "取消".localized, style: .done, target: self, action: #selector(didCancelItemClick) ) } if config.cancelPosition == .left { navigationItem.leftBarButtonItem = cancelItem } else { navigationItem.rightBarButtonItem = cancelItem } } if !previewAssets.isEmpty { if currentPreviewIndex == 0 { let photoAsset = previewAssets.first! if config.bottomView.showSelectedView && config.showBottomView { bottomView.selectedView.scrollTo(photoAsset: photoAsset) } if !isExternalPreview { if photoAsset.mediaType == .video && videoLoadSingleCell { selectBoxControl.isHidden = true } else { updateSelectBox(photoAsset.isSelected, photoAsset: photoAsset) selectBoxControl.isSelected = photoAsset.isSelected } } #if HXPICKER_ENABLE_EDITOR if let pickerController = pickerController, !config.bottomView.editButtonHidden, config.showBottomView { if photoAsset.mediaType == .photo { bottomView.editBtn.isEnabled = pickerController.config.editorOptions.isPhoto }else if photoAsset.mediaType == .video { bottomView.editBtn.isEnabled = pickerController.config.editorOptions.contains(.video) } } #endif pickerController?.previewUpdateCurrentlyDisplayedAsset( photoAsset: photoAsset, index: currentPreviewIndex ) } } }else if !isMultipleSelect { if isExternalPickerPreview { let cancelItem = UIBarButtonItem( image: "hx_picker_photolist_cancel".image, style: .done, target: self, action: #selector(didCancelItemClick) ) navigationItem.leftBarButtonItem = cancelItem } if !previewAssets.isEmpty { if currentPreviewIndex == 0 { let photoAsset = previewAssets.first! #if HXPICKER_ENABLE_EDITOR if let pickerController = pickerController, !config.bottomView.editButtonHidden, config.showBottomView { if photoAsset.mediaType == .photo { bottomView.editBtn.isEnabled = pickerController.config.editorOptions.isPhoto }else if photoAsset.mediaType == .video { bottomView.editBtn.isEnabled = pickerController.config.editorOptions.contains(.video) } } #endif pickerController?.previewUpdateCurrentlyDisplayedAsset( photoAsset: photoAsset, index: currentPreviewIndex ) } } } } func configBottomViewFrame() { if !config.showBottomView { return } var bottomHeight: CGFloat = 0 if isExternalPreview { bottomHeight = (pickerController?.selectedAssetArray.isEmpty ?? true) ? 0 : UIDevice.bottomMargin + 70 #if HXPICKER_ENABLE_EDITOR if !config.bottomView.showSelectedView && config.bottomView.editButtonHidden { if config.bottomView.editButtonHidden { bottomHeight = 0 }else { bottomHeight = UIDevice.bottomMargin + 50 } } #endif }else { if let picker = pickerController { bottomHeight = picker.selectedAssetArray.isEmpty ? 50 + UIDevice.bottomMargin : 50 + UIDevice.bottomMargin + 70 } if !config.bottomView.showSelectedView || !isMultipleSelect { bottomHeight = 50 + UIDevice.bottomMargin } } bottomView.frame = CGRect( x: 0, y: view.height - bottomHeight, width: view.width, height: bottomHeight ) } func configColor() { view.backgroundColor = PhotoManager.isDark ? config.backgroundDarkColor : config.backgroundColor } func reloadCell(for photoAsset: PhotoAsset) { guard let item = previewAssets.firstIndex(of: photoAsset), !previewAssets.isEmpty else { return } let indexPath = IndexPath(item: item, section: 0) collectionView.reloadItems(at: [indexPath]) if config.showBottomView { bottomView.selectedView.reloadData(photoAsset: photoAsset) bottomView.requestAssetBytes() } } func getCell(for item: Int) -> PhotoPreviewViewCell? { if previewAssets.isEmpty { return nil } let cell = collectionView.cellForItem( at: IndexPath( item: item, section: 0 ) ) as? PhotoPreviewViewCell return cell } func getCell(for photoAsset: PhotoAsset) -> PhotoPreviewViewCell? { guard let item = previewAssets.firstIndex(of: photoAsset) else { return nil } return getCell(for: item) } func setCurrentCellImage(image: UIImage?) { guard let image = image, let cell = getCell(for: currentPreviewIndex), !cell.scrollContentView.requestCompletion else { return } cell.scrollContentView.imageView.image = image } func deleteCurrentPhotoAsset() { if previewAssets.isEmpty || !isExternalPreview { return } let photoAsset = previewAssets[currentPreviewIndex] if let shouldDelete = pickerController?.previewShouldDeleteAsset( photoAsset: photoAsset, index: currentPreviewIndex ), !shouldDelete { return } #if HXPICKER_ENABLE_EDITOR photoAsset.photoEdit = nil photoAsset.videoEdit = nil #endif previewAssets.remove( at: currentPreviewIndex ) collectionView.deleteItems( at: [ IndexPath( item: currentPreviewIndex, section: 0 ) ] ) if config.showBottomView { bottomView.selectedView.removePhotoAsset(photoAsset: photoAsset) } pickerController?.previewDidDeleteAsset( photoAsset: photoAsset, index: currentPreviewIndex ) if previewAssets.isEmpty { didCancelItemClick() return } scrollViewDidScroll(collectionView) setupRequestPreviewTimer() } func replacePhotoAsset(at index: Int, with photoAsset: PhotoAsset) { previewAssets[index] = photoAsset reloadCell(for: photoAsset) // collectionView.reloadItems(at: [IndexPath.init(item: index, section: 0)]) } func addedCameraPhotoAsset(_ photoAsset: PhotoAsset) { guard let picker = pickerController else { return } if config.bottomView.showSelectedView && (isMultipleSelect || isExternalPreview) && config.showBottomView { bottomView.selectedView.reloadData( photoAssets: picker.selectedAssetArray ) configBottomViewFrame() bottomView.layoutSubviews() bottomView.updateFinishButtonTitle() } getCell(for: currentPreviewIndex)?.cancelRequest() previewAssets.insert( photoAsset, at: currentPreviewIndex ) collectionView.insertItems( at: [ IndexPath( item: currentPreviewIndex, section: 0 ) ] ) collectionView.scrollToItem( at: IndexPath( item: currentPreviewIndex, section: 0 ), at: .centeredHorizontally, animated: false ) scrollViewDidScroll(collectionView) setupRequestPreviewTimer() } @objc func didCancelItemClick() { pickerController?.cancelCallback() dismiss(animated: true, completion: nil) } }
38.448517
116
0.597839
4a764df70645f03930ae7b91e2332075f39290d2
47,577
// // SettingsView.swift // TextEdit.it // // Created by Mark Howard on 21/02/2021. // import SwiftUI import CodeMirror_SwiftUI import KeyboardShortcuts struct KeyboardSettings: View { var body: some View { Form { HStack { VStack { VStack { Text("New Command") .padding(.vertical) HStack { Spacer() KeyboardShortcuts.Recorder(for: .newCommand) Spacer() } } VStack { Text("Open Command") .padding(.vertical) HStack { Spacer() KeyboardShortcuts.Recorder(for: .openCommand) Spacer() } } VStack { Text("Save Command") .padding(.vertical) HStack { Spacer() KeyboardShortcuts.Recorder(for: .saveCommand) Spacer() } } } VStack { VStack { Text("Close Command") .padding(.vertical) HStack { Spacer() KeyboardShortcuts.Recorder(for: .closeCommand) Spacer() } } /* VStack { Text("Print Command") .padding(.vertical) HStack { Spacer() KeyboardShortcuts.Recorder(for: .printCommand) Spacer() } } */ VStack { Text("Duplicate Command") .padding(.vertical) HStack { Spacer() KeyboardShortcuts.Recorder(for: .duplicateCommand) Spacer() } } VStack { Text("Move To… Command") .padding(.vertical) HStack { Spacer() KeyboardShortcuts.Recorder(for: .moveToCommand) Spacer() } } } VStack { VStack { Text("Rename… Command") .padding(.vertical) HStack { Spacer() KeyboardShortcuts.Recorder(for: .renameCommand) Spacer() } } VStack { Text("Revert To… Command") .padding(.vertical) HStack { Spacer() KeyboardShortcuts.Recorder(for: .revertToCommand) Spacer() } } } } } .padding(20) .frame(width: 600, height: 300) } } struct EditorSettings: View { @AppStorage("lineWrapping") var lineWrapping = true @AppStorage("showInvisibleCharacters") var showInvisibleCharacters = false @AppStorage("fontSize") var fontSize = 12 var body: some View { Form { VStack { HStack { Spacer() Stepper("Font Size: \(fontSize)", value: $fontSize, in: 1...120) Spacer() } Toggle(isOn: $lineWrapping) { Text("Line Wrapping") } .toggleStyle(SwitchToggleStyle()) Toggle(isOn: $showInvisibleCharacters) { Text("Show Invisible Characters") } .toggleStyle(SwitchToggleStyle()) } } .padding(20) .frame(width: 400, height: 150) } } struct ThemesSettings: View { @AppStorage("selectedSyntax") var selectedSyntax = 1 @AppStorage("selectedTheme") var selectedTheme = 0 @AppStorage("syntax") var syntax: CodeMode = CodeMode.text @AppStorage("theme") var theme: CodeViewTheme = CodeViewTheme.zenburnesque var body: some View { Form { Picker(selection: $selectedTheme, label: Text("Theme: ")) { Group { Group { Button(action: {}) { Text("bbedit") } .tag(1) Button(action: {}) { Text("all-hallow-eve") } .tag(2) Button(action: {}) { Text("idleFingers") } .tag(3) Button(action: {}) { Text("spaceCadet") } .tag(4) Button(action: {}) { Text("idle") } .tag(5) Button(action: {}) { Text("oceanic") } .tag(6) Button(action: {}) { Text("clouds") } .tag(7) Button(action: {}) { Text("github") } .tag(8) Button(action: {}) { Text("ryan-light") } .tag(9) Button(action: {}) { Text("black-pearl") } .tag(10) } Group { Button(action: {}) { Text("monoindustrial") } .tag(11) Button(action: {}) { Text("happy-happy-joy-joy-2") } .tag(12) Button(action: {}) { Text("cube2media") } .tag(13) Button(action: {}) { Text("friendship-bracelet") } .tag(14) Button(action: {}) { Text("classic-modififed") } .tag(15) Button(action: {}) { Text("amy") } .tag(16) Button(action: {}) { Text("demo") } .tag(17) Button(action: {}) { Text("rdark") } .tag(18) Button(action: {}) { Text("espresso") } .tag(19) Button(action: {}) { Text("sunburst") } .tag(20) } Group { Button(action: {}) { Text("made-of-code") } .tag(21) Button(action: {}) { Text("arona") } .tag(22) Button(action: {}) { Text("putty") } .tag(23) Button(action: {}) { Text("nightlion") } .tag(24) Button(action: {}) { Text("sidewalkchalk") } .tag(25) Button(action: {}) { Text("swyphs-ii") } .tag(26) Button(action: {}) { Text("iplastic") } .tag(27) Button(action: {}) { Text("solarized-(light)") } .tag(28) Button(action: {}) { Text("mac-classic") } .tag(29) Button(action: {}) { Text("pastels-on-dark") } .tag(30) } Group { Button(action: {}) { Text("ir_black") } .tag(31) Button(action: {}) { Text("material") } .tag(32) Button(action: {}) { Text("monokai-fannonedition") } .tag(33) Button(action: {}) { Text("monokai-bright") } .tag(34) Button(action: {}) { Text("eiffel") } .tag(35) Button(action: {}) { Text("base16-light") } .tag(36) Button(action: {}) { Text("oceanic-muted") } .tag(37) Button(action: {}) { Text("summerfruit") } .tag(38) Button(action: {}) { Text("espresso-libre") } .tag(39) Button(action: {}) { Text("krtheme") } .tag(40) } Group { Button(action: {}) { Text("mreq") } .tag(41) Button(action: {}) { Text("chanfle") } .tag(42) Button(action: {}) { Text("venom") } .tag(43) Button(action: {}) { Text("juicy") } .tag(44) Button(action: {}) { Text("coda") } .tag(45) Button(action: {}) { Text("fluidvision") } .tag(46) Button(action: {}) { Text("tomorrow-night-blue") } .tag(47) Button(action: {}) { Text("migucwb-(amiga)") } .tag(48) Button(action: {}) { Text("twilight") } .tag(49) Button(action: {}) { Text("vibrant-ink") } .tag(50) } Group { Button(action: {}) { Text("summer-sun") } .tag(51) Button(action: {}) { Text("monokai") } .tag(52) Button(action: {}) { Text("rails-envy") } .tag(53) Button(action: {}) { Text("merbivore") } .tag(54) Button(action: {}) { Text("dracula") } .tag(55) Button(action: {}) { Text("pastie") } .tag(56) Button(action: {}) { Text("lowlight") } .tag(57) Button(action: {}) { Text("spectacular") } .tag(58) Button(action: {}) { Text("smoothy") } .tag(59) Button(action: {}) { Text("vibrant-fin") } .tag(60) } Group { Button(action: {}) { Text("blackboard") } .tag(61) Button(action: {}) { Text("slush-&-poppies") } .tag(62) Button(action: {}) { Text("freckle") } .tag(63) Button(action: {}) { Text("fantasyscript") } .tag(64) Button(action: {}) { Text("tomorrow-night-eighties") } .tag(65) Button(action: {}) { Text("rhuk") } .tag(66) Button(action: {}) { Text("toy-chest") } .tag(67) Button(action: {}) { Text("fake") } .tag(68) Button(action: {}) { Text("emacs-strict") } .tag(69) Button(action: {}) { Text("merbivore-soft") } .tag(70) } Group { Button(action: {}) { Text("fade-to-grey") } .tag(71) Button(action: {}) { Text("monokai-sublime") } .tag(72) Button(action: {}) { Text("johnny") } .tag(73) Button(action: {}) { Text("railscasts") } .tag(74) Button(action: {}) { Text("argonaut") } .tag(75) Button(action: {}) { Text("tomorrow-night-bright") } .tag(76) Button(action: {}) { Text("lazy") } .tag(77) Button(action: {}) { Text("tomorrow-night") } .tag(78) Button(action: {}) { Text("bongzilla") } .tag(79) Button(action: {}) { Text("zenburnesque") } .tag(80) } Group { Button(action: {}) { Text("notebook") } .tag(81) Button(action: {}) { Text("django-(smoothy)") } .tag(82) Button(action: {}) { Text("blackboard-black") } .tag(83) Button(action: {}) { Text("black-pearl-ii") } .tag(84) Button(action: {}) { Text("kuroir") } .tag(85) Button(action: {}) { Text("cobalt") } .tag(86) Button(action: {}) { Text("ayu-mirage") } .tag(87) Button(action: {}) { Text("chrome-devtools") } .tag(88) Button(action: {}) { Text("prospettiva") } .tag(89) Button(action: {}) { Text("espresso-soda") } .tag(90) } Group { Button(action: {}) { Text("birds-of-paradise") } .tag(91) Button(action: {}) { Text("text-ex-machina") } .tag(92) Button(action: {}) { Text("django") } .tag(93) Button(action: {}) { Text("tomorrow") } .tag(94) Button(action: {}) { Text("solarized-(dark)") } .tag(95) Button(action: {}) { Text("plasticcodewrap") } .tag(96) Button(action: {}) { Text("material-palenight") } .tag(97) Button(action: {}) { Text("bespin") } .tag(98) Button(action: {}) { Text("espresso-tutti") } .tag(99) Button(action: {}) { Text("vibrant-tango") } .tag(100) } } Group { Button(action: {}) { Text("tubster") } .tag(101) Button(action: {}) { Text("darkpastel") } .tag(102) Button(action: {}) { Text("dawn") } .tag(103) Button(action: {}) { Text("tango") } .tag(104) Button(action: {}) { Text("clouds-midnight") } .tag(105) Button(action: {}) { Text("glitterbomb") } .tag(106) Button(action: {}) { Text("ir_white") } .tag(107) } } .onChange(of: selectedTheme) { (themeValue) in print("Theme: \(themeValue)") if themeValue == 1 { self.theme = CodeViewTheme.bbedit } if themeValue == 2 { self.theme = CodeViewTheme.allHallowEve } if themeValue == 3 { self.theme = CodeViewTheme.idleFingers } if themeValue == 4 { self.theme = CodeViewTheme.spaceCadet } if themeValue == 5 { self.theme = CodeViewTheme.idle } if themeValue == 6 { self.theme = CodeViewTheme.oceanic } if themeValue == 7 { self.theme = CodeViewTheme.clouds } if themeValue == 8 { self.theme = CodeViewTheme.github } if themeValue == 9 { self.theme = CodeViewTheme.ryanLight } if themeValue == 10 { self.theme = CodeViewTheme.blackPearl } if themeValue == 11 { self.theme = CodeViewTheme.monoIndustrial } if themeValue == 12 { self.theme = CodeViewTheme.happyHappyJoyJoy2 } if themeValue == 13 { self.theme = CodeViewTheme.cube2Media } if themeValue == 14 { self.theme = CodeViewTheme.friendshipBracelet } if themeValue == 15 { self.theme = CodeViewTheme.classicModified } if themeValue == 16 { self.theme = CodeViewTheme.amy } if themeValue == 17 { self.theme = CodeViewTheme.default } if themeValue == 18 { self.theme = CodeViewTheme.rdrak } if themeValue == 19 { self.theme = CodeViewTheme.espresso } if themeValue == 20 { self.theme = CodeViewTheme.sunburst } if themeValue == 21 { self.theme = CodeViewTheme.madeOfCode } if themeValue == 22 { self.theme = CodeViewTheme.arona } if themeValue == 23 { self.theme = CodeViewTheme.putty } if themeValue == 24 { self.theme = CodeViewTheme.nightlion } if themeValue == 25 { self.theme = CodeViewTheme.sidewalkchalk } if themeValue == 26 { self.theme = CodeViewTheme.swyphsii } if themeValue == 27 { self.theme = CodeViewTheme.iplastic } if themeValue == 28 { self.theme = CodeViewTheme.solarizedLight } if themeValue == 29 { self.theme = CodeViewTheme.macClassic } if themeValue == 30 { self.theme = CodeViewTheme.pastelsOnDark } if themeValue == 31 { self.theme = CodeViewTheme.irBlack } if themeValue == 32 { self.theme = CodeViewTheme.material } if themeValue == 33 { self.theme = CodeViewTheme.monokaiFannonedition } if themeValue == 34 { self.theme = CodeViewTheme.monokaiBright } if themeValue == 35 { self.theme = CodeViewTheme.eiffel } if themeValue == 36 { self.theme = CodeViewTheme.base16Light } if themeValue == 37 { self.theme = CodeViewTheme.oceanicMuted } if themeValue == 38 { self.theme = CodeViewTheme.summerfruit } if themeValue == 39 { self.theme = CodeViewTheme.espressoLibre } if themeValue == 40 { self.theme = CodeViewTheme.krtheme } if themeValue == 41 { self.theme = CodeViewTheme.mreq } if themeValue == 42 { self.theme = CodeViewTheme.chanfle } if themeValue == 43 { self.theme = CodeViewTheme.venom } if themeValue == 44 { self.theme = CodeViewTheme.juicy } if themeValue == 45 { self.theme = CodeViewTheme.coda } if themeValue == 46 { self.theme = CodeViewTheme.fluidvision } if themeValue == 47 { self.theme = CodeViewTheme.tomorrowNightBlue } if themeValue == 48 { self.theme = CodeViewTheme.magicwbAmiga } if themeValue == 49 { self.theme = CodeViewTheme.twilight } if themeValue == 50 { self.theme = CodeViewTheme.vibrantInk } if themeValue == 51 { self.theme = CodeViewTheme.summerSun } if themeValue == 52 { self.theme = CodeViewTheme.monokai } if themeValue == 53 { self.theme = CodeViewTheme.railsEnvy } if themeValue == 54 { self.theme = CodeViewTheme.merbivore } if themeValue == 55 { self.theme = CodeViewTheme.dracula } if themeValue == 56 { self.theme = CodeViewTheme.pastie } if themeValue == 57 { self.theme = CodeViewTheme.lowlight } if themeValue == 58 { self.theme = CodeViewTheme.spectacular } if themeValue == 59 { self.theme = CodeViewTheme.smoothy } if themeValue == 60 { self.theme = CodeViewTheme.vibrantFin } if themeValue == 61 { self.theme = CodeViewTheme.blackboard } if themeValue == 62 { self.theme = CodeViewTheme.slushPoppies } if themeValue == 63 { self.theme = CodeViewTheme.freckle } if themeValue == 64 { self.theme = CodeViewTheme.fantasyscript } if themeValue == 65 { self.theme = CodeViewTheme.tomorrowNightEighties } if themeValue == 66 { self.theme = CodeViewTheme.rhuk } if themeValue == 67 { self.theme = CodeViewTheme.toyChest } if themeValue == 68 { self.theme = CodeViewTheme.fake } if themeValue == 69 { self.theme = CodeViewTheme.emacsStrict } if themeValue == 70 { self.theme = CodeViewTheme.merbivoreSoft } if themeValue == 71 { self.theme = CodeViewTheme.fadeToGrey } if themeValue == 72 { self.theme = CodeViewTheme.monokaiSublime } if themeValue == 73 { self.theme = CodeViewTheme.johnny } if themeValue == 74 { self.theme = CodeViewTheme.railscasts } if themeValue == 75 { self.theme = CodeViewTheme.argonaut } if themeValue == 76 { self.theme = CodeViewTheme.tomorrowNightBright } if themeValue == 77 { self.theme = CodeViewTheme.lazy } if themeValue == 78 { self.theme = CodeViewTheme.tomorrowNight } if themeValue == 79 { self.theme = CodeViewTheme.bongzilla } if themeValue == 80 { self.theme = CodeViewTheme.zenburnesque } if themeValue == 81 { self.theme = CodeViewTheme.notebook } if themeValue == 82 { self.theme = CodeViewTheme.djangoSmoothy } if themeValue == 83 { self.theme = CodeViewTheme.blackboardBlack } if themeValue == 84 { self.theme = CodeViewTheme.blackPearlii } if themeValue == 85 { self.theme = CodeViewTheme.kuroir } if themeValue == 86 { self.theme = CodeViewTheme.cobalt } if themeValue == 87 { self.theme = CodeViewTheme.ayuMirage } if themeValue == 88 { self.theme = CodeViewTheme.chromeDevtools } if themeValue == 89 { self.theme = CodeViewTheme.prospettiva } if themeValue == 90 { self.theme = CodeViewTheme.espressoSoda } if themeValue == 91 { self.theme = CodeViewTheme.birdsOfParadise } if themeValue == 92 { self.theme = CodeViewTheme.textExMachina } if themeValue == 93 { self.theme = CodeViewTheme.django } if themeValue == 94 { self.theme = CodeViewTheme.tomorrow } if themeValue == 95 { self.theme = CodeViewTheme.solarizedDark } if themeValue == 96 { self.theme = CodeViewTheme.plasticcodewrap } if themeValue == 97 { self.theme = CodeViewTheme.materialPalenight } if themeValue == 98 { self.theme = CodeViewTheme.bespin } if themeValue == 99 { self.theme = CodeViewTheme.espressoTutti } if themeValue == 100 { self.theme = CodeViewTheme.vibrantTango } if themeValue == 101 { self.theme = CodeViewTheme.tubster } if themeValue == 102 { self.theme = CodeViewTheme.darkpastel } if themeValue == 103 { self.theme = CodeViewTheme.dawn } if themeValue == 104 { self.theme = CodeViewTheme.tango } if themeValue == 105 { self.theme = CodeViewTheme.cloudsMidnight } if themeValue == 106 { self.theme = CodeViewTheme.glitterbomb } if themeValue == 107 { self.theme = CodeViewTheme.irWhite } } Picker(selection: $selectedSyntax, label: Text("Syntax Highlighting: ")) { Group { Button(action: {}) { Text("apl") } .tag(1) Button(action: {}) { Text("pgp") } .tag(2) Button(action: {}) { Text("asn") } .tag(3) Button(action: {}) { Text("cmake") } .tag(4) Button(action: {}) { Text("c") } .tag(5) Button(action: {}) { Text("cplus") } .tag(6) Button(action: {}) { Text("objc") } .tag(7) Button(action: {}) { Text("kotlin") } .tag(8) Button(action: {}) { Text("scala") } .tag(9) Button(action: {}) { Text("csharp") } .tag(10) } Group { Button(action: {}) { Text("java") } .tag(11) Button(action: {}) { Text("cobol") } .tag(12) Button(action: {}) { Text("coffeescript") } .tag(13) Button(action: {}) { Text("lisp") } .tag(14) Button(action: {}) { Text("css") } .tag(15) Button(action: {}) { Text("django") } .tag(16) Button(action: {}) { Text("dockerfile") } .tag(17) Button(action: {}) { Text("erlang") } .tag(18) Button(action: {}) { Text("fortran") } .tag(19) Button(action: {}) { Text("go") } .tag(20) } Group { Button(action: {}) { Text("groovy") } .tag(21) Button(action: {}) { Text("haskell") } .tag(22) Button(action: {}) { Text("html") } .tag(23) Button(action: {}) { Text("http") } .tag(24) Button(action: {}) { Text("javascript") } .tag(25) Button(action: {}) { Text("typescript") } .tag(26) Button(action: {}) { Text("json") } .tag(27) Button(action: {}) { Text("ecma") } .tag(28) Button(action: {}) { Text("jinja") } .tag(29) Button(action: {}) { Text("lua") } .tag(30) } Button(action: {}) { Text("markdown") } .tag(31) Group { Button(action: {}) { Text("maths") } .tag(32) Button(action: {}) { Text("pascal") } .tag(33) Button(action: {}) { Text("perl") } .tag(34) Button(action: {}) { Text("php") } .tag(35) Button(action: {}) { Text("powershell") } .tag(36) Button(action: {}) { Text("properties") } .tag(37) Button(action: {}) { Text("protobuf") } .tag(38) Button(action: {}) { Text("python") } .tag(39) Button(action: {}) { Text("r") } .tag(40) Button(action: {}) { Text("ruby") } .tag(41) } Group { Button(action: {}) { Text("rust") } .tag(42) Button(action: {}) { Text("sass") } .tag(43) Button(action: {}) { Text("scheme") } .tag(44) Button(action: {}) { Text("shell") } .tag(45) Button(action: {}) { Text("sql") } .tag(46) Button(action: {}) { Text("sqllite") } .tag(47) Button(action: {}) { Text("mysql") } .tag(48) Button(action: {}) { Text("latex") } .tag(49) Button(action: {}) { Text("swift") } .tag(50) Button(action: {}) { Text("text") } .tag(51) } Group { Button(action: {}) { Text("toml") } .tag(52) Button(action: {}) { Text("vb") } .tag(53) Button(action: {}) { Text("vue") } .tag(54) Button(action: {}) { Text("xml") } .tag(55) Button(action: {}) { Text("yaml") } .tag(56) Button(action: {}) { Text("dart") } .tag(57) Button(action: {}) { Text("ntriples") } .tag(58) Button(action: {}) { Text("sparql") } .tag(59) Button(action: {}) { Text("turtle") } .tag(60) } } .onChange(of: selectedSyntax, perform: { value in print("Syntax: \(value)") if value == 1 { self.syntax = CodeMode.apl } if value == 2 { self.syntax = CodeMode.pgp } if value == 3 { self.syntax = CodeMode.asn } if value == 4 { self.syntax = CodeMode.cmake } if value == 5 { self.syntax = CodeMode.c } if value == 6 { self.syntax = CodeMode.cplus } if value == 7 { self.syntax = CodeMode.objc } if value == 8 { self.syntax = CodeMode.kotlin } if value == 9 { self.syntax = CodeMode.scala } if value == 10 { self.syntax = CodeMode.csharp } if value == 11 { self.syntax = CodeMode.java } if value == 12 { self.syntax = CodeMode.cobol } if value == 13 { self.syntax = CodeMode.coffeescript } if value == 14 { self.syntax = CodeMode.lisp } if value == 15 { self.syntax = CodeMode.css } if value == 16 { self.syntax = CodeMode.django } if value == 17 { self.syntax = CodeMode.dockerfile } if value == 18 { self.syntax = CodeMode.erlang } if value == 19 { self.syntax = CodeMode.fortran } if value == 20 { self.syntax = CodeMode.go } if value == 21 { self.syntax = CodeMode.groovy } if value == 22 { self.syntax = CodeMode.haskell } if value == 23 { self.syntax = CodeMode.html } if value == 24 { self.syntax = CodeMode.http } if value == 25 { self.syntax = CodeMode.javascript } if value == 26 { self.syntax = CodeMode.typescript } if value == 27 { self.syntax = CodeMode.json } if value == 28 { self.syntax = CodeMode.ecma } if value == 29 { self.syntax = CodeMode.jinja } if value == 30 { self.syntax = CodeMode.lua } if value == 31 { self.syntax = CodeMode.markdown } if value == 32 { self.syntax = CodeMode.maths } if value == 33 { self.syntax = CodeMode.pascal } if value == 34 { self.syntax = CodeMode.perl } if value == 35 { self.syntax = CodeMode.php } if value == 36 { self.syntax = CodeMode.powershell } if value == 37 { self.syntax = CodeMode.properties } if value == 38 { self.syntax = CodeMode.protobuf } if value == 39 { self.syntax = CodeMode.python } if value == 40 { self.syntax = CodeMode.r } if value == 41 { self.syntax = CodeMode.ruby } if value == 42 { self.syntax = CodeMode.rust } if value == 43 { self.syntax = CodeMode.sass } if value == 44 { self.syntax = CodeMode.scheme } if value == 45 { self.syntax = CodeMode.shell } if value == 46 { self.syntax = CodeMode.sql } if value == 47 { self.syntax = CodeMode.sqllite } if value == 48 { self.syntax = CodeMode.mysql } if value == 49 { self.syntax = CodeMode.latex } if value == 50 { self.syntax = CodeMode.swift } if value == 51 { self.syntax = CodeMode.text } if value == 52 { self.syntax = CodeMode.toml } if value == 53 { self.syntax = CodeMode.vb } if value == 54 { self.syntax = CodeMode.vue } if value == 55 { self.syntax = CodeMode.xml } if value == 56 { self.syntax = CodeMode.yaml } if value == 57 { self.syntax = CodeMode.dart } if value == 58 { self.syntax = CodeMode.ntriples } if value == 59 { self.syntax = CodeMode.sparql } if value == 60 { self.syntax = CodeMode.turtle } }) } .padding(20) .frame(width: 350, height: 150) } } struct MiscSettings: View { var body: some View { Form { GroupBox(label: Label("Info", systemImage: "info.circle")) { VStack { HStack { Spacer() VStack { Text("Version: 1.2.2") Text("Build: 1") } Spacer() } } } GroupBox(label: Label("Misc.", systemImage: "ellipsis.circle")) { VStack { HStack { Spacer() Button(action: {SendEmail.send()}) { Text("Send Some Feedback") } Spacer() } } } } .padding(20) .frame(width: 350, height: 150) } } class SendEmail: NSObject { static func send() { let service = NSSharingService(named: NSSharingService.Name.composeEmail)! service.recipients = ["[email protected]"] service.subject = "Note.it Feedback" service.perform(withItems: ["Please Fill Out All Necessary Sections:", "Report A Bug - ", "Rate The App - ", "Suggest An Improvment - "]) } } extension KeyboardShortcuts.Name { static let newCommand = Self("newCommand", default: .init(.n, modifiers: [.command])) static let openCommand = Self("openCommand", default: .init(.o, modifiers: [.command])) static let saveCommand = Self("saveCommand", default: .init(.s, modifiers: [.command])) //static let printCommand = Self("printCommand", default: .init(.p, modifiers: [.command])) static let duplicateCommand = Self("duplicateCommand", default: .init(.s, modifiers: [.command, .shift])) static let moveToCommand = Self("moveToCommand") static let renameCommand = Self("renameCommand") static let revertToCommand = Self("revertToCommand") static let closeCommand = Self("closeCommand", default: .init(.w, modifiers: [.command])) }
33.552186
145
0.311726
5020228ba1bc90fbba2c362a2244e875e0c049b1
1,288
// // UIView+Constraints.swift // CaelinCore // // Created by Caelin Jackson-King on 2019-01-02. // import UIKit public extension UIView { func verticalCascadeLayout(of views: [UIView], from anchor: NSLayoutYAxisAnchor, margin: CGFloat) { guard let first = views.first else { return } var previousAnchor: NSLayoutAnchor = anchor for view in views { addSubview(view) if let opinionatedView = view as? OpinionatedView { addConstraints(opinionatedView.buildConstraints()) } addConstraints([ view.topAnchor.constraint(equalTo: previousAnchor, constant: margin), view.heightAnchor.constraint(equalTo: first.heightAnchor) ]) previousAnchor = view.bottomAnchor } } func snapToBounds(view: UIView, leaving margin: CGFloat = 0) { addConstraints([ view.leftAnchor.constraint(equalTo: leftAnchor, constant: margin), view.rightAnchor.constraint(equalTo: rightAnchor, constant: -margin), view.topAnchor.constraint(equalTo: topAnchor, constant: margin), view.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -margin) ]) } }
33.894737
103
0.621894
29200eb77db90656fb86c71288c68cf5b7fb62f4
2,164
// // AppDelegate.swift // Icon // // Created by Tobioka on 2017/10/14. // Copyright © 2017年 tnantoka. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.042553
285
0.755083
f86e518a24571a2658081a6422d91ee802657485
4,173
// // Extension.swift // CommandLineRunner // // Created by Leif Ashley on 2/1/22. // import Foundation import SwiftUI extension View { // @inlinable public func opacity(_ opacity: Double) -> some View func invisible(_ isInvisible: Bool) -> some View { return self.opacity(isInvisible ? 0 : 1) } // If conditional to apply checks to views, but this actively hides and removes views, sometimes not what is best. // and causes the views to snap around in unpredictable ways func `if`<Content: View>(_ conditional: Bool, content: (Self) -> Content) -> some View { if conditional { return AnyView(content(self)) } else { return AnyView(self) } } } extension Bundle { /// Loads a static resource from the main bundle and inflates the JSON to the given type /// - Returns: Type object or nil if no data was found func loadJson<T>(type: T.Type, resourceName: String) -> T? where T: Decodable { var result: T? = nil if let path = Bundle.main.path(forResource: resourceName, ofType: "json"), let data = FileManager.default.contents(atPath: path) { log.verbose("Path: \(path)") let decoder = JSONDecoder() do { result = try decoder.decode(T.self, from: data) } catch { log.error("Static JSON decode error for '\(resourceName)'", error: error) } } else { log.error("FATAL: cannot find json resource '\(resourceName)'", error: AppError.unknownError) } return result } /// Loads a static plist XML file and inflates the XML to the given type /// - Returns: Type object or nil if no data was found static func decodeFromPList<T>(_ type: T.Type, forResource: String) -> T? where T: Decodable { let logTitle = "Bundle.decodeFromPList" var t: T? = nil if let path = Bundle.main.path(forResource: forResource, ofType: "plist") { log.verbose("\(logTitle) Path: \(path)") if let data = FileManager.default.contents(atPath: path) { do { let decoded = try PropertyListDecoder().decode(type, from: data) t = decoded } catch { log.error("\(logTitle)", error: error) } } } return t } } extension URLComponents { /// Assists in adding name/value pairs to a URLComponent, for cleaner code mutating func addQueryString(name: String, value: String) { if queryItems == nil { queryItems = [URLQueryItem]() } queryItems?.append(URLQueryItem(name: name, value: value)) } } extension Optional where Wrapped == String { // quick unwrap for string options that might or might not be nil var valueOrDefault: String { if let value = self { return value } else { return "-" } } } extension Thread { /// Prints extended thread details for thread monitoring public var extendedDetails: String { let t: Thread = self var result = [String]() if t.isMainThread { result.append("isMainThread") } if t.isCancelled { result.append("isCanceled") } if t.isExecuting { result.append("isExecuting") } if t.isFinished { result.append("isFinished") } switch t.qualityOfService { case .background: result.append("QoS background") case .userInitiated: result.append("QoS userInitiated") case .userInteractive: result.append("QoS userInteractive") case .utility: result.append("QoS utility") default: result.append("QoS default") } result.append("threadPriority=\(t.threadPriority)") let title = "Thread" return "\(title): \(result.joined(separator: ", ")) -- \(t)" } }
30.683824
138
0.559549
562e7eedb536a7fbc0d24f51ea9887239163f927
56
struct BarcodeGiggle { var text = "Hello, World!" }
14
30
0.642857
de3589e37eac35f9b867ff0636a71604f4217039
313
// // GetLongComments.swift // ZhiHuDaily // // Created by xiabob on 17/4/13. // Copyright © 2017年 xiabob. All rights reserved. // import UIKit class GetLongComments: XBAPIBaseManager, ManagerProtocol { var newsId = 0 var path: String { return "/story/\(newsId)/long-comments" } }
16.473684
58
0.648562
e217f6a955bd18cdcd16ba861212be774fce8314
4,221
// // FlashyTabBar.swift // FlashyTabBarController // // Created by Anton Skopin on 28/11/2018. // Copyright © 2018 cuberto. All rights reserved. // import UIKit open class FlashyTabBar: UITabBar { private var buttons: [TabBarButton] = [] public var animationSpeed: Double = 1.0 { didSet { reloadAnimations() } } fileprivate var shouldSelectOnTabBar = true open override var selectedItem: UITabBarItem? { willSet { guard let newValue = newValue else { buttons.forEach { $0.setSelected(false, animated: false) } return } guard let index = items?.firstIndex(of: newValue), index != NSNotFound else { return } select(itemAt: index, animated: false) } } open override var tintColor: UIColor! { didSet { buttons.forEach { $0.tintColor = tintColor } } } open override var items: [UITabBarItem]? { didSet { reloadViews() } } open override func setItems(_ items: [UITabBarItem]?, animated: Bool) { super.setItems(items, animated: animated) reloadViews() } var barHeight: CGFloat = 49 var hasDotView: Bool = true var imageTintColor: UIColor? override open func sizeThatFits(_ size: CGSize) -> CGSize { var sizeThatFits = super.sizeThatFits(size) sizeThatFits.height = barHeight if #available(iOS 11.0, *) { sizeThatFits.height = sizeThatFits.height + safeAreaInsets.bottom } return sizeThatFits } open override func layoutSubviews() { super.layoutSubviews() let btnWidth = bounds.width / CGFloat(buttons.count) var btnHeight = bounds.height if #available(iOS 11.0, *) { btnHeight -= safeAreaInsets.bottom } for (index, button) in buttons.enumerated() { button.frame = CGRect(x: btnWidth * CGFloat(index), y: 0, width: btnWidth, height: btnHeight) button.setNeedsLayout() } } func reloadViews() { subviews.filter { String(describing: type(of: $0)) == "UITabBarButton" }.forEach { $0.removeFromSuperview() } buttons.forEach { $0.removeFromSuperview()} buttons = items?.map { self.button(forItem: $0) } ?? [] reloadAnimations() setNeedsLayout() } private func reloadAnimations() { buttons.forEach { (button) in button.selectAnimation = TabItemSelectAnimation(duration: 0.5 / animationSpeed) button.deselectAnimation = TabItemDeselectAnimation(duration: 0.5 / animationSpeed) } } private func button(forItem item: UITabBarItem) -> TabBarButton { let button = TabBarButton(item: item, hasDot: hasDotView) button.tintColor = tintColor if (imageTintColor != nil) { button.imageTintColor = imageTintColor } button.addTarget(self, action: #selector(btnPressed), for: .touchUpInside) if selectedItem != nil && item === selectedItem { button.select(animated: false) } self.addSubview(button) return button } @objc private func btnPressed(sender: TabBarButton) { guard let index = buttons.firstIndex(of: sender), index != NSNotFound, let item = items?[index] else { return } buttons.forEach { (button) in guard button != sender else { return } button.setSelected(false, animated: true) } sender.setSelected(true, animated: true) delegate?.tabBar?(self, didSelect: item) } func select(itemAt index: Int, animated: Bool = false) { guard index < buttons.count else { return } let selectedbutton = buttons[index] buttons.forEach { (button) in guard button != selectedbutton else { return } button.setSelected(false, animated: false) } selectedbutton.setSelected(true, animated: false) } }
29.93617
117
0.581142
4b97532cecd304404c4034d4c631f599c2b0560e
4,131
// // BusinessesViewController.swift // Yelp // // Created by Timothy Lee on 4/23/15. // Copyright (c) 2015 Timothy Lee. All rights reserved. // import UIKit class BusinessesViewController: UIViewController, UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate { var searchBar = UISearchBar() @IBOutlet weak var tableView: UITableView! var businesses: [Business]! var filteredDict = NSDictionary() var filteredData : [Business]! var otherBusiness: [Business]! override func viewDidLoad() { super.viewDidLoad() tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 121 automaticallyAdjustsScrollViewInsets = false self.extendedLayoutIncludesOpaqueBars = true tableView.delegate = self tableView.dataSource = self searchBar.delegate = self searchBar.sizeToFit() navigationItem.titleView = searchBar Business.searchWithTerm(term: "Thai", completion: { (businesses: [Business]?, error: Error?) -> Void in self.businesses = businesses self.tableView.reloadData() if let businesses = businesses { for business in businesses { print(business.name!) print(business.address!) } } } ) /* Example of Yelp search with more search options specified Business.searchWithTerm(term: "Restaurants", sort: .distance, categories: ["asianfusion", "burgers"]) { (businesses, error) in self.businesses = businesses for business in self.businesses { print(business.name!) print(business.address!) } } */ } func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { if searchText.isEmpty { Business.searchWithTerm(term: "Restaurants", completion: { (businesses: [Business]?, error: Error?) -> Void in self.businesses = businesses self.otherBusiness = businesses self.tableView.reloadData() }) searchBar.endEditing(false) } else { searchReload() self.tableView.reloadData() } } func searchReload(){ let searchTerm = searchBar.text! Business.searchWithTerm(term: searchTerm, completion: { (businesses: [Business]?, error: Error?) -> Void in self.businesses = businesses self.tableView.reloadData() if let businesses = businesses { for business in businesses { print(business.name!) print(business.address!) } } } ) self.businesses = otherBusiness self.tableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if businesses != nil { return businesses!.count } else{ return 0 } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "BusinessCell", for: indexPath) as! BusinessCell cell.business = businesses [indexPath.row] return cell } /* // 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. } */ }
33.048
135
0.583394
89403c5366d0890027c7530948b7972702d38200
3,265
// // TTARefresherBackGifFooter.swift // Pods // // Created by TobyoTenma on 13/05/2017. // // import UIKit open class TTARefresherBackGifFooter: TTARefresherBackStateFooter { open lazy var gifImageView: UIImageView = { let gifImageView = UIImageView() self.addSubview(gifImageView) return gifImageView }() lazy var stateImages: [TTARefresherState: [UIImage]] = [:] lazy var stateDurations: [TTARefresherState: TimeInterval] = [:] override open var pullingPercent: CGFloat { didSet { guard let images = stateImages[.idle] else { return } if state != .idle || images.count == 0 { return } gifImageView.stopAnimating() var index = CGFloat(images.count) * pullingPercent if index >= CGFloat(images.count) { index = CGFloat(images.count) - 1 } gifImageView.image = images[Int(index)] } } override open var state: TTARefresherState { didSet { if oldValue == state { return } if state == .pulling || state == .refreshing { guard let images = stateImages[state], images.count != 0 else { return } gifImageView.isHidden = false gifImageView.stopAnimating() if images.count == 1 { // Single Image gifImageView.image = images.last } else { // More than one image gifImageView.animationImages = images gifImageView.animationDuration = stateDurations[state] ?? Double(images.count) * 0.1 gifImageView.startAnimating() } } else if state == .idle { gifImageView.isHidden = false } else if state == .noMoreData { gifImageView.isHidden = true } } } } // MARK: - Public Methods extension TTARefresherBackGifFooter { public func set(images: [UIImage]?, duration: TimeInterval?, for state: TTARefresherState) { guard let images = images, let duration = duration else { return } stateImages[state] = images stateDurations[state] = duration guard let image = images.first, image.size.height > bounds.height else { return } bounds.size.height = image.size.height } public func set(images: [UIImage]?, for state: TTARefresherState) { guard let images = images else { return } set(images: images, duration: Double(images.count) * 0.1, for: state) } } // MARK: - Override Methods extension TTARefresherBackGifFooter { override open func prepare() { super.prepare() labelLeftInset = 20 } override open func placeSubviews() { super.placeSubviews() if gifImageView.constraints.count != 0 { return } gifImageView.frame = bounds if stateLabel.isHidden { gifImageView.contentMode = .center } else { gifImageView.contentMode = .right gifImageView.frame.size.width = bounds.width * 0.5 - stateLabel.ttaRefresher.textWidth() * 0.5 - labelLeftInset } } }
31.699029
123
0.577335
612f9c851e598e16406794cbc2a071e39fddd0c7
1,242
// // LifeToolsUITests.swift // LifeToolsUITests // // Created by 庄晓伟 on 16/8/2. // Copyright © 2016年 Zhuang Xiaowei. All rights reserved. // import XCTest class LifeToolsUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
33.567568
182
0.662641
622d7551ba8ca6dc2e5ae61a40726b47006e6e4d
13,167
import UIKit /** An object used to continue a binding chain. This is a throwaway object created when a table view binder's `onSection(_:)` method is called. This object declares a number of methods that take a binding handler and give it to the original table view binder to store for callback. A reference to this object should not be kept and should only be used in a binding chain. */ public class TableViewModelSingleSectionBinder<C: UITableViewCell, S: TableViewSection, M> : TableViewSingleSectionBinder<C, S> { /** Adds a handler to be called whenever a cell in the declared section is tapped. The handler is called whenever a cell in the section is tapped, passing in the row and cell that was tapped, along with the raw model object associated with the cell. The cell will be safely cast to the cell type bound to the section if this method is called in a chain after the a cell binding method method. Note that this `onTapped` variation with the raw model object is only available if a cell binding method that takes a model type was used to bind the cell type to the section. - parameter handler: The closure to be called whenever a cell is tapped in the bound section. - parameter row: The row of the cell that was tapped. - parameter cell: The cell that was tapped. - parameter model: The model object that the cell was dequeued to represent in the table. - returns: A section binder to continue the binding chain with. */ @discardableResult public func onTapped(_ handler: @escaping (_ row: Int, _ cell: C, _ model: M) -> Void) -> TableViewModelSingleSectionBinder<C, S, M> { let section = self.section let tappedHandler: CellTapCallback<S> = { [weak binder = self.binder] (_, row, cell) in guard let cell = cell as? C, let model = binder?.currentDataModel.item(inSection: section, row: row)?.model as? M else { assertionFailure("ERROR: Cell or model wasn't the right type; something went awry!") return } handler(row, cell, model) } self.binder.handlers.sectionCellTappedCallbacks[section] = tappedHandler return self } /** Adds a handler to be called whenever a cell is dequeued in the declared section. The handler is called whenever a cell in the section is dequeued, passing in the row, the dequeued cell, and the model object that the cell was dequeued to represent. The cell will be cast to the cell type bound to the section if this method is called in a chain after a cell binding method. This method can be used to perform any additional configuration of the cell. - parameter handler: The closure to be called whenever a cell is dequeued in the bound section. - parameter row: The row of the cell that was dequeued. - parameter cell: The cell that was dequeued that can now be configured. - parameter model: The model object that the cell was dequeued to represent in the table. - returns: A section binder to continue the binding chain with. */ @discardableResult public func onDequeue(_ handler: @escaping (_ row: Int, _ cell: C, _ model: M) -> Void) -> TableViewModelSingleSectionBinder<C, S, M> { let section = self.section let dequeueCallback: CellDequeueCallback<S> = { [weak binder = self.binder] (_, row, cell) in guard let cell = cell as? C, let model = binder?.currentDataModel.item(inSection: section, row: row)?.model as? M else { assertionFailure("ERROR: Cell wasn't the right type; something went awry!") return } handler(row, cell, model) } self.binder.handlers.sectionDequeuedCallbacks[section] = dequeueCallback return self } /** Adds a handler to be called when a cell of the given type emits a custom view event. To use this method, the given cell type must conform to `ViewEventEmitting`. This protocol has the cell declare an associated `ViewEvent` enum type whose cases define custom events that can be observed from the binding chain. When a cell emits an event via its `emit(event:)` method, the handler given to this method is called with the event and various other objects that allows the view controller to respond. - parameter cellType: The event-emitting cell type to observe events from. - parameter handler: The closure to be called whenever a cell of the given cell type emits a custom event. - parameter row: The row of the cell that emitted an event. - parameter cell: The cell that emitted an event. - parameter event: The custom event that the cell emitted. - parameter model: The model object that the cell was dequeued to represent in the table. - returns: A section binder to continue the binding chain with. */ @discardableResult public func onEvent<EventCell>( from cellType: EventCell.Type, _ handler: @escaping (_ row: Int, _ cell: EventCell, _ event: EventCell.ViewEvent, _ model: M) -> Void) -> TableViewModelSingleSectionBinder<C, S, M> where EventCell: UITableViewCell & ViewEventEmitting { let section = self.section let modelHandler: (Int, UITableViewCell, Any) -> Void = { [weak binder = self.binder] row, cell, event in guard let cell = cell as? EventCell, let event = event as? EventCell.ViewEvent, let model = binder?.currentDataModel.item(inSection: section, row: row)?.model as? M else { assertionFailure("ERROR: Cell, event, or model wasn't the right type; something went awry!") return } handler(row, cell, event, model) } self.binder.addEventEmittingHandler( cellType: EventCell.self, handler: modelHandler, affectedSections: self.affectedSectionScope) return self } // MARK: - @discardableResult public override func bind<H>( headerType: H.Type, viewModel: H.ViewModel?) -> TableViewModelSingleSectionBinder<C, S, M> where H : UITableViewHeaderFooterView & ViewModelBindable { super.bind(headerType: headerType, viewModel: viewModel) return self } @discardableResult public override func bind<H>( headerType: H.Type, viewModel: @escaping () -> H.ViewModel?) -> TableViewModelSingleSectionBinder<C, S, M> where H : UITableViewHeaderFooterView & ViewModelBindable { super.bind(headerType: headerType, viewModel: viewModel) return self } @discardableResult public override func bind( headerTitle: String?) -> TableViewModelSingleSectionBinder<C, S, M> { super.bind(headerTitle: headerTitle) return self } @discardableResult public override func bind( headerTitle: @escaping () -> String?) -> TableViewModelSingleSectionBinder<C, S, M> { super.bind(headerTitle: headerTitle) return self } @discardableResult public override func bind<F>( footerType: F.Type, viewModel: F.ViewModel?) -> TableViewModelSingleSectionBinder<C, S, M> where F : UITableViewHeaderFooterView & ViewModelBindable { super.bind(footerType: footerType, viewModel: viewModel) return self } @discardableResult public override func bind<F>( footerType: F.Type, viewModel: @escaping () -> F.ViewModel?) -> TableViewModelSingleSectionBinder<C, S, M> where F : UITableViewHeaderFooterView & ViewModelBindable { super.bind(footerType: footerType, viewModel: viewModel) return self } @discardableResult public override func bind( footerTitle: String?) -> TableViewModelSingleSectionBinder<C, S, M> { super.bind(footerTitle: footerTitle) return self } @discardableResult public override func bind( footerTitle: @escaping () -> String?) -> TableViewModelSingleSectionBinder<C, S, M> { super.bind(footerTitle: footerTitle) return self } // MARK: - @discardableResult override public func onDequeue(_ handler: @escaping (_ row: Int, _ cell: C) -> Void) -> TableViewModelSingleSectionBinder<C, S, M> { super.onDequeue(handler) return self } @discardableResult override public func onTapped(_ handler: @escaping (_ row: Int, _ cell: C) -> Void) -> TableViewModelSingleSectionBinder<C, S, M> { super.onTapped(handler) return self } @discardableResult override public func onEvent<EventCell>( from: EventCell.Type, _ handler: @escaping (_ row: Int, _ cell: EventCell, _ event: EventCell.ViewEvent) -> Void) -> TableViewModelSingleSectionBinder<C, S, M> where EventCell: UITableViewCell & ViewEventEmitting { super.onEvent(from: from, handler) return self } // MARK: - @discardableResult public override func cellHeight(_ handler: @escaping (_ row: Int) -> CGFloat) -> TableViewModelSingleSectionBinder<C, S, M> { super.cellHeight(handler) return self } @discardableResult public override func estimatedCellHeight(_ handler: @escaping (_ row: Int) -> CGFloat) -> TableViewModelSingleSectionBinder<C, S, M> { super.estimatedCellHeight(handler) return self } /** Adds a handler to provide the cell height for cells in the declared section. The given handler is called whenever the section reloads for each visible row, passing in the row the handler should provide the height for. - parameter handler: The closure to be called that will return the height for cells in the section. - parameter row: The row of the cell to provide the height for. - parameter model: The model for the cell to provide the height for. - returns: The argument to a 'dimensions' call. */ @discardableResult public func cellHeight(_ handler: @escaping (_ row: Int, _ model: M) -> CGFloat) -> TableViewModelSingleSectionBinder<C, S, M> { let section = self.section self.binder.handlers.sectionCellHeightBlocks[section] = { [weak binder = self.binder] (_, row: Int) in guard let model = binder?.currentDataModel.item(inSection: section, row: row)?.model as? M else { fatalError("Didn't get the right model type - something went awry!") } return handler(row, model) } return self } /** Adds a handler to provide the estimated cell height for cells in the declared section. The given handler is called whenever the section reloads for each visible row, passing in the row the handler should provide the estimated height for. - parameter handler: The closure to be called that will return the estimated height for cells in the section. - parameter row: The row of the cell to provide the estimated height for. - parameter model: The model for the cell to provide the height for. - returns: The argument to a 'dimensions' call. */ @discardableResult public func estimatedCellHeight(_ handler: @escaping (_ row: Int, _ model: M) -> CGFloat) -> TableViewModelSingleSectionBinder<C, S, M> { let section = self.section self.binder.handlers.sectionEstimatedCellHeightBlocks[section] = { [weak binder = self.binder] (_, row: Int) in guard let model = binder?.currentDataModel.item(inSection: section, row: row)?.model as? M else { fatalError("Didn't get the right model type - something went awry!") } return handler(row, model) } return self } @discardableResult public override func headerHeight(_ handler: @escaping () -> CGFloat) -> TableViewModelSingleSectionBinder<C, S, M> { super.headerHeight(handler) return self } @discardableResult public override func estimatedHeaderHeight(_ handler: @escaping () -> CGFloat) -> TableViewModelSingleSectionBinder<C, S, M> { super.estimatedHeaderHeight(handler) return self } @discardableResult public override func footerHeight(_ handler: @escaping () -> CGFloat) -> TableViewModelSingleSectionBinder<C, S, M> { super.footerHeight(handler) return self } @discardableResult public override func estimatedFooterHeight(_ handler: @escaping () -> CGFloat) -> TableViewModelSingleSectionBinder<C, S, M> { super.estimatedFooterHeight(handler) return self } }
39.422156
132
0.651781
9002c26dd6c515e3b1a9132ca8f2769beebd3cfe
718
// // Float+Stars.swift // RateMyTalkAtMobOS // // Created by Bogdan Iusco on 10/11/14. // Copyright (c) 2014 Grigaci. All rights reserved. // import Foundation let kRatingStarsMin: Float = 0 let kRatingStarsMax: Float = 4 extension Float { func roundStars() -> Float { var temp = round(2.0 * self) temp = temp / 2.0 return temp } func isRatingValid() -> Bool { let greater: NSComparisonResult = NSNumber(float: self).compare(NSNumber(float: kRatingStarsMin)) let lessOrEqual: NSComparisonResult = NSNumber(float: self).compare(NSNumber(float: kRatingStarsMax)) return greater == .OrderedDescending && lessOrEqual != .OrderedDescending } }
24.758621
109
0.662953
11f5f5f762ffadd7f2b66cf23247f58cf743d3ef
978
// // motem_iosTests.swift // motem-iosTests // // Created by Sergei Kvasov on 11/15/16. // Copyright © 2016 Mobexs.com. All rights reserved. // import XCTest @testable import motem_ios class motem_iosTests: 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.measure { // Put the code you want to measure the time of here. } } }
26.432432
111
0.633947
89b433c3af94d23a0aabb42eca9a1e4bc878adbe
3,055
// // ViewController.swift // ConnectTheDots // // Created by Manish Kumar on 2022-02-17. // import UIKit class ViewController: UIViewController { var numCircles = 5 var connections = [ConnectionView]() let renderLinesImageView = UIImageView() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .darkGray /// It's important to add the background image view first so that the lines are drawn underneath the circles. renderLinesImageView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(renderLinesImageView) NSLayoutConstraint.activate([ renderLinesImageView.leadingAnchor.constraint(equalTo: view.leadingAnchor), renderLinesImageView.trailingAnchor.constraint(equalTo: view.trailingAnchor), renderLinesImageView.topAnchor.constraint(equalTo: view.topAnchor), renderLinesImageView.bottomAnchor.constraint(equalTo: view.bottomAnchor) ]) drawAndPlaceCircles() } func drawAndPlaceCircles() { connections.forEach { view in view.removeFromSuperview() } connections.removeAll() for _ in 1...numCircles { let connection = ConnectionView(frame: CGRect(origin: .zero, size: CGSize(width: 44, height: 44))) connection.backgroundColor = .white connection.layer.cornerRadius = 22 connection.layer.borderWidth = 2 connections.append(connection) view.addSubview(connection) connection.connectionDragged = { [weak self] in self?.redrawLines() } } /// Create a circular linked list. for i in 0 ..< connections.count { if i == connections.count - 1 { // this is the last connection; join it back to the first one connections[i].nextConnection = connections[0] } else { connections[i].nextConnection = connections[i+1] } } connections.forEach(place) redrawLines() } /// Randomly place the circles but make sure that they are a little bit away from the screen edges. func place(_ connection: ConnectionView) { let randomX = CGFloat.random(in: 20...view.bounds.maxX - 20) let randomY = CGFloat.random(in: 50...view.bounds.maxY - 50) connection.center = CGPoint(x: randomX, y: randomY) } func redrawLines() { let renderer = UIGraphicsImageRenderer(bounds: view.bounds) let pattern: [CGFloat] = [4,4] /// Draw a dotted line renderLinesImageView.image = renderer.image { ctx in ctx.cgContext.setLineDash(phase: 0, lengths: pattern) for connection in connections { UIColor.green.set() ctx.cgContext.strokeLineSegments(between: [connection.nextConnection.center, connection.center]) } } } }
36.369048
117
0.617021
23391733c8cddc17115ce9058caf6d22c497256a
1,561
// // AppDelegate.swift // Restaurant // // Created by Naoki Mita on 2020-05-19. // Copyright © 2020 Naoki Mita. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { let temporaryDirectory = NSTemporaryDirectory() let urlCache = URLCache(memoryCapacity: 25_000_000, diskCapacity: 50_000_000, diskPath: temporaryDirectory) URLCache.shared = urlCache 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. } }
39.025
179
0.744395
bfef032c8403b2339f5493f93505a753c4ff8548
24,746
// // ViewController.swift // IonicRunner // import UIKit import WebKit import Cordova public class CAPBridgeViewController: UIViewController, CAPBridgeDelegate, WKUIDelegate, WKNavigationDelegate { private var webView: WKWebView? public var bridgedWebView: WKWebView? { return webView } public var bridgedViewController: UIViewController? { return self } public let cordovaParser = CDVConfigParser.init() private var hostname: String? private var allowNavigationConfig: [String]? private var basePath: String = "" private let assetsFolder = "public" private enum WebViewLoadingState { case unloaded case initialLoad(isOpaque: Bool) case subsequentLoad } private var webViewLoadingState = WebViewLoadingState.unloaded private var isStatusBarVisible = true private var statusBarStyle: UIStatusBarStyle = .default private var statusBarAnimation: UIStatusBarAnimation = .slide @objc public var supportedOrientations: [Int] = [] @objc public var startDir = "" @objc public var config: String? // Construct the Capacitor runtime public var bridge: CAPBridge? private var handler: CAPAssetHandler? override public func loadView() { let configUrl = Bundle.main.url(forResource: "config", withExtension: "xml") let configParser = XMLParser(contentsOf: configUrl!)! configParser.delegate = cordovaParser configParser.parse() guard let startPath = self.getStartPath() else { return } setStatusBarDefaults() setScreenOrientationDefaults() let capConfig = CAPConfig(self.config) HTTPCookieStorage.shared.cookieAcceptPolicy = HTTPCookie.AcceptPolicy.always let webViewConfiguration = WKWebViewConfiguration() let messageHandler = CAPMessageHandlerWrapper() self.handler = CAPAssetHandler() self.handler!.setAssetPath(startPath) var specifiedScheme = CAPBridge.defaultScheme let configScheme = capConfig.getString("server.iosScheme") ?? CAPBridge.defaultScheme // check if WebKit handles scheme and if it is valid according to Apple's documentation if !WKWebView.handlesURLScheme(configScheme) && configScheme.range(of: "^[a-z][a-z0-9.+-]*$", options: [.regularExpression, .caseInsensitive], range: nil, locale: nil) != nil { specifiedScheme = configScheme.lowercased() } webViewConfiguration.setURLSchemeHandler(self.handler, forURLScheme: specifiedScheme) webViewConfiguration.userContentController = messageHandler.contentController configureWebView(configuration: webViewConfiguration) if let appendUserAgent = (capConfig.getValue("ios.appendUserAgent") as? String) ?? (capConfig.getValue("appendUserAgent") as? String) { webViewConfiguration.applicationNameForUserAgent = appendUserAgent } webView = WKWebView(frame: .zero, configuration: webViewConfiguration) webView?.scrollView.bounces = false let availableInsets = ["automatic", "scrollableAxes", "never", "always"] if let contentInset = (capConfig.getValue("ios.contentInset") as? String), let index = availableInsets.firstIndex(of: contentInset) { webView?.scrollView.contentInsetAdjustmentBehavior = UIScrollView.ContentInsetAdjustmentBehavior.init(rawValue: index)! } else { webView?.scrollView.contentInsetAdjustmentBehavior = .never } webView?.uiDelegate = self webView?.navigationDelegate = self if let allowsLinkPreview = (capConfig.getValue("ios.allowsLinkPreview") as? Bool) { webView?.allowsLinkPreview = allowsLinkPreview } webView?.configuration.preferences.setValue(true, forKey: "allowFileAccessFromFileURLs") view = webView setKeyboardRequiresUserInteraction(false) bridge = CAPBridge(self, messageHandler, capConfig, specifiedScheme) if let scrollEnabled = bridge!.config.getValue("ios.scrollEnabled") as? Bool { webView?.scrollView.isScrollEnabled = scrollEnabled } if let backgroundColor = (bridge!.config.getValue("ios.backgroundColor") as? String) ?? (bridge!.config.getValue("backgroundColor") as? String) { webView?.backgroundColor = UIColor.capacitor.color(fromHex: backgroundColor) webView?.scrollView.backgroundColor = UIColor.capacitor.color(fromHex: backgroundColor) } else if #available(iOS 13, *) { // Use the system background colors if background is not set by user webView?.backgroundColor = UIColor.systemBackground webView?.scrollView.backgroundColor = UIColor.systemBackground } if let overrideUserAgent = (bridge!.config.getValue("ios.overrideUserAgent") as? String) ?? (bridge!.config.getValue("overrideUserAgent") as? String) { webView?.customUserAgent = overrideUserAgent } } private func getStartPath() -> String? { var resourcesPath = assetsFolder if !startDir.isEmpty { resourcesPath = URL(fileURLWithPath: resourcesPath).appendingPathComponent(startDir).relativePath } guard var startPath = Bundle.main.path(forResource: resourcesPath, ofType: nil) else { printLoadError() return nil } if !isDeployDisabled() && !isNewBinary() { let defaults = UserDefaults.standard let persistedPath = defaults.string(forKey: "serverBasePath") if persistedPath != nil && !persistedPath!.isEmpty { let libPath = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true)[0] let cordovaDataDirectory = (libPath as NSString).appendingPathComponent("NoCloud") let snapshots = (cordovaDataDirectory as NSString).appendingPathComponent("ionic_built_snapshots") startPath = (snapshots as NSString).appendingPathComponent((persistedPath! as NSString).lastPathComponent) } } self.basePath = startPath return startPath } func isDeployDisabled() -> Bool { let val = cordovaParser.settings.object(forKey: "DisableDeploy".lowercased()) as? NSString return val?.boolValue ?? false } func isNewBinary() -> Bool { if let plist = Bundle.main.infoDictionary { if let versionCode = plist["CFBundleVersion"] as? String, let versionName = plist["CFBundleShortVersionString"] as? String { let prefs = UserDefaults.standard let lastVersionCode = prefs.string(forKey: "lastBinaryVersionCode") let lastVersionName = prefs.string(forKey: "lastBinaryVersionName") if !versionCode.isEqual(lastVersionCode) || !versionName.isEqual(lastVersionName) { prefs.set(versionCode, forKey: "lastBinaryVersionCode") prefs.set(versionName, forKey: "lastBinaryVersionName") prefs.set("", forKey: "serverBasePath") prefs.synchronize() return true } } } return false } override public func viewDidLoad() { super.viewDidLoad() self.becomeFirstResponder() loadWebView() } func printLoadError() { let fullStartPath = URL(fileURLWithPath: assetsFolder).appendingPathComponent(startDir) CAPLog.print("⚡️ ERROR: Unable to load \(fullStartPath.relativePath)/index.html") CAPLog.print("⚡️ This file is the root of your web app and must exist before") CAPLog.print("⚡️ Capacitor can run. Ensure you've run capacitor copy at least") CAPLog.print("⚡️ or, if embedding, that this directory exists as a resource directory.") } func fatalLoadError() -> Never { printLoadError() exit(1) } func loadWebView() { // Set the webview to be not opaque on the inital load. This prevents // the webview from showing a white background, which is its default // loading display, as that can appear as a screen flash. This might // have already been set by something else, like a plugin, so we want // to save the current value to reset it on success or failure. if let webView = webView, case .unloaded = webViewLoadingState { webViewLoadingState = .initialLoad(isOpaque: webView.isOpaque) webView.isOpaque = false } let fullStartPath = URL(fileURLWithPath: assetsFolder).appendingPathComponent(startDir).appendingPathComponent("index") if Bundle.main.path(forResource: fullStartPath.relativePath, ofType: "html") == nil { fatalLoadError() } hostname = bridge!.config.getString("server.url") ?? "\(bridge!.getLocalUrl())" allowNavigationConfig = bridge!.config.getValue("server.allowNavigation") as? [String] CAPLog.print("⚡️ Loading app at \(hostname!)...") let request = URLRequest(url: URL(string: hostname!)!) _ = webView?.load(request) } func setServerPath(path: String) { self.basePath = path self.handler?.setAssetPath(path) } public func setStatusBarDefaults() { if let plist = Bundle.main.infoDictionary { if let statusBarHidden = plist["UIStatusBarHidden"] as? Bool { if statusBarHidden { self.isStatusBarVisible = false } } if let statusBarStyle = plist["UIStatusBarStyle"] as? String { if statusBarStyle == "UIStatusBarStyleDarkContent" { if #available(iOS 13.0, *) { self.statusBarStyle = .darkContent } else { self.statusBarStyle = .default } } else if statusBarStyle != "UIStatusBarStyleDefault" { self.statusBarStyle = .lightContent } } } } public func setScreenOrientationDefaults() { if let plist = Bundle.main.infoDictionary { if let orientations = plist["UISupportedInterfaceOrientations"] as? [String] { for orientation in orientations { if orientation == "UIInterfaceOrientationPortrait" { self.supportedOrientations.append(UIInterfaceOrientation.portrait.rawValue) } if orientation == "UIInterfaceOrientationPortraitUpsideDown" { self.supportedOrientations.append(UIInterfaceOrientation.portraitUpsideDown.rawValue) } if orientation == "UIInterfaceOrientationLandscapeLeft" { self.supportedOrientations.append(UIInterfaceOrientation.landscapeLeft.rawValue) } if orientation == "UIInterfaceOrientationLandscapeRight" { self.supportedOrientations.append(UIInterfaceOrientation.landscapeRight.rawValue) } } if self.supportedOrientations.count == 0 { self.supportedOrientations.append(UIInterfaceOrientation.portrait.rawValue) } } } } public func configureWebView(configuration: WKWebViewConfiguration) { configuration.allowsInlineMediaPlayback = true configuration.suppressesIncrementalRendering = false configuration.allowsAirPlayForMediaPlayback = true configuration.mediaTypesRequiringUserActionForPlayback = [] } public func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { // Reset the bridge on each navigation bridge!.reset() } public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { NotificationCenter.default.post(name: Notification.Name(CAPNotifications.DecidePolicyForNavigationAction.name()), object: navigationAction) let navUrl = navigationAction.request.url! /* * Give plugins the chance to handle the url */ if let plugins = bridge?.plugins { for pluginObject in plugins { let plugin = pluginObject.value let selector = NSSelectorFromString("shouldOverrideLoad:") if plugin.responds(to: selector) { let shouldOverrideLoad = plugin.shouldOverrideLoad(navigationAction) if shouldOverrideLoad != nil { if shouldOverrideLoad == true { decisionHandler(.cancel) return } else if shouldOverrideLoad == false { decisionHandler(.allow) return } } } } } if let allowNavigation = allowNavigationConfig, let requestHost = navUrl.host { for pattern in allowNavigation { if matchHost(host: requestHost, pattern: pattern.lowercased()) { decisionHandler(.allow) return } } } if navUrl.absoluteString.range(of: hostname!) == nil && (navigationAction.targetFrame == nil || (navigationAction.targetFrame?.isMainFrame)!) { if UIApplication.shared.applicationState == .active { UIApplication.shared.open(navUrl, options: [:], completionHandler: nil) } decisionHandler(.cancel) return } decisionHandler(.allow) } public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { if case .initialLoad(let isOpaque) = webViewLoadingState { webView.isOpaque = isOpaque webViewLoadingState = .subsequentLoad } CAPLog.print("⚡️ WebView loaded") } public func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { if case .initialLoad(let isOpaque) = webViewLoadingState { webView.isOpaque = isOpaque webViewLoadingState = .subsequentLoad } CAPLog.print("⚡️ WebView failed to load") CAPLog.print("⚡️ Error: " + error.localizedDescription) } public func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { CAPLog.print("⚡️ WebView failed provisional navigation") CAPLog.print("⚡️ Error: " + error.localizedDescription) } public func webViewWebContentProcessDidTerminate(_ webView: WKWebView) { webView.reload() } override public func canPerformUnwindSegueAction(_ action: Selector, from fromViewController: UIViewController, withSender sender: Any) -> Bool { return false } typealias ClosureType = @convention(c) (Any, Selector, UnsafeRawPointer, Bool, Bool, Any?) -> Void typealias NewClosureType = @convention(c) (Any, Selector, UnsafeRawPointer, Bool, Bool, Bool, Any?) -> Void func setKeyboardRequiresUserInteraction( _ value: Bool) { let frameworkName = "WK" let className = "ContentView" guard let wkc = NSClassFromString(frameworkName + className) else { return } let oldSelector: Selector = sel_getUid("_startAssistingNode:userIsInteracting:blurPreviousNode:userObject:") let newSelector: Selector = sel_getUid("_startAssistingNode:userIsInteracting:blurPreviousNode:changingActivityState:userObject:") let newerSelector: Selector = sel_getUid("_elementDidFocus:userIsInteracting:blurPreviousNode:changingActivityState:userObject:") let ios13Selector: Selector = sel_getUid("_elementDidFocus:userIsInteracting:blurPreviousNode:activityStateChanges:userObject:") if let method = class_getInstanceMethod(wkc, oldSelector) { let originalImp: IMP = method_getImplementation(method) let original: ClosureType = unsafeBitCast(originalImp, to: ClosureType.self) let block : @convention(block) (Any, UnsafeRawPointer, Bool, Bool, Any?) -> Void = { (me, arg0, arg1, arg2, arg3) in original(me, oldSelector, arg0, !value, arg2, arg3) } let imp: IMP = imp_implementationWithBlock(block) method_setImplementation(method, imp) } if let method = class_getInstanceMethod(wkc, newSelector) { self.swizzleAutofocusMethod(method, newSelector, value) } if let method = class_getInstanceMethod(wkc, newerSelector) { self.swizzleAutofocusMethod(method, newerSelector, value) } if let method = class_getInstanceMethod(wkc, ios13Selector) { self.swizzleAutofocusMethod(method, ios13Selector, value) } } func swizzleAutofocusMethod(_ method: Method, _ selector: Selector, _ value: Bool) { let originalImp: IMP = method_getImplementation(method) let original: NewClosureType = unsafeBitCast(originalImp, to: NewClosureType.self) let block : @convention(block) (Any, UnsafeRawPointer, Bool, Bool, Bool, Any?) -> Void = { (me, arg0, arg1, arg2, arg3, arg4) in original(me, selector, arg0, !value, arg2, arg3, arg4) } let imp: IMP = imp_implementationWithBlock(block) method_setImplementation(method, imp) } func handleJSStartupError(_ error: [String: Any]) { let message = error["message"] ?? "No message" let url = error["url"] as? String ?? "" let line = error["line"] ?? "" let col = error["col"] ?? "" var filename = "" if let filenameIndex = url.range(of: "/", options: .backwards)?.lowerBound { let index = url.index(after: filenameIndex) filename = String(url[index...]) } CAPLog.print("\n⚡️ ------ STARTUP JS ERROR ------\n") CAPLog.print("⚡️ \(message)") CAPLog.print("⚡️ URL: \(url)") CAPLog.print("⚡️ \(filename):\(line):\(col)") CAPLog.print("\n⚡️ See above for help with debugging blank-screen issues") } func matchHost(host: String, pattern: String) -> Bool { var host = host.split(separator: ".") var pattern = pattern.split(separator: ".") if host.count != pattern.count { return false } if host == pattern { return true } let wildcards = pattern.enumerated().filter { $0.element == "*" } for wildcard in wildcards.reversed() { host.remove(at: wildcard.offset) pattern.remove(at: wildcard.offset) } return host == pattern } override public func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override public var prefersStatusBarHidden: Bool { get { return !isStatusBarVisible } } override public var preferredStatusBarStyle: UIStatusBarStyle { get { return statusBarStyle } } override public var preferredStatusBarUpdateAnimation: UIStatusBarAnimation { get { return statusBarAnimation } } public func setStatusBarVisible(_ isStatusBarVisible: Bool) { self.isStatusBarVisible = isStatusBarVisible UIView.animate(withDuration: 0.2, animations: { self.setNeedsStatusBarAppearanceUpdate() }) } public func setStatusBarStyle(_ statusBarStyle: UIStatusBarStyle) { self.statusBarStyle = statusBarStyle UIView.animate(withDuration: 0.2, animations: { self.setNeedsStatusBarAppearanceUpdate() }) } public func setStatusBarAnimation(_ statusBarAnimation: UIStatusBarAnimation) { self.statusBarAnimation = statusBarAnimation } public func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) { let alertController = UIAlertController(title: nil, message: message, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (_) in completionHandler() })) self.present(alertController, animated: true, completion: nil) } public func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) { let alertController = UIAlertController(title: nil, message: message, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (_) in completionHandler(true) })) alertController.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { (_) in completionHandler(false) })) self.present(alertController, animated: true, completion: nil) } public func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) { let alertController = UIAlertController(title: nil, message: prompt, preferredStyle: .alert) alertController.addTextField { (textField) in textField.text = defaultText } alertController.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (_) in if let text = alertController.textFields?.first?.text { completionHandler(text) } else { completionHandler(defaultText) } })) alertController.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { (_) in completionHandler(nil) })) self.present(alertController, animated: true, completion: nil) } public func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? { if navigationAction.request.url != nil { UIApplication.shared.open(navigationAction.request.url!, options: [:], completionHandler: nil) } return nil } public func getWebView() -> WKWebView { return self.webView! } public func getServerBasePath() -> String { return self.basePath } public func setServerBasePath(path: String) { setServerPath(path: path) let request = URLRequest(url: URL(string: hostname!)!) DispatchQueue.main.async { _ = self.getWebView().load(request) } } override open var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation { return UIApplication.shared.statusBarOrientation } override public var supportedInterfaceOrientations: UIInterfaceOrientationMask { var ret = 0 if self.supportedOrientations.contains(UIInterfaceOrientation.portrait.rawValue) { ret = ret | (1 << UIInterfaceOrientation.portrait.rawValue) } if self.supportedOrientations.contains(UIInterfaceOrientation.portraitUpsideDown.rawValue) { ret = ret | (1 << UIInterfaceOrientation.portraitUpsideDown.rawValue) } if self.supportedOrientations.contains(UIInterfaceOrientation.landscapeRight.rawValue) { ret = ret | (1 << UIInterfaceOrientation.landscapeRight.rawValue) } if self.supportedOrientations.contains(UIInterfaceOrientation.landscapeLeft.rawValue) { ret = ret | (1 << UIInterfaceOrientation.landscapeLeft.rawValue) } return UIInterfaceOrientationMask.init(rawValue: UInt(ret)) } /** * Add hooks to detect failed HTTP requests func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) { if error.code == -1001 { // TIMED OUT: // CODE to handle TIMEOUT } else if error.code == -1003 { // SERVER CANNOT BE FOUND // CODE to handle SERVER not found } else if error.code == -1100 { // URL NOT FOUND ON SERVER // CODE to handle URL not found } } */ }
41.942373
208
0.644589
e5aa64091c5b00b6330094e23ecd13bc65e7e5f9
20,535
// // ProcedureKit // // Copyright © 2016 ProcedureKit. All rights reserved. // import XCTest import TestingProcedureKit @testable import ProcedureKit class KVOTests: ProcedureKitTestCase { class NSOperationKVOObserver: NSObject { let operation: Operation private var removedObserved = false private var isFinishedBlock: (() -> Void)? enum KeyPath: String { case cancelled = "isCancelled" case asynchronous = "isAsynchronous" case executing = "isExecuting" case finished = "isFinished" case ready = "isReady" case dependencies = "dependencies" case queuePriority = "queuePriority" case completionBlock = "completionBlock" } struct KeyPathSets { static let State = Set<String>([KeyPath.cancelled.rawValue, KeyPath.executing.rawValue, KeyPath.finished.rawValue, KeyPath.ready.rawValue]) } struct KVONotification { let keyPath: String let time: TimeInterval let old: Any? let new: Any? } private var orderOfKVONotifications = Protector<[KVONotification]>([]) convenience init(operation: Operation, finishingExpectation: XCTestExpectation) { self.init(operation: operation, isFinishedBlock: { [weak finishingExpectation] in DispatchQueue.main.async { guard let finishingExpectation = finishingExpectation else { return } finishingExpectation.fulfill() } }) } init(operation: Operation, isFinishedBlock: (() -> Void)? = nil) { self.operation = operation self.isFinishedBlock = isFinishedBlock super.init() let options: NSKeyValueObservingOptions = [.old, .new] operation.addObserver(self, forKeyPath: KeyPath.cancelled.rawValue, options: options, context: &TestKVOOperationKVOContext) operation.addObserver(self, forKeyPath: KeyPath.asynchronous.rawValue, options: options, context: &TestKVOOperationKVOContext) operation.addObserver(self, forKeyPath: KeyPath.executing.rawValue, options: options, context: &TestKVOOperationKVOContext) operation.addObserver(self, forKeyPath: KeyPath.finished.rawValue, options: options, context: &TestKVOOperationKVOContext) operation.addObserver(self, forKeyPath: KeyPath.ready.rawValue, options: options, context: &TestKVOOperationKVOContext) operation.addObserver(self, forKeyPath: KeyPath.dependencies.rawValue, options: options, context: &TestKVOOperationKVOContext) operation.addObserver(self, forKeyPath: KeyPath.queuePriority.rawValue, options: options, context: &TestKVOOperationKVOContext) operation.addObserver(self, forKeyPath: KeyPath.completionBlock.rawValue, options: options, context: &TestKVOOperationKVOContext) } deinit { operation.removeObserver(self, forKeyPath: KeyPath.cancelled.rawValue) operation.removeObserver(self, forKeyPath: KeyPath.asynchronous.rawValue) operation.removeObserver(self, forKeyPath: KeyPath.executing.rawValue) operation.removeObserver(self, forKeyPath: KeyPath.finished.rawValue) operation.removeObserver(self, forKeyPath: KeyPath.ready.rawValue) operation.removeObserver(self, forKeyPath: KeyPath.dependencies.rawValue) operation.removeObserver(self, forKeyPath: KeyPath.queuePriority.rawValue) operation.removeObserver(self, forKeyPath: KeyPath.completionBlock.rawValue) } var observedKVO: [KVONotification] { return orderOfKVONotifications.read { array in return array } } func observedKVOFor(_ keyPaths: Set<String>) -> [KVONotification] { return observedKVO.filter({ (notification) -> Bool in keyPaths.contains(notification.keyPath) }) } var frequencyOfKVOKeyPaths: [String: Int] { return observedKVO.reduce([:]) { (accu: [String: Int], element) in let keyPath = element.keyPath var accu = accu accu[keyPath] = accu[keyPath]?.advanced(by: 1) ?? 1 return accu } } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard context == &TestKVOOperationKVOContext else { super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) return } guard object as AnyObject? === operation else { return } guard let keyPath = keyPath else { return } if let isFinishedBlock = self.isFinishedBlock, keyPath == KeyPath.finished.rawValue { orderOfKVONotifications.write { (array) -> Void in array.append(KVONotification(keyPath: keyPath, time: NSDate().timeIntervalSinceReferenceDate, old: change?[.oldKey], new: change?[.newKey])) DispatchQueue.main.async { isFinishedBlock() } } } else { orderOfKVONotifications.write { (array) -> Void in array.append(KVONotification(keyPath: keyPath, time: NSDate().timeIntervalSinceReferenceDate, old: change?[.oldKey], new: change?[.newKey])) } } } } func test__nsoperation_kvo__procedure_state_transition_from_initializing_to_pending() { let kvoObserver = NSOperationKVOObserver(operation: procedure) procedure.willEnqueue(on: queue) // trigger state transition from .initialized -> .willEnqueue procedure.pendingQueueStart() // trigger state transition from .willEnqueue -> .pending let observedKVO = kvoObserver.observedKVOFor(NSOperationKVOObserver.KeyPathSets.State) XCTAssertEqual(observedKVO.count, 0) // should be no KVO notification on any NSOperation keyPaths for this internal state transition } func test__nsoperation_kvo__procedure_state_transition_to_executing() { class NoFinishOperation: Procedure { override func execute() { // do not finish } } let procedure = NoFinishOperation() weak var expDidExecute = expectation(description: "") procedure.addDidExecuteBlockObserver { _ in DispatchQueue.main.async { expDidExecute?.fulfill() } } let kvoObserver = NSOperationKVOObserver(operation: procedure) procedure.willEnqueue(on: queue) // trigger state transition from .initialized -> .willEnqueue procedure.pendingQueueStart() // trigger state transition from .willEnqueue -> .pending procedure.start() // trigger state transition from .pending -> .executing waitForExpectations(timeout: 3, handler: nil) let observedKVO = kvoObserver.observedKVOFor(NSOperationKVOObserver.KeyPathSets.State) // should be a single KVO notification for NSOperation keyPath "isExecuting" for this internal state transition XCTAssertEqual(observedKVO.count, 1, "ObservedKVO = \(observedKVO)") XCTAssertEqual(observedKVO.get(safe: 0)?.keyPath, NSOperationKVOObserver.KeyPath.executing.rawValue) } func test__nsoperation_kvo__procedure_state_transition_to_executing_via_queue() { class NoFinishOperation: Procedure { var didExecuteExpectation: XCTestExpectation init(didExecuteExpectation: XCTestExpectation) { self.didExecuteExpectation = didExecuteExpectation super.init() } override func execute() { didExecuteExpectation.fulfill() // do not finish } } let didFinishGroup = DispatchGroup() didFinishGroup.enter() let didExecuteExpectation = expectation(description: "Test: \(#function); DidExecute") let operation = NoFinishOperation(didExecuteExpectation: didExecuteExpectation) operation.addDidFinishBlockObserver { _, _ in didFinishGroup.leave() } let kvoObserver = NSOperationKVOObserver(operation: operation) run(operation: operation) // trigger state transition from .initialized -> .executing via the queue waitForExpectations(timeout: 5, handler: nil) let observedKVO = kvoObserver.observedKVOFor(NSOperationKVOObserver.KeyPathSets.State) // should be a single KVO notification for NSOperation keyPath "isExecuting" for this internal state transition XCTAssertEqual(observedKVO.count, 1) XCTAssertEqual(observedKVO.get(safe: 0)?.keyPath, NSOperationKVOObserver.KeyPath.executing.rawValue) weak var expDidFinish = expectation(description: "Test: \(#function); Did Complete Operation") didFinishGroup.notify(queue: DispatchQueue.main, execute: { expDidFinish?.fulfill() }) operation.finish() waitForExpectations(timeout: 5, handler: nil) } private func verifyKVO_cancelledNotifications(_ observedKVO: [NSOperationKVOObserver.KVONotification]) -> (success: Bool, isReadyIndex: Int?, failureMessage: String?) { // ensure that the observedKVO contains: // "isReady", with at least one "isCancelled" before it if let isReadyIndex = observedKVO.index(where: { $0.keyPath == NSOperationKVOObserver.KeyPath.ready.rawValue }) { var foundIsCancelled = false guard isReadyIndex > 0 else { return (success: false, isReadyIndex: isReadyIndex, failureMessage: "Found isReady KVO notification, but no isCancelled beforehand.") } for idx in (0..<isReadyIndex) { if observedKVO[idx].keyPath == NSOperationKVOObserver.KeyPath.cancelled.rawValue { guard let newBool = observedKVO[idx].new as? Bool, newBool == true else { continue } foundIsCancelled = true break } } if foundIsCancelled { return (success: true, isReadyIndex: isReadyIndex, failureMessage: nil) } else { return (success: false, isReadyIndex: isReadyIndex, failureMessage: "Found isReady KVO notification, but no isCancelled beforehand.") } } else { return (success: false, isReadyIndex: nil, failureMessage: "Did not find isReady KVO notification") } } func test__nsoperation_kvo__procedure_cancel_from_initialized() { let kvoObserver = NSOperationKVOObserver(operation: procedure) procedure.cancel() let observedKVO = kvoObserver.observedKVOFor(NSOperationKVOObserver.KeyPathSets.State) // NOTE: To fully match NSOperation, this should be 2 KVO notifications, in the order: isCancelled, isReady // Because Operation handles cancelled status internally *and* calls super.cancel (to trigger Ready status change), // a total of 3 KVO notifications are generated in the order: isCancelled, isCancelled, isReady XCTAssertGreaterThanOrEqual(observedKVO.count, 2) let cancelledVerifyResult = verifyKVO_cancelledNotifications(observedKVO) XCTAssertTrue(cancelledVerifyResult.success, cancelledVerifyResult.failureMessage!) XCTAssertLessThanOrEqual(cancelledVerifyResult.isReadyIndex ?? 0, 3) } func test__nsoperation_kvo__groupprocedure_cancel_from_initialized() { let child = TestProcedure() let group = GroupProcedure(operations: [child]) let kvoObserver = NSOperationKVOObserver(operation: group) group.cancel() let observedKVO = kvoObserver.observedKVOFor(NSOperationKVOObserver.KeyPathSets.State) // NOTE: To fully match NSOperation, this should be 2 KVO notifications, in the order: isCancelled, isReady // Because Operation handles cancelled status internally *and* calls super.cancel (to trigger Ready status change), // a total of 3 KVO notifications are generated in the order: isCancelled, isCancelled, isReady XCTAssertGreaterThanOrEqual(observedKVO.count, 2) let cancelledVerifyResult = verifyKVO_cancelledNotifications(observedKVO) XCTAssertTrue(cancelledVerifyResult.success, cancelledVerifyResult.failureMessage!) XCTAssertLessThanOrEqual(cancelledVerifyResult.isReadyIndex ?? 0, 3) } func test__nsoperation_kvo__groupprocedure_child_cancel_from_initialized() { let child = TestProcedure(delay: 1.0) let group = GroupProcedure(operations: [child]) let kvoObserver = NSOperationKVOObserver(operation: child) group.cancel() let observedKVO = kvoObserver.observedKVOFor(NSOperationKVOObserver.KeyPathSets.State) // NOTE: To fully match NSOperation, this should be 2 KVO notifications, in the order: isCancelled, isReady // Because Operation handles cancelled status internally *and* calls super.cancel (to trigger Ready status change), // a total of 3 KVO notifications are generated in the order: isCancelled, isCancelled, isReady XCTAssertGreaterThanOrEqual(observedKVO.count, 2) let cancelledVerifyResult = verifyKVO_cancelledNotifications(observedKVO) XCTAssertTrue(cancelledVerifyResult.success, cancelledVerifyResult.failureMessage!) XCTAssertLessThanOrEqual(cancelledVerifyResult.isReadyIndex ?? 0, 3) } func test__nsoperation_kvo__nsoperation_cancel_from_initialized() { let operation = BlockOperation { } let kvoObserver = NSOperationKVOObserver(operation: operation) operation.cancel() let observedKVO = kvoObserver.observedKVOFor(NSOperationKVOObserver.KeyPathSets.State) XCTAssertEqual(observedKVO.count, 2) XCTAssertEqual(observedKVO.get(safe: 0)?.keyPath, NSOperationKVOObserver.KeyPath.cancelled.rawValue) XCTAssertEqual(observedKVO.get(safe: 1)?.keyPath, NSOperationKVOObserver.KeyPath.ready.rawValue) } func test__nsoperation_kvo__procedure_cancelled_to_completion() { let expectationIsFinishedKVO = expectation(description: "Test: \(#function); Did Receive isFinished KVO Notification") let kvoObserver = NSOperationKVOObserver(operation: procedure, finishingExpectation: expectationIsFinishedKVO) procedure.cancel() wait(for: procedure) let observedKVO = kvoObserver.observedKVOFor(NSOperationKVOObserver.KeyPathSets.State) let keyPathFrequency = kvoObserver.frequencyOfKVOKeyPaths XCTAssertGreaterThanOrEqual(observedKVO.count, 3) // first three KVO notifications should contain isCancelled and isReady (in that order) let cancelledVerifyResult = verifyKVO_cancelledNotifications(observedKVO) XCTAssertTrue(cancelledVerifyResult.success, cancelledVerifyResult.failureMessage!) XCTAssertLessThanOrEqual(cancelledVerifyResult.isReadyIndex ?? 0, 3) // it is valid, but not necessary, for a cancelled operation to transition through isExecuting // last KVO notification should always be isFinished XCTAssertEqual(observedKVO.last?.keyPath, NSOperationKVOObserver.KeyPath.finished.rawValue, "Notifications were: \(observedKVO)") // isFinished should only be sent once XCTAssertEqual(keyPathFrequency[NSOperationKVOObserver.KeyPath.finished.rawValue], 1) } func test__nsoperation_kvo__groupprocedure_cancelled_to_completion() { let expectationIsFinishedKVO = expectation(description: "Test: \(#function); Did Receive isFinished KVO Notification") let child = TestProcedure(delay: 1.0) let group = GroupProcedure(operations: [child]) let kvoObserver = NSOperationKVOObserver(operation: group, finishingExpectation: expectationIsFinishedKVO) group.cancel() wait(for: group) let observedKVO = kvoObserver.observedKVOFor(NSOperationKVOObserver.KeyPathSets.State) let keyPathFrequency = kvoObserver.frequencyOfKVOKeyPaths XCTAssertGreaterThanOrEqual(observedKVO.count, 3) // first three KVO notifications should contain isCancelled and isReady (in that order) let cancelledVerifyResult = verifyKVO_cancelledNotifications(observedKVO) XCTAssertTrue(cancelledVerifyResult.success, cancelledVerifyResult.failureMessage!) XCTAssertLessThanOrEqual(cancelledVerifyResult.isReadyIndex ?? 0, 3) // it is valid, but not necessary, for a cancelled operation to transition through isExecuting // last KVO notification should always be isFinished XCTAssertEqual(observedKVO.last?.keyPath, NSOperationKVOObserver.KeyPath.finished.rawValue) // isFinished should only be sent once XCTAssertEqual(keyPathFrequency[NSOperationKVOObserver.KeyPath.finished.rawValue], 1) } func test__nsoperation_kvo__procedure_execute_to_completion() { let expectationIsFinishedKVO = expectation(description: "Test: \(#function); Did Receive isFinished KVO Notification") let kvoObserver = NSOperationKVOObserver(operation: procedure, finishingExpectation: expectationIsFinishedKVO) wait(for: procedure) let observedKVO = kvoObserver.observedKVOFor(NSOperationKVOObserver.KeyPathSets.State) XCTAssertEqual(observedKVO.count, 3) XCTAssertEqual(observedKVO.get(safe: 0)?.keyPath, NSOperationKVOObserver.KeyPath.executing.rawValue) XCTAssertEqual(observedKVO.get(safe: 1)?.keyPath, NSOperationKVOObserver.KeyPath.executing.rawValue) XCTAssertEqual(observedKVO.get(safe: 2)?.keyPath, NSOperationKVOObserver.KeyPath.finished.rawValue) } func test__nsoperation_kvo__groupprocedure_execute_to_completion() { let expectationIsFinishedKVO = expectation(description: "Test: \(#function); Did Receive isFinished KVO Notification") let child = TestProcedure(delay: 1.0) let group = GroupProcedure(operations: [child]) let kvoObserver = NSOperationKVOObserver(operation: group, finishingExpectation: expectationIsFinishedKVO) wait(for: group) let observedKVO = kvoObserver.observedKVOFor(NSOperationKVOObserver.KeyPathSets.State) XCTAssertEqual(observedKVO.count, 3) XCTAssertEqual(observedKVO.get(safe: 0)?.keyPath, NSOperationKVOObserver.KeyPath.executing.rawValue) XCTAssertEqual(observedKVO.get(safe: 1)?.keyPath, NSOperationKVOObserver.KeyPath.executing.rawValue) XCTAssertEqual(observedKVO.get(safe: 2)?.keyPath, NSOperationKVOObserver.KeyPath.finished.rawValue) } func test__nsoperation_kvo__procedure_execute_with_dependencies_to_completion() { let expectationIsFinishedKVO = expectation(description: "Test: \(#function); Did Receive isFinished KVO Notification") let delay = DelayProcedure(by: 0.1) let operation = TestProcedure() let kvoObserver = NSOperationKVOObserver(operation: operation, finishingExpectation: expectationIsFinishedKVO) operation.addDependency(delay) wait(for: delay, operation) let observedKVO = kvoObserver.observedKVOFor(NSOperationKVOObserver.KeyPathSets.State.union([NSOperationKVOObserver.KeyPath.dependencies.rawValue])) XCTAssertEqual(observedKVO.count, 6) XCTAssertEqual(observedKVO.get(safe: 0)?.keyPath, NSOperationKVOObserver.KeyPath.ready.rawValue) XCTAssertEqual(observedKVO.get(safe: 1)?.keyPath, NSOperationKVOObserver.KeyPath.dependencies.rawValue) XCTAssertEqual(observedKVO.get(safe: 2)?.keyPath, NSOperationKVOObserver.KeyPath.ready.rawValue) XCTAssertEqual(observedKVO.get(safe: 3)?.keyPath, NSOperationKVOObserver.KeyPath.executing.rawValue) XCTAssertEqual(observedKVO.get(safe: 4)?.keyPath, NSOperationKVOObserver.KeyPath.executing.rawValue) XCTAssertEqual(observedKVO.get(safe: 5)?.keyPath, NSOperationKVOObserver.KeyPath.finished.rawValue) } } extension Collection { // Returns the element at the specified index iff it is within bounds, otherwise nil. func get(safe index: Index) -> Iterator.Element? { return indices.contains(index) ? self[index] : nil } } private var TestKVOOperationKVOContext = 0
53.897638
172
0.702264
900f94777b7ee0a3b29abf884fae20ea86011d40
2,682
// Copyright 2019 Algorand, Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // SelectAssetHeaderView.swift import UIKit class SelectAssetHeaderView: BaseView { private let layout = Layout<LayoutConstants>() private lazy var imageView = UIImageView() private lazy var titleLabel: UILabel = { UILabel().withAlignment(.left).withFont(UIFont.font(withWeight: .medium(size: 14.0))).withTextColor(Colors.Text.primary) }() override func configureAppearance() { backgroundColor = Colors.Component.assetHeader } override func prepareLayout() { setupImageViewLayout() setupTitleLabelLayout() } } extension SelectAssetHeaderView { private func setupImageViewLayout() { imageView.contentMode = .scaleAspectFit addSubview(imageView) imageView.snp.makeConstraints { make in make.leading.equalToSuperview().inset(layout.current.horizontalInset) make.size.equalTo(layout.current.imageSize) make.top.bottom.equalToSuperview().inset(layout.current.verticalInset) } } private func setupTitleLabelLayout() { addSubview(titleLabel) titleLabel.snp.makeConstraints { make in make.leading.equalTo(imageView.snp.trailing).offset(layout.current.labelInset) make.centerY.equalTo(imageView) make.trailing.equalToSuperview().inset(layout.current.horizontalInset) } } } extension SelectAssetHeaderView { func bind(_ viewModel: SelectAssetViewModel) { titleLabel.text = viewModel.accountName imageView.image = viewModel.accountImage } } extension SelectAssetHeaderView { private struct LayoutConstants: AdaptiveLayoutConstants { let horizontalInset: CGFloat = 16.0 let containerInset: CGFloat = 4.0 let labelInset: CGFloat = 12.0 let buttonSize = CGSize(width: 40.0, height: 40.0) let imageSize = CGSize(width: 24.0, height: 24.0) let verticalInset: CGFloat = 12.0 let buttonOffset: CGFloat = 2.0 let trailingInset: CGFloat = 8.0 } }
32.313253
128
0.683072
091b53ab10329e3bc328cb6f0bf146a1f839e0e4
1,766
// // Statio // Varun Santhanam // import Combine import Foundation @testable import ShortRibs @testable import Statio import XCTest final class DeviceBoardStreamTests: TestCase { let deviceBoardStorage = DeviceBoardStoringMock() var stream: DeviceBoardStream! override func setUp() { super.setUp() stream = .init(deviceBoardStorage: deviceBoardStorage) } func test_subscribe_loadsFromStorage_filtersDuplicates() { let storedBoards = [DeviceBoard(identifier: "0", name: "0", part: "0", frequency: 0)] var emits = [[DeviceBoard]]() deviceBoardStorage.retrieveCachedBoardsHandler = { storedBoards } stream.boards .sink { boards in emits.append(boards) } .cancelOnTearDown(testCase: self) XCTAssertEqual(deviceBoardStorage.retrieveCachedBoardsCallCount, 1) XCTAssertEqual(emits, [storedBoards]) stream.update(boards: storedBoards) XCTAssertEqual(emits, [storedBoards]) } func test_subscribe_loadsFromStorage_replacesNewValues() { let storedBoards = [DeviceBoard(identifier: "0", name: "0", part: "0", frequency: 0)] let newBoards = [DeviceBoard(identifier: "1", name: "1", part: "1", frequency: 1)] var emits = [[DeviceBoard]]() deviceBoardStorage.retrieveCachedBoardsHandler = { storedBoards } stream.boards .sink { boards in emits.append(boards) } .cancelOnTearDown(testCase: self) XCTAssertEqual(deviceBoardStorage.retrieveCachedBoardsCallCount, 1) XCTAssertEqual(emits, [storedBoards]) stream.update(boards: newBoards) XCTAssertEqual(emits, [storedBoards, newBoards]) } }
25.970588
93
0.659117
5d4506c2c598d7312d7314db1597d5bfb9fe7085
10,921
// // SAThemeManager.swift // Saralin // // Created by zhang on 2/18/16. // Copyright © 2016 zaczh. All rights reserved. // import UIKit class SAThemeManager { var activeTheme: SATheme! init() { NotificationCenter.default.addObserver(self, selector: #selector(handleUserLoggedIn(_:)), name: Notification.Name.SAUserLoggedInNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(handleUserLoggedOut(_:)), name: Notification.Name.SAUserLoggedOutNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(handleUserPreferenceChange(_:)), name: Notification.Name.SAUserPreferenceChangedNotification, object: nil) loadUserTheme() } @objc func handleUserLoggedOut(_ notification: NSNotification) { // what should we do here? } @objc func handleUserLoggedIn(_ notification: NSNotification) { loadUserTheme() } @objc func handleUserPreferenceChange(_ notification: NSNotification) { let userInfo = notification.userInfo guard let key = userInfo?[SAAccount.Preference.changedPreferenceNameKey] as? SAAccount.Preference else { return } if key == SAAccount.Preference.theme_id { loadUserTheme() } } func loadUserTheme() { guard let themeID = Account().preferenceForkey(SAAccount.Preference.theme_id) as? Int, let theme = getThemeOf(id: themeID) else { return } activeTheme = theme if #available(iOS 13.0, *) { let autoSwitch = Account().preferenceForkey(.automatically_change_theme_to_match_system_appearance) as? Bool ?? true if !autoSwitch { return } let traitCollection = UITraitCollection.current let shouldSwitchTheme = (traitCollection.userInterfaceStyle == .dark && theme.colorScheme == 0) || (traitCollection.userInterfaceStyle == .light && theme.colorScheme == 1) if !shouldSwitchTheme { return } // theme not match var oldTheme: SATheme? if let oldThemeID = Account().preferenceForkey(.theme_id_before_night_switch) as? Int { oldTheme = getThemeOf(id: oldThemeID) } if let t = oldTheme, t.matchesTraitCollection(traitCollection) { activeTheme = t return } if theme.colorScheme == 0 { // switch to dark activeTheme = .darkTheme return } // switch to light activeTheme = .whiteTheme return } } func getThemeOf(id: Int) -> SATheme? { for theme in SATheme.allThemes { if theme.identifier == id { return theme } } return nil } func switchTheme() { let switchToNewTheme: ((SATheme) -> Void) = { (theme) in Account().savePreferenceValue(self.activeTheme.identifier as AnyObject, forKey: .theme_id_before_night_switch) self.activeTheme = theme Account().savePreferenceValue(theme.identifier as AnyObject, forKey: .theme_id) } if let oldThemeID = Account().preferenceForkey(.theme_id_before_night_switch) as? Int, let theme = getThemeOf(id: oldThemeID), theme.colorScheme != activeTheme.colorScheme { switchToNewTheme(theme) return } if activeTheme.colorScheme == 1 { // change to day let toTheme = SATheme.whiteTheme switchToNewTheme(toTheme) } else { // change to night let toTheme = SATheme.darkTheme switchToNewTheme(toTheme) } } func switchThemeBySystemStyleChange() { let switchToNewTheme: ((SATheme) -> Void) = { (theme) in if let oldThemeID = Account().preferenceForkey(.theme_id_before_night_switch) as? Int, let olodTheme = self.getThemeOf(id: oldThemeID), olodTheme.colorScheme == theme.colorScheme { self.activeTheme = olodTheme Account().savePreferenceValue(olodTheme.identifier as AnyObject, forKey: .theme_id) return } Account().savePreferenceValue(self.activeTheme.identifier as AnyObject, forKey: .theme_id_before_night_switch) self.activeTheme = theme Account().savePreferenceValue(theme.identifier as AnyObject, forKey: .theme_id) } if UITraitCollection.current.userInterfaceStyle == .light { // change to day let toTheme = SATheme.whiteTheme switchToNewTheme(toTheme) } else if UITraitCollection.current.userInterfaceStyle == .dark { // change to night let toTheme = SATheme.darkTheme switchToNewTheme(toTheme) } } } class SATheme: NSObject { static let allThemes = [SATheme.defaultTheme, SATheme.darkTheme, SATheme.whiteTheme] // unique theme ID var identifier = 0 // color title var name: String = "" // main color scheme. 0 for light, 1 for dark var colorScheme = 0 // global color var globalTintColor = "#000000" var barTintColor = "#000000" var textColor = "#000000" var backgroundColor = "#000000" var foregroundColor = "#000000" // web page var htmlLinkColor = "#000000" var htmlBlockQuoteBackgroundColor = "#000000" var htmlBlockQuoteTextColor = "#000000" // table view var tableCellTextColor = "#000000" var tableCellGrayedTextColor = "#000000" var tableCellSupplementTextColor = "#000000" var tableCellHighlightColor = "#000000" var tableCellTintColor = "#000000" var tableHeaderTextColor = "#000000" var tableCellSeperatorColor = "#000000" var tableHeaderBackgroundColor = "#000000" // bar var navigationBarStyle: UIBarStyle = .default var navigationBarTextColor = "#000000" var toolBarStyle: UIBarStyle = .default // other color & style var statusBarStyle: UIStatusBarStyle! = .default var threadTitleFontSizeInPt: CGFloat = 12 var keyboardAppearence: UIKeyboardAppearance = .default var visualBlurEffectStyle: UIBlurEffect.Style = .dark var activityIndicatorStyle: UIActivityIndicatorView.Style = UIActivityIndicatorView.Style.medium func matchesTraitCollection(_ traitCollection: UITraitCollection) -> Bool { return (colorScheme == 0 && traitCollection.userInterfaceStyle == .light) || (colorScheme == 1 && traitCollection.userInterfaceStyle == .dark) } static let defaultTheme: SATheme = { () in let theme = SATheme() theme.identifier = 0 theme.name = "黄色主题" theme.colorScheme = 0 theme.textColor = "#455c93" theme.globalTintColor = "#455c93" theme.barTintColor = "#fcfdfa" theme.navigationBarTextColor = "#000000" theme.htmlBlockQuoteBackgroundColor = "#d5e0af" theme.htmlBlockQuoteTextColor = "#455c93" theme.htmlLinkColor = "#4c6afa" theme.backgroundColor = "#fcfdfa" theme.foregroundColor = "#F6F7EB" theme.tableCellTintColor = "#455c93" theme.tableCellSeperatorColor = "#33333333" theme.tableCellTextColor = "#455c93" theme.tableCellGrayedTextColor = "#888888" theme.tableHeaderTextColor = "#455c93" theme.tableHeaderBackgroundColor = "#F6F7EB" theme.tableCellSupplementTextColor = "#5a5a5a" theme.tableCellHighlightColor = "#d5e0af" theme.navigationBarStyle = .default theme.toolBarStyle = .default theme.statusBarStyle = .default theme.keyboardAppearence = .default theme.visualBlurEffectStyle = .light theme.activityIndicatorStyle = .medium return theme }() static let darkTheme: SATheme = { () in let theme = SATheme() theme.identifier = 1 theme.name = "夜间主题" theme.colorScheme = 1 theme.textColor = "#BBBBBB" theme.globalTintColor = "#CB8841" theme.barTintColor = "#00000000" theme.navigationBarTextColor = "#d5d6e0" theme.htmlBlockQuoteBackgroundColor = "#221e27" theme.htmlBlockQuoteTextColor = "#8d9abc" theme.htmlLinkColor = "#8d9abc" theme.tableCellHighlightColor = "#222222" theme.backgroundColor = "#000000" theme.foregroundColor = "#1C1C1D" theme.tableCellSeperatorColor = "#434345" // RGBA theme.tableCellTextColor = "#BBBBBB" theme.tableHeaderTextColor = "#BBBBBB" theme.tableHeaderBackgroundColor = "#00000000"//clear color theme.tableCellTintColor = "#BBBBBB" theme.tableCellSupplementTextColor = "#636A6E" theme.tableCellGrayedTextColor = "#999999" theme.navigationBarStyle = .black theme.toolBarStyle = .black theme.statusBarStyle = .lightContent theme.keyboardAppearence = .dark theme.visualBlurEffectStyle = .dark theme.activityIndicatorStyle = .medium return theme }() static let whiteTheme: SATheme = { () in let theme = SATheme() theme.identifier = 2 theme.name = "白色主题" theme.colorScheme = 0 theme.textColor = "#3e3a3f" theme.globalTintColor = "#457cff" theme.barTintColor = "#ffffff" theme.navigationBarTextColor = "#000000" theme.backgroundColor = "#ececec" theme.foregroundColor = "#FFFFFF" theme.htmlBlockQuoteBackgroundColor = "#eeebf6" theme.htmlBlockQuoteTextColor = "#33333399" theme.htmlLinkColor = "#8b6214" theme.tableCellTintColor = "48463F" theme.tableCellSeperatorColor = "#33333333" theme.tableCellTextColor = "#3e3a3f" theme.tableCellGrayedTextColor = "#888888" theme.tableHeaderTextColor = "#48463F" theme.tableHeaderBackgroundColor = "#00000000"//clear color theme.tableCellSupplementTextColor = "#5a5a5a" theme.tableCellHighlightColor = "#b6b6b6" theme.navigationBarStyle = .default theme.toolBarStyle = .default theme.statusBarStyle = .default theme.keyboardAppearence = .default theme.visualBlurEffectStyle = .light theme.activityIndicatorStyle = .medium return theme }() }
35.003205
183
0.612398
0a69c32d885dc3d7e4b523986542144ee4325b84
535
// // TTModeHueSceneMidnightOilOptions.swift // Turn Touch iOS // // Created by Samuel Clay on 10/19/16. // Copyright © 2016 Turn Touch. All rights reserved. // import UIKit class TTModeHueSceneMidnightOilOptions: TTModeHueSceneOptions { required init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: "TTModeHueSceneOptions", bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
24.318182
82
0.702804
3300c1f04c0702148267683ee79dafafdf53ba97
5,896
// // Copyright © 2019 Optimize Fitness Inc. // Licensed under the MIT license // https://github.com/OptimizeFitness/Minerva/blob/master/LICENSE // import Foundation import RxSwift import UIKit open class ButtonCellModel: BaseListCellModel { public typealias ButtonAction = (_ model: ButtonCellModel, _ button: UIButton) -> Void public var buttonAction: ButtonAction? public var isSelected = BehaviorSubject<Bool>(value: false) public var directionalLayoutMargins = NSDirectionalEdgeInsets(top: 8, leading: 16, bottom: 8, trailing: 16) public var numberOfLines = 0 public var textVerticalMargin: CGFloat = 15.0 public var textHorizontalMargin: CGFloat = 15.0 public var accessoryImageWidthHeight: CGFloat = 15.0 public var textAlignment: NSTextAlignment = .center public var cellFillsWidth = false public var titleEdgeInsets: UIEdgeInsets = .zero public var buttonColor: UIColor? public var selectedButtonColor: UIColor? public var backgroundColor: UIColor? public var selectedAttributedText: NSAttributedString? public var borderWidth: CGFloat = 0 public var borderRadius: CGFloat = 4 public var borderColor: UIColor? public var selectedBorderColor: UIColor? fileprivate let attributedText: NSAttributedString public init(identifier: String, attributedText: NSAttributedString) { self.attributedText = attributedText super.init(identifier: identifier) } public convenience init(attributedText: NSAttributedString) { self.init(identifier: attributedText.string, attributedText: attributedText) } public convenience init(identifier: String, text: String, font: UIFont, textColor: UIColor) { let string = NSAttributedString( string: text, font: font, fontColor: textColor ) self.init(identifier: identifier, attributedText: string) } public convenience init(text: String, font: UIFont, textColor: UIColor) { self.init(identifier: text, text: text, font: font, textColor: textColor) } // MARK: - BaseListCellModel override open func identical(to model: ListCellModel) -> Bool { guard let model = model as? Self, super.identical(to: model) else { return false } return attributedText == model.attributedText && numberOfLines == model.numberOfLines && textVerticalMargin == model.textVerticalMargin && textHorizontalMargin == model.textHorizontalMargin && accessoryImageWidthHeight == model.accessoryImageWidthHeight && textAlignment == model.textAlignment && buttonColor == model.buttonColor && selectedButtonColor == model.selectedButtonColor && selectedAttributedText == model.selectedAttributedText && borderWidth == model.borderWidth && borderRadius == model.borderRadius && borderColor == model.borderColor && selectedBorderColor == model.selectedBorderColor && cellFillsWidth == model.cellFillsWidth && titleEdgeInsets == model.titleEdgeInsets && backgroundColor == model.backgroundColor && directionalLayoutMargins == model.directionalLayoutMargins } } public final class ButtonCell: BaseReactiveListCell<ButtonCellModel> { private let button: UIButton = { let button = UIButton() button.titleLabel?.adjustsFontForContentSizeCategory = true button.titleLabel?.minimumScaleFactor = 0.5 button.titleLabel?.adjustsFontSizeToFitWidth = true button.titleLabel?.lineBreakMode = .byWordWrapping button.clipsToBounds = true return button }() override public init(frame: CGRect) { super.init(frame: frame) contentView.addSubview(button) backgroundView = UIView() setupConstraints() button.addTarget(self, action: #selector(pressedButton(_:)), for: .touchUpInside) } override public func prepareForReuse() { super.prepareForReuse() button.setBackgroundImage(nil, for: .normal) button.setBackgroundImage(nil, for: .highlighted) button.setBackgroundImage(nil, for: .selected) } override public func bind(model: ButtonCellModel, sizing: Bool) { super.bind(model: model, sizing: sizing) button.titleLabel?.textAlignment = model.textAlignment button.titleLabel?.numberOfLines = model.numberOfLines button.titleEdgeInsets = model.titleEdgeInsets button.contentEdgeInsets = UIEdgeInsets( top: model.textVerticalMargin, left: model.textHorizontalMargin, bottom: model.textVerticalMargin, right: model.textHorizontalMargin ) button.setAttributedTitle(model.attributedText, for: .normal) button.setAttributedTitle(model.selectedAttributedText, for: .selected) contentView.directionalLayoutMargins = model.directionalLayoutMargins guard !sizing else { return } button.setBackgroundImage(model.buttonColor?.image(), for: .normal) button.setBackgroundImage(model.buttonColor?.withAlphaComponent(0.8).image(), for: .highlighted) button.setBackgroundImage(model.selectedBorderColor?.image(), for: .selected) backgroundView?.backgroundColor = model.backgroundColor button.layer.borderWidth = model.borderWidth button.layer.cornerRadius = model.borderRadius button.isUserInteractionEnabled = model.buttonAction != nil model.isSelected.subscribe(onNext: { [weak self, weak model] isSelected -> Void in self?.button.isSelected = isSelected let borderColor = isSelected ? model?.selectedBorderColor?.cgColor : model?.borderColor?.cgColor self?.button.layer.borderColor = borderColor }).disposed(by: disposeBag) } @objc private func pressedButton(_ sender: UIButton) { guard let model = model else { return } model.buttonAction?(model, sender) } } // MARK: - Constraints extension ButtonCell { private func setupConstraints() { button.anchorTo(layoutGuide: contentView.layoutMarginsGuide) contentView.shouldTranslateAutoresizingMaskIntoConstraints(false) } }
36.171779
109
0.745251
693fef2b0edc5901cca6f4ad28ab63dc0a1fa6ed
589
// // SideMenuExtension.swift // Diversidade // // Created by Francisco José A. C. Souza on 24/02/16. // Copyright © 2016 Francisco José A. C. Souza. All rights reserved. // import UIKit extension UIViewController { func configureSideMenu(menuButton:UIBarButtonItem!){ if let revealController = self.revealViewController(){ menuButton.target = revealController menuButton.action = #selector(SWRevealViewController.revealToggle(_:)) self.view.addGestureRecognizer(revealController.panGestureRecognizer()) } } }
28.047619
83
0.682513
761ef814269a66d68a78987a64a05dbb2a668838
1,539
// // CGPointTests.swift // BFKit-Swift // // The MIT License (MIT) // // Copyright (c) 2015 - 2019 Fabrizio Brancati. // // 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. @testable import BFKit import Foundation import XCTest internal class CGPointTests: XCTestCase { internal func testDistanceTo() { let point1 = CGPoint.zero let point2 = CGPoint(x: 0, y: 100) let distance = point1.distanceTo(point2) XCTAssertEqual(distance, 100) } }
37.536585
82
0.721897
e52f445e03cf95fe448ed242cf002702cb5b3639
2,726
//: [Previous](@previous) import Foundation //: # MemoryLeak //print("\n---------- [ Lazy var closure ] ----------\n") // Dog instance has bark property // ⬇︎ ⇡ // bark property has Dog instance final class Dog { let name: String = "토리" lazy var bark: () -> () = { [unowned self] in print(self.name + "가 짖습니다.", terminator: " ") } deinit { print("이 문장 보이면 아님 ->", terminator: " ") } } var dog: Dog? = Dog() dog?.bark() dog = nil // 강한 순환 참조를 하고 있기 때문에 nil을 넣어줘도 Dog와 bark는 서로 연결되어 있어 종료되지 않는다. // 따라서 unowned를 쓰거나, weak을 써줘서 약한 참조를 해줘야 된다. print("메모리 릭!\n") // print => "토리가 짖습니다. 이 문장 보이면 아님 -> 메모리 릭!" print("\n---------- [ weak capture ] ----------\n") final class Callee { deinit { print("🔫🔫 응. 아니야.") } var storedProperty: (() -> ())? func noEscapingFunc(closure: () -> Void) { // self.storedProperty = closure // Compile Error } func escapingFunc(closure: @escaping () -> Void) { self.storedProperty = closure } } final class Caller { let callee = Callee() var name = "James" func memoryLeak() { // 1) // Caller has callee // ⬇︎ ⬆︎ // Callee has caller // callee.escapingFunc { // self.name = "Giftbot" // } // 2) weak을 줘서 강한 순환 참조를 끊어줌 // callee.escapingFunc { [weak self] in // self?.name = "Giftbot" // } } func anotherLeak() { // 1) // callee.escapingFunc { // DispatchQueue.main.async { let _ = 1 + 1 } // // caller와 관련된게 없으면 캡처할게 없어서 메모리릭 발생하지 않는다. // } // 2) // callee.escapingFunc { // DispatchQueue.main.async { [weak self] in // self?.name = "Giftbot" // /* // 메모리릭 발생.. weak self를 써줬지만 시점이 문제다. // DispatchQueue가 사용하는 self는 즉, < calle.escapingFunc { [self] in > // 이렇게 되어있다고 볼 수 있다. 1번에서도 마찬가지지만, 그 안에서 self를 참조하는 것이 없기 때문에 // 메모리 릭이 발생하지 않았는데, 2번은 [weak self]에서 [self]를 참조하고 있기 때문에 메모리릭이 발생한다. // */ // } // } // 3) callee.escapingFunc { [weak self] in DispatchQueue.main.async { self?.name = "Giftbot" /* 이번에는 DispatchQueue에서 [self]를 쓰더라도, [weak self]를 참조한 거라, [weak self]가 종료되면 [self]도 종료된다. */ } } } } print("버그??? 🐛🐛🐛", terminator: " ") var caller: Caller? = Caller() //caller?.memoryLeak() caller?.anotherLeak() DispatchQueue.main.asyncAfter(deadline: .now() + 1.1) { caller = nil } //: [Next](@next)
23.912281
86
0.483125
14051f34db61762fdf7fd330c6b0c8e3b863ad68
4,317
// Automatically generated by the Fast Binary Encoding compiler, do not modify! // https://github.com/chronoxor/FastBinaryEncoding // Source: test.fbe // Version: 1.7.0.0 import Foundation import ChronoxorFbe import ChronoxorProto // Fast Binary Encoding optional EnumTyped field model public class FieldModelOptionalEnumTyped: FieldModel { public var _buffer: Buffer public var _offset: Int // Field size public let fbeSize: Int = 1 + 4 // Base field model value public let value: FieldModelEnumTyped public var fbeExtra: Int { if !hasValue() { return 0 } let fbeOptionalOffset = Int(readUInt32(offset: fbeOffset + 1)) if (fbeOptionalOffset == 0) || ((_buffer.offset + fbeOptionalOffset + 4) > _buffer.size) { return 0 } _buffer.shift(offset: fbeOptionalOffset) let fbeResult = value.fbeSize + value.fbeExtra _buffer.unshift(offset: fbeOptionalOffset) return fbeResult } public required init() { let buffer = Buffer() let offset = 0 _buffer = buffer _offset = offset value = FieldModelEnumTyped(buffer: buffer, offset: 0) } public required init(buffer: Buffer, offset: Int) { _buffer = buffer _offset = offset value = FieldModelEnumTyped(buffer: buffer, offset: 0) } public func hasValue() -> Bool { if (_buffer.offset + fbeOffset + fbeSize) > _buffer.size { return false } let fbeHasValue = Int32(readInt8(offset: fbeOffset)) return fbeHasValue != 0 } public func verify() -> Bool { if _buffer.offset + fbeOffset + fbeSize > _buffer.size { return true } let fbeHasValue = Int(readInt8(offset: fbeOffset)) if fbeHasValue == 0 { return true } let fbeOptionalOffset = Int(readUInt32(offset: fbeOffset + 1)) if fbeOptionalOffset == 0 { return false } _buffer.shift(offset: fbeOptionalOffset) let fbeResult = value.verify() _buffer.unshift(offset: fbeOptionalOffset) return fbeResult } // Get the optional value (being phase) func getBegin() -> Int { if !hasValue() { return 0 } let fbeOptionalOffset = Int(readUInt32(offset: fbeOffset + 1)) if fbeOptionalOffset <= 0 { assertionFailure("Model is broken!") return 0 } _buffer.shift(offset: fbeOptionalOffset) return fbeOptionalOffset } // Get the optional value (end phase) func getEnd(fbeBegin: Int) { _buffer.unshift(offset: fbeBegin) } public func get(defaults: EnumTyped? = nil) -> EnumTyped? { let fbeBegin = getBegin() if fbeBegin == 0 { return defaults } let optional = value.get() getEnd(fbeBegin: fbeBegin) return optional } // Set the optional value (begin phase) func setBegin(hasValue: Bool) throws -> Int { if _buffer.offset + fbeOffset + fbeSize > _buffer.size { assertionFailure("Model is broken!") return 0 } let fbeHasValue = hasValue ? 1 : 0 write(offset: fbeOffset, value: Int8(fbeHasValue)) if fbeHasValue == 0 { return 0 } let fbeOptionalSize = value.fbeSize let fbeOptionalOffset = try _buffer.allocate(size: fbeOptionalSize) - _buffer.offset if (fbeOptionalOffset <= 0) || ((_buffer.offset + fbeOptionalOffset + fbeOptionalSize) > _buffer.size) { assertionFailure("Model is broken!") return 0 } write(offset: fbeOffset + 1, value: UInt32(fbeOptionalOffset)) _buffer.shift(offset: fbeOptionalOffset) return fbeOptionalOffset } // Set the optional value (end phase) func setEnd(fbeBegin: Int) { _buffer.unshift(offset: fbeBegin) } // Set the optional value public func set(value optional: EnumTyped?) throws { let fbeBegin = try setBegin(hasValue: optional != nil) if fbeBegin == 0 { return } try value.set(value: optional!) setEnd(fbeBegin: fbeBegin) } }
27.150943
112
0.598564
5621b45500d1828f7dd9a0af146ffffa92f8962e
510
// // UITableViewExtension.swift // QuizApp // // Created by Abdoulaye Diallo on 10/23/21. // import UIKit extension UITableView { func register(_ type: UITableViewCell.Type){ let className = String(describing: type) register(UINib(nibName: className, bundle: nil), forCellReuseIdentifier: className) } func dequeCell<T>(_ type: T.Type) -> T? { let className = String(describing: type) return dequeueReusableCell(withIdentifier: className) as? T } }
23.181818
91
0.666667
23a80337e114433da1ca13bc6669da8aa1b45ab2
1,997
// // VStack.swift // Components // // Created by Victor Freitas on 15/06/21. // import UIKit import TinyConstraints open class VStack: UIStackView { public init (_ views: UIView..., spacing: CGFloat = 16, distribution: UIStackView.Distribution = .fill, alignment: UIStackView.Alignment = .fill, padding: [Padding] = []) { super.init(frame: .zero) axis = .vertical self.spacing = spacing self.distribution = distribution self.alignment = alignment views.forEach { [weak self] view in guard let self = self else { return } self.addArrangedSubview(view) } setPadding(padding, for: .content) isLayoutMarginsRelativeArrangement = true } required public init(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setPadding(_ padding: [Padding], for type: PaddingType) { var paddings = PaddingModel() padding.forEach { padding in switch padding { case let .top(top): paddings.top = top case let .bottom(bottom): paddings.bottom = bottom case let .left(left): paddings.left = left case let .right(right): paddings.right = right case let .vertical(vertical): paddings.top = vertical paddings.bottom = vertical case let .horizontal(horizontal): paddings.left = horizontal paddings.right = horizontal } } switch type { case .content: layoutMargins = .init(top: paddings.top, left: paddings.left, bottom: paddings.bottom, right: paddings.right) } } }
28.528571
121
0.516274
d5f59d9663e630d9a51050d66a936e196bf95c9d
316
// // UIColor-Extention.swift // DouYuZB // // Created by allen on 16/10/15. // Copyright © 2016年 allen. All rights reserved. // import UIKit extension UIColor{ convenience init(r: CGFloat, g: CGFloat, b: CGFloat) { self.init(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: 1.0) } }
18.588235
80
0.613924
622184118116f2a2ecf8e8419a74e0bf061b4133
696
// // CEFWebPluginInfoVisitor.g.swift // CEF.swift // // Created by Tamas Lustyik on 2015. 08. 07.. // Copyright © 2015. Tamas Lustyik. All rights reserved. // import Foundation func CEFWebPluginInfoVisitor_visit(ptr: UnsafeMutablePointer<cef_web_plugin_info_visitor_t>, pluginInfo: UnsafeMutablePointer<cef_web_plugin_info_t>, index: Int32, totalCount: Int32) -> Int32 { guard let obj = CEFWebPluginInfoVisitorMarshaller.get(ptr) else { return 0 } return obj.visit(CEFWebPluginInfo.fromCEF(pluginInfo)!, index: Int(index), totalCount: Int(totalCount)) ? 1 : 0 }
31.636364
115
0.62931
561809f8167444d41b61ec486163f707afffbf89
1,987
/// Copyright (c) 2018 Razeware LLC /// /// Permission is hereby granted, free of charge, to any person obtaining a copy /// of this software and associated documentation files (the "Software"), to deal /// in the Software without restriction, including without limitation the rights /// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell /// copies of the Software, and to permit persons to whom the Software is /// furnished to do so, subject to the following conditions: /// /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software. /// /// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, /// distribute, sublicense, create a derivative work, and/or sell copies of the /// Software in any work that is designed, intended, or marketed for pedagogical or /// instructional purposes related to programming, coding, application development, /// or information technology. Permission for such use, copying, modification, /// merger, publication, distribution, sublicensing, creation of derivative works, /// or sale is expressly withheld. /// /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN /// THE SOFTWARE. import Foundation import CoreData extension Category { @nonobjc public class func fetchRequest() -> NSFetchRequest<Category> { return NSFetchRequest<Category>(entityName: "Category") } @NSManaged public var categoryID: String? @NSManaged public var name: String? @NSManaged public var venue: Venue? }
46.209302
83
0.754404
ef3c59a765333b7c0f8ed4c037abd8202653754a
22,411
// // SQTextEditorView.swift // SQRichTextEditor // // Created by Jesse on 2019/12/10. // #if os(iOS) import UIKit import WebKit public protocol SQTextEditorDelegate: AnyObject { /// Called when the editor components is ready. func editorDidLoad(_ editor: SQTextEditorView) /// Called when the user selected some text or moved the cursor to a different position. func editor(_ editor: SQTextEditorView, selectedTextAttributeDidChange attribute: SQTextAttribute) /// Called when the user inserted, deleted or changed the style of some text. func editor(_ editor: SQTextEditorView, contentHeightDidChange height: Int) func editorDidFocus(_ editor: SQTextEditorView) func editorDidTapDoneButton(_ editor: SQTextEditorView) func editor(_ editor: SQTextEditorView, cursorPositionDidChange position: SQEditorCursorPosition) } /// Make optional protocol methods public extension SQTextEditorDelegate { func editorDidLoad(_ editor: SQTextEditorView) {} func editor(_ editor: SQTextEditorView, selectedTextAttributeDidChange attribute: SQTextAttribute) {} func editor(_ editor: SQTextEditorView, contentHeightDidChange height: Int) {} func editorDidFocus(_ editor: SQTextEditorView) {} func editorDidTapDoneButton(_ editor: SQTextEditorView) {} func editor(_ editor: SQTextEditorView, cursorPositionDidChange position: SQEditorCursorPosition) {} } open class SQTextEditorView: UIView { public weak var delegate: SQTextEditorDelegate? public lazy var selectedTextAttribute = SQTextAttribute() public lazy var contentHeight: Int = 0 private enum JSFunctionType { case getHTML case insertHTML(html: String) case setSelection( startElementId: String, startIndex: Int, endElementId: String, endIndex: Int) case getSelectedText case setFormat(type: RichTextFormatType) case removeFormat(type: RichTextFormatType) case setTextColor(hex: String) case setTextBackgroundColor(hex: String) case setTextSize(size: Int) case insertImage(url: String) case makeLink(url: String) case removeLink case clear case focusEditor(isFocused: Bool) case getEditorHeight var name: String { switch self { case .getHTML: return "getHTML()" case .insertHTML(let html): let safetyHTML = html .replacingOccurrences(of: "\n", with: "\\n") .replacingOccurrences(of: "\r", with: "\\r") return "insertHTML('\(safetyHTML)')" case .setSelection(let sId, let s, let eId, let e): return "setTextSelection('\(sId)','\(s)','\(eId)','\(e)')" case .getSelectedText: return "getSelectedText()" case .setFormat(let type): return "setFormat('\(type.keyName)')" case .removeFormat(let type): return "removeFormat('\(type.keyName)')" case .setTextColor(let hex): return "setTextColor('\(hex)')" case .setTextBackgroundColor(let hex): return "setTextBackgroundColor('\(hex)')" case .setTextSize(let size): return "setFontSize('\(size)')" case .insertImage(let url): return "insertImage('\(url)')" case .makeLink(let url): return "makeLink('\(url)')" case .removeLink: return "removeLink()" case .clear: return "clear()" case .focusEditor(let isFocused): return "focusEditor('\(isFocused)')" case .getEditorHeight: return "getEditorHeight()" } } } public enum JSMessageName: String, CaseIterable { case fontInfo case format case isFocused case cursorPosition } private enum RichTextFormatType { case bold case italic case strikethrough case underline var keyName: String { switch self { case .bold: return "bold" case .italic: return "italic" case .strikethrough: return "strikethrough" case .underline: return "underline" } } } open lazy var webView: WKWebView = { let config = WKWebViewConfiguration() config.preferences = WKPreferences() config.preferences.minimumFontSize = 10 config.preferences.javaScriptEnabled = true config.preferences.javaScriptCanOpenWindowsAutomatically = false config.processPool = WKProcessPool() config.userContentController = WKUserContentController() JSMessageName.allCases.forEach { config.userContentController.add(self, name: $0.rawValue) } // inject css to html if customCss == nil, let cssURL = Bundle.module.url(forResource: "editor", withExtension: "css"), let css = try? String(contentsOf: cssURL, encoding: .utf8) { customCss = css } if let css = customCss { let cssStyle = """ javascript:(function() { var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; style.innerHTML = window.atob('\(encodeStringTo64(fromString: css))'); parent.appendChild(style)})() """ let cssScript = WKUserScript(source: cssStyle, injectionTime: .atDocumentEnd, forMainFrameOnly: false) config.userContentController.addUserScript(cssScript) } let _webView = WKWebView(frame: .zero, configuration: config) _webView.translatesAutoresizingMaskIntoConstraints = false _webView.navigationDelegate = self _webView.allowsLinkPreview = false _webView.setKeyboardRequiresUserInteraction(false) return _webView }() private lazy var editorEventQueue: OperationQueue = { let _editorEventQueue = OperationQueue() _editorEventQueue.maxConcurrentOperationCount = 1 return _editorEventQueue }() private var lastContentHeight: Int = 0 { didSet { if contentHeight != lastContentHeight { contentHeight = lastContentHeight delegate?.editor(self, contentHeightDidChange: contentHeight) } } } private var timer: RepeatingTimer? public var customCss: String? public init(customCss: String? = nil) { self.customCss = customCss super.init(frame: .zero) setupUI() setupEditor() } @available(*, unavailable) required public init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { timer = nil JSMessageName.allCases.forEach { webView.configuration .userContentController .removeScriptMessageHandler(forName: $0.rawValue) } } public func encodeStringTo64(fromString: String) -> String { let plainData = fromString.data(using: .utf8) return plainData?.base64EncodedString(options: []) ?? "" } // MARK: - Private Methods private func setupUI() { addSubview(webView) webView.topAnchor.constraint(equalTo: topAnchor).isActive = true webView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true webView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true webView.rightAnchor.constraint(equalTo: rightAnchor).isActive = true } private func setupEditor() { if let path = Bundle.module.path(forResource: "index", ofType: "html") { let url = URL(fileURLWithPath: path) let request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 5.0) webView.load(request) } } private func setFormat(_ type: RichTextFormatType, completion: ((_ error: Error?) -> ())?) { webView.evaluateJavaScript(JSFunctionType.setFormat(type: type).name, completionHandler: { _, error in completion?(error) }) } private func removeFormat(_ type: RichTextFormatType, completion: ((_ error: Error?) -> ())?) { webView.evaluateJavaScript(JSFunctionType.removeFormat(type: type).name, completionHandler: { _, error in completion?(error) }) } private func observerContentHeight() { timer = nil timer = RepeatingTimer(timeInterval: 0.2) timer?.eventHandler = { [weak self] in guard let self = `self` else { return } DispatchQueue.main.async { self.getEditorHeight() } } timer?.resume() } private func getEditorHeight() { webView.evaluateJavaScript(JSFunctionType.getEditorHeight.name, completionHandler: { [weak self] height, error in guard let self = `self` else { return } if let height = height as? Int, error == nil { self.lastContentHeight = height } }) } // MARK: - Public Methods /** Returns the HTML value of the editor in its current state. - Parameter html: HTML String. */ public func getHTML(completion: @escaping (_ html: String?) -> ()) { webView.evaluateJavaScript(JSFunctionType.getHTML.name, completionHandler: { value, _ in completion(value as? String) }) } /** Inserts an HTML fragment at the current cursor location, or replaces the selection if selected. The value supplied should not contain <body> tags or anything outside of that. - Parameter html: The html String to insert. - Parameter completion: The block to execute after the operation finishes. This takes an error of script evaluation as a parameter. You may specify nil for this parameter. */ public func insertHTML(_ html: String, completion: ((_ error: Error?) -> ())? = nil) { webView.evaluateJavaScript(JSFunctionType.insertHTML(html: html).name, completionHandler: { _, error in completion?(error) }) } /** Changes the current selection position. The selected range will be selected from the first node that type equal 'TEXT_NODE' under the input element id - Parameter startElementId: The element ID for range of start selection - Parameter startIndex: Sets the starting position of the element that the id you specified. - Parameter endElementId: The element ID for range of end selection - Parameter endIndex: Sets the ending position of the element that the id you specified. - Parameter completion: The block to execute after the operation finishes. This takes an error of script evaluation as a parameter. You may specify nil for this parameter. HTML: ``` <div id="a">123<br></div> <div id="b">456<br></div> ``` The selected text is `12` ``` setSelection(startElementId: a, startIndex: 0, endElementId: a, endIndex: 2) ``` The selected text is `34` ``` setSelection(startElementId: a, startIndex: 2, endElementId: b, endIndex: 1) ``` */ public func setTextSelection(startElementId: String, startIndex: Int, endElementId: String, endIndex: Int, completion: ((_ error: Error?) -> ())? = nil) { webView.evaluateJavaScript(JSFunctionType.setSelection(startElementId: startElementId, startIndex: startIndex, endElementId: endElementId, endIndex: endIndex).name, completionHandler: { _, error in completion?(error) }) } /** Returns the text currently selected in the editor. - Parameter text: Selected text. */ public func getSelectedText(completion: @escaping (_ text: String?) -> ()) { webView.evaluateJavaScript(JSFunctionType.getSelectedText.name, completionHandler: { value, _ in completion(value as? String) }) } /** Makes any non-bold currently selected text bold (by wrapping it in a 'b' tag), otherwise removes any bold formatting from the selected text. */ public func bold(completion: ((_ error: Error?) -> ())? = nil) { selectedTextAttribute.format.hasBold ? removeFormat(.bold, completion: completion) : setFormat(.bold, completion: completion) } /** Makes any non-italic currently selected text italic (by wrapping it in an 'i' tag), otherwise removes any italic formatting from the selected text. */ public func italic(completion: ((_ error: Error?) -> ())? = nil) { selectedTextAttribute.format.hasItalic ? removeFormat(.italic, completion: completion) : setFormat(.italic, completion: completion) } /** Makes any non-underlined currently selected text underlined (by wrapping it in a 'u' tag), otherwise removes any underline formatting from the selected text. */ public func underline(completion: ((_ error: Error?) -> ())? = nil) { selectedTextAttribute.format.hasUnderline ? removeFormat(.underline, completion: completion) : setFormat(.underline, completion: completion) } /** Makes any non-strikethrough currently selected text underlined (by wrapping it in a 'del' tag), otherwise removes any strikethrough formatting from the selected text. */ public func strikethrough(completion: ((_ error: Error?) -> ())? = nil) { selectedTextAttribute.format.hasStrikethrough ? removeFormat(.strikethrough, completion: completion) : setFormat(.strikethrough, completion: completion) } /** Sets the colour of the selected text. - Parameter color: The colour to set. */ public func setText(color: UIColor, completion: ((_ error: Error?) -> ())? = nil) { let hex = Helper.rgbColorToHex(color: color) webView.evaluateJavaScript(JSFunctionType.setTextColor(hex: hex).name, completionHandler: { _, error in completion?(error) }) } /** Sets the colour of the background of the selected text. - Parameter color: The colour to set. */ public func setText(backgroundColor: UIColor, completion: ((_ error: Error?) -> ())? = nil) { let hex = Helper.rgbColorToHex(color: backgroundColor) webView.evaluateJavaScript(JSFunctionType.setTextBackgroundColor(hex: hex).name, completionHandler: { _, error in completion?(error) }) } /** Sets the font size for the selected text. - Parameter size: A size to set. The absolute length units will be 'px' */ public func setText(size: Int, completion: ((_ error: Error?) -> ())? = nil) { webView.evaluateJavaScript(JSFunctionType.setTextSize(size: size).name, completionHandler: { _, error in completion?(error) }) } /** Inserts an image at the current cursor location. - Parameter url: The source path for the image. */ public func insertImage(url: String, completion: ((_ error: Error?) -> ())? = nil) { webView.evaluateJavaScript(JSFunctionType.insertImage(url: url).name, completionHandler: { _, error in completion?(error) }) } /** Makes the currently selected text a link. If no text is selected, the URL or email will be inserted as text at the current cursor point and made into a link. - Parameter url: The url or email to link to. */ public func makeLink(url: String, completion: ((_ error: Error?) -> ())? = nil) { webView.evaluateJavaScript(JSFunctionType.makeLink(url: url).name, completionHandler: { _, error in completion?(error) }) } /** Removes any link that is currently at least partially selected. */ public func removeLink(completion: ((_ error: Error?) -> ())? = nil) { webView.evaluateJavaScript(JSFunctionType.removeLink.name, completionHandler: { _, error in completion?(error) }) } /** Clear Editor's content. Method removes all Blocks and inserts new initial empty Block `<div><br></div>` */ public func clear(completion: ((_ error: Error?) -> ())? = nil) { webView.evaluateJavaScript(JSFunctionType.clear.name, completionHandler: { _, error in completion?(error) }) } /** The editor gained focus or lost focus */ public func focus(_ isFocused: Bool, completion: ((_ error: Error?) -> ())? = nil) { webView.evaluateJavaScript(JSFunctionType.focusEditor(isFocused: isFocused).name, completionHandler: { [weak self] _, error in if !isFocused { self?.webView.endEditing(true) } completion?(error) }) } } extension SQTextEditorView: WKNavigationDelegate { public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { observerContentHeight() delegate?.editorDidLoad(self) } } extension SQTextEditorView: WKScriptMessageHandler { public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { if let name = JSMessageName(rawValue: message.name) { let body: Any = message.body editorEventQueue.addOperation { [weak self] in guard let self = `self` else { return } switch name { case .format: if let dict = body as? [String: Bool], let data = try? JSONSerialization.data(withJSONObject: dict, options: []), let format = try? JSONDecoder().decode(SQTextAttributeFormat.self, from: data) { DispatchQueue.main.async { self.selectedTextAttribute.format = format self.delegate?.editor(self, selectedTextAttributeDidChange: self.selectedTextAttribute) } } case .fontInfo: if let dict = body as? [String: Any], let data = try? JSONSerialization.data(withJSONObject: dict, options: []), let fontInfo = try? JSONDecoder().decode(SQTextAttributeTextInfo.self, from: data) { DispatchQueue.main.async { self.selectedTextAttribute.textInfo = fontInfo self.delegate?.editor(self, selectedTextAttributeDidChange: self.selectedTextAttribute) } } case .isFocused: DispatchQueue.main.async { if let value = body as? Bool { value ? self.delegate?.editorDidFocus(self) : self.delegate?.editorDidTapDoneButton(self) } } case .cursorPosition: if let dict = body as? [String: Any], let data = try? JSONSerialization.data(withJSONObject: dict, options: []), let position = try? JSONDecoder().decode(SQEditorCursorPosition.self, from: data) { DispatchQueue.main.async { self.delegate?.editor(self, cursorPositionDidChange: position) } } } } } } } #endif
38.975652
179
0.544152
f4d4c78fa9bad40e80fb1b1b9cf3dd608cca5739
10,300
import Foundation protocol CollectionViewUpdaterDelegate: NSObjectProtocol { func collectionViewUpdater<T>(_ updater: CollectionViewUpdater<T>, didUpdate collectionView: UICollectionView) func collectionViewUpdater<T>(_ updater: CollectionViewUpdater<T>, updateItemAtIndexPath indexPath: IndexPath, in collectionView: UICollectionView) } class CollectionViewUpdater<T: NSFetchRequestResult>: NSObject, NSFetchedResultsControllerDelegate { let fetchedResultsController: NSFetchedResultsController<T> let collectionView: UICollectionView var isSlidingNewContentInFromTheTopEnabled: Bool = false var sectionChanges: [WMFSectionChange] = [] var objectChanges: [WMFObjectChange] = [] weak var delegate: CollectionViewUpdaterDelegate? var isGranularUpdatingEnabled: Bool = true // when set to false, individual updates won't be pushed to the collection view, only reloadData() required init(fetchedResultsController: NSFetchedResultsController<T>, collectionView: UICollectionView) { self.fetchedResultsController = fetchedResultsController self.collectionView = collectionView super.init() self.fetchedResultsController.delegate = self } deinit { self.fetchedResultsController.delegate = nil } public func performFetch() { do { try fetchedResultsController.performFetch() } catch let error { assert(false) DDLogError("Error fetching \(String(describing: fetchedResultsController.fetchRequest.predicate)) for \(String(describing: self.delegate)): \(error)") } sectionCounts = fetchSectionCounts() collectionView.reloadData() } @objc func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { sectionChanges = [] objectChanges = [] } @objc func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { let objectChange = WMFObjectChange() objectChange.fromIndexPath = indexPath objectChange.toIndexPath = newIndexPath objectChange.type = type objectChanges.append(objectChange) } @objc func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) { let sectionChange = WMFSectionChange() sectionChange.sectionIndex = sectionIndex sectionChange.type = type sectionChanges.append(sectionChange) } private var previousSectionCounts: [Int] = [] private var sectionCounts: [Int] = [] private func fetchSectionCounts() -> [Int] { let sections = fetchedResultsController.sections ?? [] return sections.map { $0.numberOfObjects } } @objc func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { previousSectionCounts = sectionCounts sectionCounts = fetchSectionCounts() guard isGranularUpdatingEnabled else { collectionView.reloadData() delegate?.collectionViewUpdater(self, didUpdate: self.collectionView) return } var didInsertFirstSection = false var didOnlyChangeItems = true var sectionDelta = 0 var objectsInSectionDelta = 0 var forceReload = false for sectionChange in sectionChanges { didOnlyChangeItems = false switch sectionChange.type { case .delete: guard sectionChange.sectionIndex < previousSectionCounts.count else { forceReload = true break } sectionDelta -= 1 case .insert: sectionDelta += 1 objectsInSectionDelta += sectionCounts[sectionChange.sectionIndex] if sectionChange.sectionIndex == 0 { didInsertFirstSection = true } default: break } } for objectChange in objectChanges { switch objectChange.type { case .delete: guard let fromIndexPath = objectChange.fromIndexPath, fromIndexPath.section < previousSectionCounts.count, fromIndexPath.item < previousSectionCounts[fromIndexPath.section] else { forceReload = true break } // there seems to be a very specific bug about deleting the item at index path 0,2 when there are 3 items in the section ¯\_(ツ)_/¯ if fromIndexPath.section == 0 && fromIndexPath.item == 2 && previousSectionCounts[0] == 3 { forceReload = true break } default: break } } let sectionCountsMatch = (previousSectionCounts.count + sectionDelta) == sectionCounts.count guard !forceReload, sectionCountsMatch, objectChanges.count < 1000 && sectionChanges.count < 10 else { // reload data for invalid changes & larger changes collectionView.reloadData() delegate?.collectionViewUpdater(self, didUpdate: self.collectionView) return } guard isSlidingNewContentInFromTheTopEnabled else { performBatchUpdates() return } guard let columnarLayout = collectionView.collectionViewLayout as? ColumnarCollectionViewLayout else { performBatchUpdates() return } guard !previousSectionCounts.isEmpty && didInsertFirstSection && sectionDelta > 0 else { if didOnlyChangeItems { columnarLayout.animateItems = true columnarLayout.slideInNewContentFromTheTop = false UIView.animate(withDuration: 0.8, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: .allowUserInteraction, animations: { self.performBatchUpdates() }, completion: nil) } else { columnarLayout.animateItems = false columnarLayout.slideInNewContentFromTheTop = false performBatchUpdates() } return } columnarLayout.animateItems = true columnarLayout.slideInNewContentFromTheTop = true UIView.animate(withDuration: 0.7 + 0.1 * TimeInterval(objectsInSectionDelta), delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: .allowUserInteraction, animations: { self.performBatchUpdates() }, completion: nil) } func performBatchUpdates() { let collectionView = self.collectionView collectionView.performBatchUpdates({ DDLogDebug("=== WMFBU BATCH UPDATE START \(String(describing: self.delegate)) ===") for objectChange in objectChanges { switch objectChange.type { case .delete: if let fromIndexPath = objectChange.fromIndexPath { DDLogDebug("WMFBU object delete: \(fromIndexPath)") collectionView.deleteItems(at: [fromIndexPath]) } else { assert(false, "unhandled delete") DDLogError("Unhandled delete: \(objectChange)") } case .insert: if let toIndexPath = objectChange.toIndexPath { DDLogDebug("WMFBU object insert: \(toIndexPath)") collectionView.insertItems(at: [toIndexPath]) } else { assert(false, "unhandled insert") DDLogError("Unhandled insert: \(objectChange)") } case .move: if let fromIndexPath = objectChange.fromIndexPath, let toIndexPath = objectChange.toIndexPath { DDLogDebug("WMFBU object move delete: \(fromIndexPath)") collectionView.deleteItems(at: [fromIndexPath]) DDLogDebug("WMFBU object move insert: \(toIndexPath)") collectionView.insertItems(at: [toIndexPath]) } else { assert(false, "unhandled move") DDLogError("Unhandled move: \(objectChange)") } break case .update: if let updatedIndexPath = objectChange.toIndexPath ?? objectChange.fromIndexPath { delegate?.collectionViewUpdater(self, updateItemAtIndexPath: updatedIndexPath, in: collectionView) } else { assert(false, "unhandled update") DDLogDebug("WMFBU unhandled update: \(objectChange)") } @unknown default: break } } for sectionChange in sectionChanges { switch sectionChange.type { case .delete: DDLogDebug("WMFBU section delete: \(sectionChange.sectionIndex)") collectionView.deleteSections(IndexSet(integer: sectionChange.sectionIndex)) case .insert: DDLogDebug("WMFBU section insert: \(sectionChange.sectionIndex)") collectionView.insertSections(IndexSet(integer: sectionChange.sectionIndex)) default: DDLogDebug("WMFBU section update: \(sectionChange.sectionIndex)") collectionView.reloadSections(IndexSet(integer: sectionChange.sectionIndex)) } } DDLogDebug("=== WMFBU BATCH UPDATE END ===") }) { (finished) in self.delegate?.collectionViewUpdater(self, didUpdate: collectionView) } } }
45.175439
215
0.602816
ac8c26ef9e533b2ca58db8674dbddc0401564ce6
746
import UIKit func imageOfSize(_ size: CGSize, _ whatToDraw:() -> () ) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, false, 0) whatToDraw() let result = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return result } func makeRoundedRectangleMaker(_ sz:CGSize) -> () -> UIImage { func f () -> UIImage { let im = imageOfSize(sz) { let p = UIBezierPath(roundedRect: CGRect(origin: CGPoint.zero, size: sz), cornerRadius: 8 ) p.stroke() } return im } return f } let maker = makeRoundedRectangleMaker(CGSize(width: 45, height: 20)) // maker() print(maker())
26.642857
85
0.58311
1a4393ac1be2f3567a0970fd0c977c03d9333154
2,473
// // UserAccoundDetailsResponseHandlerSpec.swift // CreatubblesAPIClient // // Copyright (c) 2017 Creatubbles Pte. Ltd. // // 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 Quick import Nimble @testable import CreatubblesAPIClient class UserAccoundDetailsResponseHandlerSpec: QuickSpec { override func spec() { describe("UserAccoundDetails Response Handler") { it("Should fetch AccountDetails when user is logged in") { guard let userIdentifier = TestConfiguration.testUserIdentifier else { return } let request = UserAccountDetailsRequest(userId: userIdentifier) let sender = TestComponentsFactory.requestSender waitUntil(timeout: TestConfiguration.timeoutShort) { done in sender.login(TestConfiguration.username, password: TestConfiguration.password) { (error: Error?) -> Void in expect(error).to(beNil()) sender.send(request, withResponseHandler:UserAccountDetailsResponseHandler { (accountDetails, error) -> (Void) in expect(accountDetails).notTo(beNil()) expect(error).to(beNil()) done() }) } } } } } }
44.963636
100
0.644561
91184110022729f3a29fd4069abbd1a02b094258
1,749
// // AlertController.swift // Flix // // Created by Hein Soe on 9/9/18. // Copyright © 2018 Hein Soe. All rights reserved. // import UIKit extension UIViewController { // MARK:FETCH MOVIES EXTENSIONS func fetchMovies (apiStr: String,success: @escaping (_ movies: [[String: Any]]) -> () ) { let url = URL(string: apiStr)! let request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 10) let session = URLSession(configuration: .default, delegate: nil, delegateQueue: OperationQueue.main) let task = session.dataTask(with: request) { (data, response, error) in // MARK:This will run when the network request return if let error = error { print(error.localizedDescription) let showAlert = UIAlertController(title: "Cannot Get Movies", message: "Internet appears to be offline", preferredStyle: .alert) let tryAgainAction = UIAlertAction (title: "Try Again!!", style: .default) { (action) in self.fetchMovies(apiStr: apiStr, success: success) } showAlert.addAction(tryAgainAction) self.present(showAlert, animated: true, completion: nil) } else if let data = data { let dataDictionary = try! JSONSerialization.jsonObject(with: data, options: []) as! [String: Any] let fetchedMovies = dataDictionary["results"] as! [[String: Any]] // MARK:WILL Do success here -- Movies WILL be set and table view WILL be reloaded. success(fetchedMovies) } } task.resume() } }
39.75
144
0.593482
ddf75955928fbca5b6ff123ad6652966177aa333
602
// // Cats.swift // MyFavoriteCats // // Created by Matheus Villaça on 23/02/22. // import Foundation struct Image: Codable { let url: URL } final class Cats: Codable, Equatable { let catBreed: String let imageCat: Image? private enum CodingKeys : String, CodingKey { case catBreed = "name" case imageCat = "image" } init(catBreed: String, imageCat: Image) { self.catBreed = catBreed self.imageCat = imageCat } static func == (lhs: Cats, rhs: Cats) -> Bool { return lhs.catBreed == rhs.catBreed } }
17.705882
51
0.591362
26713abaa7ef5376e0c63e6f8fbbe1a6848e60fb
5,847
// // CustomImageSliderViewController.swift // Sample App // // Created by Jelzon Monzon on 1/6/21. // Copyright © 2021 LiveLike. All rights reserved. // import EngagementSDK import Lottie import UIKit class CustomImageSliderViewController: Widget { private let model: ImageSliderWidgetModel let timer: CustomWidgetBarTimer = { let timer = CustomWidgetBarTimer() timer.translatesAutoresizingMaskIntoConstraints = false return timer }() var magnitudeIndicatorLeadingConstraint: NSLayoutConstraint? let magnitudeIndicator: AnimationView = { let animationView = AnimationView(name: "image-slider-avg") animationView.translatesAutoresizingMaskIntoConstraints = false return animationView }() private var thumbImages: [UIImage?] private var imageSliderView: CustomImageSliderView { return view as! CustomImageSliderView } override var dismissSwipeableView: UIView { return imageSliderView.headerView } override init(model: ImageSliderWidgetModel) { self.model = model self.thumbImages = .init(repeating: nil, count: model.options.count) super.init(model: model) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func loadView() { let imageSliderView = CustomImageSliderView() imageSliderView.titleLabel.text = model.question model.options.enumerated().forEach { index, option in URLSession.shared.dataTask(with: option.imageURL) { [weak self] data, _, error in guard let self = self else { return } if let error = error { print("Failed to load image from url: \(error)") return } DispatchQueue.main.async { if let data = data { if let image = UIImage(data: data) { let thumbSize = CGSize(width: 40, height: 40) UIGraphicsBeginImageContextWithOptions(thumbSize, false, 0.0) image.draw(in: CGRect(x: 0, y: 0, width: thumbSize.width, height: thumbSize.height)) guard let scaledImage: UIImage = UIGraphicsGetImageFromCurrentImageContext() else { return } UIGraphicsEndImageContext() self.thumbImages[index] = scaledImage self.updateThumbImage() } } } }.resume() } imageSliderView.slider.addTarget(self, action: #selector(sliderValueChanged), for: .valueChanged) imageSliderView.slider.addSubview(magnitudeIndicator) magnitudeIndicator.centerYAnchor.constraint(equalTo: imageSliderView.slider.centerYAnchor).isActive = true magnitudeIndicator.widthAnchor.constraint(equalToConstant: 20).isActive = true magnitudeIndicator.heightAnchor.constraint(equalToConstant: 40).isActive = true imageSliderView.addSubview(timer) timer.topAnchor.constraint(equalTo: imageSliderView.topAnchor).isActive = true timer.leadingAnchor.constraint(equalTo: imageSliderView.leadingAnchor).isActive = true timer.trailingAnchor.constraint(equalTo: imageSliderView.trailingAnchor).isActive = true timer.heightAnchor.constraint(equalToConstant: 5).isActive = true view = imageSliderView } override func viewDidLoad() { super.viewDidLoad() let newThumbImage = getThumbImage() imageSliderView.slider.setThumbImage(newThumbImage, for: .normal) model.delegate = self timer.play(duration: model.interactionTimeInterval) DispatchQueue.main.asyncAfter(deadline: .now() + model.interactionTimeInterval) { [weak self] in guard let self = self else { return } self.model.lockInVote(magnitude: Double(self.imageSliderView.slider.value)) { _ in self.updateMagnitudeIndicator(self.model.averageMagnitude) self.magnitudeIndicator.play() DispatchQueue.main.asyncAfter(deadline: .now() + 6) { self.delegate?.widgetDidEnterState(widget: self, state: .finished) } } } model.markAsInteractive() model.registerImpression() } func updateMagnitudeIndicator(_ magnitude: Double) { magnitudeIndicatorLeadingConstraint?.isActive = false let averageXPosition = CGFloat(magnitude) * imageSliderView.slider.bounds.width magnitudeIndicatorLeadingConstraint = magnitudeIndicator.centerXAnchor.constraint( equalTo: imageSliderView.slider.leadingAnchor, constant: averageXPosition ) magnitudeIndicatorLeadingConstraint?.isActive = true } @objc private func sliderValueChanged() { updateThumbImage() } private func updateThumbImage() { let newThumbImage = getThumbImage() imageSliderView.slider.setThumbImage(newThumbImage, for: .normal) } private func getThumbImage() -> UIImage? { if thumbImages.count == 1 { return thumbImages[0] } else { let imageIndex: Int = Int(round(imageSliderView.slider.value * Float(thumbImages.count - 1))) return thumbImages[imageIndex] } } } extension CustomImageSliderViewController: ImageSliderWidgetModelDelegate { func imageSliderWidgetModel(_ model: ImageSliderWidgetModel, averageMagnitudeDidChange averageMagnitude: Double) { DispatchQueue.main.async { [weak self] in guard let self = self else { return } self.updateMagnitudeIndicator(averageMagnitude) } } }
37.967532
120
0.648025
9cfa211f66e10161f2e10f2c31d2471f4d625073
1,075
// // ViewController.swift // RYDonutChart // // Created by Rahul Yadav on 14/04/19. // Copyright © 2019 RYTheDev. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var ourImageView: UIImageView! let imageBorderWidth:CGFloat = 2.0 @IBOutlet weak var piechartOverlayView: Piechart! var firstTimeFlagViewDidLayout = true override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if firstTimeFlagViewDidLayout { firstTimeFlagViewDidLayout = false ourImageView.layoutIfNeeded() ourImageView.layer.cornerRadius = ourImageView.bounds.width/2 ourImageView.layer.borderWidth = imageBorderWidth ourImageView.layer.borderColor = UIColor.white.cgColor piechartOverlayView.addLayers() } } }
25.595238
80
0.645581
bbb70d61a36289ebf72e1797b5b9931d9b2159ab
1,938
// // NSValidatedUserInterfaceItem.swift // // CotEditor // https://coteditor.com // // Created by 1024jp on 2018-12-26. // // --------------------------------------------------------------------------- // // © 2018 1024jp // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import AppKit protocol StatableItem: AnyObject { var state: NSControl.StateValue { get set } } extension NSMenuItem: StatableItem { } extension StatableToolbarItem: StatableItem { } extension NSValidatedUserInterfaceItem { var toolTip: String? { get { switch self { case let item as NSMenuItem: return item.toolTip case let item as NSToolbarItem: return item.toolTip case let item as NSCustomTouchBarItem: return item.toolTip default: // -> Only NSMenuItem and NSToolbarItem inherit NSValidatedUserInterfaceItem. preconditionFailure() } } set { switch self { case let item as NSMenuItem: item.toolTip = newValue case let item as NSToolbarItem: item.toolTip = newValue case let item as NSCustomTouchBarItem: item.toolTip = newValue default: preconditionFailure() } } } }
27.295775
93
0.579979
f7ded64504735706d129cee8433a36239fb2a513
5,687
// RUN: rm -rf %t // RUN: mkdir -p %t // RUN: %build-irgen-test-overlays // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t -I %S/../IDE/Inputs/custom-modules) %s -emit-ir -enable-swift-newtype | %FileCheck %s // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t -I %S/../IDE/Inputs/custom-modules) %s -emit-ir -enable-swift-newtype -O | %FileCheck %s -check-prefix=OPT import CoreFoundation import Foundation import Newtype // REQUIRES: objc_interop // Witness table for synthesized ClosedEnums : _ObjectiveCBridgeable. // CHECK: @_TWPVSC10ClosedEnums21_ObjectiveCBridgeable7Newtype = linkonce_odr // CHECK-LABEL: define %CSo8NSString* @_TF7newtype14getErrorDomainFT_VSC11ErrorDomain() public func getErrorDomain() -> ErrorDomain { // CHECK: load %CSo8NSString*, %CSo8NSString** getelementptr inbounds (%VSC11ErrorDomain, %VSC11ErrorDomain* {{.*}}@SNTErrOne return .one } // CHECK-LABEL: _TF7newtype6getFooFT_VCSo14NSNotification4Name public func getFoo() -> NSNotification.Name { return NSNotification.Name.Foo // CHECK: load {{.*}} @FooNotification // CHECK: ret } // CHECK-LABEL: _TF7newtype21getGlobalNotificationFSiSS public func getGlobalNotification(_ x: Int) -> String { switch x { case 1: return kNotification // CHECK: load {{.*}} @kNotification case 2: return Notification // CHECK: load {{.*}} @Notification case 3: return swiftNamedNotification // CHECK: load {{.*}} @kSNNotification default: return NSNotification.Name.bar.rawValue // CHECK: load {{.*}} @kBarNotification } // CHECK: ret } // CHECK-LABEL: _TF7newtype17getCFNewTypeValueFT6useVarSb_VSC9CFNewType public func getCFNewTypeValue(useVar: Bool) -> CFNewType { if (useVar) { return CFNewType.MyCFNewTypeValue // CHECK: load {{.*}} @MyCFNewTypeValue } else { return FooAudited() // CHECK: call {{.*}} @FooAudited() } // CHECK: ret } // CHECK-LABEL: _TF7newtype21getUnmanagedCFNewTypeFT6useVarSb_GVs9UnmanagedCSo8CFString_ public func getUnmanagedCFNewType(useVar: Bool) -> Unmanaged<CFString> { if (useVar) { return CFNewType.MyCFNewTypeValueUnaudited // CHECK: load {{.*}} @MyCFNewTypeValueUnaudited } else { return FooUnaudited() // CHECK: call {{.*}} @FooUnaudited() } // CHECK: ret } // Triggers instantiation of ClosedEnum : _ObjectiveCBridgeable // witness table. public func hasArrayOfClosedEnums(closed: [ClosedEnum]) { } // CHECK-LABEL: _TF7newtype11compareABIsFT_T_ public func compareABIs() { let new = getMyABINewType() let old = getMyABIOldType() takeMyABINewType(new) takeMyABIOldType(old) takeMyABINewTypeNonNull(new!) takeMyABIOldTypeNonNull(old!) let newNS = getMyABINewTypeNS() let oldNS = getMyABIOldTypeNS() takeMyABINewTypeNonNullNS(newNS!) takeMyABIOldTypeNonNullNS(oldNS!) // Make sure that the calling conventions align correctly, that is we don't // have double-indirection or anything else like that // CHECK: declare %struct.__CFString* @getMyABINewType() // CHECK: declare %struct.__CFString* @getMyABIOldType() // // CHECK: declare void @takeMyABINewType(%struct.__CFString*) // CHECK: declare void @takeMyABIOldType(%struct.__CFString*) // // CHECK: declare void @takeMyABINewTypeNonNull(%struct.__CFString*) // CHECK: declare void @takeMyABIOldTypeNonNull(%struct.__CFString*) // // CHECK: declare %0* @getMyABINewTypeNS() // CHECK: declare %0* @getMyABIOldTypeNS() // // CHECK: declare void @takeMyABINewTypeNonNullNS(%0*) // CHECK: declare void @takeMyABIOldTypeNonNullNS(%0*) } // OPT-LABEL: define i1 @_TF7newtype12compareInitsFT_Sb public func compareInits() -> Bool { let mf = MyInt(rawValue: 1) let mfNoLabel = MyInt(1) let res = mf.rawValue == MyInt.one.rawValue && mfNoLabel.rawValue == MyInt.one.rawValue // OPT: [[ONE:%.*]] = load i32, i32*{{.*}}@kMyIntOne{{.*}}, align 4 // OPT-NEXT: [[COMP:%.*]] = icmp eq i32 [[ONE]], 1 takesMyInt(mf) takesMyInt(mfNoLabel) takesMyInt(MyInt(rawValue: kRawInt)) takesMyInt(MyInt(kRawInt)) // OPT: tail call void @takesMyInt(i32 1) // OPT-NEXT: tail call void @takesMyInt(i32 1) // OPT-NEXT: [[RAWINT:%.*]] = load i32, i32*{{.*}} @kRawInt{{.*}}, align 4 // OPT-NEXT: tail call void @takesMyInt(i32 [[RAWINT]]) // OPT-NEXT: tail call void @takesMyInt(i32 [[RAWINT]]) return res // OPT-NEXT: ret i1 [[COMP]] } // CHECK-LABEL: anchor // OPT-LABEL: anchor public func anchor() -> Bool { return false } class ObjCTest { // CHECK-LABEL: define hidden %0* @_TToFC7newtype8ObjCTest19optionalPassThroughfGSqVSC11ErrorDomain_GSqS1__ // CHECK: [[CASTED:%.+]] = ptrtoint %0* %2 to i{{32|64}} // CHECK: [[RESULT:%.+]] = call i{{32|64}} @_TFC7newtype8ObjCTest19optionalPassThroughfGSqVSC11ErrorDomain_GSqS1__(i{{32|64}} [[CASTED]], %C7newtype8ObjCTest* {{%.+}}) // CHECK: [[OPAQUE_RESULT:%.+]] = inttoptr i{{32|64}} [[RESULT]] to %0* // CHECK: ret %0* [[OPAQUE_RESULT]] // CHECK: {{^}$}} // OPT-LABEL: define hidden %0* @_TToFC7newtype8ObjCTest19optionalPassThroughfGSqVSC11ErrorDomain_GSqS1__ // OPT: ret %0* %2 // OPT: {{^}$}} @objc func optionalPassThrough(_ ed: ErrorDomain?) -> ErrorDomain? { return ed } // CHECK-LABEL: define hidden i32 @_TToFC7newtype8ObjCTest18integerPassThroughfVSC5MyIntS1_ // CHECK: [[RESULT:%.+]] = call i32 @_TFC7newtype8ObjCTest18integerPassThroughfVSC5MyIntS1_(i32 %2, %C7newtype8ObjCTest* {{%.+}}) // CHECK: ret i32 [[RESULT]] // CHECK: {{^}$}} // OPT-LABEL: define hidden i32 @_TToFC7newtype8ObjCTest18integerPassThroughfVSC5MyIntS1_ // OPT: ret i32 %2 // OPT: {{^}$}} @objc func integerPassThrough(_ num: MyInt) -> MyInt { return num } }
35.54375
169
0.699666
fed80e906ce53e295ac470ec933a58d1096b0894
3,024
import CommandLineKit import Foundation import RomeKit import Alamofire let env = ProcessInfo.processInfo.environment if let baseUrl = env["ROME_ENDPOINT"], let apiKey = env["ROME_KEY"] { let bootstrap = RomeKit.Bootstrap.init(baseUrl: baseUrl, apiKey: apiKey) bootstrap?.start() } else { print("Environment variables ROME_ENDPOINT & ROME_KEY not set") } let cli = CommandLine() var build = BoolOption(shortFlag: "b", longFlag: "build", helpMessage: "Fetches builds from Rome server and builds the rest using Carthage") let platform = StringOption(shortFlag: "p", longFlag: "platform", required: false, helpMessage: "Choose between: osx,ios,watchos,tvos") let upload = BoolOption(shortFlag: "u", longFlag: "upload", helpMessage: "Runs the archive command on every repository and uploads the specific version on Rome server") let uploadSelf = MultiStringOption(shortFlag: "s", longFlag: "self", required: false, helpMessage: "Builds & uploads self, requires product name & revision parameters") let archiveUpload = MultiStringOption(shortFlag: "a", longFlag: "archive", helpMessage: "Archive & uploads only self, requires product name & revision parameters") let help = BoolOption(shortFlag: "h", longFlag: "help", helpMessage: "Gives a list of supported operations") cli.addOptions(build, platform, upload, uploadSelf, archiveUpload, help) do { try cli.parse() let additionalArguments = cli.unparsedArguments.filter {$0 != "--"} if build.value { BuildCommand().build(platforms: platform.value, additionalArguments: additionalArguments) } else if upload.value { if let uploadSelfParameters = uploadSelf.value { if uploadSelfParameters.count == 2 { UploadSelfCommand().upload(productName: uploadSelfParameters[0], revision: uploadSelfParameters[1], platforms: platform.value, additionalArguments: additionalArguments) } else { print("Uploading self requires product name & revision parameters") } } else { UploadCommand().upload(platforms: platform.value, additionalArguments: additionalArguments) } } else if let archiveParameters = archiveUpload.value { if archiveParameters.count == 2 { ArchiveCommand().upload(productName: archiveParameters[0], revision: archiveParameters[1], platforms: platform.value) } else { print("Uploading self requires product name & revision parameters") } } else { HelpCommand().printHelp() } } catch { cli.printUsage(error) exit(EX_USAGE) }
40.32
184
0.609458
1affb5502edce512b1138f8486624de57bf449ca
492
// 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 // RUN: not --crash %target-swift-frontend %s -emit-ir extension CountableRange{{}{}protocol P{typealias a:A{}func 丏 protocol A:CountableRange
44.727273
79
0.760163
f433776c3212713c1832ecdb8214ce0b2017958e
620
// // Playlist.swift // YoutubeApp // // Created by David Thorn on 01.07.19. // Copyright © 2019 David Thorn. All rights reserved. // import Foundation public struct PageInfo: Codable { public let totalResults: Int public let resultsPerPage: Int } public struct Playlists: Codable { public let kind: String public let etag: String public let items: [Playlist] public let pageInfo: PageInfo } public struct Playlist: Codable { public let kind: String public let etag: String public let id: String public let snippet: Snippet public let contentDetails: ContentDetails }
20.666667
54
0.706452
1aaf96e62f5164b2e8fd723548064091bc1a7739
5,232
// File created from ScreenTemplate // $ createScreen.sh .KeyBackup/Recover/PrivateKey KeyBackupRecoverFromPrivateKey /* Copyright 2020 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import UIKit final class KeyBackupRecoverFromPrivateKeyViewController: UIViewController { // MARK: - Constants // MARK: - Properties // MARK: Outlets @IBOutlet private weak var shieldImageView: UIImageView! @IBOutlet private weak var informationLabel: UILabel! // MARK: Private private var viewModel: KeyBackupRecoverFromPrivateKeyViewModelType! private var theme: Theme! private var errorPresenter: MXKErrorPresentation! private var activityPresenter: ActivityIndicatorPresenter! // MARK: - Setup class func instantiate(with viewModel: KeyBackupRecoverFromPrivateKeyViewModelType) -> KeyBackupRecoverFromPrivateKeyViewController { let viewController = StoryboardScene.KeyBackupRecoverFromPrivateKeyViewController.initialScene.instantiate() viewController.viewModel = viewModel viewController.theme = ThemeService.shared().theme return viewController } // MARK: - Life cycle override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.title = VectorL10n.keyBackupRecoverTitle self.setupViews() self.activityPresenter = ActivityIndicatorPresenter() self.errorPresenter = MXKErrorAlertPresentation() self.registerThemeServiceDidChangeThemeNotification() self.update(theme: self.theme) self.viewModel.viewDelegate = self self.viewModel.process(viewAction: .recover) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) } override var preferredStatusBarStyle: UIStatusBarStyle { return self.theme.statusBarStyle } // MARK: - Private private func registerThemeServiceDidChangeThemeNotification() { NotificationCenter.default.addObserver(self, selector: #selector(themeDidChange), name: .themeServiceDidChangeTheme, object: nil) } @objc private func themeDidChange() { self.update(theme: ThemeService.shared().theme) } private func setupViews() { let cancelBarButtonItem = MXKBarButtonItem(title: VectorL10n.cancel, style: .plain) { [weak self] in self?.cancelButtonAction() } self.navigationItem.rightBarButtonItem = cancelBarButtonItem let shieldImage = Asset.Images.keyBackupLogo.image.withRenderingMode(.alwaysTemplate) self.shieldImageView.image = shieldImage self.informationLabel.text = VectorL10n.keyBackupRecoverFromPrivateKeyInfo } private func update(theme: Theme) { self.theme = theme self.view.backgroundColor = theme.headerBackgroundColor if let navigationBar = self.navigationController?.navigationBar { theme.applyStyle(onNavigationBar: navigationBar) } self.shieldImageView.tintColor = theme.textPrimaryColor self.informationLabel.textColor = theme.textPrimaryColor } private func render(viewState: KeyBackupRecoverFromPrivateKeyViewState) { switch viewState { case .loading: self.renderLoading() case .loaded: self.renderLoaded() case .error(let error): self.render(error: error) } } private func renderLoading() { self.activityPresenter.presentActivityIndicator(on: self.view, animated: true) } private func renderLoaded() { self.activityPresenter.removeCurrentActivityIndicator(animated: true) } private func render(error: Error) { self.activityPresenter.removeCurrentActivityIndicator(animated: true) self.errorPresenter.presentError(from: self, forError: error, animated: true, handler: nil) } // MARK: - Actions private func cancelButtonAction() { self.viewModel.process(viewAction: .cancel) } } // MARK: - KeyBackupRecoverFromPrivateKeyViewModelViewDelegate extension KeyBackupRecoverFromPrivateKeyViewController: KeyBackupRecoverFromPrivateKeyViewModelViewDelegate { func keyBackupRecoverFromPrivateKeyViewModel(_ viewModel: KeyBackupRecoverFromPrivateKeyViewModelType, didUpdateViewState viewSate: KeyBackupRecoverFromPrivateKeyViewState) { self.render(viewState: viewSate) } }
32.90566
178
0.702026
e6bfb9493af883711e5a049366a624b38dd7a1df
1,925
// // MapButtons.swift // Open Conquest // // Created by Zach Wild on 1/8/20. // Copyright © 2020 Zach Wild. All rights reserved. // import Foundation import SpriteKit enum GameSceneButtonTypeEnum { case attack case view case message } class MapButton: SKSpriteNode { init(buttonType: GameSceneButtonTypeEnum) { var texture: SKTexture? switch buttonType { case .attack: texture = SKTexture(imageNamed: "attack-city-button") case .view: texture = SKTexture(imageNamed: "view-city-button") case .message: texture = SKTexture(imageNamed: "message-city-button") } super.init(texture: texture, color: UIColor.clear, size: CGSize(width: 64, height: 64)) // set initial properties zPosition = 1 isHidden = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class MessageCityButton: MapButton { init() { super.init(buttonType: .message) // name property is the only unique identifier used to determine which button is pressed name = GameSceneNodeNames.messageCityButton.rawValue } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class AttackCityButton: MapButton { init() { super.init(buttonType: .attack) name = GameSceneNodeNames.attackCityButton.rawValue } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class ViewCityButton: MapButton { init() { super.init(buttonType: .view) name = GameSceneNodeNames.viewCityButton.rawValue } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
24.367089
96
0.626494
234092f6b64da6354b1227bdd4179c7feed31d3b
2,122
import UIKit // Inicjalizator "convenience" (convenience initializaters) /* Jak wiadomo metoda init służy do inicjalizacji pól obiektów podczas ich tworzenia wartościami domyślnymi Czasami jednak chcielibyśmy mieć wiele możliwości inicjalizacji, stąd też możemy utworzyć wiele metod init z różnymi parametrami. Wynika to z tego, że czasami nie wiemy jakie wartości powinny być zainicjalizowane wraz z tworzeniem nowego obiektu. Init która będzie miała maksymalną ilość parametrów to w Swift przyjmuje nazwę "Designated" (pol. oznaczony?) */ class Traktor { let iloscKM: Int let kolor: String // piszemy metodę init, która inicjalizuje 2 parametry, czyli maksymalną ich ilość // taka forma nazywa się "Designated" init(iloscKM: Int, kolor: String) { self.iloscKM = iloscKM self.kolor = kolor } // piszemy metodę init, która przyjmuje tylko jeden parametr - jego nazwa to "convenience" convenience init(iloscKM: Int) { // następnie nasza metoda init, wywołuje metodę convenience i przekazuje w parametrze argumenty do niej a podczas tworzenia obiektu, drugi parametr (w naszym przypadku kolor) przyjmie wartość domyślną self.init(iloscKM: iloscKM, kolor: "czarny") } // tworzymy kolejny inicjalizator convenience który nie przyjmuje nic w argumencie convenience init() { // poniższe wartości zostaną przekazane jako argument do bazowego inicjalizatora (Designated) self.init(iloscKM: 100, kolor: "niebieski") } } // tworzymy obiekt bez żadnego parametru, jak widać został utworzony z wartościami domyślnymi naszego ostatniego konstruktora let malyTraktor = Traktor() //tworzę obiekt używając init z jednym parametrem, jak widać drugi argument został przekazany jako domyślny z tego init let sredniTraktor = Traktor(iloscKM: 200) // tworzę obiekt używając nasz główny init let duzyTraktor = Traktor(iloscKM: 900, kolor: "zielony") //używanie metody init oraz convinience init możemy porównać
25.878049
246
0.715834
50f5984310d348db011429d7292d45f798960b51
682
// // PreCalculateTextHeight.swift // swifttips // // Created by Aaron on 26/7/2016. // Copyright © 2016 sightcorner. All rights reserved. // import Foundation import UIKit /** 计算在给定的文字类型和宽度限制下,文本将会占到的高度 - parameter text: 文本文字 - parameter font: 字体类型 - parameter width: 宽度 - returns: 文本的高度 */ func preCalculateTextHeight(text: String, font: UIFont, width: CGFloat) -> CGFloat { let label:UILabel = UILabel(frame: CGRect.init(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude)) label.numberOfLines = 0 label.lineBreakMode = .byWordWrapping label.font = font label.text = text label.sizeToFit() return label.frame.height }
22.733333
118
0.702346
d7221f8ec988e24757914e4d69615ac24f20a531
28
// Empty swift source file.
14
27
0.714286
e4a9cea631a5524664dd2d5a09fd390ef22c4dad
3,253
// // TwitterClient.swift // Twitter // // Created by Fatama on 2/24/16. // Copyright © 2016 Fatama. All rights reserved. // import UIKit import BDBOAuth1Manager class TwitterClient: BDBOAuth1SessionManager { static let sharedInstance = TwitterClient(baseURL: NSURL(string: "https://api.twitter.com")!, consumerKey: "xLvqcGypG6hdHhj3Djs5HyUuL", consumerSecret: "eykSPl1QgAwwwVGfbDVuLkSuQ1FXE4Sa2xMyrbCnVd7Xn0PcVd") var loginSuccess: (() -> ())? var loginFailure: ((NSError) -> ())? func login (success: () -> (), failure: (NSError) -> ()) { loginSuccess = success loginFailure = failure TwitterClient.sharedInstance.deauthorize() TwitterClient.sharedInstance.fetchRequestTokenWithPath("oauth/request_token", method: "GET", callbackURL: NSURL(string: "mytwitterdemo://oauth"), scope: nil, success: { (requestToken: BDBOAuth1Credential!) -> Void in let url = NSURL(string: "https://api.twitter.com/oauth/authorize?oauth_token=\(requestToken.token)")! UIApplication.sharedApplication().openURL(url) }) { (error: NSError!) -> Void in print("error: \(error.localizedDescription)") self.loginFailure?(error) } } func logout () { User.currentUser = nil deauthorize() NSNotificationCenter.defaultCenter().postNotificationName(User.userDidLogoutNotification, object: nil) } func handleOpenUrl (url: NSURL) { let requestToken = BDBOAuth1Credential(queryString: url.query) fetchAccessTokenWithPath("oauth/access_token", method: "POST", requestToken: requestToken, success: { (accessToken:BDBOAuth1Credential!) -> Void in self.currentAccount({ (user: User) -> () in User.currentUser = user self.loginSuccess?() }, failure: { (error: NSError) -> () in self.loginFailure?(error) }) }) { (error: NSError!) -> Void in print ("error: \(error.localizedDescription)") self.loginFailure?(error) } } func homeTimeLine(success: ([Tweet]) -> (), failure: (NSError) -> ()) { GET("1.1/statuses/home_timeline.json", parameters: nil, progress: nil, success: { (task: NSURLSessionDataTask, response: AnyObject?) -> Void in let dictionaries = response as! [NSDictionary] let tweets = Tweet.tweetsWithArray(dictionaries) success(tweets) }, failure: { (task: NSURLSessionDataTask?, error: NSError) -> Void in failure(error) }) } func currentAccount(success: (User) -> (), failure: (NSError) -> ()) { GET("1.1/account/verify_credentials.json", parameters: nil, progress: nil, success: { (task: NSURLSessionDataTask, response: AnyObject?) -> Void in print("account: \(response)") let userDictionary = response as! NSDictionary let user = User(dictionary: userDictionary) success (user) }, failure: { (task: NSURLSessionDataTask?, error: NSError) -> Void in failure (error) }) } }
39.192771
224
0.603136
d5b6c3377bf62c5c62bc00a80f38fa45a7f805a8
981
import Foundation import UIKit // Defining enum for throwing error // throw RangeError.NotInRange... is used to throw the error enum RangeError: Error { case NotInRange(String) } // Start of class Calculator class Calculator { // Start of function power func power(n: Int, p: Int) throws -> Int { // Add your code here guard n >= 0 && p >= 0 else { let strError = "n and p should be non-negative" throw RangeError.NotInRange(strError) } let result = Int(pow(Double(n), Double(p))) return result } // End of function power } // End of class Calculator let myCalculator = Calculator() let t = Int(readLine()!)! for _ in 0..<t { let np = readLine()!.components(separatedBy: " ").map { Int($0)! } let n = np[0] let p = np[1] do { let ans = try myCalculator.power(n: n, p: p) print(ans) } catch let RangeError.NotInRange(errorMsg) { print(errorMsg) } }
25.153846
70
0.601427
89204c43f044c4f28764c4e55cffba9a3ba6a8b6
2,749
// // EventsListViewController.swift // Eventer // // Created by Yaroslav Magin on 06/06/2021. // Copyright © 2021 Marinmir Ltd. All rights reserved. // import RxCocoa import RxSwift import UIKit final class EventsListViewController: UIViewController { // MARK: - Private properties private let disposeBag = DisposeBag() private let viewModel: EventsListViewModelBindable private var events: [EventCardViewModel] = [] // MARK: - Initializers init(viewModel: EventsListViewModelBindable) { self.viewModel = viewModel super.init(nibName: nil, bundle: nil) } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Public methods override func loadView() { super.loadView() let view = EventsListView() view.bind(to: viewModel) self.view = view view.dataSource = self view.delegate = self } override func viewDidLoad() { super.viewDidLoad() viewModel.events.drive(onNext: { events in self.events = events (self.view as? EventsListView)?.reload() }).disposed(by: disposeBag) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tabBarController?.tabBar.isHidden = true tabBarController?.tabBar.isTranslucent = true } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) tabBarController?.tabBar.isHidden = false tabBarController?.tabBar.isTranslucent = false } } extension EventsListViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return events.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: EventCollectionCell.cellReuseIdentifier, for: indexPath) as? EventCollectionCell else { return UICollectionViewCell() } cell.configure(with: events[indexPath.row]) cell.didTapCell = { self.viewModel.onEventTap(index: indexPath.row) } return cell } } extension EventsListViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { collectionView.deselectItem(at: indexPath, animated: false) viewModel.onEventTap(index: indexPath.row) } }
28.340206
168
0.664605
6274e87b153e5b35a00568a2adc7089bd3b904d1
3,198
/******************************************************************************* * Copyright (c) 2016 William Arthur Hood * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished * to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ******************************************************************************/ import Foundation public class ConjoinedControls : WebInterfaceControl { private var orientation: ConjoinedControlsOrientation = ConjoinedControlsOrientation.AlphaAbove var contentAlpha: WebInterfaceControl! = nil var contentOmega: WebInterfaceControl! = nil init(alpha: WebInterfaceControl, omega: WebInterfaceControl, position: ConjoinedControlsOrientation) { contentAlpha = alpha; contentOmega = omega; orientation = position; } public var htmlRendition : String { var result: String = "<table border=\"0\">" switch (orientation) { case ConjoinedControlsOrientation.AlphaAbove: result.append("<tr>") result.append(contentAlpha.htmlRendition) result.append("</tr><tr>") result.append(contentOmega.htmlRendition) result.append("</tr>") break; case ConjoinedControlsOrientation.AlphaBelow: result.append("<tr>") result.append(contentOmega.htmlRendition) result.append("</tr><tr>") result.append(contentAlpha.htmlRendition) result.append("</tr>") break; case ConjoinedControlsOrientation.AlphaLeft: result.append("<tr><td>") result.append(contentAlpha.htmlRendition) result.append("</td><td>&nbsp;</td><td>") result.append(contentOmega.htmlRendition) result.append("</td></tr>") break; case ConjoinedControlsOrientation.AlphaRight: result.append("<tr><td>") result.append(contentOmega.htmlRendition) result.append("</td><td>&nbsp;</td><td>") result.append(contentAlpha.htmlRendition) result.append("</td></tr>") break; } result.append("</table>"); return result } }
42.078947
106
0.627267
08d862c72671a821ef456068273f56885465c622
1,624
// // MGTableViewEmptySupport.swift // mgbaseproject // // Created by Magical Water on 2018/2/19. // Copyright © 2018年 Magical Water. All rights reserved. // import UIKit //可以在資料數量為0時顯示資料為空提示文字 public class MGTableViewEmptySupport: UITableView { @IBInspectable var textSize: CGFloat = 20 { didSet { if let label = emptyLabel { label.font = label.font.withSize(textSize) } } } @IBInspectable var textColor: UIColor = UIColor.white { didSet { if let label = emptyLabel { label.textColor = textColor } } } var emptyLabel: UILabel! public override func didMoveToSuperview() { if emptyLabel == nil { createEmptyLabel(superview!) } } override init(frame: CGRect, style: UITableViewStyle) { super.init(frame: frame, style: style) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } private func createEmptyLabel(_ inView: UIView) { emptyLabel = UILabel(frame: self.bounds) inView.addSubview(emptyLabel) emptyLabel.font = emptyLabel?.font.withSize(textSize) emptyLabel.textColor = textColor emptyLabel.textAlignment = .center emptyLabel.translatesAutoresizingMaskIntoConstraints = false emptyLabel.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true emptyLabel.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true } override public func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { endEditing(true) } }
27.525424
88
0.662562
280fbe0e92d5b9c39eba4651092f0db768160f24
3,406
// // TweetViewController.swift // Twitter Client // // Created by Sean McRoskey on 4/14/17. // Copyright © 2017 codepath. All rights reserved. // import UIKit import ARSLineProgress class TweetViewController: UIViewController { private static let dateFormatter = DateFormatter() @IBOutlet weak var authorNameLabel: UILabel! @IBOutlet weak var authorImageView: UIImageView! @IBOutlet weak var authorHandleLabel: UILabel! @IBOutlet weak var tweetTextLabel: UILabel! @IBOutlet weak var createdAtLabel: UILabel! @IBOutlet weak var numberFavoritesLabel: UILabel! @IBOutlet weak var numberTweetsLabel: UILabel! @IBOutlet weak var favoritedButton: UIButton! var tweet: Tweet? { didSet{ if (self.isViewLoaded){ updateViewsWithCurrentTweet() } } } override func viewDidLoad() { super.viewDidLoad() TweetViewController.dateFormatter.dateStyle = .medium TweetViewController.dateFormatter.timeStyle = .medium updateViewsWithCurrentTweet() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let navController = segue.destination as? UINavigationController { let replyTweetController = navController.topViewController as! NewTweetViewController replyTweetController.isInReplyTo = self.tweet } } func updateViewsWithCurrentTweet(){ if let tweet = tweet { authorNameLabel.text = tweet.author.name authorHandleLabel.text = tweet.author.handle tweetTextLabel.text = tweet.fullDescription createdAtLabel.text = TweetViewController.dateFormatter.string(from: tweet.createdAtDate) authorImageView.setImageWith(tweet.author.profileImageUrl) numberTweetsLabel.text = "\(tweet.numberOfRetweets)" numberFavoritesLabel.text = "\(tweet.numberOfFavorites)" favoritedButton.imageView?.image = tweet.favorited ? #imageLiteral(resourceName: "twitter_favorite_on") : #imageLiteral(resourceName: "twitter_favorite") } } @IBAction func onReplyButton(_ sender: Any) { } @IBAction func onRetweetButton(_ sender: Any) { User.current!.retweet(tweet!, completion: { (updatedTweet) in self.tweet = updatedTweet self.updateViewsWithCurrentTweet() }) { (error) in ARSLineProgress.showFail() } } @IBAction func onFavoriteButton(_ sender: Any) { User.current!.favorite(tweet!, completion: { (updatedTweet) in self.tweet = updatedTweet self.updateViewsWithCurrentTweet() }) { (error) in ARSLineProgress.showFail() } } /* // 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. } */ }
33.392157
165
0.657369
50026674656eb230ae0c49e490a1308575f19c18
1,329
import Foundation // The Number of case in enum and its method tends to swell. // Use struct and static constant instead. // BEFORE public enum SushiEnum: String { case マグロ case サバ case サケ // NOTE: Defined as func because lizard doesn't calcurate CCN in computed property. public func enName() -> String { switch self { case .マグロ: return "tuna" case .サバ: return "mackerel" case .サケ: return "salmon" } } public func price() -> Int { switch self { case .マグロ: return 380 case .サバ: return 270 case .サケ: return 160 } } } // AFTER public struct SushiStruct { public let jaName: String public let enName: String public let price: Int private init( jaName: String, enName: String, price: Int ) { self.jaName = jaName self.enName = enName self.price = price } } extension SushiStruct { public static let tuna: SushiStruct = .init(jaName: "マグロ", enName: "tuna", price: 380) public static let mackerel: SushiStruct = .init(jaName: "サバ", enName: "mackerel", price: 270) public static let salmon: SushiStruct = .init(jaName: "サケ", enName: "salmon", price: 160) }
21.435484
97
0.571859
1e7974d6cb86f6dbc738a9cc1f7394203e7e65bf
4,754
// // GameViewController.swift // YellowZB // // Created by zzr on 2018/4/3. // Copyright © 2018年 zzr. All rights reserved. // import UIKit private let kEdgeMargin: CGFloat = 10 private let kItemW: CGFloat = (kScreenW - 2 * kEdgeMargin)/3 private let kItemH: CGFloat = kItemW * 11/10 private let kHeaderViewH: CGFloat = 50.0 private let kGameViewH: CGFloat = 90 private let kGameCellID = "kGameCellID" private let kHeaderViewID = "kHeaderViewID" class GameViewController: BaseViewController { //MARK:- 懒加载属性 fileprivate lazy var gameVM: GameViewModel = GameViewModel() fileprivate lazy var collectionView: UICollectionView = {[unowned self] in //1.创建布局 let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: kItemW, height: kItemH) layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.sectionInset = UIEdgeInsets(top: 0, left: kEdgeMargin, bottom: 0, right: kEdgeMargin) layout.headerReferenceSize = CGSize(width: kScreenW, height: kHeaderViewH) //2.创建UICollectionView let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout) collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth] collectionView.register(UINib(nibName: "CollectionGameCell", bundle: nil), forCellWithReuseIdentifier: kGameCellID) collectionView.register(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID) collectionView.dataSource = self collectionView.backgroundColor = UIColor.white return collectionView }() fileprivate lazy var topHeaderView: CollectionHeaderView = { let headerView = CollectionHeaderView.collectionHeaderView() headerView.frame = CGRect(x: 0, y: -(kHeaderViewH + kGameViewH), width: kScreenW, height: kHeaderViewH) headerView.iconImage.image = UIImage(named: "Img_orange") headerView.titleLabel.text = "常见" headerView.moreBtn.isHidden = true return headerView }() fileprivate lazy var gameView: RecommendGameView = { let gameView = RecommendGameView.recommendGameView() gameView.frame = CGRect(x: 0, y: -kGameViewH, width: kScreenW, height: kGameViewH) return gameView }() //MARK:- 系统回调 override func viewDidLoad() { super.viewDidLoad() setUpUI() loadData() } //MARK:- 设置ui界面 override func setUpUI() { //给contentView赋值 contentView = collectionView //添加uicolltionview view.addSubview(collectionView) //2.添加顶部的headerview collectionView.addSubview(topHeaderView) //3.将常用游戏的View添加到collectionView中 collectionView.addSubview(gameView) //设置collectionview内边距 collectionView.contentInset = UIEdgeInsets(top: kHeaderViewH + kGameViewH, left: 0, bottom: 0, right: 0) super.setUpUI() } } extension GameViewController { } //MARK:- 请求数据 extension GameViewController { fileprivate func loadData() { gameVM.loadAllGameData { //1.展示全部游戏 self.collectionView.reloadData() //2.展示常用游戏 self.gameView.groups = Array(self.gameVM.games[0..<10]) self.loadDataFinished() } } } //MARK:- 准守UICollectionViewDataSource的数据源代理 extension GameViewController : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return gameVM.games.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kGameCellID, for: indexPath) as! CollectionGameCell cell.baseGame = gameVM.games[indexPath.item] return cell } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { //1.取出headerview let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kHeaderViewID, for: indexPath) as! CollectionHeaderView //2.设置属性 headerView.titleLabel.text = "全部" headerView.iconImage.image = UIImage(named: "Img_orange") headerView.moreBtn.isHidden = true return headerView } }
33.013889
185
0.669752
d90ccf4ad57f6790f96eb68e21709b2999f6cb32
34,088
import Proximiio; import ProximiioMapbox; import ProximiioProcessor; import SwiftyJSON; enum ProximiioMapboxNativeError: Error { case destinationNotSpecified case destinationNotFound } @objc(ProximiioMapboxNative) class ProximiioMapboxNative: RCTEventEmitter, ProximiioMapboxNavigation { @objc override static func requiresMainQueueSetup() -> Bool { return true } var instance = ProximiioMapbox.shared; var lastLocation : ProximiioLocation? var lastLevel = NSNumber(0) var lastRoute : PIORoute? var hasListeners = false var ready = false var snapEnabled = false var syncStatus = "INITIAL_WAITING" var amenitiesCache : Array<NSDictionary> = Array() var featuresCache : Array<NSDictionary> = Array() let snap = ProximiioSnapProcessor() override func startObserving() { hasListeners = true } override func stopObserving() { hasListeners = false } override func supportedEvents() -> [String]! {[ "ProximiioFloorChanged", "ProximiioMapboxInitialized", "ProximiioMapboxFailed", "ProximiioMapboxRouteStarted", "ProximiioMapboxRouteCanceled", "ProximiioMapboxRouteUpdated", "ProximiioMapboxOnNavigationLandmark", "ProximiioMapboxOnNavigationHazard", "ProximiioMapboxOnNavigationSegment", "ProximiioMapboxOnNavigationDecision", "ProximiioMapboxAmenitiesChanged", "ProximiioMapboxFeaturesChanged", "ProximiioMapboxStyleChanged", "ProximiioMapboxSyncStatusChanged", "ProximiioMapboxFeaturesChangedInternal", "ProximiioMapboxAmenitiesChangedInternal", "ProximiioMapbox.RouteEventUpdate", "ProximiioMapbox.RouteEvent", "ProximiioMapboxLocationUpdate", "ProximiioMapbox.RouteEvent", "ProximiioMapbox.RouteEventUpdate", "ProximiioMapboxOnNavigationLandmark", "ProximiioMapboxOnNavigationHazard", "ProximiioMapboxOnNavigationSegment", "ProximiioMapboxOnNavigationDecision", "ProximiioMapboxAmenitiesChangedInternal", "ProximiioMapboxSyncStatusChanged", "ProximiioMapboxFeaturesChangedInternal", "ProximiioMapboxStyleChanged" ]} @objc(authorize:resolver:rejecter:) func authorize(_ token: String, resolver resolve:@escaping RCTPromiseResolveBlock, rejecter reject:@escaping RCTPromiseRejectBlock) -> Void { updateSyncStatus("INITIAL_WAITING") self.ready = false let config = ProximiioMapboxConfiguration(token: token) instance.setup(mapView: nil, configuration: config) instance.mapNavigation = self instance.initialize { authResult in switch authResult { case .failure: reject("AUTH_FAILURE", "Authorization Failed", nil) case .invalid: reject("AUTH_FAILURE", "Authorization Invalid", nil) case .success: self._synchronize(initial: true) { success in if (success) { // self.instance.routeCancel(silent: true) self.ready = true resolve(["ready": true]) self.startDatabaseObserver() } else { reject("SYNC_FAILURE", "Initial Synchronization Failed", nil) } } } } } @objc(getAmenities:reject:) func getAmenities(resolve:@escaping RCTPromiseResolveBlock, reject:@escaping RCTPromiseRejectBlock) -> Void { resolve(getConvertedAmenities()) } @objc(getFeatures:reject:) func getFeatures(resolve:@escaping RCTPromiseResolveBlock, reject:@escaping RCTPromiseRejectBlock) -> Void { resolve(getConvertedFeatures()) } @objc(getSyncStatus:reject:) func getSyncStatus(resolve:@escaping RCTPromiseResolveBlock, reject:@escaping RCTPromiseRejectBlock) -> Void { resolve(syncStatus) } @objc(synchronize:reject:) func synchronize(resolve:@escaping RCTPromiseResolveBlock, reject:@escaping RCTPromiseRejectBlock) -> Void { _synchronize(initial: false) { success in if (success) { resolve(["success": true]) } else { reject("SYNC FAILURE", "Update Synchronization Failed", nil) } } } @objc(updateLocation:longitude:sourceType:accuracy:resolver:rejecter:) func updateLocation(_ latitude: NSNumber, longitude: NSNumber, sourceType: String, accuracy: NSNumber, resolver resolve:RCTPromiseResolveBlock, rejecter reject:RCTPromiseRejectBlock) -> Void { let location = ProximiioLocation(latitude: latitude.doubleValue, longitude: longitude.doubleValue, horizontalAccuracy: accuracy.floatValue) location.sourceType = sourceType instance.userLocation = location lastLocation = location resolve(convertLocation(location)) } @objc(updateLevel:resolve:reject:) func updateLevel(level: NSNumber, resolve:RCTPromiseResolveBlock, reject:RCTPromiseRejectBlock) -> Void { lastLevel = level } @objc(routeCalculate:resolve:reject:) func routeCalculate(configuration: NSDictionary, resolve:@escaping RCTPromiseResolveBlock, reject:@escaping RCTPromiseRejectBlock) -> Void { do { let config = try convertDictionaryToRouteConfiguration(data: configuration) instance.routeCalculate(configuration: config) { route in self._handleRoute(route: route, resolve: resolve, reject: reject) } } catch ProximiioMapboxNativeError.destinationNotFound { reject("ROUTE_NOT_FOUND", "Destination not found", nil) } catch ProximiioMapboxNativeError.destinationNotSpecified { reject("ROUTE_NOT_FOUND", "Destination not specified", nil) } catch { reject("ROUTE_NOT_FOUND", "Unknown Error", nil) } } @objc(routeFind:) func routeFind(configuration: NSDictionary) -> Void { do { let config = try convertDictionaryToRouteConfiguration(data: configuration) instance.routeFind(configuration: config) { route in self.lastRoute = route if (route != nil) { let convertedRoute = self._convertRoute(route: route, nodeIndex: nil, position: nil) self._sendEvent(name: "ProximiioMapbox.RouteEvent", body: convertedRoute) } else { self.routeEvent(eventType: .routeNotfound, text: "Route Not Found", additionalText: nil, data: nil); } } } catch ProximiioMapboxNativeError.destinationNotFound { self.routeEvent(eventType: .routeNotfound, text: "Route Not Found", additionalText: nil, data: nil); } catch ProximiioMapboxNativeError.destinationNotSpecified { self.routeEvent(eventType: .routeNotfound, text: "Route Not Found", additionalText: nil, data: nil); } catch { self.routeEvent(eventType: .canceled, text: "Unknown Error", additionalText: nil, data: nil); } } @objc(routeFindAndPreview:) func routeFindAndPreview(configuration: NSDictionary) -> Void { do { let config = try convertDictionaryToRouteConfiguration(data: configuration) instance.routeFindAndPreview(configuration: config) { route in self.lastRoute = route if (route != nil) { let convertedRoute = self._convertRoute(route: route, nodeIndex: nil, position: nil) self._sendEvent(name: "ProximiioMapbox.RouteEvent", body: convertedRoute) } else { self.routeEvent(eventType: .routeNotfound, text: "Route Not Found", additionalText: nil, data: nil); } } } catch ProximiioMapboxNativeError.destinationNotFound { self.routeEvent(eventType: .routeNotfound, text: "Route Not Found", additionalText: nil, data: nil); } catch ProximiioMapboxNativeError.destinationNotSpecified { self.routeEvent(eventType: .routeNotfound, text: "Route Not Found", additionalText: nil, data: nil); } catch { self.routeEvent(eventType: .canceled, text: "Unknown Error", additionalText: nil, data: nil); } } @objc(routeFindAndStart:) func routeFindAndStart(configuration: NSDictionary) -> Void { do { let config = try convertDictionaryToRouteConfiguration(data: configuration) instance.routeFindAndStart(configuration: config) { route in self.lastRoute = route if (route != nil) { let convertedRoute = self._convertRoute(route: route, nodeIndex: nil, position: nil) self._sendEvent(name: "ProximiioMapbox.RouteEvent", body: convertedRoute) } else { self.routeEvent(eventType: .routeNotfound, text: "Route Not Found", additionalText: nil, data: nil); } } } catch ProximiioMapboxNativeError.destinationNotFound { self.routeEvent(eventType: .routeNotfound, text: "Route Not Found", additionalText: nil, data: nil); } catch ProximiioMapboxNativeError.destinationNotSpecified { self.routeEvent(eventType: .routeNotfound, text: "Route Not Found", additionalText: nil, data: nil); } catch { self.routeEvent(eventType: .canceled, text: "Unknown Error", additionalText: nil, data: nil); } } @objc(routeStart:reject:) func routeStart(resolve:@escaping RCTPromiseResolveBlock, reject:@escaping RCTPromiseRejectBlock) -> Void { instance.routeStart() resolve(true) } @objc(routeCancel:reject:) func routeCancel(resolve:@escaping RCTPromiseResolveBlock, reject:@escaping RCTPromiseRejectBlock) -> Void { instance.routeCancel(silent: false) resolve(true) } @objc(setStepImmediateThreshold:) func setStepImmediateThreshold(thresholdInMeters: NSNumber) -> Void { instance.navigation?.setStepImmediateThreshold(inMeters: thresholdInMeters.doubleValue) } @objc(setStepPreparationThreshold:) func setStepPreparationThreshold(thresholdInMeters: NSNumber) -> Void { instance.navigation?.setStepPreparationThreshold(inMeters: thresholdInMeters.doubleValue) } @objc(setRouteFinishThreshold:) func setRouteFinishThreshold(thresholdInMeters: NSNumber) -> Void { instance.navigation?.setRouteFinishThreshold(inMeters: thresholdInMeters.doubleValue) } @objc(setRerouteEnabled:) func setRerouteEnabled(enabled: NSNumber) -> Void { instance.navigation?.setReRouting(automatic: enabled.boolValue) } @objc(setReRouteThreshold:) func setReRouteThreshold(thresholdInMeters: NSNumber) -> Void { instance.navigation?.setReRouting(inMeters: thresholdInMeters.doubleValue) } // TTS @objc(ttsEnable:reject:) func ttsEnable(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) -> Void { instance.navigation?.ttsEnable(enable: true) resolve(true) } @objc(ttsDisable) func ttsDisable() -> Void { instance.navigation?.ttsEnable(enable: false) } @objc(ttsHeadingCorrectionEnabled:) func ttsHeadingCorrectionEnabled(enabled: NSNumber) -> Void { instance.navigation?.ttsHeadingCorrection(enabled: enabled.boolValue) } @objc(ttsHeadingCorrectionThresholds:thresholdDegrees:) func ttsHeadingCorrectionThresholds(_ thresholdInMeters: NSNumber, thresholdDegrees: NSNumber) -> Void { instance.navigation?.ttsHeadingCorrectionThreshold(meters: thresholdInMeters.doubleValue, degrees: thresholdDegrees.doubleValue) } @objc(ttsReassuranceInstructionEnabled:) func ttsReassuranceInstructionEnabled(enabled: NSNumber) -> Void { instance.navigation?.ttsReassuranceInstruction(enabled: enabled.boolValue) } @objc(ttsReassuranceInstructionDistance:) func ttsReassuranceInstructionDistance(distance: NSNumber) -> Void { instance.navigation?.ttsReassuranceInstruction(distance: distance.doubleValue) } @objc(ttsRepeatLastInstruction) func ttsRepeatLastInstruction() -> Void { instance.navigation?.ttsRepeatLastInstruction() } @objc(ttsHazardAlert:metadataKeys:) func ttsHazardAlert(enabled: NSNumber, metadataKeys: NSArray) -> Void { instance.navigation?.ttsHazardAlert(enabled: enabled.boolValue, metadataKeys: metadataKeys.map({($0 as! NSNumber).intValue})) } @objc(ttsSegmentAlert:exitEnabled:metadataKeys:) func ttsSegmentAlert(enterEnabled: NSNumber, exitEnabled: NSNumber, metadataKeys: NSArray) -> Void { instance.navigation?.ttsSegmentAlert(enterEnabled: enterEnabled.boolValue, exitEnabled: exitEnabled.boolValue, metadataKeys: metadataKeys.map({($0 as! NSNumber).intValue})) } @objc(ttsDecisionAlert:metadataKeys:) func ttsDecisionAlert(enabled: NSNumber, metadataKeys: NSArray) -> Void { instance.navigation?.ttsDecisionAlert(enabled: enabled.boolValue, metadataKeys: metadataKeys.map({($0 as! NSNumber).intValue})) } @objc(ttsLandmarkAlert:metadataKeys:) func ttsLandmarkAlert(enabled: NSNumber, metadataKeys: NSArray) -> Void { instance.navigation?.ttsLandmarkAlert(enabled: enabled.boolValue, metadataKeys: metadataKeys.map({($0 as! NSNumber).intValue})) } @objc(ttsLevelChangerMetadataKeys:) func ttsLevelChangerMetadataKeys(metadataKeys: NSArray) -> Void { instance.navigation?.ttsLevelChangerMetadataKeys(metadataKeys: metadataKeys.map({($0 as! NSNumber).intValue})) } @objc(setUserLocationToRouteSnappingEnabled:) func setUserLocationToRouteSnappingEnabled(_enabled: NSNumber) -> Void { let enabled = _enabled.boolValue; if (enabled) { if (snapEnabled) { return } ProximiioLocationManager.shared().addProcessor(snap, avoidDuplicates: true) snapEnabled = true } else { if (!snapEnabled) { return } // TODO remove the snap processor } } @objc(setUserLocationToRouteSnappingThreshold:) func setUserLocationToRouteSnappingThreshold(threshold: NSNumber) -> Void { snap.threshold = threshold.doubleValue } @objc(ttsDestinationMetadataKeys:) func ttsDestinationMetadataKeys(metadataKeys: NSArray) -> Void { // TODO } @objc(setLevelOverrideMap:) func setLevelOverrideMap(overrideMap: NSDictionary) -> Void { var local = [Int: String](); for key: NSNumber in overrideMap.allKeys as! [NSNumber] { local[key.intValue] = overrideMap[key] as? String } instance.levelNameMapper = local; } @objc(setUnitConversion:) func setUnitConversion(unitConversion: NSDictionary) -> Void { let unitConversion = convertDictionaryToPIOUnitConversion(data: unitConversion) instance.navigation?.setUnitConversion(conversion: unitConversion) } // PRIVATE FUNCTIONS private func _handleRoute(route: PIORoute?, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) -> Void { lastRoute = route if (route != nil) { let convertedRoute = self._convertRoute(route: route, nodeIndex: nil, position: nil) resolve(convertedRoute) _sendEvent(name: "ProximiioMapbox.RouteEvent", body: convertedRoute) } else { reject("ROUTE_NOT_FOUND", "Route not found", nil) } } private func _convertRoute(route: PIORoute?, nodeIndex: Int?, position: CLLocationCoordinate2D?) -> NSDictionary { if (route == nil) { return NSDictionary() } let routeMap = self.convertPIORouteToDictionary(route: route!) let features = NSMutableArray() if (nodeIndex != nil && position != nil) { let remaining = route?.lineStringFrom(startNodeIndex: nodeIndex!, firstPoint: position!) remaining?.forEach({ feature in feature.identifier = "route-node-remaining-\(remaining!.firstIndex(of: feature) ?? 0)" features.add(feature.toDictionary()) }) let completed = route?.lineStringUntil(endNodeIndex: nodeIndex!, lastPoint: position!) completed?.forEach({ feature in feature.identifier = "route-node-completed-\(completed!.firstIndex(of: feature) ?? 0)" feature.properties["completed"] = true features.add(feature.toDictionary()) }) } else { let list = route?.getLineStringFeatureList() list!.forEach({ feature in feature.identifier = "route-node-\(list!.firstIndex(of: feature) ?? 0)" features.add(feature.toDictionary()) }) } routeMap["features"] = features return routeMap } private func _synchronize(initial: Bool, completion: @escaping (Bool) -> ()) -> Void { self.updateSyncStatus(initial ? "INITIAL_RUNNING" : "UPDATE_RUNNING") Proximiio.sharedInstance().sync { completed in if (completed) { self.amenitiesCache = self.instance.database.amenities().map { self.convertAmenityToDictionary($0) } self.amenitiesChanged() self.featuresCache = self.instance.database.features().map { $0.toDictionary() as NSDictionary } self.updateSyncStatus(initial ? "INITIAL_FINISHED" : "UPDATE_FINISHED") self.featuresChanged() completion(true) } else { self.updateSyncStatus("INITIAL_ERROR") completion(false) } } } private func getConvertedAmenities() -> Array<NSDictionary> { return self.amenitiesCache } private func getConvertedFeatures() -> Array<NSDictionary> { return self.featuresCache } private func amenitiesChanged() -> Void { self._sendEvent(name: "ProximiioMapboxAmenitiesChangedInternal", body:self.getConvertedAmenities()); } private func featuresChanged() -> Void { self._sendEvent(name: "ProximiioMapboxFeaturesChangedInternal", body:self.getConvertedFeatures()); } private func convertAmenityToDictionary(_ amenity: ProximiioAmenity) -> NSDictionary { let iconOffset = amenity.iconOffset == nil ? NSArray() : NSArray(array: [amenity.iconOffset[0], amenity.iconOffset[1]]) return NSDictionary(dictionary: [ "id": amenity.identifier as String, "icon": amenity.icon as String, "iconOffset": iconOffset, "category": amenity.category as String, "title": amenity.title as String ]) } private func convertProximiioGeoJSONtoDictionary(_ feature: ProximiioGeoJSON) -> NSDictionary { return feature.toDictionary() as NSDictionary } private func convertLocation(_ location: ProximiioLocation) -> NSDictionary { let data = NSMutableDictionary(dictionary: [ "lat": location.coordinate.latitude, "lng": location.coordinate.longitude ]) data["sourceType"] = location.sourceType as String? != nil ? location.sourceType : "unknown" data["accuracy"] = location.horizontalAccuracy > 0 ? location.horizontalAccuracy : 0 return data; } private func convertRouteOptions(data: NSDictionary) -> PIOWayfindingOptions { return PIOWayfindingOptions(avoidElevators: data["avoidElevators"] as! Bool? ?? false, avoidBarriers: data["avoidBarriers"] as! Bool? ?? false, avoidEscalators: data["avoidEscalators"] as! Bool? ?? false, avoidNarrowPaths: data["avoidNarrowPaths"] as! Bool? ?? false, avoidRamps: data["avoidRamps"] as! Bool? ?? false, avoidRevolvingDoors: data["avoidRevolvingDoors"] as! Bool? ?? false, avoidStaircases: data["avoidStaircases"] as! Bool? ?? false, avoidTicketGates: data["avoidTicketGates"] as! Bool? ?? false, pathFixDistance: ((data["pathFixDistance"] as! NSNumber?) ?? NSNumber(1.0)).doubleValue) } private func convertPIOWayfindingOptionsToDictionary(options: PIOWayfindingOptions) -> NSDictionary { // TODO make PIOWayfindingOptions.toJSON public return NSDictionary() } private func convertDictionaryToRouteConfiguration(data: NSDictionary) throws -> PIORouteConfiguration { var start : ProximiioGeoJSON? var destination : ProximiioGeoJSON? if (data["startFeatureId"] != nil) { let results = instance.database.features(search: data["startFeatureId"] as! String) if (results.count == 1) { start = results.first } } if (data["startLatLonLevel"] != nil && lastLocation != nil && (data["startLatLonLevel"] as! Array<NSNumber>).count == 3) { let _data = data["startLatLonLevel"] as! Array<NSNumber> start = ProximiioGeoJSON(dictionary: [ "type": "Feature", "geometry": [ "type": "Point", "coordinates": [ _data[1], _data[0] ] ], "properties": [ "level": _data[2] ] ]) } if (start == nil && lastLocation != nil) { start = ProximiioGeoJSON(dictionary: [ "type": "Feature", "geometry": [ "type": "Point", "coordinates": [lastLocation!.coordinate.longitude, lastLocation!.coordinate.latitude ] ], "properties": [ "level": lastLevel ] ]) } if (data["destinationFeatureId"] != nil) { // let results = instance.database.features(search: data["destinationFeatureId"] as! String) let results = instance.database.features().filter { feature in feature.identifier as String == data["destinationFeatureId"] as! String } if (results.count == 1) { destination = results.first } else { throw ProximiioMapboxNativeError.destinationNotFound } } if (data["destinationLatLonLevel"] != nil && lastLocation != nil && (data["destinationLatLonLevel"] as! Array<NSNumber>).count == 3) { let _data = data["destinationLatLonLevel"] as! Array<NSNumber> destination = ProximiioGeoJSON(dictionary: [ "type": "Feature", "geometry": [ "type": "Point", "coordinates": [ _data[1], _data[0] ] ], "properties": [ "level": _data[2] ] ]) } if (destination == nil) { throw ProximiioMapboxNativeError.destinationNotSpecified } let options = data["wayfindingOptions"] != nil ? convertRouteOptions(data: data["wayfindingOptions"] as! NSDictionary) : getDefaultWayfindingOptions() return PIORouteConfiguration(start: start, destination: destination!, waypointList: [], wayfindingOptions: options) } private func convertPIORouteToDictionary(route: PIORoute) -> NSMutableDictionary { return NSMutableDictionary(dictionary: [ "configuration": self.convertPIORouteConfigurationToDictionary(config: route.configuration), "destination": route.destination.toDictionary() as NSDictionary, "distanceCustom": route.summary["distanceCustom"] as! NSNumber, "distanceCustomUnit": route.summary["distanceCustomUnit"] as! NSString, "distanceMeters": route.summary["distanceMeters"] as! NSNumber, "lastNodeWithPathIndex": (route.summary["steps"] as! NSArray).count - 1, "steps": route.summary["steps"]! ]) } private func convertPIORouteConfigurationToDictionary(config: PIORouteConfiguration) -> NSDictionary { let data = NSDictionary(dictionary: [ "start": config.start?.toJSON() ?? NSDictionary() as Any, "destination": convertProximiioGeoJSONtoDictionary(config.destination), "wayfindingOptions": self.convertPIOWayfindingOptionsToDictionary(options: config.wayfindingOptions), "waypoingList": NSArray() ]) return data } private func convertDictionaryToPIOUnitConversion(data: NSDictionary) -> PIOUnitConversion { let stageList: [NSDictionary] = data["stageList"] as! [NSDictionary] let stages = stageList.map({ _stage in let stage = _stage as NSDictionary return PIOUnitConversion.UnitStage(unitName: stage["unitName"] as! String, unitConversionToMeters: (stage["unitConversionToMeters"] as! NSNumber).doubleValue, minValueInMeters: (stage["minValueInMeters"] as! NSNumber).doubleValue, decimals: (stage["decimalPoints"] as! NSNumber).intValue) } as (NSDictionary) -> PIOUnitConversion.UnitStage) return PIOUnitConversion(stageList: stages) } private func _convertStepDirection(step: PIOGuidanceDirection) -> String { var stepDirection = "NONE" switch step { case .downElevator: stepDirection = "DOWN_ELEVATOR" case .downStairs: stepDirection = "DOWN_STAIRS" case .downEscalator: stepDirection = "DOWN_ESCALATOR" case .exitElevator: stepDirection = "EXIT_ELEVATOR" case .exitStairs: stepDirection = "EXIT_STAIRS" case .exitEscalator: stepDirection = "EXIT_ESCALATOR" case .finish: stepDirection = "FINISH" case .leftHard: stepDirection = "HARD_LEFT" case .leftNormal: stepDirection = "LEFT" case .leftSlight: stepDirection = "SLIGHT_LEFT" case .none: stepDirection = "NONE" case .rightHard: stepDirection = "HARD_RIGHT" case .rightNormal: stepDirection = "RIGHT" case .rightSlight: stepDirection = "SLIGHT_RIGHT" case .start: stepDirection = "START" case .straight: stepDirection = "STRAIGHT" case .turnAround: stepDirection = "TURN_AROUND" case .upElevator: stepDirection = "UP_ELEVATOR" case .upEscalator: stepDirection = "UP_ESCALATOR" case .upStairs: stepDirection = "UP_STAIRS" } return stepDirection } private func getDefaultWayfindingOptions() -> PIOWayfindingOptions { return PIOWayfindingOptions(avoidElevators: false, avoidBarriers: false, avoidEscalators: false, avoidNarrowPaths: false, avoidRamps: false, avoidRevolvingDoors: false, avoidStaircases: false, avoidTicketGates: false, pathFixDistance: 1.0) } private func startDatabaseObserver() -> Void { } private func updateSyncStatus(_ status: String) -> Void { syncStatus = status } private func _sendEvent(name: String, body: Any) -> Void { if (hasListeners) { // NSLog("ProximiioMapboxNative -> sending event: \(name) body: \(body)") self.sendEvent(withName: name, body: body) } } // dummy delegates we dont need func onRoute(route: PIORoute?) { // NSLog("onRoute: \(route)") } func routeEvent(eventType type: PIORouteUpdateType, text: String, additionalText: String?, data: PIORouteUpdateData?) { var eventType = "UNKNOWN" switch type { case .calculating: eventType = "CALCULATING" case .canceled: eventType = "CANCELED" case .finished: eventType = "FINISHED" case .immediate: eventType = "DIRECTION_IMMEDIATE" case .new: eventType = "DIRECTION_NEW" case .osrmNetworkError: eventType = "ROUTE_OSRM_NETWORK_ERROR" case .recalculating: eventType = "RECALCULATING" case .routeNotfound: eventType = "ROUTE_NOT_FOUND" case .soon: eventType = "DIRECTION_SOON" case .update: eventType = "DIRECTION_UPDATE" } let body = NSMutableDictionary(dictionary: [ "eventType": eventType, "text": text, "additionalText": additionalText ?? "" ]) var _data = NSDictionary() if (data != nil) { _data = NSDictionary(dictionary: [ "nodeIndex": data!.nodeIndex, "stepBearing": data!.stepBearing, "stepDirection": _convertStepDirection(step: data!.stepDirection), "stepDistance": data!.stepDistance, "stepDistanceTotal": data!.stepDistanceTotal, "nextStepDistance": data!.nextStepDistance ?? NSNumber(0), "nextStepDirection": _convertStepDirection(step: data!.nextStepDirection), "position": [ "latitude": data!.position.latitude, "longitude": data!.position.longitude ], "pathLengthRemaining": data!.pathLengthRemaining ]) } body["data"] = _data body["route"] = _convertRoute(route: lastRoute, nodeIndex: data?.nodeIndex, position: data?.position) _sendEvent(name: "ProximiioMapbox.RouteEventUpdate", body: body) } func onLandmarkEntered(_ landmarks: [PIOLandmark]) { // TODO - Convert Landmarks to something sane let data = NSDictionary(dictionary: [ "type": "enter", "landmarks": NSArray() ]) _sendEvent(name: "ProximiioMapboxOnNavigationLandmark", body: data) } func onLandmarkExit(_ landmarks: [ProximiioGeoJSON]) { // TODO - Convert Landmarks to something sane let data = NSDictionary(dictionary: [ "type": "exit", "landmarks": NSArray() ]) _sendEvent(name: "ProximiioMapboxOnNavigationLandmark", body: data) } func onHazardEntered(_ hazard: ProximiioGeoJSON) { let data = NSDictionary(dictionary: [ "type": "enter", "hazard": convertProximiioGeoJSONtoDictionary(hazard) ]) _sendEvent(name: "ProximiioMapboxOnNavigationHazard", body: data) } func onHazardExit(_ hazard: ProximiioGeoJSON) { let data = NSDictionary(dictionary: [ "type": "exit", "hazard": convertProximiioGeoJSONtoDictionary(hazard) ]) _sendEvent(name: "ProximiioMapboxOnNavigationHazard", body: data) } func onSegmentEntered(_ segment: ProximiioGeoJSON) { let data = NSDictionary(dictionary: [ "type": "enter", "segment": convertProximiioGeoJSONtoDictionary(segment) ]) _sendEvent(name: "ProximiioMapboxOnNavigationSegment", body: data) } func onSegmentExit(_ segment: ProximiioGeoJSON) { let data = NSDictionary(dictionary: [ "type": "exit", "segment": convertProximiioGeoJSONtoDictionary(segment) ]) _sendEvent(name: "ProximiioMapboxOnNavigationSegment", body: data) } func onDecisionEntered(_ decision: ProximiioGeoJSON) { let data = NSDictionary(dictionary: [ "type": "enter", "decision": convertProximiioGeoJSONtoDictionary(decision) ]) _sendEvent(name: "ProximiioMapboxOnNavigationDecision", body: data) } func onDecisionExit(_ decision: ProximiioGeoJSON) { let data = NSDictionary(dictionary: [ "type": "exit", "decision": convertProximiioGeoJSONtoDictionary(decision) ]) _sendEvent(name: "ProximiioMapboxOnNavigationDecision", body: data) } func onPositionUpdate(_ position: CLLocationCoordinate2D) { // dummy delegate method, functinality replaced by compass-heading rn module } func onHeadingUpdate(_ heading: Double) { // dummy } func onTTS() { // dummy } func onTTSDirection(text: String?) { // dummy } }
42.61
196
0.608895
099ad5c60ab7c9a2d7bfbe6a63aa681dbab8c789
405
// // Models.swift // WorkFromWherever // // Created by Jay Stakelon on 5/31/21. // import Foundation struct ChannelList: Codable { var channels: [Channel] } struct Channel: Codable, Identifiable { var id = UUID() var title: String var sounds: [Sound]? } struct Sound: Codable, Identifiable { var id = UUID() var title: String var path: String var volume: CGFloat }
15.576923
39
0.649383
7a6cc54ee462566fe880a6a632a22667f7e77633
2,956
// // AppDelegate.swift // Flicks_2 // // Created by daniel on 1/12/17. // Copyright © 2017 Notabela. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var tabBarController: UITabBarController! let globalTint = UIColor(red: 225/255, green: 214/255, blue: 43/255, alpha: 1) func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { window = UIWindow(frame: UIScreen.main.bounds) let storyboard = UIStoryboard(name: "Main", bundle: nil) let nowPlayingNavController = storyboard.instantiateViewController(withIdentifier: "MoviesNavigationController") as! UINavigationController let nowPlayingViewController = nowPlayingNavController.topViewController as! MoviesViewController nowPlayingViewController.endPoint = "now_playing" nowPlayingViewController.tabBarItem.title = "Now Playing" nowPlayingViewController.tabBarItem.image = UIImage(named: "now_playing.png") let topRatedNavController = storyboard.instantiateViewController(withIdentifier: "MoviesNavigationController") as! UINavigationController let topRatedViewController = topRatedNavController.topViewController as! MoviesViewController topRatedViewController.endPoint = "top_rated" topRatedViewController.tabBarItem.title = "Top Rated" topRatedViewController.tabBarItem.image = UIImage(named: "top_rated.png") tabBarController = UITabBarController() tabBarController.viewControllers = [nowPlayingNavController, topRatedNavController] window?.rootViewController = tabBarController window?.makeKeyAndVisible() UINavigationBar.appearance().barStyle = .black UINavigationBar.appearance().isTranslucent = true tabBarController.tabBar.barStyle = .black tabBarController.tabBar.isTranslucent = true tabBarController.tabBar.tintColor = globalTint return true } func moviesFilePath(endPoint: String) -> String { let paths = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask) let filePath = paths[0].appendingPathComponent("\(endPoint)File.plist") return filePath.path } func saveMovies(_ movies: Movies, endPoint: String) -> Bool { let success = NSKeyedArchiver.archiveRootObject(movies, toFile: moviesFilePath(endPoint: endPoint)) assert(success, "failed to write archive") return success } func readMovies(endPoint: String, completion: (_ movies: Movies?) -> Void) { let path = moviesFilePath(endPoint: endPoint) let unarchivedObject = NSKeyedUnarchiver.unarchiveObject(withFile: path) completion(unarchivedObject as? Movies) } }
37.897436
147
0.712788
262a9176d36c0e61562dd763d731c1ffb986bfd0
12,870
// // RSDJSONValue.swift // Research // // Copyright © 2017-2018 Sage Bionetworks. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // 3. Neither the name of the copyright holder(s) nor the names of any contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. No license is granted to the trademarks of // the copyright holders even if such marks are included in this software. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import Foundation /// Protocol for converting an object to a dictionary representation. This is included for reverse-compatiblility to /// older implementations that are not Swift 4 `Codable` and instead use a dictionary representation. public protocol RSDDictionaryRepresentable { /// Return the dictionary representation for this object. func dictionaryRepresentation() -> [AnyHashable : Any] } /// Protocol for converting objects to JSON serializable objects. public protocol RSDJSONValue { /// Return a JSON-type object. Elements may be any one of the JSON types. func jsonObject() -> RSDJSONSerializable /// Encode the object. func encode(to encoder: Encoder) throws } extension NSString : RSDJSONValue { public func jsonObject() -> RSDJSONSerializable { return String(self) } public func encode(to encoder: Encoder) throws { try (self as String).encode(to: encoder) } } extension String : RSDJSONValue { public func jsonObject() -> RSDJSONSerializable { return String(self) } } extension NSNumber : RSDJSONValue { public func jsonObject() -> RSDJSONSerializable { return self.copy() as! NSNumber } } extension Int : RSDJSONValue { public func jsonObject() -> RSDJSONSerializable { return self } } extension Int8 : RSDJSONValue { public func jsonObject() -> RSDJSONSerializable { return self } } extension Int16 : RSDJSONValue { public func jsonObject() -> RSDJSONSerializable { return self } } extension Int32 : RSDJSONValue { public func jsonObject() -> RSDJSONSerializable { return self } } extension Int64 : RSDJSONValue { public func jsonObject() -> RSDJSONSerializable { return self } } extension UInt : RSDJSONValue { public func jsonObject() -> RSDJSONSerializable { return self } } extension UInt8 : RSDJSONValue { public func jsonObject() -> RSDJSONSerializable { return self } } extension UInt16 : RSDJSONValue { public func jsonObject() -> RSDJSONSerializable { return self } } extension UInt32 : RSDJSONValue { public func jsonObject() -> RSDJSONSerializable { return self } } extension UInt64 : RSDJSONValue { public func jsonObject() -> RSDJSONSerializable { return self } } extension Bool : RSDJSONValue { public func jsonObject() -> RSDJSONSerializable { return self } } extension Double : RSDJSONValue { public func jsonObject() -> RSDJSONSerializable { return self } } extension Float : RSDJSONValue { public func jsonObject() -> RSDJSONSerializable { return self } } extension NSNull : RSDJSONValue { public func jsonObject() -> RSDJSONSerializable { return self } } extension NSDate : RSDJSONValue { public func jsonObject() -> RSDJSONSerializable { return (self as Date).jsonObject() } public func encode(to encoder: Encoder) throws { try (self as Date).encode(to: encoder) } } extension Date : RSDJSONValue { public func jsonObject() -> RSDJSONSerializable { return RSDFactory.shared.timestampFormatter.string(from: self) } } extension DateComponents : RSDJSONValue { public func jsonObject() -> RSDJSONSerializable { guard let date = self.date ?? Calendar(identifier: .iso8601).date(from: self) else { return NSNull() } return defaultFormatter().string(from: date) } public func defaultFormatter() -> DateFormatter { if ((year == nil) || (year == 0)) && ((month == nil) || (month == 0)) && ((day == nil) || (day == 0)) { return RSDFactory.shared.timeOnlyFormatter } else if ((hour == nil) || (hour == 0)) && ((minute == nil) || (minute == 0)) { if let year = year, year > 0, let month = month, month > 0, let day = day, day > 0 { return RSDFactory.shared.dateOnlyFormatter } // Build the format string if not all components are included var formatString = "" if let year = year, year > 0 { formatString = "yyyy" } if let month = month, month > 0 { if formatString.count > 0 { formatString.append("-") } formatString.append("MM") if let day = day, day > 0 { formatString.append("-") formatString.append("dd") } } let formatter = DateFormatter() formatter.dateFormat = formatString return formatter } return RSDFactory.shared.timestampFormatter } } extension NSDateComponents : RSDJSONValue { public func jsonObject() -> RSDJSONSerializable { return (self as DateComponents).jsonObject() } public func encode(to encoder: Encoder) throws { try (self as DateComponents).encode(to: encoder) } } extension Data : RSDJSONValue { public func jsonObject() -> RSDJSONSerializable { return self.base64EncodedString() } } extension NSData : RSDJSONValue { public func jsonObject() -> RSDJSONSerializable { return (self as Data).jsonObject() } public func encode(to encoder: Encoder) throws { try (self as Data).encode(to: encoder) } } extension NSUUID : RSDJSONValue { public func jsonObject() -> RSDJSONSerializable { return self.uuidString } public func encode(to encoder: Encoder) throws { try (self as UUID).encode(to: encoder) } } extension UUID : RSDJSONValue { public func jsonObject() -> RSDJSONSerializable { return self.uuidString } } extension NSURL : RSDJSONValue { public func jsonObject() -> RSDJSONSerializable { return self.absoluteString ?? NSNull() } public func encode(to encoder: Encoder) throws { try (self as URL).encode(to: encoder) } } extension URL : RSDJSONValue { public func jsonObject() -> RSDJSONSerializable { return self.absoluteString } } fileprivate func _convertToJSONValue(from object: Any) -> RSDJSONSerializable { if let obj = object as? RSDJSONValue { return obj.jsonObject() } else if let obj = object as? RSDDictionaryRepresentable { let dictionary = obj.dictionaryRepresentation() if JSONSerialization.isValidJSONObject(dictionary), let cast = dictionary as? [String : RSDJSONSerializable] { return cast } else { return dictionary.jsonObject() } } else if let obj = object as? NSObjectProtocol { return obj.description } else { return NSNull() } } fileprivate func _encode(value: Any, to nestedEncoder:Encoder) throws { // Note: need to special-case encoding a Date, Data type, or NonConformingNumber since these // are not encoding correctly unless cast to a nested container that can handle // custom encoding strategies. if let date = value as? Date { var container = nestedEncoder.singleValueContainer() try container.encode(date) } else if let data = value as? Data { var container = nestedEncoder.singleValueContainer() try container.encode(data) } else if let nestedArray = value as? [Any] { let encodable = AnyCodableArray(nestedArray) try encodable.encode(to: nestedEncoder) } else if let nestedDictionary = value as? Dictionary<String, Any> { let encodable = AnyCodableDictionary(nestedDictionary) try encodable.encode(to: nestedEncoder) } else if let number = (value as? RSDJSONNumber)?.jsonNumber() { var container = nestedEncoder.singleValueContainer() try container.encode(number) } else if let encodable = value as? RSDJSONValue { try encodable.encode(to: nestedEncoder) } else if let encodable = value as? Encodable { try encodable.encode(to: nestedEncoder) } else { let context = EncodingError.Context(codingPath: nestedEncoder.codingPath, debugDescription: "Could not encode value \(value).") throw EncodingError.invalidValue(value, context) } } extension NSDictionary : RSDJSONValue, Encodable { public func jsonObject() -> RSDJSONSerializable { var dictionary : [String : RSDJSONSerializable] = [:] for (key, value) in self { let strKey = "\(key)" dictionary[strKey] = _convertToJSONValue(from: value) } return dictionary } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: AnyCodingKey.self) for (key, value) in self { let strKey = "\(key)" let codingKey = AnyCodingKey(stringValue: strKey)! let nestedEncoder = container.superEncoder(forKey: codingKey) try _encode(value: value, to: nestedEncoder) } } } extension Dictionary : RSDJSONValue { public func jsonObject() -> RSDJSONSerializable { return (self as NSDictionary).jsonObject() } } extension Dictionary where Value : Any { public func encode(to encoder: Encoder) throws { try (self as NSDictionary).encode(to: encoder) } } extension NSArray : RSDJSONValue { public func jsonObject() -> RSDJSONSerializable { return self.map { _convertToJSONValue(from: $0) } } public func encode(to encoder: Encoder) throws { var container = encoder.unkeyedContainer() for value in self { let nestedEncoder = container.superEncoder() try _encode(value: value, to: nestedEncoder) } } } extension Array : RSDJSONValue { public func jsonObject() -> RSDJSONSerializable { return (self as NSArray).jsonObject() } } extension Array where Element : Any { public func encode(to encoder: Encoder) throws { try (self as NSArray).encode(to: encoder) } } extension Set : RSDJSONValue { public func jsonObject() -> RSDJSONSerializable { return Array(self).jsonObject() } } extension Set where Element : Any { public func encode(to encoder: Encoder) throws { try Array(self).encode(to: encoder) } } extension NSNull : Encodable { public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encodeNil() } } extension NSNumber : Encodable { public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() if self === kCFBooleanTrue as NSNumber { try container.encode(true) } else if self === kCFBooleanFalse as NSNumber { try container.encode(false) } else if NSNumber(value: self.intValue) == self { try container.encode(self.intValue) } else { try container.encode(self.doubleValue) } } }
30.211268
135
0.650816
abc8f1777f014fb622e4367b8f5060cd1f8977b2
10,282
import Flutter import UIKit import Photos struct AlbumItem: Hashable { var name: String var identifier: String static func ==(lhs: AlbumItem, rhs: AlbumItem) -> Bool { return (lhs.name, lhs.identifier) == (rhs.name, rhs.identifier) } var hashValue: Int { return name.hashValue << 2 | identifier.hashValue } } public class SwiftAdvImagePickerPlugin: NSObject, FlutterPlugin { var controller: FlutterViewController! var imagesResult: FlutterResult? var messenger: FlutterBinaryMessenger let genericError = "500" init(cont: FlutterViewController, messenger: FlutterBinaryMessenger) { self.controller = cont; self.messenger = messenger; super.init(); } public static func register(with registrar: FlutterPluginRegistrar) { let channel = FlutterMethodChannel(name: "adv_image_picker", binaryMessenger: registrar.messenger()) let app = UIApplication.shared let controller : FlutterViewController = app.delegate!.window!!.rootViewController as! FlutterViewController; let instance = SwiftAdvImagePickerPlugin.init(cont: controller, messenger: registrar.messenger()) registrar.addMethodCallDelegate(instance, channel: channel) } public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { switch (call.method) { case "getIosStoragePermission": getStoragePermission(result: result) break; case "getAlbums": let fetchOptions = PHFetchOptions() let smartAlbums: PHFetchResult = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .smartAlbumUserLibrary, options: fetchOptions) let albums: PHFetchResult = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions) var arr = [Any](); let allAlbums: Array<PHFetchResult<PHAssetCollection>> = [smartAlbums, albums] for i in 0 ..< allAlbums.count { let resultx: PHFetchResult = allAlbums[i] resultx.enumerateObjects { (asset, index, stop) -> Void in let opts = PHFetchOptions() if #available(iOS 9.0, *) { opts.fetchLimit = 1 } var assetCount = asset.estimatedAssetCount if assetCount == NSNotFound { let fetchOptions = PHFetchOptions() fetchOptions.predicate = NSPredicate(format: "mediaType == %d", PHAssetMediaType.image.rawValue) assetCount = PHAsset.fetchAssets(in: asset, options: fetchOptions).count } if assetCount > 0 { let item = ["name": asset.localizedTitle!, "assetCount": assetCount, "identifier": asset.localIdentifier] as [String : Any] arr.append(item) } } } result(arr) break; case "getAlbumAssetsId": let arguments = call.arguments as! Dictionary<String, AnyObject> let albumName = arguments["albumName"] as! String var resuuuu: [String] = [] let fetchOptions = PHFetchOptions() let smartAlbums: PHFetchResult = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .smartAlbumUserLibrary, options: fetchOptions) let albums: PHFetchResult = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions) let allAlbums: Array<PHFetchResult<PHAssetCollection>> = [smartAlbums, albums] for i in 0 ..< allAlbums.count { let resultx: PHFetchResult = allAlbums[i] resultx.enumerateObjects { (asset, index, stop) -> Void in if asset.localizedTitle == albumName { let opt = PHFetchOptions() let ass = PHAsset.fetchAssets(in: asset, options: opt) ass.enumerateObjects{(object: AnyObject!, count: Int, stop: UnsafeMutablePointer<ObjCBool>) in if object is PHAsset { let eachass = object as! PHAsset resuuuu.append(eachass.localIdentifier) } } } } } result(resuuuu) case "getAlbumThumbnail": let arguments = call.arguments as! Dictionary<String, AnyObject> let imagePath = (arguments["imagePath"] ?? "" as AnyObject) as! String let quality = arguments["quality"] as! Int let reqWidth = (arguments["width"] ?? 0 as AnyObject) as! Int let reqHeight = (arguments["height"] ?? 0 as AnyObject) as! Int if let image = UIImage(contentsOfFile: imagePath) { if (reqWidth != 0 && reqHeight != 0) { let initialWidth = image.size.width; let initialHeight = image.size.height; let width: CGFloat = CGFloat(reqWidth); let height: CGFloat = CGFloat(reqHeight); let newSize = CGSize(width: width, height: height); var rectWidth: CGFloat var rectHeight: CGFloat //if the request size is landscape if (width > height) { rectHeight = initialHeight / initialWidth * width rectWidth = width } else if (height > width) { //if the request size is portrait rectHeight = height rectWidth = initialWidth / initialHeight * height } else { //if the request size is square if initialWidth > initialHeight { rectHeight = width rectWidth = initialWidth / initialHeight * width } else { rectHeight = initialHeight / initialWidth * width rectWidth = width } } let posX: CGFloat = (width - rectWidth) / 2 let posY: CGFloat = (height - rectHeight) / 2 let rect = CGRect(x: posX, y: posY, width: rectWidth, height: rectHeight) UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0) image.draw(in: rect) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() self.messenger.send(onChannel: "adv_image_picker/image/fetch/thumbnails/\(imagePath)", message: newImage!.jpegData(compressionQuality: CGFloat(quality / 100))) } else { result(true) break } } result(true) case "getAlbumOriginal": let arguments = call.arguments as! Dictionary<String, AnyObject> let imagePath = (arguments["imagePath"] ?? "" as AnyObject) as! String let quality = arguments["quality"] as! Int let maxSize = (arguments["maxSize"] ?? 0 as AnyObject) as! Int if let image = UIImage(contentsOfFile: imagePath) { if (maxSize != 0) { let initialWidth = image.size.width; let initialHeight = image.size.height; let floatMaxSize = CGFloat(maxSize); let width: CGFloat = initialHeight.isLess(than: initialWidth) ? floatMaxSize : (initialWidth / initialHeight * floatMaxSize); let height: CGFloat = initialWidth.isLessThanOrEqualTo(initialHeight) ? floatMaxSize : (initialHeight / initialWidth * floatMaxSize); let newSize = CGSize(width: width, height: height); let rect = CGRect(x: 0, y: 0, width: width, height: height) UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0) image.draw(in: rect) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() self.messenger.send(onChannel: "adv_image_picker/image/fetch/original/\(imagePath)", message: newImage!.jpegData(compressionQuality: CGFloat(quality / 100))) } else { self.messenger.send(onChannel: "adv_image_picker/image/fetch/original/\(imagePath)", message: image.jpegData(compressionQuality: CGFloat(quality / 100))) } } result(true) default: result(FlutterMethodNotImplemented) } } private func getStoragePermission(result: @escaping FlutterResult) -> Void { let hasPermission = checkPermission(permission: "Storage") if(!hasPermission) { PHPhotoLibrary.requestAuthorization { status in switch status { case .authorized: result(true) break; default: result(false) break; } } } else { result(true) } } private func checkPermission(permission : String) -> Bool { var hasPermission: Bool! if permission == "Storage" { let status = PHPhotoLibrary.authorizationStatus() hasPermission = status == PHAuthorizationStatus.authorized } return hasPermission ?? false } }
45.697778
180
0.532387
f4f9b986321f330d8fffb64b89093f191476d207
1,472
import Async /// Creates connections to an identified PostgreSQL database. public final class PostgreSQLDatabase: Database { /// This database's configuration. public let config: PostgreSQLDatabaseConfig /// If non-nil, will log queries. public var logger: PostgreSQLLogger? /// Creates a new `PostgreSQLDatabase`. public init(config: PostgreSQLDatabaseConfig) { self.config = config } /// See `Database.makeConnection()` public func makeConnection(on worker: Worker) -> Future<PostgreSQLConnection> { let config = self.config return Future.flatMap(on: worker) { return try PostgreSQLConnection.connect(hostname: config.hostname, port: config.port, on: worker) { error in print("[PostgreSQL] \(error)") }.flatMap(to: PostgreSQLConnection.self) { client in client.logger = self.logger return client.authenticate( username: config.username, database: config.database, password: config.password ).transform(to: client) } } } } /// A connection created by a `PostgreSQLDatabase`. extension PostgreSQLConnection: DatabaseConnection, BasicWorker { } extension DatabaseIdentifier { /// Default identifier for `PostgreSQLDatabase`. public static var psql: DatabaseIdentifier<PostgreSQLDatabase> { return .init("psql") } }
34.232558
120
0.644701
21602df3965e3a914ce9886fdd38d9ed70445399
4,901
// // CPYFolder.swift // Clipy // // Created by 古林俊佑 on 2015/06/21. // Copyright (c) 2015年 Shunsuke Furubayashi. All rights reserved. // import Cocoa import RealmSwift final class CPYFolder: Object { // MARK: - Properties dynamic var index = 0 dynamic var enable = true dynamic var title = "" dynamic var identifier = UUID().uuidString let snippets = List<CPYSnippet>() // MARK: Primary Key override static func primaryKey() -> String? { return "identifier" } } // MARK: - Copy extension CPYFolder { func deepCopy() -> CPYFolder { let folder = CPYFolder(value: self) var snippets = [CPYSnippet]() if realm == nil { snippets.forEach { let snippet = CPYSnippet(value: $0) snippets.append(snippet) } } else { self.snippets.sorted(byKeyPath: #keyPath(CPYSnippet.index), ascending: true).forEach { let snippet = CPYSnippet(value: $0) snippets.append(snippet) } } folder.snippets.removeAll() folder.snippets.append(objectsIn: snippets) return folder } } // MARK: - Add Snippet extension CPYFolder { func createSnippet() -> CPYSnippet { let snippet = CPYSnippet() snippet.title = "untitled snippet" snippet.index = Int(snippets.count) return snippet } func mergeSnippet(_ snippet: CPYSnippet) { let realm = try! Realm() guard let folder = realm.object(ofType: CPYFolder.self, forPrimaryKey: identifier) else { return } let copySnippet = CPYSnippet(value: snippet) folder.realm?.transaction { folder.snippets.append(copySnippet) } } func insertSnippet(_ snippet: CPYSnippet, index: Int) { let realm = try! Realm() guard let folder = realm.object(ofType: CPYFolder.self, forPrimaryKey: identifier) else { return } guard let savedSnippet = realm.object(ofType: CPYSnippet.self, forPrimaryKey: snippet.identifier) else { return } folder.realm?.transaction { folder.snippets.insert(savedSnippet, at: index) } folder.rearrangesSnippetIndex() } func removeSnippet(_ snippet: CPYSnippet) { let realm = try! Realm() guard let folder = realm.object(ofType: CPYFolder.self, forPrimaryKey: identifier) else { return } guard let savedSnippet = realm.object(ofType: CPYSnippet.self, forPrimaryKey: snippet.identifier), let index = folder.snippets.index(of: savedSnippet) else { return } folder.realm?.transaction { folder.snippets.remove(objectAtIndex: index) } folder.rearrangesSnippetIndex() } } // MARK: - Add Folder extension CPYFolder { static func create() -> CPYFolder { let realm = try! Realm() let folder = CPYFolder() folder.title = "untitled folder" let lastFolder = realm.objects(CPYFolder.self).sorted(byKeyPath: #keyPath(CPYFolder.index), ascending: true).last folder.index = lastFolder?.index ?? -1 folder.index += 1 return folder } func merge() { let realm = try! Realm() if let folder = realm.object(ofType: CPYFolder.self, forPrimaryKey: identifier) { folder.realm?.transaction { folder.index = index folder.enable = enable folder.title = title } } else { let copyFolder = CPYFolder(value: self) realm.transaction { realm.add(copyFolder, update: true) } } } } // MARK: - Remove Folder extension CPYFolder { func remove() { let realm = try! Realm() guard let folder = realm.object(ofType: CPYFolder.self, forPrimaryKey: identifier) else { return } folder.realm?.transaction { folder.realm?.delete(folder.snippets) } folder.realm?.transaction { folder.realm?.delete(folder) } } } // MARK: - Migrate Index extension CPYFolder { static func rearrangesIndex(_ folders: [CPYFolder]) { for (index, folder) in folders.enumerated() { if folder.realm == nil { folder.index = index } let realm = try! Realm() guard let savedFolder = realm.object(ofType: CPYFolder.self, forPrimaryKey: folder.identifier) else { return } savedFolder.realm?.transaction { savedFolder.index = index } } } func rearrangesSnippetIndex() { for (index, snippet) in snippets.enumerated() { if snippet.realm == nil { snippet.index = index } let realm = try! Realm() guard let savedSnippet = realm.object(ofType: CPYSnippet.self, forPrimaryKey: snippet.identifier) else { return } savedSnippet.realm?.transaction { savedSnippet.index = index } } } }
34.034722
174
0.611304
1dd8c7d17b8fcf572e52298ff51afb7be4493a72
17,564
// // EditUserPlant.swift // iInspection // // Created by Cohen Plontke on 2019-08-11. // Copyright © 2019 Cohen Plontke. All rights reserved. // import UIKit class EditUserPlantView: UIView { // Count select is used to attach the listener to the tableView var registerIsShown: Bool = false var tableViewIsShown: Bool = false var countSelect: Int = 0 let descriptionLabel: UILabel = { let label = UILabel() label.text = "User is not registered to a plant.\nPlease select which applies to you" label.numberOfLines = 2 label.textColor = .white label.frame.size.width = 50 label.font = UIFont(name: label.font.fontName, size: 20) label.lineBreakMode = NSLineBreakMode.byWordWrapping label.sizeToFit() label.translatesAutoresizingMaskIntoConstraints = false return label }() public static var plantTableView : UITableView = { let table = UITableView() table.translatesAutoresizingMaskIntoConstraints = false return table }() //Creates the White Container let inputsContainer: UIView = { let view = UIView() view.backgroundColor = UIColor.white view.translatesAutoresizingMaskIntoConstraints = false view.layer.cornerRadius = 5 view.layer.masksToBounds = false return view }() public static var plantNameTextField: UITextField = { let textField = UITextField() textField.placeholder = "Plant Name" textField.translatesAutoresizingMaskIntoConstraints = false return textField }() public static var companyTextField: UITextField = { let textField = UITextField() textField.placeholder = "Company Name" textField.translatesAutoresizingMaskIntoConstraints = false return textField }() let titleLabel: UILabel = { let label = UILabel() label.text = "Plant Registration" label.textColor = .white label.font = UIFont(name: label.font.fontName, size: 40) label.translatesAutoresizingMaskIntoConstraints = false return label }() public var registerButton: UIButton = { let button = UIButton() button.setTitle("Register New Plant", for: .normal) button.backgroundColor = UIColor(red: 80/255, green: 101/255, blue: 161/255, alpha: 1) button.translatesAutoresizingMaskIntoConstraints = false button.addTarget(self, action: #selector(registerWasPressed), for: .touchUpInside) return button }() public var secondRegisterButton: UIButton = { let button = UIButton() button.setTitle("Register Plant", for: .normal) button.backgroundColor = UIColor(red: 80/255, green: 101/255, blue: 161/255, alpha: 1) button.translatesAutoresizingMaskIntoConstraints = false button.addTarget(EditUserPlant(), action: #selector(EditUserPlant.handleSecondRegisterPressed), for: .touchUpInside) return button }() public var selectButton: UIButton = { let button = UIButton() button.setTitle("Request to Join Existing Plant", for: .normal) button.backgroundColor = UIColor(red: 80/255, green: 101/255, blue: 161/255, alpha: 1) button.addTarget(self, action: #selector(selectWasPressed), for: .touchUpInside) button.translatesAutoresizingMaskIntoConstraints = false return button }() public var backButton: UIButton = { let button = UIButton() button.setTitle("Back", for: .normal) button.backgroundColor = UIColor(red: 80/255, green: 101/255, blue: 161/255, alpha: 1) button.addTarget(self, action: #selector(registerWasPressed), for: .touchUpInside) button.translatesAutoresizingMaskIntoConstraints = false return button }() let companySeparatorView: UIView = { let view = UIView() view.backgroundColor = UIColor(red: 220/255, green: 220/255, blue: 220/255, alpha: 1) view.translatesAutoresizingMaskIntoConstraints = false return view }() public var selectBackButton: UIButton = { let button = UIButton() button.setTitle("Back", for: .normal) button.backgroundColor = UIColor(red: 80/255, green: 101/255, blue: 161/255, alpha: 1) button.addTarget(self, action: #selector(selectWasPressed), for: .touchUpInside) button.translatesAutoresizingMaskIntoConstraints = false return button }() let cancelRequestButton: UIButton = { let button = UIButton() button.setTitle("Cancel Request", for: .normal) button.backgroundColor = UIColor(red: 80/255, green: 101/255, blue: 161/255, alpha: 1) button.addTarget(EditUserPlant(), action: #selector(EditUserPlant.cancelRequest), for: .touchUpInside) button.translatesAutoresizingMaskIntoConstraints = false return button }() public var secondSelectButton : UIButton = { let button = UIButton() button.setTitle("Select Plant", for: .normal) button.backgroundColor = UIColor(red: 80/255, green: 101/255, blue: 161/255, alpha: 1) button.translatesAutoresizingMaskIntoConstraints = false button.addTarget(EditUserPlant(), action: #selector(EditUserPlant.handleSecondSelectPressed), for: .touchUpInside) return button }() override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor(red: 61/255, green: 91/255, blue: 151/255, alpha: 1) self.addSubview(titleLabel) self.addSubview(descriptionLabel) self.addSubview(registerButton) self.addSubview(selectButton) self.addSubview(inputsContainer) self.addSubview(secondRegisterButton) self.addSubview(backButton) self.addSubview(EditUserPlantView.plantTableView) self.addSubview(selectBackButton) self.addSubview(secondSelectButton) self.addSubview(cancelRequestButton) inputsContainer.addSubview(companySeparatorView) addObservers() setupSubViews() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // listens for the users inputs func addObservers() { NotificationCenter.default.addObserver(self, selector: #selector(requestWasSent), name: NSNotification.Name("requestSent"), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(requestWasCancelled), name: NSNotification.Name("requestHasBeenCancelled"), object: nil) } // setup all of the subviews func setupSubViews() { setupTitleLabel() setupDescriptionLabel() setupRegisterButton() setupSelectButton() setupInputsContainer() setupBackButton() setupSecondRegisterButton() setupTableView() setupBackButtonSelect() setupSecondSelectButton() setupCancelButton() } func setupTitleLabel() { titleLabel.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true titleLabel.topAnchor.constraint(equalTo: self.topAnchor, constant: 100).isActive = true titleLabel.bottomAnchor.constraint(equalTo: titleLabel.topAnchor, constant: 100).isActive = true } func setupDescriptionLabel() { descriptionLabel.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true descriptionLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor).isActive = true descriptionLabel.bottomAnchor.constraint(equalTo: descriptionLabel.topAnchor, constant: 100).isActive = true } func setupRegisterButton() { registerButton.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 15).isActive = true registerButton.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -15).isActive = true registerButton.topAnchor.constraint(equalTo: descriptionLabel.bottomAnchor, constant: 15).isActive = true registerButton.bottomAnchor.constraint(equalTo: registerButton.topAnchor, constant: 100).isActive = true } func setupInputsContainer() { inputsContainer.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true inputsContainer.centerYAnchor.constraint(equalTo: self.descriptionLabel.bottomAnchor, constant: 75).isActive = true inputsContainer.widthAnchor.constraint(equalTo: self.widthAnchor, constant: -24).isActive = true inputsContainer.heightAnchor.constraint(equalToConstant: 70).isActive = true inputsContainer.isHidden = true inputsContainer.addSubview(EditUserPlantView.plantNameTextField) inputsContainer.addSubview(EditUserPlantView.companyTextField) setupSeperatorView() setupPlantNickNameTextField() setupCompanyTextField() } func setupSecondSelectButton() { secondSelectButton.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -15).isActive = true secondSelectButton.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 15).isActive = true secondSelectButton.topAnchor.constraint(equalTo: selectBackButton.bottomAnchor, constant: 15).isActive = true secondSelectButton.bottomAnchor.constraint(equalTo: secondSelectButton.topAnchor, constant: 50).isActive = true secondSelectButton.isHidden = true } func setupSelectButton() { selectButton.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 15).isActive = true selectButton.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -15).isActive = true selectButton.topAnchor.constraint(equalTo: registerButton.bottomAnchor, constant: 15).isActive = true selectButton.bottomAnchor.constraint(equalTo: selectButton.topAnchor, constant: 100).isActive = true } func setupBackButton() { backButton.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -15).isActive = true backButton.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 15).isActive = true backButton.topAnchor.constraint(equalTo: inputsContainer.bottomAnchor, constant: 15).isActive = true backButton.bottomAnchor.constraint(equalTo: backButton.topAnchor, constant: 50).isActive = true backButton.isHidden = true } func setupBackButtonSelect() { selectBackButton.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -15).isActive = true selectBackButton.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 15).isActive = true selectBackButton.topAnchor.constraint(equalTo: EditUserPlantView.plantTableView.bottomAnchor, constant: 15).isActive = true selectBackButton.bottomAnchor.constraint(equalTo: selectBackButton.topAnchor, constant: 50).isActive = true selectBackButton.isHidden = true } func setupSecondRegisterButton() { secondRegisterButton.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -15).isActive = true secondRegisterButton.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 15).isActive = true secondRegisterButton.topAnchor.constraint(equalTo: backButton.bottomAnchor, constant: 15).isActive = true secondRegisterButton.bottomAnchor.constraint(equalTo: secondRegisterButton.topAnchor, constant: 50).isActive = true secondRegisterButton.isHidden = true } func setupSeperatorView(){ companySeparatorView.leftAnchor.constraint(equalTo: inputsContainer.leftAnchor).isActive = true companySeparatorView.rightAnchor.constraint(equalTo: inputsContainer.rightAnchor).isActive = true companySeparatorView.topAnchor.constraint(equalTo: inputsContainer.topAnchor, constant: 34).isActive = true companySeparatorView.bottomAnchor.constraint(equalTo: companySeparatorView.topAnchor, constant: 1).isActive = true } func setupPlantNickNameTextField() { EditUserPlantView.plantNameTextField.leftAnchor.constraint(equalTo: inputsContainer.leftAnchor, constant: 3).isActive = true EditUserPlantView.plantNameTextField.rightAnchor.constraint(equalTo: inputsContainer.rightAnchor).isActive = true EditUserPlantView.plantNameTextField.topAnchor.constraint(equalTo: inputsContainer.topAnchor).isActive = true EditUserPlantView.plantNameTextField.bottomAnchor.constraint(equalTo: companySeparatorView.topAnchor).isActive = true } func setupCompanyTextField() { EditUserPlantView.companyTextField.leftAnchor.constraint(equalTo: inputsContainer.leftAnchor, constant: 3).isActive = true EditUserPlantView.companyTextField.rightAnchor.constraint(equalTo: inputsContainer.rightAnchor).isActive = true EditUserPlantView.companyTextField.topAnchor.constraint(equalTo: companySeparatorView.bottomAnchor, constant: 5).isActive = true EditUserPlantView.plantNameTextField.bottomAnchor.constraint(equalTo: inputsContainer.bottomAnchor).isActive = true } func setupTableView() { EditUserPlantView.plantTableView.heightAnchor.constraint(equalToConstant: 200).isActive = true EditUserPlantView.plantTableView.widthAnchor.constraint(equalTo: self.widthAnchor, constant: -24).isActive = true EditUserPlantView.plantTableView.topAnchor.constraint(equalTo: descriptionLabel.bottomAnchor, constant: 25).isActive = true EditUserPlantView.plantTableView.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -12).isActive = true EditUserPlantView.plantTableView.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 12).isActive = true EditUserPlantView.plantTableView.isHidden = true } func setupCancelButton() { cancelRequestButton.heightAnchor.constraint(equalToConstant: 50).isActive = true cancelRequestButton.widthAnchor.constraint(equalTo: self.widthAnchor, constant: -24).isActive = true cancelRequestButton.topAnchor.constraint(equalTo: descriptionLabel.bottomAnchor, constant: 25).isActive = true cancelRequestButton.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -12).isActive = true cancelRequestButton.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 12).isActive = true cancelRequestButton.isHidden = true } // the register button was pressed adjust the view @objc func registerWasPressed() { if !registerIsShown { print("Setup input container view") registerButton.isHidden = true backButton.isHidden = false selectButton.isHidden = true inputsContainer.isHidden = false secondRegisterButton.isHidden = false registerIsShown = true descriptionLabel.text = "Enter the plants name and company" } else { print("registerIsShown == true") descriptionLabel.text = "User is not registered to a plant.\nPlease select which applies to you" inputsContainer.isHidden = true registerButton.isHidden = false selectButton.isHidden = false backButton.isHidden = true secondRegisterButton.isHidden = true registerIsShown = false } } //select was pressed adjust the view accordingly @objc func selectWasPressed() { if self.countSelect == 0 { NotificationCenter.default.post(name: NSNotification.Name("attachPlantListener"), object: nil) self.countSelect += 1 } if !tableViewIsShown { EditUserPlantView.plantTableView.isHidden = false registerButton.isHidden = true descriptionLabel.text = "Please Select Your Plant" selectButton.isHidden = true selectBackButton.isHidden = false tableViewIsShown = true secondSelectButton.isHidden = false } else { EditUserPlantView.plantTableView.isHidden = true registerButton.isHidden = false descriptionLabel.text = "User is not registered to a plant.\nPlease select which applies to you" selectButton.isHidden = false selectBackButton.isHidden = true secondSelectButton.isHidden = true tableViewIsShown = false } } // Once requested the user cannot do anything else @objc func requestWasSent() { selectBackButton.isHidden = true secondSelectButton.isHidden = true registerButton.isHidden = true selectButton.isHidden = true tableViewIsShown = false EditUserPlantView.plantTableView.isHidden = true titleLabel.text = "Request Sent" descriptionLabel.text = "Please notify your lead\nto accept your request" cancelRequestButton.isHidden = false } //The User has cancelled their request revert the screen @objc func requestWasCancelled() { print("request has been cancelled") titleLabel.text = "Plant Registration" descriptionLabel.text = "User is not registered to a plant.\nPlease select which applies to you" selectButton.isHidden = false registerButton.isHidden = false cancelRequestButton.isHidden = true } }
45.151671
161
0.696652
d76b057a27a8ecbf3ffbe3757ccbc3805800d0ff
3,661
/// Copyright (c) 2021 Razeware LLC /// /// Permission is hereby granted, free of charge, to any person obtaining a copy /// of this software and associated documentation files (the "Software"), to deal /// in the Software without restriction, including without limitation the rights /// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell /// copies of the Software, and to permit persons to whom the Software is /// furnished to do so, subject to the following conditions: /// /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software. /// /// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, /// distribute, sublicense, create a derivative work, and/or sell copies of the /// Software in any work that is designed, intended, or marketed for pedagogical or /// instructional purposes related to programming, coding, application development, /// or information technology. Permission for such use, copying, modification, /// merger, publication, distribution, sublicensing, creation of derivative works, /// or sale is expressly withheld. /// /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN /// THE SOFTWARE. import Foundation import Combine final class ComputationSubscription<Output>: Subscription { private let duration: TimeInterval private let sendCompletion: () -> Void private let sendValue: (Output) -> Subscribers.Demand private let finalValue: Output private var cancelled = false init(duration: TimeInterval, sendCompletion: @escaping () -> Void, sendValue: @escaping (Output) -> Subscribers.Demand, finalValue: Output) { self.duration = duration self.finalValue = finalValue self.sendCompletion = sendCompletion self.sendValue = sendValue } func request(_ demand: Subscribers.Demand) { if !cancelled { print("Beginning expensive computation on thread \(Thread.current.number)") } Thread.sleep(until: Date(timeIntervalSinceNow: duration)) if !cancelled { print("Completed expensive computation on thread \(Thread.current.number)") _ = self.sendValue(self.finalValue) self.sendCompletion() } } func cancel() { cancelled = true } } extension Publishers { public struct ExpensiveComputation: Publisher { public typealias Output = String public typealias Failure = Never public let duration: TimeInterval public init(duration: TimeInterval) { self.duration = duration } public func receive<S>(subscriber: S) where S : Subscriber, Failure == S.Failure, Output == S.Input { Swift.print("ExpensiveComputation subscriber received on thread \(Thread.current.number)") let subscription = ComputationSubscription( duration: duration, sendCompletion: { subscriber.receive(completion: .finished) }, sendValue: { subscriber.receive($0) }, finalValue: "Computation complete" ) subscriber.receive(subscription: subscription) } } }
41.602273
145
0.691068
f525d5ab349dcf91a15d4442f027c10bfe1aa403
920
// // WeatherDayTests.swift // WeatherDayTests // // Created by Thinh Nguyen X. on 9/21/20. // Copyright © 2020 Thinh Nguyen X. All rights reserved. // import XCTest @testable import WeatherDay class WeatherDayTests: XCTestCase { override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
26.285714
111
0.656522
1626644dbe25b94fdf641b310592ff60d9f1fc7d
3,008
// ------------------------------------------------------------------------------------------------- // Copyright (C) 2016-2019 HERE Europe B.V. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // SPDX-License-Identifier: Apache-2.0 // License-Filename: LICENSE // // ------------------------------------------------------------------------------------------------- import XCTest import functional class AttributesTests: XCTestCase { let attributes: Attributes = Attributes() func testBuiltInTypeAttribute() { attributes.builtInTypeAttribute = 42 XCTAssertEqual(42, attributes.builtInTypeAttribute) } func testReadonlyAttribute() { XCTAssertEqual(3.14, attributes.readonlyAttribute, accuracy: 1e-6) } func testStructAttribute() { let expectedStruct = Attributes.ExampleStruct(value: 2.71, intValue: []) attributes.structAttribute = expectedStruct let actualStruct = attributes.structAttribute XCTAssertEqual(expectedStruct.value, actualStruct.value, accuracy: 1e-6) } func testStructArrayLiteralAttribute() { var expectedStruct = Attributes.ExampleStruct(value: 2.71, intValue: []) expectedStruct.intValue = [1, 2, 3, 4] XCTAssertEqual(expectedStruct.intValue, [1, 2, 3, 4]) } func testStaticAttribute() { Attributes.staticAttribute = "fooBar" XCTAssertEqual("fooBar", Attributes.staticAttribute) } func testCachedProperty() { let instance = CachedProperties() XCTAssertEqual(0, instance.callCount) let result1 = instance.cachedProperty _ = instance.cachedProperty XCTAssertEqual(1, instance.callCount) XCTAssertEqual(["foo", "bar"], result1) } func testStaticCachedProperty() { XCTAssertEqual(0, CachedProperties.staticCallCount) let result1 = CachedProperties.staticCachedProperty _ = CachedProperties.staticCachedProperty XCTAssertEqual(1, CachedProperties.staticCallCount) XCTAssertEqual(Data([0, 1, 2]), result1) } static var allTests = [ ("testBuiltInTypeAttribute", testBuiltInTypeAttribute), ("testReadonlyAttribute", testReadonlyAttribute), ("testStructAttribute", testStructAttribute), ("testStructArrayLiteralAttribute", testStructArrayLiteralAttribute), ("testStaticAttribute", testStaticAttribute), ("testCachedProperty", testCachedProperty), ("testStaticCachedProperty", testStaticCachedProperty) ] }
33.422222
100
0.666223
14d7df0f1a56822f40f35df1ffa05c5cc9746e5d
4,673
// // ParseCoding.swift // ParseSwift // // Created by Florent Vilmart on 17-07-24. // Copyright © 2017 Parse. All rights reserved. // import Foundation // MARK: ParseCoding /// Custom coding for Parse objects. enum ParseCoding {} // MARK: Coders extension ParseCoding { /// The JSON Encoder setup with the correct `dateEncodingStrategy` /// strategy for `Parse`. static func jsonEncoder() -> JSONEncoder { let encoder = JSONEncoder() encoder.dateEncodingStrategy = parseDateEncodingStrategy encoder.outputFormatting = .sortedKeys return encoder } /// The JSON Decoder setup with the correct `dateDecodingStrategy` /// strategy for `Parse`. This encoder is used to decode all data received /// from the server. static func jsonDecoder() -> JSONDecoder { let decoder = JSONDecoder() decoder.dateDecodingStrategy = dateDecodingStrategy return decoder } /// The Parse Encoder is used to JSON encode all `ParseObject`s and /// types in a way meaninful for a Parse Server to consume. static func parseEncoder() -> ParseEncoder { ParseEncoder( dateEncodingStrategy: parseDateEncodingStrategy, outputFormatting: .sortedKeys ) } } // MARK: Coding public extension ParseObject { /// The Parse encoder is used to JSON encode all `ParseObject`s and /// types in a way meaninful for a Parse Server to consume. static func getEncoder() -> ParseEncoder { return ParseCoding.parseEncoder() } /// The Parse encoder is used to JSON encode all `ParseObject`s and /// types in a way meaninful for a Parse Server to consume. func getEncoder() -> ParseEncoder { return Self.getEncoder() } /// The JSON encoder setup with the correct `dateEncodingStrategy` /// strategy to send data to a Parse Server. static func getJSONEncoder() -> JSONEncoder { return ParseCoding.jsonEncoder() } /// The JSON encoder setup with the correct `dateEncodingStrategy` /// strategy to send data to a Parse Server. func getJSONEncoder() -> JSONEncoder { return Self.getJSONEncoder() } /// The JSON decoder setup with the correct `dateDecodingStrategy` /// strategy to decode data from a Parse Server. This encoder is used to decode all data received /// from the server. static func getDecoder() -> JSONDecoder { ParseCoding.jsonDecoder() } /// The JSON decoder setup with the correct `dateDecodingStrategy` /// strategy to decode data from a Parse Server. This encoder is used to decode all data received /// from the server. func getDecoder() -> JSONDecoder { Self.getDecoder() } } // MARK: Dates extension ParseCoding { enum DateEncodingKeys: String, CodingKey { case iso case type = "__type" } static let dateFormatter: DateFormatter = { var dateFormatter = DateFormatter() dateFormatter.locale = Locale(identifier: "en_US_POSIX") dateFormatter.timeZone = TimeZone(secondsFromGMT: 0) dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" return dateFormatter }() static let parseDateEncodingStrategy: JSONEncoder.DateEncodingStrategy = .custom { (date, encoder) in var container = encoder.container(keyedBy: DateEncodingKeys.self) try container.encode("Date", forKey: .type) let dateString = dateFormatter.string(from: date) try container.encode(dateString, forKey: .iso) } static let dateDecodingStrategy: JSONDecoder.DateDecodingStrategy = .custom({ (decoder) -> Date in do { let container = try decoder.singleValueContainer() let decodedString = try container.decode(String.self) if let date = dateFormatter.date(from: decodedString) { return date } else { throw ParseError( code: .unknownError, message: "An invalid date string was provided when decoding dates." ) } } catch { let container = try decoder.container(keyedBy: DateEncodingKeys.self) if let decoded = try container.decodeIfPresent(String.self, forKey: .iso), let date = dateFormatter.date(from: decoded) { return date } else { throw ParseError( code: .unknownError, message: "An invalid date string was provided when decoding dates." ) } } }) }
33.378571
105
0.635352
dd1463b1621859d4ec6988f08202750e8173a117
383
import PackageDescription let libraries = [ Target(name: "Replacer"), Target(name: "TestReplacer", dependencies: [ .Target(name: "Replacer"), ] ), ] let package = Package( name: "Replacer", targets: libraries, dependencies: [ .Package(url: "https://github.com/Alamofire/Alamofire.git", majorVersion: 4), ] )
20.157895
85
0.577023
eb110d821d77dbb531ea524e20e4cc17d7c43969
3,356
import XCTest import Differific class UITableViewExtensionsTests: XCTestCase { class DataSourceMock: NSObject, UITableViewDataSource { var models = [String]() init(models: [String] = []) { self.models = models } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return models.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) return cell } } func testReloadWithInsertions() { let dataSource = DataSourceMock() let tableView = UITableView() tableView.dataSource = dataSource tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell") let old = dataSource.models let new = ["Foo", "Bar", "Baz"] let manager = DiffManager() let changes = manager.diff(old, new) var ranBefore: Bool = false var ranCompletion: Bool = false tableView.reload(with: changes, updateDataSource: { dataSource.models = new ranBefore = true }) { ranCompletion = true } XCTAssertTrue(ranBefore) XCTAssertTrue(ranCompletion) } func testReloadWithMove() { let dataSource = DataSourceMock(models: ["Foo", "Bar", "Baz"]) let tableView = UITableView() tableView.dataSource = dataSource tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell") let old = dataSource.models let new = ["Baz", "Bar", "Foo"] let manager = DiffManager() let changes = manager.diff(old, new) var ranBefore: Bool = false var ranCompletion: Bool = false tableView.reload(with: changes, updateDataSource: { dataSource.models = new ranBefore = true }) { ranCompletion = true } XCTAssertTrue(ranBefore) XCTAssertTrue(ranCompletion) } func testReloadWithDeletions() { let dataSource = DataSourceMock(models: ["Foo", "Bar", "Baz"]) let tableView = UITableView() tableView.dataSource = dataSource tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell") let old = dataSource.models let new = [String]() let manager = DiffManager() let changes = manager.diff(old, new) var ranBefore: Bool = false var ranCompletion: Bool = false tableView.reload(with: changes, updateDataSource: { dataSource.models = new ranBefore = true }) { ranCompletion = true } XCTAssertTrue(ranBefore) XCTAssertTrue(ranCompletion) } func testReloadWithEmptyChanges() { let dataSource = DataSourceMock(models: ["Foo", "Bar", "Baz"]) let tableView = UITableView() tableView.dataSource = dataSource tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell") let old = dataSource.models let new = ["Foo", "Bar", "Baz"] let manager = DiffManager() let changes = manager.diff(old, new) var ranBefore: Bool = false var ranCompletion: Bool = false tableView.reload(with: changes, updateDataSource: { dataSource.models = new ranBefore = true }) { ranCompletion = true } XCTAssertFalse(ranBefore) XCTAssertTrue(ranCompletion) } }
26.634921
100
0.654648
2f15029b9304a0d8ffc1dafaa9ddd47bdbc96ad2
1,693
// MIT License // // Copyright (c) 2020 linhey // // 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. #if canImport(SwiftUI) import SwiftUI @available(iOS 13.0, macOS 11.0, tvOS 13.0, watchOS 6.0, *) public extension SwiftUI.Image { /// Creates a instance of `Image` with a system symbol image of the given type. /// /// - Parameter systemSymbol: The `SFSymbol` describing this image. init(_ symbol: SFSymbol) { self.init(systemName: symbol.rawValue) } } @available(iOS 13.0, macOS 11.0, tvOS 13.0, watchOS 6.0, *) public extension SFSymbol { func convert() -> Image { return SwiftUI.Image(self) } } #endif
35.270833
83
0.720024
f45fd217b96d3cce87a8ab05bd83a7def11cd939
1,098
// // UartSettingTableViewCell.swift // Bluefruit Connect // // Created by Antonio García on 08/02/16. // Copyright © 2016 Adafruit. All rights reserved. // import UIKit class UartSettingTableViewCell: UITableViewCell { // UI @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var segmentedControl: UISegmentedControl! @IBOutlet weak var switchControl: UISwitch! var onSwitchEnabled : ((enabled: Bool) -> ())? var onSegmentedControlIndexChanged : ((selectedIndex: Int) -> ())? override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } @IBAction func onSwitchValueChanged(sender: UISwitch) { onSwitchEnabled?(enabled: sender.on) } @IBAction func onSegmentedControlValueChanged(sender: UISegmentedControl) { onSegmentedControlIndexChanged?(selectedIndex: sender.selectedSegmentIndex) } }
26.780488
83
0.689435
6adaa35dbb117eb6d8efbb9ac17213d25c9dbdaa
2,079
// // RAML+Resources.swift // RAML // // Created by Christoph Pageler on 24.07.17. // import Foundation public extension RAML { public func enumerateResource(_ closure: @escaping (_ resource: Resource,_ resourceChain: [Resource], _ stop: inout Bool) -> ()) { enumerateResourcesIn(typeWhoHasResources: self) { resource, resourceChain, stop in closure(resource, resourceChain, &stop) } } public func absolutePathForResource(_ resourceToFind: Resource) -> String { var foundResourceWithChain: [Resource]? = nil enumerateResource { resource, resourceChain, stop in if resource === resourceToFind { stop = true foundResourceWithChain = resourceChain } } if let foundResourceWithChain = foundResourceWithChain { var path = "" for resource in foundResourceWithChain { path += resource.path } return path } else { return resourceToFind.path } } private func enumerateResourcesIn(typeWhoHasResources: HasResources, resourceChain: [Resource]? = nil, closure: @escaping (_ resource: Resource, _ resourceChain: [Resource], _ stop: inout Bool) -> ()) { // enumerate resource for resource in typeWhoHasResources.resources ?? [] { // make chain variable var resourceChainForDepth = resourceChain ?? [] // append chain resourceChainForDepth.append(resource) // call closure and check for stop var stop = false closure(resource, resourceChainForDepth, &stop) if stop { return } // call recursive enumerateResourcesIn(typeWhoHasResources: resource, resourceChain: resourceChainForDepth, closure: closure) } } }
34.081967
137
0.554113
219470f9bccde37cab7e45f68e5e6bf1cd0029e0
322
import UIKit extension UIFontDescriptorSymbolicTraits { init(_ attributes: Attributes) { self.init(rawValue: (attributes.style.contains(.bold) ? UIFontDescriptorSymbolicTraits.traitBold.rawValue : 0) | (attributes.style.contains(.italic) ? UIFontDescriptorSymbolicTraits.traitItalic.rawValue : 0) ) } }
32.2
193
0.76087
69491399366d9b41ef8d14a215645c061e370cc5
6,384
// // Copyright (c) 2021 Related Code - https://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 Walkthrough5View: UIViewController { @IBOutlet var collectionView: UICollectionView! @IBOutlet var pageControl: UIPageControl! private var collections: [[String: String]] = [] //------------------------------------------------------------------------------------------------------------------------------------------- override func viewDidLoad() { super.viewDidLoad() collectionView.register(UINib(nibName: "Walkthrough5Cell", bundle: nil), forCellWithReuseIdentifier: "Walkthrough5Cell") pageControl.pageIndicatorTintColor = UIColor.lightGray pageControl.currentPageIndicatorTintColor = AppColor.Theme loadCollections() } // MARK: - Collections methods //------------------------------------------------------------------------------------------------------------------------------------------- func loadCollections() { collections.removeAll() var dict1: [String: String] = [:] dict1["feature1"] = "Feature #1" dict1["description1"] = "It is those feelings that drive our love of delicious food and our desire to serve you better" dict1["feature2"] = "Feature #2" dict1["description2"] = "It is those feelings that drive our love of delicious food and our desire to serve you better" collections.append(dict1) collections.append(dict1) collections.append(dict1) collections.append(dict1) refreshCollectionView() } // MARK: - User actions //------------------------------------------------------------------------------------------------------------------------------------------- @IBAction func actionSkip(_ sender: UIButton) { dismiss(animated: true) } // MARK: - Refresh methods //------------------------------------------------------------------------------------------------------------------------------------------- func refreshCollectionView() { collectionView.reloadData() } } // MARK:- UICollectionViewDataSource //----------------------------------------------------------------------------------------------------------------------------------------------- extension Walkthrough5View: UICollectionViewDataSource { //------------------------------------------------------------------------------------------------------------------------------------------- func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } //------------------------------------------------------------------------------------------------------------------------------------------- func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return collections.count } //------------------------------------------------------------------------------------------------------------------------------------------- func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Walkthrough5Cell", for: indexPath) as! Walkthrough5Cell cell.bindData(index: indexPath.item, data: collections[indexPath.row]) return cell } } // MARK:- UICollectionViewDelegate //----------------------------------------------------------------------------------------------------------------------------------------------- extension Walkthrough5View: UICollectionViewDelegate { //------------------------------------------------------------------------------------------------------------------------------------------- func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { print("didSelectItemAt \(indexPath.row)") } //------------------------------------------------------------------------------------------------------------------------------------------- func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { pageControl.currentPage = indexPath.row } } // MARK:- UICollectionViewDelegateFlowLayout //----------------------------------------------------------------------------------------------------------------------------------------------- extension Walkthrough5View: UICollectionViewDelegateFlowLayout { //------------------------------------------------------------------------------------------------------------------------------------------- func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let height = collectionView.frame.size.height let width = collectionView.frame.size.width return CGSize(width: width, height: height) } //------------------------------------------------------------------------------------------------------------------------------------------- func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) } //------------------------------------------------------------------------------------------------------------------------------------------- func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 0 } //------------------------------------------------------------------------------------------------------------------------------------------- func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 0 } }
44.643357
172
0.480107
0163950713e4240dcf23a3f0d9240486fdc05b71
507
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse let b = 0] = true { } class A : a { protocol a { class b[c<T, e? { typealias e == ") d<e: T, 3] { } typealias e: e
28.166667
78
0.698225
bb248a339f5475a692ddf2da81ee4d9e016618c1
100
import XCTest @testable import RedisSwiftTests XCTMain([ testCase(RedisSwiftTests.allTests) ])
14.285714
38
0.79
18c032ed4d7cd018b4260b7f5a9af1c67299bd47
7,173
// // CameraSettingCell.swift // GIFMaker // // Created by indream on 15/9/20. // Copyright © 2015年 indream. All rights reserved. // import UIKit class CameraSettingCell: UITableViewCell { @IBOutlet weak var focusLabel: UILabel! @IBOutlet weak var focusSlider: UISlider! @IBOutlet weak var speedLabel: UILabel! @IBOutlet weak var speedSlider: UISlider! @IBOutlet weak var isoLabel: UILabel! @IBOutlet weak var isoSlider: UISlider! @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var timeSlider: UISlider! @IBOutlet weak var intervalLabel: UILabel! @IBOutlet weak var intervalSlider: UISlider! var cid:Int16 = 0 var sid:Int16 = 0 weak var tableView:UITableView! func setCameraIndex(_ sid:Int16, cid:Int16){ self.cid = cid if(self.cid<0){ self.cid = 0 } self.sid = sid if(self.sid<0){ self.sid = 0 } updateConfig() } override func awakeFromNib() { super.awakeFromNib() updateConfig() } func updateConfig(){ let cam:CameraModel? = DataManager.sharedManager().camera(sid,cid: cid)! if(cam==nil){ DataManager.sharedManager().createCamera(sid,cid: cid) } let focus:Float = Float(cam!.focus) let speed:Float = Float(cam!.speed) if((focusSlider) != nil){ focusSlider.value = focus focusLabel.text = String(format: "%.2f", focusSlider.value/8000.0) speedSlider.value = 0 speedLabel.text = String(format: "1/%.0f", speed) isoSlider.value = Float(cam!.iso) isoLabel.text = String(format: "%.0f", isoSlider.value) } if((timeSlider) != nil){ timeSlider.value = 0 timeLabel.text = String(format: "%d %@", cam!.time,NSLocalizedString("secs", comment: "")) intervalSlider.value = 0 intervalLabel.text = String(format: "%.1f %@ / %d %@", cam!.interval,NSLocalizedString("secs", comment: ""),Int(Float(cam!.time)/Float(cam!.interval)),NSLocalizedString("frames", comment: "")) } } func assignTableView(_ tableView:UITableView){ self.tableView = tableView } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } @IBAction func focusChanged(_ sender: AnyObject) { focusLabel.text = String(format: "%.2f", focusSlider.value/8000.0) let cam:CameraModel = DataManager.sharedManager().camera(sid,cid: cid)! cam.focus = focusSlider.value tableView.alpha = 0.1 VideoManager.sharedManager().configureDevice(sid,cid:cid) } @IBAction func speedChanged(_ sender: AnyObject) { let cam:CameraModel = DataManager.sharedManager().camera(sid,cid: cid)! var scale:Float = 1 if(cam.speed<500){ scale = 3 } if(cam.speed<300){ scale = 5 } if(cam.speed<100){ scale = 10 } if(cam.speed<50){ scale = 20 } let speed = speedSlider.value/scale if(Float(cam.speed)+speed<2){ speedLabel.text = String(format: "1/%d", 2) }else{ speedLabel.text = String(format: "1/%.0f", Float(cam.speed)+speed) } tableView.alpha = 0.1 VideoManager.sharedManager().configureDevice(sid,cid:cid) } @IBAction func speedTouchEnd(_ sender: AnyObject) { let cam:CameraModel = DataManager.sharedManager().camera(sid,cid: cid)! var scale:Float = 1 if(cam.speed<500){ scale = 3 } if(cam.speed<300){ scale = 5 } if(cam.speed<100){ scale = 10 } if(cam.speed<50){ scale = 20 } cam.speed += Int16(speedSlider.value/scale) if(cam.speed<2){ cam.speed = 2 }else if(cam.speed>8000){ cam.speed = 8000 } speedLabel.text = String(format: "1/%d", cam.speed) speedSlider.value = 0 tableView.alpha = 1.0 VideoManager.sharedManager().configureDevice(sid,cid:cid) } @IBAction func focusEnd(_ sender: AnyObject) { tableView.alpha = 1.0 } @IBAction func isoEnd(_ sender: AnyObject) { tableView.alpha = 1.0 } @IBAction func isoChanged(_ sender: AnyObject) { isoLabel.text = String(format: "%.0f", isoSlider.value) let cam:CameraModel = DataManager.sharedManager().camera(sid,cid: cid)! cam.iso = Int16(isoSlider.value) tableView.alpha = 0.1 VideoManager.sharedManager().configureDevice(sid,cid:cid) } @IBAction func timeChanged(_ sender: AnyObject) { let cam:CameraModel = DataManager.sharedManager().camera(sid,cid: cid)! let time = timeSlider.value/2 timeLabel.text = String(format: "%.1f %@", Float(cam.time)+time,NSLocalizedString("secs", comment: "")) intervalLabel.text = String(format: "%.1f %@ / %d %@", cam.interval,NSLocalizedString("secs", comment: ""),Int((Float(cam.time)+time)/cam.interval),NSLocalizedString("frames", comment: "")) } @IBAction func timeTouchEnd(_ sender: AnyObject) { let cam:CameraModel = DataManager.sharedManager().camera(sid,cid: cid)! cam.time += Int32(floorf(timeSlider.value/2)) if(cam.time<0){ cam.time = 0 } timeSlider.value = 0 timeLabel.text = String(format: "%.1f %@", Float(cam.time),NSLocalizedString("secs", comment: "")) intervalLabel.text = String(format: "%.1f %@ / %d %@", cam.interval,NSLocalizedString("secs", comment: ""),Int((Float(cam.time)/cam.interval)),NSLocalizedString("frames", comment: "")) } @IBAction func intervalChanged(_ sender: AnyObject) { let cam:CameraModel = DataManager.sharedManager().camera(sid,cid: cid)! let interval = intervalSlider.value/4 if((cam.interval+interval)>0.1){ intervalLabel.text = String(format: "%.1f %@ / %d %@", (cam.interval+interval),NSLocalizedString("secs", comment: ""),Int(Float(cam.time)/Float(cam.interval+interval)),NSLocalizedString("frames", comment: "")) }else{ intervalLabel.text = String(format: "%.1f %@ / %d %@",0.1,NSLocalizedString("secs", comment: ""),Int(Float(cam.time)/0.1),NSLocalizedString("frames", comment: "")) } } @IBAction func intervalTouchEnd(_ sender: AnyObject) { let cam:CameraModel = DataManager.sharedManager().camera(sid,cid: cid)! cam.interval += intervalSlider.value/4 if(cam.interval<0.1){ cam.interval = 0.1 } intervalSlider.value = 0 timeLabel.text = String(format: "%.1f %@", Float(cam.time),NSLocalizedString("secs", comment: "")) intervalLabel.text = String(format: "%.1f %@ / %d %@", cam.interval,NSLocalizedString("secs", comment: ""),Int((Float(cam.time)/cam.interval)),NSLocalizedString("frames", comment: "")) } }
38.564516
221
0.596821
90602cc7f222f531b514fb0df3fd70ad7924775a
198
class RADWIMPS { func then() -> RADWIMPS { print("前", terminator: ""); return self; } func 世() { print("世"); } } let radwimps = RADWIMPS(); radwimps.then().then().then().世();
13.2
34
0.535354
bfaf48fe9c67f7e4e1cb873d2ae4041e844e4f00
946
// // View+extensions.swift // piggy-bank // // Created by Никита Гайко on 03/02/2019. // Copyright © 2019 Nikita Gayko. All rights reserved. // import UIKit extension UIView { @IBInspectable var cornerRadius: CGFloat { get { return layer.cornerRadius } set { layer.cornerRadius = newValue } } @IBInspectable var borderWidth: CGFloat { get { return layer.borderWidth } set { layer.borderWidth = newValue } } @IBInspectable var borderColor: UIColor? { get { if let cgColor = layer.borderColor { return UIColor(cgColor: cgColor) } else { return nil } } set { layer.borderColor = newValue?.cgColor } } @IBInspectable var maskToBounds: Bool { get { return layer.masksToBounds } set { layer.masksToBounds = newValue } } }
21.5
55
0.557082
76e372f48d5955854217a0d3236fdc61d9f63e22
1,427
// // PreWorkUITests.swift // PreWorkUITests // // Created by Keylly Castillo on 1/15/22. // import XCTest class PreWorkUITests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // UI tests must launch the application that they test. let app = XCUIApplication() app.launch() // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testLaunchPerformance() throws { if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 7.0, *) { // This measures how long it takes to launch your application. measure(metrics: [XCTApplicationLaunchMetric()]) { XCUIApplication().launch() } } } }
33.186047
182
0.655922
164b719e004b11d9fff9fea15fffb6870a88c3c3
2,920
// // File.swift // // // Created by Callum Trounce on 11/06/2019. // import Foundation import Combine struct DownloadInfo { enum State { case progress(Float) case result(URL) } let url: URL var state: State } final class Downloader: NSObject { private let queue = DispatchQueue( label: "SWURL.DownloaderQueue" + UUID().uuidString, qos: .userInitiated, attributes: .concurrent ) private var tasks: [URLSessionDownloadTask: CurrentValueSubject<DownloadInfo, Error>] = [:] private lazy var session: URLSession = { [weak self] in let urlSession = URLSession.init( configuration: .default, delegate: self, delegateQueue: OperationQueue() ) return urlSession }() func download(from url: URL) -> CurrentValueSubject<DownloadInfo, Error> { // Only place where `tasks` is written to, therefore place barrier flag. queue.sync(flags: .barrier) { let task = session.downloadTask(with: url) let subject = CurrentValueSubject<DownloadInfo, Error>.init( DownloadInfo.init( url: url, state: .progress(0) ) ) tasks[task] = subject task.resume() return subject } } } extension Downloader: URLSessionDownloadDelegate { func urlSession( _ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL ) { queue.async { [weak self] in guard let self = self, var downloadInfo = self.tasks[downloadTask]?.value else { return } downloadInfo.state = .result(location) self.tasks[downloadTask]?.send(downloadInfo) self.tasks[downloadTask]?.send(completion: .finished) SwURLDebug.log( level: .info, message: "Download of \(downloadInfo.url) finished download to \(location)" ) } } func urlSession( _ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64 ) { queue.async { [weak self] in guard let self = self, var downloadInfo = self.tasks[downloadTask]?.value else { return } let fractionDownloaded = Float(Double(totalBytesWritten) / Double(totalBytesExpectedToWrite)) downloadInfo.state = .progress(fractionDownloaded) self.tasks[downloadTask]?.send(downloadInfo) SwURLDebug.log( level: .info, message: "Download of \(downloadInfo.url) reached progress: \(fractionDownloaded)" ) } } }
27.037037
105
0.57911
16c7368d93d66b964a845afed563f63a0117567e
2,717
// // SceneDelegate.swift // CoLoS // // Created by Tim Jaeger on 02.01.21. // import UIKit import SwiftUI import CoreLocation class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). // Create the SwiftUI view that provides the window contents. let contentView = ContentView() // Use a UIHostingController as window root view controller. if let windowScene = scene as? UIWindowScene { let window = UIWindow(windowScene: windowScene) window.rootViewController = UIHostingController(rootView: contentView) self.window = window window.makeKeyAndVisible() } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
42.453125
147
0.706294
ff8c8c008a9f58ee4f0a46b0b17c270a04525ced
2,280
// // ModerationOverviewViewController.swift // Slide for Reddit // // Created by Carlos Crane on 11/16/20. // Copyright © 2020 Haptic Apps. All rights reserved. // import reddift import UIKit import UserNotifications class ModerationOverviewViewController: UITableViewController { var subs: [String] init() { self.subs = ["All moderated subs"] self.subs.append(contentsOf: AccountController.modSubs) super.init(style: .plain) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) setupBaseBarColors() if #available(iOS 13.0, *) { self.isModalInPresentation = true } } override func loadView() { super.loadView() self.view.backgroundColor = UIColor.backgroundColor self.title = "Subs you Moderate" self.tableView.separatorStyle = .none self.tableView.register(SubredditCellView.classForCoder(), forCellReuseIdentifier: "sub") } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 75 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "sub") as? SubredditCellView cell?.setSubreddit(subreddit: subs[indexPath.row], nav: self.navigationController) return cell! } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let vc = ModerationViewController(indexPath.row == 0 ? "mod" : subs[indexPath.row]) VCPresenter.showVC(viewController: vc, popupIfPossible: true, parentNavigationController: self.navigationController, parentViewController: self) } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: return self.subs.count // + 1 default: fatalError("Unknown number of sections") } } }
32.571429
152
0.669298
5bc8757d2c880f2be0f39895fbcba7cbd26f72a2
1,179
// // UI // // Copyright © 2018 mkerekes. All rights reserved. // import UIKit public class TableFooter: UITableViewCell { @IBOutlet var nextButton: UIButton! public typealias NextAction = () -> Void public var nextAction: NextAction? public var dataModel: DataModel? { didSet { guard let model = dataModel else { return } nextButton.isHidden = !model.isVisible nextButton.isEnabled = model.isEnabled nextButton.setTitle(model.title, for: .normal) guard let imageName = model.asset else { return } nextButton.setBackgroundImage(UIImage(named: imageName), for: .normal) } } @IBAction func didTap(_ sender: Any) { nextAction?() } public struct DataModel { let title: String? let asset: String? let isVisible: Bool let isEnabled: Bool public init(title: String?, asset: String?, isVisible: Bool, isEnabled: Bool) { self.title = title self.asset = asset self.isVisible = isVisible self.isEnabled = isEnabled } } }
26.795455
87
0.581849
9bfe612b9bfa4aaa9463bde52889ee9ac425e400
789
// // RHView.swift // RHScrollView // // Created by Rashwan Lazkani on 2018-11-14. // Copyright © 2018 Rashwan Lazkani. All rights reserved. // import UIKit public class RHView: UIView { override public var backgroundColor: UIColor? { didSet { super.backgroundColor = backgroundColor } } var image: UIImage? = UIImage() init() { super.init(frame: .zero) } public init(backgroundColor: UIColor?) { super.init(frame: .zero) self.backgroundColor = backgroundColor } public init(image: UIImage?) { super.init(frame: .zero) self.image = image } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
20.763158
59
0.593156
f4092a75d08513d2b9d5bdf341dc9607371ff229
10,411
// // UIFunctionsHelper.swift // MarmaraEgzersiz // // Created by Muhendis on 3.05.2018. // Copyright © 2018 Muhendis. All rights reserved. // import UIKit import UserNotifications import Charts class ControllerFunctionsHelper { static func show_error(viewController : UIViewController, title: String, info:String) { let alert = UIAlertController(title: title, message: info, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Tamam", style: .default, handler: nil)) viewController.present(alert, animated: true) } static func show_error_eng(viewController : UIViewController, title: String, info:String) { let alert = UIAlertController(title: title, message: info, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil)) viewController.present(alert, animated: true) } static func show_logout(viewController : UIViewController, title: String, info:String) { let alert = UIAlertController(title: title, message: info, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Vazgeç", style: .default, handler: nil)) alert.addAction(UIAlertAction(title: "Çıkış", style: .default, handler: { action in switch action.style{ case .default: let storyboard = UIStoryboard(name: "Main", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: "LoginViewControllerStoryBoard") viewController.present(controller, animated: true, completion: nil) case .cancel: print("cancel") case .destructive: print("d") }})) viewController.present(alert, animated: true) } static func show_info(title: String, info:String) { if var topController = UIApplication.shared.keyWindow?.rootViewController { while let presentedViewController = topController.presentedViewController { topController = presentedViewController } let alert = UIAlertController(title: title, message: info, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Tamam", style: .default, handler: nil)) topController.present(alert, animated: true) } } static func show_info_eng(title: String, info:String) { if var topController = UIApplication.shared.keyWindow?.rootViewController { while let presentedViewController = topController.presentedViewController { topController = presentedViewController } let alert = UIAlertController(title: title, message: info, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil)) topController.present(alert, animated: true) } } static func show_registered_info(viewController : UIViewController, title: String, info:String) { let alert = UIAlertController(title: title, message: info, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Tamam", style: .default, handler: { action in switch action.style{ case .default: /*let storyboard = UIStoryboard(name: "Main", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: "LoginViewControllerStoryBoard") as? LoginViewController controller?.isLoggingOut = true viewController.present(controller!, animated: true, completion: nil)*/ ControllerFunctionsHelper.present_controller(identifier: Identifiers.LOGIN_VIEW_CONTROLLER, viewController: viewController) case .cancel: print("cancel") case .destructive: print("d") }})) viewController.present(alert, animated: true) } static func get_todays_date() -> String { let date = Date() let formatter = DateFormatter() formatter.dateFormat = "dd-MM-yyyy" let result = formatter.string(from: date) return result } static func get_date_by_index(index : Int) -> String { let date = NSCalendar.current.date(byAdding: .day, value: index, to: Date()) let formatter = DateFormatter() formatter.dateFormat = "dd-MM-yyyy" let result = formatter.string(from: date!) return result } static func format_date_from_string(dateString : String) -> Date { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd-MM-yyyy" guard let date = dateFormatter.date(from: dateString) else { fatalError("ERROR: Date conversion failed due to mismatched format.") } return date } static func calculate_days_between_dates(firstDateString:String,secondDateString:String) -> Int?{ let calendar = NSCalendar.current let firstDate = format_date_from_string(dateString: firstDateString) let secondDate = format_date_from_string(dateString: secondDateString) // Replace the hour (time) of both dates with 00:00 let date1 = calendar.startOfDay(for: firstDate) let date2 = calendar.startOfDay(for: secondDate) let components = calendar.dateComponents([.day], from: date1, to: date2) return components.day } static func present_controller(identifier:String,viewController:UIViewController){ let storyboard = UIStoryboard(name: "Main", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: identifier) viewController.present(controller, animated: true, completion: nil) } static func scheduleAppAlarms(hours: Int, minutes: Int, title:String,message:String){ print("Controller alarm") print(message) print(title) let content = UNMutableNotificationContent() content.categoryIdentifier = "exerciseNotifications" content.sound = UNNotificationSound.default() content.title = NSString.localizedUserNotificationString(forKey: title, arguments: nil) content.body = NSString.localizedUserNotificationString(forKey: message, arguments: nil) // Configure the trigger for a 7am wakeup. var dateInfo = DateComponents() dateInfo.hour = hours dateInfo.minute = minutes let trigger = UNCalendarNotificationTrigger(dateMatching: dateInfo, repeats: true) // Create the request object. let request = UNNotificationRequest(identifier: String(hours)+String(minutes), content: content, trigger: trigger) let center = UNUserNotificationCenter.current() center.add(request) { (error : Error?) in if let theError = error { print("Alarm Error") print(theError.localizedDescription) } } } static func load_bar_graph(mDailyChart:BarChartView, totalDuration: Int, viewController : DailyStatisticsViewController) { var barChartEntry = [ChartDataEntry]() barChartEntry.append(BarChartDataEntry(x: 2, y: Double(totalDuration/60))) var bar = BarChartDataSet(values: barChartEntry, label: "Egzersiz Süresi (dk)") if isLanguageEnglish(){ bar = BarChartDataSet(values: barChartEntry, label: "Exercise Time (min)") } bar.setColor(UIColor(red: 5/255.0, green: 48/255.0, blue: 86/255.0, alpha: 1)) let data = BarChartData() data.addDataSet(bar) data.barWidth = 0.1 mDailyChart.data = data mDailyChart.noDataText = "Egzersiz verisi bulunamadı" var desc = Description() desc.text = "Günlük Tamamlanan Egzersiz Süresi" if isLanguageEnglish(){ mDailyChart.noDataText = "No exercise data found" desc.text = "Daily Finished Exercise Time" } desc.yOffset = -10 mDailyChart.chartDescription = desc mDailyChart.notifyDataSetChanged() mDailyChart.setNeedsDisplay() mDailyChart.setNeedsLayout() mDailyChart.animate(yAxisDuration: 1) viewController.view.setNeedsLayout() //mDailyChart.chartDescription?.text = "Günlük Tamamlanan Egzersiz Süresi" } static func load_line_graph(mWeeklyChart:BarChartView, lineChartEntry: [BarChartDataEntry], viewController : WeeklyStatisticsViewController) { var line = BarChartDataSet(values: lineChartEntry, label: "Egzersiz Süresi (dk)") if isLanguageEnglish(){ line = BarChartDataSet(values: lineChartEntry, label: "Exercise Time (min)") } line.setColor(UIColor(red: 5/255.0, green: 48/255.0, blue: 86/255.0, alpha: 1)) //line.colors = [UIColor(red: 5/255.0, green: 48/255.0, blue: 86/255.0, alpha: 1)] //line.circleColors = [UIColor(red: 5/255.0, green: 48/255.0, blue: 86/255.0, alpha: 1)] let data = BarChartData() data.addDataSet(line) mWeeklyChart.data = data mWeeklyChart.noDataText = "Egzersiz verisi bulunamadı" var desc = Description() desc.text = "Son 1 Haftada Tamamlanan Egzersiz Süreleri" if isLanguageEnglish(){ mWeeklyChart.noDataText = "No exercise data found" desc.text = "Finished Exercise Time in Last Week" } desc.yOffset = -10 mWeeklyChart.chartDescription = desc //mDailyChart.chartDescription?.text = "Günlük Tamamlanan Egzersiz Süresi" } static func isLanguageEnglish() -> Bool { let preferences = UserDefaults.standard if preferences.object(forKey: Keys.userFileLanguageEnglishKey) == nil { return false } else { return preferences.bool(forKey: Keys.userFileLanguageEnglishKey) } } }
40.352713
147
0.625876
b97a42d67a51aed7d8c3f33d78abe5c5d103ccb9
5,817
/** * Copyright IBM Corporation 2016 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import UIKit import MapKit import CoreLocation class RestaurantDetailViewController: UIViewController { var chosenRestaurant:Restaurant! /* Restaurant chosen by the user to see details. */ var reviewKeywords:String! @IBOutlet weak var eventDetailHolderView: UIView! @IBOutlet weak var backButton: UIButton! @IBOutlet weak var scrollViewContentView: UIView! @IBOutlet weak var restaurantDetailHolderView: UIView! let kBackButtonTitle = "RESTAURANTS" /// restaurant detail view weak var restaurantDetailView: RecommendedRestaurantDetailView! private let buttonFrame = CGRect.init(x: 31, y: 39.5, width: 109, height: 13) /** Method called upon view did load to set up holderView, map, and adds subview */ override func viewDidLoad() { super.viewDidLoad() setUpHolderViewWithRestaurant() setupRecommendedRestaurantDetailView() eventDetailHolderView.addSubview(restaurantDetailView) // set up navigation items. Utils.setNavigationItems(viewController: self, rightButtons: [MoreIconBarButtonItem()], leftButtons: [WhitePathIconBarButtonItem(), UIBarButtonItem(customView: backButton)]) Utils.setupNavigationTitleLabel(viewController: self, title: "", spacing: 1.0, titleFontSize: 17, color: UIColor.white) self.navigationController?.isNavigationBarHidden = false } override func viewWillAppear(_ animated: Bool) { self.navigationController?.isNavigationBarHidden = false // Set up the navigation bar so that we can color the nav bar to be dark blue, and the default symbols to be white. Utils.setupBackButton(button: backButton, title: kBackButtonTitle, textColor: UIColor.white, frame: buttonFrame) // set up navigation items. Utils.setNavigationItems(viewController: self, rightButtons: [MoreIconBarButtonItem()], leftButtons: [WhitePathIconBarButtonItem(), UIBarButtonItem(customView: backButton)]) Utils.setupNavigationTitleLabel(viewController: self, title: "", spacing: 1.0, titleFontSize: 17, color: UIColor.white) } override func viewWillDisappear(_ animated: Bool) { self.navigationController?.isNavigationBarHidden = true } @IBAction func didPressBackButton(_ sender: AnyObject) { _ = self.navigationController?.popViewController(animated: true) } func setupRecommendedRestaurantDetailView() { // splice the restaurant address into address, city, state. var locationAddress = self.chosenRestaurant.getAddress().components(separatedBy: ",") // load data into restaurant details view restaurantDetailView.setupData(openNowStatus: self.chosenRestaurant.getOpenNowStatus(), openingTimeNow: self.chosenRestaurant.getOpeningTimeNow(), locationName:self.chosenRestaurant.getName(), locationAddress: locationAddress[0], city: "\(locationAddress[1]),\(locationAddress[2])", fullAddress: self.chosenRestaurant.getAddress(), priceLevel: Double(self.chosenRestaurant.getExpense()), rating: self.chosenRestaurant.getRating(), reviewNegativeHighlight: self.determineReviewSentiment(type: "negative"), reviewPositiveHighlight: self.determineReviewSentiment(type: "positive")) // Make website view clickable. let tap = UITapGestureRecognizer(target: self, action: #selector(visitWebsiteTapped)) restaurantDetailView.visitWebsiteView.addGestureRecognizer(tap) } func setUpHolderViewWithRestaurant() { restaurantDetailView = RecommendedRestaurantDetailView.instanceFromNib() } @objc func visitWebsiteTapped() { UIApplication.shared.open(URL(string: self.chosenRestaurant.getWebsite())!, options: [:]) } /** Method to determine positive and negative sentiments in reviews. - paramater type: String to specify whether to determine positive or negative sentiments. */ func determineReviewSentiment(type:String) -> String{ if self.chosenRestaurant.getReviews().count == 0 { return "No reviews found for me to analyze what people thought of this restaurant." } if type == "negative" { if self.chosenRestaurant.getNegativeSentiments().count == 0 { return "I found 0 hints to any negative sentiments in the reviews I have." } else { return self.chosenRestaurant.getNegativeSentiments().joined(separator: ", ") } } else { if self.chosenRestaurant.getPositiveSentiments().count == 0 { return "I found 0 hints to any positive sentiments in the reviews I have." } else { return self.chosenRestaurant.getPositiveSentiments().joined(separator: ", ") } } } }
46.536
181
0.663057
62f9e567bdf6cf3f91106920e39a16c461769fd5
6,457
// // CollectionViewTableViewCell.swift // zScanner // // Created by Jan Provazník on 28/05/2020. // Copyright © 2020 Institut klinické a experimentální medicíny. All rights reserved. // import UIKit import RxSwift import SnapKit protocol CollectionViewCellDelegate { func reeditMedia(media: Media) func deleteDocument() func createNewMedia() func reload() } class CollectionViewTableViewCell: UITableViewCell { // MARK: Instance part private(set) var viewModel: MediaListViewModel? private var delegate: CollectionViewCellDelegate? override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupView() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK: Lifecycle override func prepareForReuse() { super.prepareForReuse() viewModel = nil disposeBag = DisposeBag() } // MARK: Interface func setup(with field: CollectionViewField, viewModel: MediaListViewModel, delegate: CollectionViewCellDelegate) { self.viewModel = viewModel self.delegate = delegate field.picturesCount.accept(viewModel.mediaArray.value.count) resetHeight() collectionView.reloadData() } func reloadCells() { collectionView.reloadData() } // MARK: Helpers private var disposeBag = DisposeBag() var heightConstraint: Constraint? private func setupView() { selectionStyle = .none preservesSuperviewLayoutMargins = true contentView.preservesSuperviewLayoutMargins = true contentView.addSubview(deleteButton) deleteButton.snp.makeConstraints { make in make.leading.trailing.centerX.bottom.equalToSuperview() make.height.equalTo(30) } contentView.addSubview(collectionView) collectionView.snp.makeConstraints { make in make.top.leading.trailing.equalToSuperview() make.bottom.equalTo(deleteButton.snp.top).inset(-10) } } private func resetHeight() { let count = viewModel!.mediaArray.value.count + 1 let elementsPair = (count+1)/2 let newHeight = CGFloat(elementsPair) * (itemWidth + margin) + margin + deleteButton.frame.height heightConstraint?.deactivate() collectionView.snp.makeConstraints { make in heightConstraint = make.height.equalTo(newHeight).priority(999).constraint } } @objc private func deleteDocument() { delegate?.deleteDocument() } private lazy var collectionView: UICollectionView = { let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: flowLayout) collectionView.backgroundColor = .white collectionView.isScrollEnabled = false collectionView.register(PhotoSelectorCollectionViewCell.self, forCellWithReuseIdentifier: "PhotoSelectorCollectionViewCell") collectionView.register(AddNewMediaCollectionViewCell.self, forCellWithReuseIdentifier: "AddNewMediaCollectionViewCell") collectionView.dataSource = self return collectionView }() private lazy var flowLayout: UICollectionViewLayout = { let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: itemWidth, height: itemWidth) layout.scrollDirection = .vertical layout.minimumInteritemSpacing = margin layout.minimumLineSpacing = margin layout.sectionInset = UIEdgeInsets(top: margin, left: margin, bottom: margin, right: margin) return layout }() private let margin: CGFloat = 10 private let numberofColumns: CGFloat = 2 private var itemWidth: CGFloat { let screenWidth = UIScreen.main.bounds.width return (screenWidth - (numberofColumns + 1) * margin) / numberofColumns } private lazy var deleteButton: UIButton = { let button = UIButton() let attributedString = NSAttributedString(string: "newDocumentPhotos.deleteDocument.title".localized, attributes: [ .underlineStyle: NSUnderlineStyle.single.rawValue, .foregroundColor: UIColor.red, .font: UIFont.footnote ]) button.setAttributedTitle(attributedString, for: .normal) button.addTarget(self, action: #selector(deleteDocument), for: .touchUpInside) return button }() } // MARK: - UICollectionViewDataSource implementation extension CollectionViewTableViewCell: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return (viewModel?.mediaArray.value.count ?? 0) + 1 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if indexPath.row == viewModel?.mediaArray.value.count { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "AddNewMediaCollectionViewCell", for: indexPath) as! AddNewMediaCollectionViewCell cell.setup(delegate: self) return cell } else { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotoSelectorCollectionViewCell", for: indexPath) as! PhotoSelectorCollectionViewCell let media = viewModel!.mediaArray.value[indexPath.row] cell.setup(with: media, delegate: self) return cell } } } // MARK: - PhotoSelectorCellDelegate implementation extension CollectionViewTableViewCell: PhotoSelectorCellDelegate { func edit(media: Media) { delegate?.reeditMedia(media: media) } func delete(media: Media) { viewModel?.removeMedia(media) collectionView.reloadData() resetHeight() delegate?.reload() } } // MARK: - AddNewMediaCellDelegate implementation extension CollectionViewTableViewCell: AddNewMediaCellDelegate { func createNewMedia() { delegate?.createNewMedia() } }
35.674033
165
0.657116
d6624c427282c712e04b65ca0b87951e2c4b2c75
6,388
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // import CoreFoundation public struct _NSRange { public var location: Int public var length: Int public init() { location = 0 length = 0 } public init(location: Int, length: Int) { self.location = location self.length = length } internal init(_ range: CFRange) { location = range.location == kCFNotFound ? NSNotFound : range.location length = range.length } } extension CFRange { internal init(_ range: NSRange) { location = range.location == NSNotFound ? kCFNotFound : range.location length = range.length } } public typealias NSRange = _NSRange extension NSRange { public init(_ x: Range<Int>) { location = x.startIndex length = x.count } @warn_unused_result public func toRange() -> Range<Int>? { if location == NSNotFound { return nil } let min = location let max = location + length return min..<max } } extension NSRange: NSSpecialValueCoding { init(bytes: UnsafePointer<Void>) { let buffer = UnsafePointer<Int>(bytes) self.location = buffer.pointee self.length = buffer.advanced(by: 1).pointee } init?(coder aDecoder: NSCoder) { if aDecoder.allowsKeyedCoding { if let location = aDecoder.decodeObjectOfClass(NSNumber.self, forKey: "NS.rangeval.location") { self.location = location.integerValue } else { self.location = 0 } if let length = aDecoder.decodeObjectOfClass(NSNumber.self, forKey: "NS.rangeval.length") { self.length = length.integerValue } else { self.length = 0 } } else { NSUnimplemented() } } func encodeWithCoder(aCoder: NSCoder) { if aCoder.allowsKeyedCoding { aCoder.encodeObject(NSNumber(integer: self.location), forKey: "NS.rangeval.location") aCoder.encodeObject(NSNumber(integer: self.length), forKey: "NS.rangeval.length") } else { NSUnimplemented() } } static func objCType() -> String { #if arch(i386) || arch(arm) return "{_NSRange=II}" #elseif arch(x86_64) || arch(arm64) return "{_NSRange=QQ}" #else NSUnimplemented() #endif } func getValue(value: UnsafeMutablePointer<Void>) { UnsafeMutablePointer<NSRange>(value).pointee = self } func isEqual(aValue: Any) -> Bool { if let other = aValue as? NSRange { return other.location == self.location && other.length == self.length } else { return false } } var hash: Int { return self.location &+ self.length } var description: String? { return NSStringFromRange(self) } } public typealias NSRangePointer = UnsafeMutablePointer<NSRange> public func NSMakeRange(loc: Int, _ len: Int) -> NSRange { return NSRange(location: loc, length: len) } public func NSMaxRange(range: NSRange) -> Int { return range.location + range.length } public func NSLocationInRange(loc: Int, _ range: NSRange) -> Bool { return !(loc < range.location) && (loc - range.location) < range.length } public func NSEqualRanges(range1: NSRange, _ range2: NSRange) -> Bool { return range1.location == range2.location && range1.length == range2.length } public func NSUnionRange(range1: NSRange, _ range2: NSRange) -> NSRange { let max1 = range1.location + range1.length let max2 = range2.location + range2.length let maxend: Int if max1 > max2 { maxend = max1 } else { maxend = max2 } let minloc: Int if range1.location < range2.location { minloc = range1.location } else { minloc = range2.location } return NSMakeRange(minloc, maxend - minloc) } public func NSIntersectionRange(range1: NSRange, _ range2: NSRange) -> NSRange { let max1 = range1.location + range1.length let max2 = range2.location + range2.length let minend: Int if max1 < max2 { minend = max1 } else { minend = max2 } if range2.location <= range1.location && range1.location < max2 { return NSMakeRange(range1.location, minend - range1.location) } else if range1.location <= range2.location && range2.location < max1 { return NSMakeRange(range2.location, minend - range2.location) } return NSMakeRange(0, 0) } public func NSStringFromRange(range: NSRange) -> String { return "{\(range.location), \(range.length)}" } public func NSRangeFromString(aString: String) -> NSRange { let emptyRange = NSMakeRange(0, 0) if aString.isEmpty { // fail early if the string is empty return emptyRange } let scanner = NSScanner(string: aString) let digitSet = NSCharacterSet.decimalDigitCharacterSet() scanner.scanUpToCharactersFromSet(digitSet) if scanner.atEnd { // fail early if there are no decimal digits return emptyRange } guard let location = scanner.scanInteger() else { return emptyRange } let partialRange = NSMakeRange(location, 0) if scanner.atEnd { // return early if there are no more characters after the first int in the string return partialRange } scanner.scanUpToCharactersFromSet(digitSet) if scanner.atEnd { // return early if there are no integer characters after the first int in the string return partialRange } guard let length = scanner.scanInteger() else { return partialRange } return NSMakeRange(location, length) } extension NSValue { public convenience init(range: NSRange) { self.init() self._concreteValue = NSSpecialValue(range) } public var rangeValue: NSRange { let specialValue = self._concreteValue as! NSSpecialValue return specialValue._value as! NSRange } }
29.036364
107
0.631027
cc661e02aed464be03b176f34ea3815632b369c0
6,912
// // DemoPhotoViewController.swift // YangMingShanDemo // // Copyright 2016 Yahoo Inc. // Licensed under the terms of the BSD license. Please see LICENSE file in the project root for terms. // import UIKit import YangMingShan class DemoPhotoViewController: UIViewController, YMSPhotoPickerViewControllerDelegate, UICollectionViewDataSource, UICollectionViewDelegate { let cellIdentifier = "imageCellIdentifier" var images: NSArray! = [] @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var numberOfPhotoSelectionTextField: UITextField! @IBAction func presentPhotoPicker(_ sender: AnyObject) { if self.numberOfPhotoSelectionTextField.text!.count > 0 && UInt(self.numberOfPhotoSelectionTextField.text!) != 1 { let pickerViewController = YMSPhotoPickerViewController.init() pickerViewController.numberOfPhotoToSelect = UInt(self.numberOfPhotoSelectionTextField.text!)! pickerViewController.sourceType = .both; let customColor = UIColor.init(red:248.0/255.0, green:217.0/255.0, blue:44.0/255.0, alpha:1.0) pickerViewController.theme.titleLabelTextColor = UIColor.black pickerViewController.theme.navigationBarBackgroundColor = customColor pickerViewController.theme.tintColor = UIColor.black pickerViewController.theme.orderTintColor = customColor pickerViewController.theme.orderLabelTextColor = UIColor.black pickerViewController.theme.cameraVeilColor = customColor pickerViewController.theme.cameraIconColor = UIColor.white pickerViewController.theme.statusBarStyle = .default self.yms_presentCustomAlbumPhotoView(pickerViewController, delegate: self) } else { self.yms_presentAlbumPhotoView(with: self) } } @objc func deletePhotoImage(_ sender: UIButton!) { let mutableImages: NSMutableArray! = NSMutableArray.init(array: images) mutableImages.removeObject(at: sender.tag) self.images = NSArray.init(array: mutableImages) self.collectionView.performBatchUpdates({ self.collectionView.deleteItems(at: [IndexPath.init(item: sender.tag, section: 0)]) }, completion: nil) } override func viewDidLoad() { let barButtonItem: UIBarButtonItem! = UIBarButtonItem.init(barButtonSystemItem: .organize, target: self, action:#selector(presentPhotoPicker(_:))) self.navigationItem.rightBarButtonItem = barButtonItem self.collectionView.register(UINib.init(nibName: "DemoImageViewCell", bundle: nil), forCellWithReuseIdentifier: cellIdentifier) } // MARK: - YMSPhotoPickerViewControllerDelegate func photoPickerViewControllerDidReceivePhotoAlbumAccessDenied(_ picker: YMSPhotoPickerViewController!) { let alertController = UIAlertController.init(title: "Allow photo album access?", message: "Need your permission to access photo albumbs", preferredStyle: .alert) let dismissAction = UIAlertAction.init(title: "Cancel", style: .cancel, handler: nil) let settingsAction = UIAlertAction.init(title: "Settings", style: .default) { (action) in UIApplication.shared.openURL(URL.init(string: UIApplicationOpenSettingsURLString)!) } alertController.addAction(dismissAction) alertController.addAction(settingsAction) self.present(alertController, animated: true, completion: nil) } func photoPickerViewControllerDidReceiveCameraAccessDenied(_ picker: YMSPhotoPickerViewController!) { let alertController = UIAlertController.init(title: "Allow camera album access?", message: "Need your permission to take a photo", preferredStyle: .alert) let dismissAction = UIAlertAction.init(title: "Cancel", style: .cancel, handler: nil) let settingsAction = UIAlertAction.init(title: "Settings", style: .default) { (action) in UIApplication.shared.openURL(URL.init(string: UIApplicationOpenSettingsURLString)!) } alertController.addAction(dismissAction) alertController.addAction(settingsAction) // The access denied of camera is always happened on picker, present alert on it to follow the view hierarchy picker.present(alertController, animated: true, completion: nil) } func photoPickerViewController(_ picker: YMSPhotoPickerViewController!, didFinishPicking image: UIImage!) { picker.dismiss(animated: true) { self.images = [image] self.collectionView.reloadData() } } func photoPickerViewController(_ picker: YMSPhotoPickerViewController!, didFinishPickingMedia mediaAssets: [PHAsset]!) { picker.dismiss(animated: true) { let imageManager = PHImageManager.init() let options = PHImageRequestOptions.init() options.deliveryMode = .highQualityFormat options.resizeMode = .exact options.isSynchronous = true let mutableImages: NSMutableArray! = [] for asset: PHAsset in photoAssets { let scale = UIScreen.main.scale let targetSize = CGSize(width: (self.collectionView.bounds.width - 20*2) * scale, height: (self.collectionView.bounds.height - 20*2) * scale) imageManager.requestImage(for: asset, targetSize: targetSize, contentMode: .aspectFill, options: options, resultHandler: { (image, info) in mutableImages.add(image!) }) } self.images = mutableImages.copy() as? NSArray self.collectionView.reloadData() } } // MARK: - UICollectionViewDataSource func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.images.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell: DemoImageViewCell! = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! DemoImageViewCell cell.photoImageView.image = self.images.object(at: (indexPath as NSIndexPath).item) as? UIImage cell.deleteButton.tag = (indexPath as NSIndexPath).item cell.deleteButton.addTarget(self, action: #selector(DemoPhotoViewController.deletePhotoImage(_:)), for: .touchUpInside) return cell } // MARK: - UICollectionViewDelegateFlowLayout func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize { return CGSize(width: collectionView.bounds.width, height: collectionView.bounds.height) } }
46.702703
169
0.700955
1ebbd2814b71f4cc0fcbdad166ea5bb7ed158e05
723
// // CarouselView.swift // VideoScrubber // // Created by Abheyraj Singh on 15/07/15. // Copyright © 2015 Housing Labs. All rights reserved. // import UIKit class CarouselView: UIView { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var titleLabel: UILabel! var view: UIView! override init(frame: CGRect) { super.init(frame: frame) self.view = NSBundle.mainBundle().loadNibNamed("CarouselView", owner: self, options: nil)[0] as! UIView self.frame = frame self.view.frame = self.frame self.view.setNeedsLayout() self.addSubview(view) } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! } }
23.322581
111
0.643154
bb1b21f60fcc384cb8c60cebb75b21d4c8569b66
846
// // BerryFarmerCommand.swift // pssamcKit // // Created by Eduardo Pinto on 05/07/20. // import Foundation import SwiftCLI class BerryFarmerCommand: Command { func execute() throws { let calendar = try Calendar(format: calendarFormat) let iterations = Int(iterationsToSave ?? "5") ?? 5 let bot = BerryFarmerBot(calendar: calendar, iterationsToSave: iterations) let device = try Device() let runner = Runner(device: device, bot: bot) try runner.run() } var name: String = "berryfarmer" var shortDescription: String = "Berry Farmer bot. Takes calendar type, e.g. 'us' (default), 'jp' or 'eu', and iterations to save (defaults to 5) as optional parameters." @Param var calendarFormat: String? @Param var iterationsToSave: String? }
27.290323
173
0.643026
ed81b31a39a14751465985c27d0059b6f0a8d97f
16,210
// // Calculator.swift // Dive Planner // // Created by PeroPeroMan on 2015/07/27. // Copyright © 2015年 TMDC. All rights reserved. // import Foundation class Calculator { private var group_matrix: [(begin: Float, end: Float, min: [(begin: Int, end: Int, group: String)])] = [] private var repeat_group_matrix: [String: [(begin: Float, end: Float, time: (rnt: Int, abt: Int))]] = [:] private var surface_interval_group: [String: [(begin: Int, end: Int, group: String)]] = [:] init () { setGroupMatrix() setRepeatGroupMatirx() setSurfaceIntervalGroup() } private func setGroupMatrix() { let depth10: [(begin: Int, end: Int, group: String)] = [(0,10,"A"),(11,20,"B"),(21,26,"C"),(27,30,"D"),(31,34,"E"),(35,37,"F"),(38,41,"G"),(42,45,"H"),(46,50,"I"),(51,54,"J"),(55,59,"K"),(60,64,"L"),(65,70,"M"),(71,75,"N"),(76,82,"O"),(83,88,"P"),(89,95,"Q"),(96,104,"R"),(105,112,"S"),(113,122,"T"),(123,133,"U"),(134,145,"V"),(146,160,"W"),(161,178,"X"),(179,199,"Y"),(200,219,"Z")] let depth12: [(begin: Int, end: Int, group: String)] = [(0,9,"A"),(10,17,"B"),(18,23,"C"),(24,26,"D"),(27,29,"E"),(30,32,"F"),(33,35,"G"),(36,38,"H"),(39,42,"I"),(43,45,"J"),(46,49,"K"),(50,53,"L"),(54,57,"M"),(58,62,"N"),(63,66,"O"),(67,71,"P"),(72,76,"Q"),(77,82,"R"),(83,88,"S"),(89,94,"T"),(95,101,"U"),(102,108,"V"),(109,116,"W"),(117,125,"X"),(126,134,"Y"),(135,147,"Z")] let depth14: [(begin: Int, end: Int, group: String)] = [(0,8,"A"),(9,15,"B"),(16,19,"C"),(20,22,"D"),(23,24,"E"),(25,27,"F"),(28,29,"G"),(30,32,"H"),(33,35,"I"),(36,37,"J"),(38,40,"K"),(41,43,"L"),(44,47,"M"),(48,50,"N"),(51,53,"O"),(54,57,"P"),(58,61,"Q"),(62,64,"R"),(65,68,"S"),(69,73,"T"),(74,77,"U"),(78,82,"V"),(83,87,"W"),(88,92,"X"),(93,98,"Y")] let depth16: [(begin: Int, end: Int, group: String)] = [(0,7,"A"),(8,13,"B"),(14,17,"C"),(18,19,"D"),(20,21,"E"),(22,23,"F"),(24,25,"G"),(26,27,"H"),(28,29,"I"),(30,32,"J"),(33,34,"K"),(35,37,"L"),(38,39,"M"),(40,42,"N"),(43,45,"O"),(46,48,"P"),(49,50,"Q"),(51,53,"R"),(54,56,"S"),(57,60,"T"),(61,63,"U"),(64,67,"V"),(68,70,"W"),(71,72,"X")] let depth18: [(begin: Int, end: Int, group: String)] = [(0,6,"A"),(7,11,"B"),(12,15,"C"),(16,16,"D"),(17,18,"E"),(19,20,"F"),(21,22,"G"),(23,24,"H"),(25,26,"I"),(27,28,"J"),(29,30,"K"),(31,32,"L"),(33,34,"M"),(35,36,"N"),(37,39,"O"),(40,41,"P"),(42,43,"Q"),(44,46,"R"),(47,48,"S"),(49,51,"T"),(52,53,"U"),(54,55,"V"),(56,56,"W")] let depth20: [(begin: Int, end: Int, group: String)] = [(0,6,"A"),(7,10,"B"),(11,13,"C"),(14,15,"D"),(16,16,"E"),(17,18,"F"),(19,20,"G"),(21,21,"H"),(22,23,"I"),(24,25,"J"),(26,26,"K"),(27,28,"L"),(29,30,"M"),(31,32,"N"),(33,34,"O"),(35,36,"P"),(37,38,"Q"),(39,40,"R"),(41,42,"S"),(43,44,"T"),(45,45,"U")] let depth22: [(begin: Int, end: Int, group: String)] = [(0,5,"A"),(6,9,"B"),(10,12,"C"),(13,13,"D"),(14,15,"E"),(16,16,"F"),(17,18,"G"),(19,19,"H"),(20,21,"I"),(22,22,"J"),(23,24,"K"),(25,25,"L"),(26,27,"M"),(28,29,"N"),(30,30,"O"),(31,32,"P"),(33,34,"Q"),(35,36,"R"),(37,37,"S")] let depth25: [(begin: Int, end: Int, group: String)] = [(0,4,"A"),(5,8,"B"),(9,10,"C"),(11,11,"D"),(12,13,"E"),(14,14,"F"),(15,15,"G"),(16,17,"H"),(18,18,"I"),(19,19,"J"),(20,21,"K"),(22,22,"L"),(23,23,"M"),(24,25,"N"),(26,26,"O"),(27,28,"P"),(29,29,"Q")] let depth30: [(begin: Int, end: Int, group: String)] = [(0,3,"A"),(4,6,"B"),(7,8,"C"),(9,9,"D"),(10,10,"E"),(11,11,"F"),(12,12,"G"),(13,13,"H"),(14,14,"I"),(15,15,"J"),(16,16,"K"),(17,17,"L"),(18,19,"M"),(20,20,"N")] let depth35: [(begin: Int, end: Int, group: String)] = [(0,3,"A"),(4,5,"B"),(6,7,"C"),(8,8,"D"),(9,9,"F"),(10,10,"G"),(11,11,"H"),(12,12,"I"),(13,13,"J"),(14,14,"K")] let depth40: [(begin: Int, end: Int, group: String)] = [(0,5,"B"),(6,6,"C"),(7,7,"E"),(8,8,"F"),(9,9,"G")] let depth45: [(begin: Int, end: Int, group: String)] = [(0,4,"B"),(5,6,"D"),(7,7,"E"),(8,8,"F")] group_matrix.append((0,10,depth10)); group_matrix.append((10,12,depth12)); group_matrix.append((12,14,depth14)); group_matrix.append((14,16,depth16)); group_matrix.append((16,18,depth18)); group_matrix.append((18,20,depth20)); group_matrix.append((20,22,depth22)); group_matrix.append((22,25,depth25)); group_matrix.append((25,30,depth30)); group_matrix.append((30,35,depth35)); group_matrix.append((35,40,depth40)); group_matrix.append((40,45,depth45)); } private func setRepeatGroupMatirx() { var list: [[(begin: Float, end: Float, time: (rnt: Int, abt: Int))]] = [] list.append([(0,10,(10,209)),(11,12,(9,138)),(13,14,(8,90)),(15,16,(7,65)),(17,18,(6,50)),(19,20,(6,39)),(21,22,(5,32)),(23,25,(4,25)),(26,30,(3,17)),(31,35,(3,11)),(36,40,(2,7))]) list.append([(0,10,(20,119)),(11,12,(17,130)),(13,14,(15,83)),(15,16,(13,59)),(17,18,(11,45)),(19,20,(10,35)),(21,22,(9,28)),(23,25,(8,21)),(26,30,(6,14)),(31,35,(5,9)),(36,40,(5,4))]) list.append([(0,10,(26,193)),(11,12,(23,124)),(13,14,(19,79)),(15,16,(17,55)),(17,18,(15,41)),(19,20,(13,32)),(21,22,(12,25)),(23,25,(10,19)),(26,30,(8,12)),(31,35,(7,7)),(36,40,(6,-1))]) list.append([(0,10,(30,189)),(11,12,(26,121)),(13,14,(22,76)),(15,16,(19,53)),(17,18,(16,40)),(19,20,(15,30)),(21,22,(13,24)),(23,25,(11,18)),(26,30,(9,11)),(31,35,(8,6)),(36,40,(7,-1))]) list.append([(0,10,(34,185)),(11,12,(29,118)),(13,14,(24,74)),(15,16,(21,51)),(17,18,(18,38)),(19,20,(16,29)),(21,22,(15,22)),(23,25,(13,16)),(26,30,(10,10)),(31,35,(9,5)),(36,40,(7,-1))]) list.append([(0,10,(37,182)),(11,12,(32,115)),(13,14,(27,71)),(15,16,(23,49)),(17,18,(20,36)),(19,20,(18,27)),(21,22,(16,21)),(23,25,(14,15)),(26,30,(11,9)),(31,35,(9,5)),(36,40,(8,-1))]) list.append([(0,10,(10,209)),(11,12,(9,138)),(13,14,(8,90)),(15,16,(7,65)),(17,18,(6,50)),(19,20,(6,39)),(21,22,(5,32)),(23,25,(4,25)),(26,30,(3,17)),(31,35,(3,11)),(36,40,(2,7))]) list.append([(0,10,(45,174)),(11,12,(38,109)),(13,14,(32,66)),(15,16,(27,45)),(17,18,(24,32)),(19,20,(21,24)),(21,22,(19,18)),(23,25,(17,12)),(26,30,(13,7)),(31,35,(11,3))]) list.append([(0,10,(50,169)),(11,12,(42,105)),(13,14,(35,63)),(15,16,(29,43)),(17,18,(26,30)),(19,20,(23,22)),(21,22,(21,16)),(23,25,(18,11)),(26,30,(14,6)),(31,35,(12,-1))]) list.append([(0,10,(54,165)),(11,12,(45,102)),(13,14,(37,61)),(15,16,(32,40)),(17,18,(28,28)),(19,20,(25,20)),(21,22,(22,15)),(23,25,(19,10)),(26,30,(15,5)),(31,35,(13,-1))]) list.append([(0,10,(59,160)),(11,12,(49,98)),(13,14,(40,58)),(15,16,(34,38)),(17,18,(30,26)),(19,20,(26,19)),(21,22,(24,13)),(23,25,(21,8)),(26,30,(16,4)),(31,35,(14,-1))]) list.append([(0,10,(64,155)),(11,12,(53,94)),(13,14,(43,55)),(15,16,(37,35)),(17,18,(32,24)),(19,20,(28,17)),(21,22,(25,12)),(23,25,(22,7)),(26,30,(17,3))]) list.append([(0,10,(70,149)),(11,12,(57,90)),(13,14,(47,51)),(15,16,(39,33)),(17,18,(34,22)),(19,20,(30,15)),(21,22,(27,10)),(23,25,(23,6)),(26,30,(19,-1))]) list.append([(0,10,(75,144)),(11,12,(62,85)),(13,14,(50,48)),(15,16,(42,30)),(17,18,(36,20)),(19,20,(32,13)),(21,22,(29,8)),(23,25,(25,4)),(26,30,(20,-1))]) list.append([(0,10,(82,137)),(11,12,(66,81)),(13,14,(53,45)),(15,16,(45,27)),(17,18,(39,17)),(19,20,(34,11)),(21,22,(30,7)),(23,25,(26,3))]) list.append([(0,10,(88,131)),(11,12,(71,76)),(13,14,(57,41)),(15,16,(48,24)),(17,18,(41,15)),(19,20,(36,9)),(21,22,(32,5)),(23,25,(28,-1))]) list.append([(0,10,(95,124)),(11,12,(76,71)),(13,14,(61,37)),(15,16,(50,22)),(17,18,(43,13)),(19,20,(38,7)),(21,22,(34,3)),(23,25,(29,-1))]) list.append([(0,10,(88,131)),(11,12,(71,76)),(13,14,(57,41)),(15,16,(48,24)),(17,18,(41,15)),(19,20,(36,9)),(21,22,(32,5)),(23,25,(28,-1))]) list.append([(0,10,(104,115)),(11,12,(82,65)),(13,14,(64,34)),(15,16,(53,19)),(17,18,(46,10)),(19,20,(40,5)),(21,22,(36,-1))]) list.append([(0,10,(112,107)),(11,12,(88,59)),(13,14,(68,30)),(15,16,(56,16)),(17,18,(48,8)),(19,20,(42,3)),(21,22,(37,-1))]) list.append([(0,10,(122,97)),(11,12,(94,53)),(13,14,(73,25)),(15,16,(60,12)),(17,18,(51,5)),(19,20,(44,-1))]) list.append([(0,10,(133,86)),(11,12,(101,46)),(13,14,(77,21)),(15,16,(63,9)),(17,18,(53,3)),(19,20,(45,-1))]) list.append([(0,10,(145,74)),(11,12,(108,39)),(13,14,(82,16)),(15,16,(67,5)),(17,18,(55,-1))]) list.append([(0,10,(160,59)),(11,12,(116,31)),(13,14,(87,11)),(15,16,(70,2)),(17,18,(56,-1))]) list.append([(0,10,(178,41)),(11,12,(125,22)),(13,14,(92,6)),(15,16,(72,-1))]) list.append([(0,10,(199,20)),(11,12,(134,13)),(13,14,(98,-1))]) list.append([(0,10,(219,-1)),(11,12,(147,-1))]) for i in 0..<list.count-1 { let label = UnicodeScalar((Int)(UnicodeScalar("A").value)+i) repeat_group_matrix[(String)(label)] = list[i] } } private func setSurfaceIntervalGroup() { var list: [[(begin: Int, end: Int, group: String)]] = [] list.append([(0,180,"A")]) list.append([(0,47,"B"),(48,228,"A")]) list.append([(0,21,"C"),(22,69,"B"),(70,250,"A")]) list.append([(0,8,"D"),(9,30,"C"),(31,78,"B"),(79,249,"A")]) list.append([(0,7,"E"),(8,16,"D"),(17,38,"C"),(39,87,"B"),(88,268,"A")]) list.append([(0,7,"F"),(8,15,"E"),(16,24,"D"),(25,46,"C"),(47,94,"B"),(95,275,"A")]) list.append([(0,6,"G"),(7,13,"F"),(14,22,"E"),(23,31,"D"),(32,53,"C"),(54,101,"B"),(102,282,"A")]) list.append([(0,5,"H"),(6,12,"G"),(13,20,"F"),(21,28,"E"),(29,37,"D"),(38,59,"C"),(60,107,"B"),(108,288,"A")]) list.append([(0,5,"I"),(6,11,"H"),(12,18,"G"),(19,26,"F"),(27,34,"E"),(35,43,"D"),(44,65,"C"),(66,113,"B"),(114,294,"A")]) list.append([(0,5,"I"),(6,11,"H"),(12,18,"G"),(19,26,"F"),(27,34,"E"),(35,43,"D"),(44,65,"C"),(66,113,"B"),(114,294,"A")]) list.append([(0,5,"J"),(6,11,"I"),(12,17,"H"),(18,24,"G"),(25,31,"F"),(32,40,"E"),(41,49,"D"),(50,71,"C"),(72,119,"B"),(120,300,"A")]) list.append([(0,4,"K"),(5,10,"J"),(11,16,"I"),(17,22,"H"),(23,29,"G"),(30,37,"F"),(38,45,"E"),(46,54,"D"),(55,76,"C"),(77,124,"B"),(125,305,"A")]) list.append([(0,4,"L"),(5,9,"K"),(10,15,"J"),(16,21,"I"),(22,27,"H"),(28,34,"G"),(35,42,"F"),(43,50,"E"),(51,59,"D"),(60,81,"C"),(82,129,"B"),(130,310,"A")]) list.append([(0,4,"M"),(5,9,"L"),(10,14,"K"),(15,19,"J"),(20,25,"I"),(26,32,"H"),(33,39,"G"),(40,46,"F"),(47,55,"E"),(56,64,"D"),(65,85,"C"),(86,134,"B"),(135,315,"A")]) list.append([(0,3,"N"),(4,8,"M"),(9,13,"L"),(14,18,"K"),(19,24,"J"),(25,30,"I"),(31,36,"H"),(37,43,"G"),(44,51,"F"),(52,59,"E"),(60,68,"D"),(69,90,"C"),(91,138,"B"),(139,319,"A")]) list.append([(0,3,"O"),(4,8,"N"),(9,12,"M"),(13,17,"L"),(18,23,"K"),(24,28,"J"),(29,34,"I"),(35,41,"H"),(42,47,"G"),(48,55,"F"),(56,63,"E"),(64,72,"D"),(73,94,"C"),(95,143,"B"),(144,324,"A")]) list.append([(0,3,"P"),(4,7,"O"),(8,12,"N"),(13,16,"M"),(17,21,"L"),(22,27,"K"),(28,32,"J"),(33,38,"I"),(39,45,"H"),(46,51,"G"),(52,59,"F"),(60,77,"E"),(78,76,"D"),(77,98,"C"),(99,147,"B"),(148,328,"A")]) list.append([(0,3,"Q"),(4,7,"P"),(8,11,"O"),(12,16,"N"),(17,20,"M"),(21,25,"L"),(26,30,"K"),(21,36,"J"),(37,42,"I"),(43,48,"H"),(49,55,"G"),(56,63,"F"),(64,71,"E"),(72,80,"D"),(81,102,"C"),(103,150,"B"),(151,331,"A")]) list.append([(0,3,"R"),(4,7,"Q"),(8,11,"P"),(12,15,"O"),(16,19,"N"),(20,24,"M"),(25,29,"L"),(30,34,"K"),(35,40,"J"),(41,46,"I"),(47,52,"H"),(53,59,"G"),(60,67,"F"),(68,75,"E"),(76,84,"D"),(85,106,"C"),(107,154,"B"),(155,335,"A")]) list.append([(0,3,"S"),(4,6,"R"),(7,10,"Q"),(11,14,"P"),(15,18,"O"),(19,23,"N"),(24,27,"M"),(28,32,"L"),(33,38,"K"),(39,43,"J"),(44,49,"I"),(50,56,"H"),(57,63,"G"),(64,70,"F"),(71,78,"E"),(79,87,"D"),(88,109,"C"),(110,158,"B"),(159,339,"A")]) list.append([(0,2,"T"),(3,6,"S"),(7,10,"R"),(11,13,"Q"),(14,17,"P"),(18,22,"O"),(23,26,"N"),(27,31,"M"),(32,36,"L"),(37,41,"K"),(42,47,"J"),(48,53,"I"),(54,59,"H"),(60,66,"G"),(67,73,"F"),(74,82,"E"),(83,91,"D"),(92,113,"C"),(114,161,"B"),(162,342,"A")]) list.append([(0,2,"U"),(3,6,"T"),(7,9,"S"),(10,13,"R"),(14,17,"Q"),(18,21,"P"),(22,25,"O"),(26,29,"N"),(30,34,"M"),(35,39,"L"),(40,44,"K"),(45,50,"J"),(51,56,"I"),(57,62,"H"),(63,69,"G"),(70,77,"F"),(78,85,"E"),(86,94,"D"),(95,116,"C"),(117,164,"B"),(165,345,"A")]) list.append([(0,2,"V"),(3,5,"U"),(6,9,"T"),(10,12,"S"),(13,16,"R"),(17,20,"Q"),(21,24,"P"),(25,28,"O"),(29,33,"N"),(34,37,"M"),(38,42,"L"),(43,47,"K"),(48,53,"J"),(54,59,"I"),(60,65,"H"),(66,72,"G"),(73,80,"F"),(81,88,"E"),(89,97,"D"),(98,119,"C"),(120,167,"B"),(168,348,"A")]) list.append([(0,2,"W"),(3,5,"V"),(6,8,"U"),(9,12,"T"),(13,15,"S"),(16,19,"R"),(20,23,"Q"),(24,27,"P"),(28,31,"O"),(32,36,"N"),(37,40,"M"),(41,45,"L"),(46,50,"K"),(51,56,"J"),(57,62,"I"),(63,68,"H"),(69,75,"G"),(76,83,"F"),(84,91,"E"),(92,100,"D"),(101,122,"C"),(123,170,"B"),(171,351,"A")]) list.append([(0,2,"X"),(3,5,"W"),(6,8,"V"),(9,11,"U"),(12,15,"T"),(16,18,"S"),(19,22,"R"),(23,26,"Q"),(27,30,"P"),(31,34,"O"),(35,39,"N"),(40,43,"M"),(44,48,"L"),(49,53,"K"),(54,59,"J"),(60,65,"I"),(66,71,"H"),(72,78,"G"),(79,86,"F"),(87,94,"E"),(95,103,"D"),(104,125,"C"),(126,173,"B"),(174,354,"A")]) list.append([(0,2,"Y"),(3,5,"X"),(6,8,"W"),(9,11,"V"),(12,14,"U"),(15,18,"T"),(19,21,"S"),(22,25,"R"),(26,29,"Q"),(30,33,"P"),(34,37,"O"),(38,41,"N"),(42,46,"M"),(47,51,"L"),(52,56,"K"),(57,62,"J"),(63,68,"I"),(69,74,"H"),(75,81,"G"),(82,89,"F"),(90,97,"E"),(98,106,"D"),(107,128,"C"),(129,176,"B"),(177,357,"A")]) list.append([(0,2,"Z"),(3,5,"Y"),(6,8,"X"),(9,11,"W"),(12,14,"V"),(15,17,"U"),(18,20,"T"),(21,24,"S"),(25,28,"R"),(29,31,"Q"),(32,35,"P"),(36,40,"O"),(41,44,"N"),(45,49,"M"),(50,54,"L"),(55,59,"K"),(60,65,"J"),(66,71,"I"),(72,77,"H"),(78,84,"G"),(85,91,"F"),(92,100,"E"),(101,109,"D"),(110,131,"C"),(132,179,"B"),(180,360,"A")]) for i in 0..<list.count { let label = UnicodeScalar((Int)(UnicodeScalar("A").value)+i) surface_interval_group[(String)(label)] = list[i] } } func getGroup(WaterDepth water_depth: Float, BottomTime bottom_time: Int) -> String { for depth in group_matrix { if depth.begin < water_depth && depth.end >= water_depth { for min in depth.min { if min.begin <= bottom_time && min.end >= bottom_time { return min.group } } } } return "" } func getGroupAfterSI(Group group: String, SurfaceInterval surface_interval: Int) -> String { for interval in surface_interval_group[group]! { if interval.begin <= surface_interval && interval.end >= surface_interval { return interval.group } } return "" } func getRNT(Group group: String, WaterDepth water_depth: Float) -> Int { for properties in repeat_group_matrix[group]! { if properties.begin <= water_depth && properties.end >= water_depth { return properties.time.rnt } } return -1 } func getABT(Group group: String, WaterDepth water_depth: Float) -> Int { for properties in repeat_group_matrix[group]! { if properties.begin <= water_depth && properties.end >= water_depth { return properties.time.abt } } return -1 } }
69.570815
392
0.451511
11434a53489e2b6b15d51c97b5ff7f8d0807df38
2,152
// // LifecycleUITests.swift // iOSDemoUITests // // Created by Mukund Agarwal on 12/05/2020. // Copyright © 2020 Bitrise. All rights reserved. // import XCTest class LifecycleUITests: XCTestCase { // MARK: - Property let app = XCUIApplication() // MARK: - Setup override func setUp() { super.setUp() app.launch() } // MARK: - Tests func testForegroundToBackground() { measure(metrics: [XCTCPUMetric(), XCTMemoryMetric()]) { moveAppToForeground() _ = app.wait(for: .runningForeground, timeout: 5) moveAppToBackground() _ = app.wait(for: .runningBackground, timeout: 5) } } func testBackgroundToForeground() { measure(metrics: [XCTCPUMetric(), XCTMemoryMetric()]) { moveAppToForeground() moveAppToBackground() _ = app.wait(for: .runningBackground, timeout: 5) moveAppToForeground() _ = app.wait(for: .runningForeground, timeout: 5) } } func testMultipleForegroundToBackground() { measure(metrics: [XCTCPUMetric(), XCTMemoryMetric()]) { _ = app.wait(for: .runningForeground, timeout: 5) moveAppToBackground() moveAppToForeground() moveAppToBackground() moveAppToForeground() moveAppToBackground() moveAppToForeground() moveAppToBackground() moveAppToForeground() _ = app.wait(for: .runningForeground, timeout: 5) } } func testLockScreen() { measure(metrics: [XCTCPUMetric(), XCTMemoryMetric()]) { _ = app.wait(for: .runningForeground, timeout: 5) XCUIDevice.shared.perform(NSSelectorFromString("pressLockButton")) _ = app.wait(for: .runningForeground, timeout: 5) } } // MARK: - Private methods private func moveAppToBackground() { XCUIDevice.shared.press(.home) } private func moveAppToForeground() { app.activate() } }
26.567901
78
0.567379