label
int64
0
1
text
stringlengths
0
2.8M
0
// // KeychainManager.swift // CoatCode // // Created by 강민석 on 2020/10/05. // Copyright © 2020 MinseokKang. All rights reserved. // import Foundation import KeychainAccess class KeychainManager { static let shared = KeychainManager() fileprivate let usernameKey = "usernameKey" private init() { } let keychain = Keychain(service: Configs.App.bundleIdentifier) var username: String? { get { return keychain[usernameKey] } set { keychain[usernameKey] = "\(newValue!)" } } }
0
// // PreviewUI.swift // ReformTools // // Created by Laszlo Korte on 30.08.15. // Copyright © 2015 Laszlo Korte. All rights reserved. // public final class MaskUI { public enum State { case disabled case clip(x: Double, y: Double, width: Double, height: Double) } public var state : State = .disabled public init() {} }
0
import Foundation import UIKit /** A view controller that supports interaction to start removing transiton. It works as a wrapper for another view controller or using with subclassing. If you have already implementation of view controller and want to get flexibility, you can use this class as a wrapper. ```swift let yourController = YourViewController() let fluidController = FluidViewController( bodyViewController: yourController, ... ) ``` You may specify ``AnyRemovingInteraction`` */ open class FluidGestureHandlingViewController: FluidTransitionViewController, UIGestureRecognizerDelegate { // MARK: - Properties @available(*, unavailable, message: "Unsupported") open override var navigationController: UINavigationController? { super.navigationController } public private(set) lazy var fluidPanGesture: FluidPanGestureRecognizer = FluidPanGestureRecognizer( target: self, action: #selector(handlePanGesture) ) public private(set) lazy var fluidScreenEdgePanGesture: UIScreenEdgePanGestureRecognizer = _EdgePanGestureRecognizer( target: self, action: #selector(handleEdgeLeftPanGesture) ) private var registeredGestures: [UIGestureRecognizer] = [] public var removingInteraction: AnyRemovingInteraction? { didSet { guard isViewLoaded else { return } setupGestures() } } // MARK: - Initializers public init( content: FluidWrapperViewController.Content?, addingTransition: AnyAddingTransition?, removingTransition: AnyRemovingTransition?, removingInteraction: AnyRemovingInteraction? ) { self.removingInteraction = removingInteraction super.init( content: content, addingTransition: addingTransition, removingTransition: removingTransition ) } deinit { Log.debug(.fluidController, "Deinit \(self)") } @available(*, unavailable) public required init?( coder: NSCoder ) { fatalError() } // MARK: - Functions open override func viewDidLoad() { super.viewDidLoad() setupGestures() } private func setupGestures() { assert(Thread.isMainThread) registeredGestures.forEach { view.removeGestureRecognizer($0) } registeredGestures = [] guard let interaction = removingInteraction else { return } for handler in interaction.handlers { switch handler { case .gestureOnLeftEdge: let created = fluidScreenEdgePanGesture created.edges = .left view.addGestureRecognizer(created) created.delegate = self registeredGestures.append(created) case .gestureOnScreen: let created = fluidPanGesture view.addGestureRecognizer(created) created.delegate = self registeredGestures.append(created) } } fluidPanGesture.require(toFail: fluidScreenEdgePanGesture) } @objc private func handleEdgeLeftPanGesture(_ gesture: _EdgePanGestureRecognizer) { guard let interaction = removingInteraction else { return } for handler in interaction.handlers { if case .gestureOnLeftEdge(_, let handler) = handler { handler(gesture, .init(viewController: self)) } } } @objc private func handlePanGesture(_ gesture: FluidPanGestureRecognizer) { guard let removingInteraction = removingInteraction else { return } for handler in removingInteraction.handlers { if case .gestureOnScreen(_, let handler) = handler { handler(gesture, .init(viewController: self)) } } } public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { switch gestureRecognizer { case fluidPanGesture, fluidScreenEdgePanGesture: let isDirectDescendant = parent is FluidStackController return isDirectDescendant default: assertionFailure() return true } } public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool { switch gestureRecognizer { case fluidPanGesture: if let removingInteraction = removingInteraction { for handler in removingInteraction.handlers { if case .gestureOnScreen(let condition, _) = handler { var resultPlaceholder: Bool = false condition( fluidPanGesture, .shouldBeRequiredToFailBy( otherGestureRecognizer: otherGestureRecognizer, completion: { result in // non-escaping resultPlaceholder = result } ) ) return resultPlaceholder } } } case fluidScreenEdgePanGesture: if let removingInteraction = removingInteraction { for handler in removingInteraction.handlers { if case .gestureOnLeftEdge(let condition, _) = handler { var resultPlaceholder: Bool = false condition( fluidScreenEdgePanGesture, .shouldBeRequiredToFailBy( otherGestureRecognizer: otherGestureRecognizer, completion: { result in // non-escaping resultPlaceholder = result } ) ) return resultPlaceholder } } } default: break } return false } public func gestureRecognizer( _ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer ) -> Bool { switch gestureRecognizer { case fluidPanGesture: if let removingInteraction = removingInteraction { for handler in removingInteraction.handlers { if case .gestureOnScreen(let condition, _) = handler { var resultPlaceholder: Bool = false condition( fluidPanGesture, .shouldRecognizeSimultaneouslyWith( otherGestureRecognizer: otherGestureRecognizer, completion: { result in // non-escaping resultPlaceholder = result } ) ) return resultPlaceholder } } } case fluidScreenEdgePanGesture: if let removingInteraction = removingInteraction { for handler in removingInteraction.handlers { if case .gestureOnLeftEdge(let condition, _) = handler { var resultPlaceholder: Bool = false condition( fluidScreenEdgePanGesture, .shouldRecognizeSimultaneouslyWith( otherGestureRecognizer: otherGestureRecognizer, completion: { result in // non-escaping resultPlaceholder = result } ) ) return resultPlaceholder } } } default: break } return true } } final class _EdgePanGestureRecognizer: UIScreenEdgePanGestureRecognizer { weak var trackingScrollView: UIScrollView? override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) { trackingScrollView = event.findScrollView() super.touchesBegan(touches, with: event) } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent) { super.touchesMoved(touches, with: event) } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent) { super.touchesEnded(touches, with: event) } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent) { super.touchesCancelled(touches, with: event) } } public final class FluidPanGestureRecognizer: UIPanGestureRecognizer { public private(set) weak var trackingScrollView: UIScrollView? public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) { trackingScrollView = event.findScrollView() super.touchesBegan(touches, with: event) } public override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent) { super.touchesMoved(touches, with: event) } public override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent) { super.touchesEnded(touches, with: event) } public override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent) { super.touchesCancelled(touches, with: event) } } extension UIEvent { fileprivate func findScrollView() -> UIScrollView? { guard let firstTouch = allTouches?.first, let targetView = firstTouch.view else { return nil } let scrollView = sequence(first: targetView, next: \.next).map { $0 } .first { guard let scrollView = $0 as? UIScrollView else { return false } func isScrollable(scrollView: UIScrollView) -> Bool { let contentInset: UIEdgeInsets if #available(iOS 11.0, *) { contentInset = scrollView.adjustedContentInset } else { contentInset = scrollView.contentInset } return (scrollView.bounds.width - (contentInset.right + contentInset.left) <= scrollView.contentSize.width) || (scrollView.bounds.height - (contentInset.top + contentInset.bottom) <= scrollView.contentSize.height) } return isScrollable(scrollView: scrollView) } return (scrollView as? UIScrollView) } }
0
import Foundation import MapKit protocol Region { // Internal representation var points:[CLLocationCoordinate2D] { get } var title:String { get } // Map presentation var annotations:[MKAnnotation] { get } var overlays:[MKOverlay] { get } // Serialization func toJSON() -> String static func fromJSON(json:String) -> Region? } func regionsAsJSON(regions:[Region]) -> String { let list = regions.map({$0.toJSON()}) return "[\(list.joinWithSeparator(","))]" }
0
// // UIColor+TweaksTests.swift // SwiftTweaks // // Created by Bryan Clark on 11/20/15. // Copyright © 2015 Khan Academy. All rights reserved. // import XCTest @testable import SwiftTweaks class UIColor_TweaksTests: XCTestCase { // MARK: Hex-To-Color private struct HexToColorTestCase { let string: String let expectedColor: UIColor? static func verify(testCase: HexToColorTestCase) { if let generatedColor = UIColor.colorWithHexString(testCase.string) { if let expectedColor = testCase.expectedColor { XCTAssertEqual(generatedColor.hexString, expectedColor.hexString, "Generated color with hex \(generatedColor.hexString) from test string \(testCase.string), but expected color with hex \(expectedColor.hexString)") } else { XCTFail("Generated a color from hex string \(testCase.string), but expected no color.") } } else if let expectedColor = testCase.expectedColor { XCTFail("Failed to generate expected color: \(expectedColor.hexString) from hex string \(testCase.string)") } } } func testHexToColor() { let testCases = [ HexToColorTestCase(string: "FF0000", expectedColor: UIColor(red: 1, green: 0, blue: 0, alpha: 1)), HexToColorTestCase(string: "00FF00", expectedColor: UIColor(red: 0, green: 1, blue: 0, alpha: 1)), HexToColorTestCase(string: "0000FF", expectedColor: UIColor(red: 0, green: 0, blue: 1, alpha: 1)), HexToColorTestCase(string: "000000", expectedColor: UIColor(red: 0, green: 0, blue: 0, alpha: 1)), HexToColorTestCase(string: "FFFFFF", expectedColor: UIColor(red: 1, green: 1, blue: 1, alpha: 1)), HexToColorTestCase(string: "FFFF00", expectedColor: UIColor(red: 1, green: 1, blue: 0, alpha: 1)), HexToColorTestCase(string: "E6A55E", expectedColor: UIColor(red:0.905, green:0.649, blue:0.369, alpha:1.000)), // While we *accept* colors with alpha values in their hex codes, we don't *generate* hexes with alpha. HexToColorTestCase(string: "00000000", expectedColor: UIColor(red: 0, green: 0, blue: 0, alpha: 0)), HexToColorTestCase(string: "000000FF", expectedColor: UIColor(red: 0, green: 0, blue: 0, alpha: 1)), // Invalid strings HexToColorTestCase(string: "Hello", expectedColor: nil), HexToColorTestCase(string: "blue", expectedColor: nil), HexToColorTestCase(string: "", expectedColor: nil), // Three-letter test cases (not yet supported, though I'd like them to be someday!) HexToColorTestCase(string: "f00", expectedColor: nil), HexToColorTestCase(string: "aaa", expectedColor: nil), HexToColorTestCase(string: "111", expectedColor: nil), ] testCases.forEach { HexToColorTestCase.verify($0) } // Re-run tests, prepending a "#" to each string. testCases .map { return HexToColorTestCase(string: "#"+$0.string, expectedColor: $0.expectedColor) } .forEach { HexToColorTestCase.verify($0) } } // MARK: Color-To-Hex private struct ColorToHexTestCase { let color: UIColor let expectedHex: String static func verify(testCase: ColorToHexTestCase) { XCTAssertEqual(testCase.color.hexString, testCase.expectedHex, "Expected color \(testCase.color) to generate #\(testCase.expectedHex)") } } func testColorToHex() { let testCases = [ ColorToHexTestCase(color: UIColor.redColor(), expectedHex: "#FF0000"), ColorToHexTestCase(color: UIColor.greenColor(), expectedHex: "#00FF00"), ColorToHexTestCase(color: UIColor.blueColor(), expectedHex: "#0000FF"), ColorToHexTestCase(color: UIColor.whiteColor(), expectedHex: "#FFFFFF"), ColorToHexTestCase(color: UIColor.blackColor(), expectedHex: "#000000"), // Our UI ignores the alpha component of a hex code - so we expect a 6-character hex even when alpha's present ColorToHexTestCase(color: UIColor.redColor().colorWithAlphaComponent(0), expectedHex: "#FF0000"), ColorToHexTestCase(color: UIColor.blackColor().colorWithAlphaComponent(0.234), expectedHex: "#000000"), ColorToHexTestCase(color: UIColor.whiteColor().colorWithAlphaComponent(1.0), expectedHex: "#FFFFFF") ] testCases.forEach { ColorToHexTestCase.verify($0) } } }
0
// 378. Kth Smallest Element in a Sorted Matrix /** Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix. Note that it is the kth smallest element in the sorted order, not the kth distinct element. Example: matrix = [ [ 1, 5, 9], [10, 11, 13], [12, 13, 15] ], k = 8, return 13. Note: You may assume k is always valid, 1 ≤ k ≤ n2. */ func kthSmallest(_ matrix: [[Int]], _ k: Int) -> Int { guard matrix.count > 0 && matrix[0].count > 0 else { return 0 } var indexArray = Array(repeating: 0, count: matrix.count) var k = k while k > 0 { // find smallest value and save rowNumber var smallRow = 0 var smallValue = Int.max for i in 0..<matrix.count { if indexArray[i] < matrix[0].count { if matrix[i][indexArray[i]] <= smallValue { smallValue = min(smallValue, matrix[i][indexArray[i]]) smallRow = i } } } k -= 1 if k == 0 { return matrix[smallRow][indexArray[smallRow]] } indexArray[smallRow] += 1 } return 0 }
0
// // FilterViewController.swift // Ookami // // Created by Maka on 22/2/17. // Copyright © 2017 Mikunj Varsani. All rights reserved. // import UIKit import Cartography //A View controller for displaying a list of filters class FilterViewController: UIViewController { //The table view lazy var tableView: UITableView = { let t = UITableView(frame: .zero, style: .grouped) t.cellLayoutMarginsFollowReadableWidth = false t.delegate = self t.dataSource = self t.tableFooterView = UIView(frame: .zero) t.backgroundColor = Theme.ControllerTheme().backgroundColor return t }() //The filters we want to show var filters: [FilterGroup] { didSet { tableView.reloadData() } } /// Create a filter view controller. /// /// - Parameter filters: An array of filter groups to display init(filters: [FilterGroup] = []) { self.filters = filters super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("use init(filters:) instead") } override func viewDidLoad() { super.viewDidLoad() //Add the tableview self.view.addSubview(tableView) constrain(tableView) { view in view.edges == view.superview!.edges } } } //MARK:- Data source extension FilterViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return filters.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return filters[section].filters.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell(style: .value1, reuseIdentifier: "FilterValueCell") cell.tintColor = Theme.Colors().secondary let filter = filters[indexPath.section].filters[indexPath.row] cell.textLabel?.text = filter.name.capitalized cell.detailTextLabel?.text = filter.secondaryText cell.accessoryType = filter.accessory return cell } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return filters[section].name } } //MARK:- Delegate extension FilterViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let filter = filters[indexPath.section].filters[indexPath.row] filter.onTap(self, tableView, tableView.cellForRow(at: indexPath)) } }
0
// // ViewController.swift // transitions // // Created by Daniel Alpizar on 4/9/21. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func SegueTapped(_ sender: Any) { let mainStoryBoard = UIStoryboard(name: "Main", bundle: Bundle.main) guard let greenViewController = mainStoryBoard.instantiateViewController( withIdentifier: "GreenViewController") as? GreenViewController else{ print("Couldn’t find the view controller") return } //navigationController?.pushViewController(greenViewController, animated: true) greenViewController.modalTransitionStyle = .coverVertical present(greenViewController, animated: true, completion: nil) } }
0
// // TLStoryOverlayControlView.swift // TLStoryCamera // // Created by GarryGuo on 2017/5/31. // Copyright © 2017年 GarryGuo. All rights reserved. // import UIKit protocol TLStoryOverlayControlDelegate: NSObjectProtocol { func storyOverlayCameraRecordingStart() func storyOverlayCameraRecordingFinish(type:TLStoryType, recordTime: TimeInterval) func storyOverlayCameraZoom(distance:CGFloat) func storyOverlayCameraFlashChange() -> AVCaptureDevice.TorchMode func storyOverlayCameraSwitch() func storyOverlayCameraFocused(point:CGPoint) func storyOverlayCameraClose() } class TLStoryOverlayControlView: UIView { public weak var delegate:TLStoryOverlayControlDelegate? fileprivate lazy var cameraBtn = TLStoryCameraButton.init(frame: CGRect.init(x: 0, y: 0, width: 80, height: 80)) fileprivate lazy var flashBtn:TLButton = { let btn = TLButton.init(type: UIButton.ButtonType.custom) btn.showsTouchWhenHighlighted = true btn.setImage(UIImage.tl_imageWithNamed(named: "story_publish_icon_flashlight_auto"), for: .normal) btn.addTarget(self, action: #selector(flashAction), for: .touchUpInside) return btn }() fileprivate lazy var switchBtn:TLButton = { let btn = TLButton.init(type: UIButton.ButtonType.custom) btn.showsTouchWhenHighlighted = true btn.setImage(UIImage.tl_imageWithNamed(named: "story_publish_icon_cam_turn"), for: .normal) btn.addTarget(self, action: #selector(switchAction), for: .touchUpInside) return btn }() fileprivate lazy var closeBtn:TLButton = { let btn = TLButton.init(type: UIButton.ButtonType.custom) btn.showsTouchWhenHighlighted = true btn.setImage(UIImage.tl_imageWithNamed(named: "story_icon_close"), for: .normal) btn.addTarget(self, action: #selector(closeAction), for: .touchUpInside) return btn }() fileprivate lazy var cameraBtnHintLabel: UILabel = { let l = UILabel(frame: CGRect(x: 0, y: 0, width: 60, height: 20)) l.font = UIFont.systemFont(ofSize: 15) l.textColor = UIColor.init(colorHex: 0xffffff, alpha: 0.8) l.text = TLStoryConfiguration.restrictMediaType == nil ? TLStoryCameraResource.string(key: "tl_photo_video_hint") : (TLStoryConfiguration.restrictMediaType == .photo ? TLStoryCameraResource.string(key: "tl_photo_hint") : TLStoryCameraResource.string(key: "tl_video_hint")) l.sizeToFit() return l }() fileprivate var photoLibraryHintView:TLPhotoLibraryHintView? fileprivate var tapGesture:UITapGestureRecognizer? fileprivate var doubleTapGesture:UITapGestureRecognizer? override init(frame: CGRect) { super.init(frame: frame) closeBtn.sizeToFit() closeBtn.center = CGPoint.init(x: self.width - closeBtn.width / 2 - 15, y: closeBtn.height / 2 + 15) addSubview(closeBtn) cameraBtn.center = CGPoint.init(x: self.center.x, y: self.bounds.height - 52 - 40) cameraBtn.delegete = self addSubview(cameraBtn) if (TLStoryConfiguration.showCameraBtnHint) { cameraBtnHintLabel.center = CGPoint.init(x: self.center.x, y: cameraBtn.centerY - cameraBtn.height / 2 - 20 / 2 - 5) addSubview(cameraBtnHintLabel) } flashBtn.sizeToFit() flashBtn.center = CGPoint.init(x: cameraBtn.centerX - 100, y: cameraBtn.centerY) addSubview(flashBtn) switchBtn.sizeToFit() switchBtn.center = CGPoint.init(x: cameraBtn.centerX + 100, y: cameraBtn.centerY) addSubview(switchBtn) photoLibraryHintView = TLPhotoLibraryHintView.init(frame: CGRect.init(x: 0, y: 0, width: 200, height: 50)) photoLibraryHintView?.center = CGPoint.init(x: self.self.width / 2, y: self.height - 25) addSubview(photoLibraryHintView!) tapGesture = UITapGestureRecognizer.init(target: self, action: #selector(tapAction)) tapGesture?.delegate = self tapGesture!.numberOfTapsRequired = 1 self.addGestureRecognizer(tapGesture!) doubleTapGesture = UITapGestureRecognizer.init(target: self, action: #selector(doubleTapAction)) doubleTapGesture?.delegate = self doubleTapGesture!.numberOfTapsRequired = 2 self.addGestureRecognizer(doubleTapGesture!) tapGesture!.require(toFail: doubleTapGesture!) } public func dismiss() { self.isHidden = true self.cameraBtn.reset() self.photoLibraryHintView?.isHidden = false self.cameraBtnHintLabel.isHidden = false } public func display() { self.isHidden = false self.cameraBtn.show() } public func beginHintAnim () { photoLibraryHintView?.startAnim() } @objc fileprivate func tapAction(sender:UITapGestureRecognizer) { let point = sender.location(in: self) self.delegate?.storyOverlayCameraFocused(point: point) } @objc fileprivate func doubleTapAction(sender:UITapGestureRecognizer) { self.delegate?.storyOverlayCameraSwitch() } @objc fileprivate func closeAction() { self.delegate?.storyOverlayCameraClose() } @objc fileprivate func flashAction(sender: UIButton) { let mode = self.delegate?.storyOverlayCameraFlashChange() let imgs = [AVCaptureDevice.TorchMode.on:UIImage.tl_imageWithNamed(named: "story_publish_icon_flashlight_on"), AVCaptureDevice.TorchMode.off:UIImage.tl_imageWithNamed(named: "story_publish_icon_flashlight_off"), AVCaptureDevice.TorchMode.auto:UIImage.tl_imageWithNamed(named: "story_publish_icon_flashlight_auto")] sender.setImage(imgs[mode!]!, for: .normal) } @objc fileprivate func switchAction(sender: UIButton) { UIView.animate(withDuration: 0.3, animations: { sender.transform = sender.transform.rotated(by: CGFloat(Double.pi)) }) { (x) in self.delegate?.storyOverlayCameraSwitch() } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension TLStoryOverlayControlView: UIGestureRecognizerDelegate { override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { let point = gestureRecognizer.location(in: self) if self.cameraBtn.frame.contains(point) { return false } return true } } extension TLStoryOverlayControlView: TLStoryCameraButtonDelegate { internal func cameraStart(hoopButton: TLStoryCameraButton) { self.delegate?.storyOverlayCameraRecordingStart() photoLibraryHintView?.isHidden = true cameraBtnHintLabel.isHidden = true } internal func cameraDrag(hoopButton: TLStoryCameraButton, offsetY: CGFloat) { self.delegate?.storyOverlayCameraZoom(distance: offsetY) } internal func cameraComplete(hoopButton: TLStoryCameraButton, type: TLStoryType) { self.delegate?.storyOverlayCameraRecordingFinish(type: type, recordTime: hoopButton.progress) self.isHidden = true } } class TLPhotoLibraryHintView: UIView { fileprivate lazy var hintLabel:UILabel = { let label = UILabel.init() label.textColor = UIColor.init(colorHex: 0xffffff, alpha: 0.8) label.font = UIFont.systemFont(ofSize: 12) label.text = TLStoryCameraResource.string(key: "tl_swipe_up_open_album") label.layer.shadowColor = UIColor.black.cgColor label.layer.shadowOffset = CGSize.init(width: 1, height: 1) label.layer.shadowRadius = 2 label.layer.shadowOpacity = 0.7 return label }() fileprivate lazy var arrowIco = UIImageView.init(image: UIImage.tl_imageWithNamed(named: "story_icon_up")) override init(frame: CGRect) { super.init(frame: frame) self.addSubview(hintLabel) hintLabel.sizeToFit() hintLabel.center = CGPoint.init(x: self.width / 2, y: self.height - 10 - hintLabel.height / 2) self.addSubview(arrowIco) arrowIco.sizeToFit() arrowIco.center = CGPoint.init(x: self.width / 2, y: 10 + arrowIco.height / 2) } public func startAnim() { UIView.animate(withDuration: 0.8, delay: 0, options: [.repeat,.autoreverse], animations: { self.arrowIco.centerY = 5 + self.arrowIco.height / 2 }, completion: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
0
// // SettingsTableViewController.swift // WeatherApp // // Created by Suraj Shandil on 7/29/21. // import UIKit class SettingsTableViewController: UITableViewController { @IBOutlet weak var unitsSegment: UISegmentedControl! @IBOutlet weak var mapTypeSegment: UISegmentedControl! @IBOutlet weak var resetBookmarkSwitch: UISwitch! var settingsManager = SettingsManager.sharedInstance // MARK: - View Life Cycles - override func viewDidLoad() { super.viewDidLoad() self.setupNavbar() self.configureSegmentControlsAndSwitchAppearance() self.setupDefaultSettings() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem } // MARK: - Private Method Implementation - private func configureSegmentControlsAndSwitchAppearance() { unitsSegment.selectedSegmentTintColor = .systemTeal mapTypeSegment.selectedSegmentTintColor = .systemTeal resetBookmarkSwitch.onTintColor = .systemTeal } private func setupDefaultSettings() { unitsSegment.selectedSegmentIndex = settingsManager.unitType == 0 ? 0 : 1 resetBookmarkSwitch.isOn = settingsManager.resetBookMark == false ? false : true mapTypeSegment.selectedSegmentIndex = settingsManager.mapType == 0 ? 0 : 1 } private func setupNavbar() { title = "Settings" let leftBarButtonItem = UIBarButtonItem(image: UIImage(systemName: "arrowtriangle.backward.fill"), style: .plain, target: self, action: #selector(goBack)) leftBarButtonItem.tintColor = .white navigationItem.leftBarButtonItem = leftBarButtonItem navigationController?.navigationBar.barTintColor = .systemGray2 } @objc private func goBack() { debugPrint(self.navigationController?.viewControllers as Any) self.navigationController?.popViewController(animated: true) } private func reloadTableViewData() { tableView.reloadData() } // MARK: - Table view data source - override func numberOfSections(in tableView: UITableView) -> Int { return 3 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } // MARK: - UIButton Action - @IBAction func unitSegmentIndexChanged(_ sender: Any) { let segment = sender as! UISegmentedControl if segment.selectedSegmentIndex == 1 { settingsManager.unitType = 1 } else { settingsManager.unitType = 0 } self.reloadTableViewData() } @IBAction func mapSegmentIndexChanged(_ sender: Any) { let segment = sender as! UISegmentedControl if segment.selectedSegmentIndex == 1 { settingsManager.mapType = 1 } else { settingsManager.mapType = 0 } self.reloadTableViewData() } @IBAction func resetBookmarkValueChanged(_ sender: Any) { let bookmarkSwitch = sender as! UISwitch if bookmarkSwitch.isOn { settingsManager.resetBookMark = true } else { settingsManager.resetBookMark = false } self.reloadTableViewData() } }
0
// // LogsTool.swift // Baymax // // Created by Simon Mitchell on 01/04/2020. // Copyright © 2020 3 SIDED CUBE. All rights reserved. // import Foundation /// A tool for displaying logs collated using `Logger` objects public class LogsTool: DiagnosticTool { /// Disables or enables Baymax logging public static var loggingEnabled: Bool { get { return UserDefaults.standard.baymaxLoggingEnabled } set { UserDefaults.standard.baymaxLoggingEnabled = newValue } } /// Instructs Baymax logging to either be on or off by default, /// defaults to `false` public static var loggingEnabledByDefault: Bool = false /// Can be provided to override how logs are shared by default /// /// You will be handed an array of log files, and the sender if you return false, indicating /// that you weren't able to share them, then they will continue to be shared /// using the default mechanism! public static var shareHandler: (([LogFile], Any) -> Bool)? public var displayName: String { return "Logs" } public func launchUI(in navigationController: UINavigationController) { let view = LogsTableViewController(style: .grouped) navigationController.show(view, sender: self) } }
0
// // ViewController.swift // Chambas // // Created by David Velarde on 11/3/16. // Copyright © 2016 Area51. All rights reserved. // import UIKit class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate { var arrayEmpresas = [Empresa]() var empresaSeleccionada : Empresa? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let empresa1 = Empresa() empresa1.nombre = "Amazon" empresa1.imagen = "amazon" empresa1.descripcion = "Empresa que vende cosas" empresa1.numeroEmpleados = 2500 empresa1.ceo = "Jorge Espinoza" empresa1.direccion = "Av. Republica de Panama 2476" //empresa1.localizacion = CGPoint(x: 35.787873, y: -121.8860108) let localizacion1 = [ "latitud" : 35.0, "longitud":40.0] let localizacion2 = [ "latitud" : 40.0, "longitud":-10.0] let localizacion3 = [ "latitud" : 45.0, "longitud":-40.0] let localizacion4 = [ "latitud" : 50.0, "longitud":-100.0] empresa1.localizacion.append(localizacion1) empresa1.localizacion.append(localizacion2) empresa1.localizacion.append(localizacion3) empresa1.localizacion.append(localizacion4) arrayEmpresas.append(empresa1) arrayEmpresas.append(empresa1) arrayEmpresas.append(empresa1) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return arrayEmpresas.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! EmpresaCell let empresa = arrayEmpresas[indexPath.row] as Empresa cell.imgEmpresa.image = UIImage(named: empresa.imagen) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { empresaSeleccionada = arrayEmpresas[indexPath.row] performSegue(withIdentifier: "fromMainToDetail", sender: self) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let vc = segue.destination as! DetalleViewController vc.empresaRecibida = empresaSeleccionada } }
0
// // Character.swift // GOT-Challenge-Swift // // Created by Conrado Mateu Gisbert on 08/03/17. // Copyright © 2017 conradomateu. All rights reserved. // import Foundation @testable import GOT_Challenge_Swift extension GOT_Challenge_Swift.Character: Equatable { } public func == (lhs: GOT_Challenge_Swift.Character, rhs: GOT_Challenge_Swift.Character) -> Bool { return lhs.id == rhs.id }
0
import Syft enum SongExpressionError: Error { case unknown } protocol SongExpression { func evaluate() -> String } struct SongNumber: SongExpression { let value: Int func evaluate() -> String { return "\(value)" } } //func song() -> Pipeline<SongExpression> { //// let input = "[].length() = 0\n[_|y].length() = 1.+(y.length())" // let input = "" // return Pipeline(defaultInput: input, parser: makeParser(), transformer: makeTransformer()) { ast in // let result = ast.evaluate() // return "\(result)" // } //}
0
// // FontMetrics.swift // Capable // // Created by Christoph Wendt on 31.03.18. // import Foundation import UIKit class FontMetrics: FontMetricsProtocol { var osVersionProvider: OsVersionProviderProtocol init() { self.osVersionProvider = OsVersionProvider() } var scaler: CGFloat { get { return UIFont.preferredFont(forTextStyle: .body).pointSize / 17.0 } } func scaledFont(for font: UIFont) -> UIFont { if(self.osVersionProvider.isOsVersionPrior11()) { return self.scaledFontPriorIOS11(for: font) } else { return self.scaledFontSinceIOS11(for: font) } } func scaledFontPriorIOS11(for font: UIFont) -> UIFont { let scaledFontSize = font.pointSize * self.scaler return font.withSize(scaledFontSize) } func scaledFontSinceIOS11(for font: UIFont) -> UIFont { if #available(iOS 11.0, tvOS 11.0, watchOS 4.0, *) { let fontMetrics = UIFontMetrics.default return fontMetrics.scaledFont(for: font) } fatalError() } }
0
// // FunctionalSwiftExampleUITests.swift // FunctionalSwiftExampleUITests // // Created by Daniel Mandea on 06/05/2019. // Copyright © 2019 Daniel Mandea. All rights reserved. // import XCTest class FunctionalSwiftExampleUITests: XCTestCase { override func 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. } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
0
// // RSSItem.swift // SwiftRSS_Example // // Created by Thibaut LE LEVIER on 28/09/2014. // Copyright (c) 2014 Thibaut LE LEVIER. All rights reserved. // import UIKit class RSSItem: NSObject, NSCoding { var title: String? var link: NSURL? func setLink(let linkString: String!) { link = NSURL(string: linkString) } var guid: String? var pubDate: NSDate? func setPubDate(let dateString: String!) { pubDate = NSDate.dateFromInternetDateTimeString(dateString) } var itemDescription: String? var content: String? // Wordpress specifics var commentsLink: NSURL? func setCommentsLink(let linkString: String!) { commentsLink = NSURL(string: linkString) } var commentsCount: Int? var commentRSSLink: NSURL? func setCommentRSSLink(let linkString: String!) { commentRSSLink = NSURL(string: linkString) } var author: String? var categories: [String]! = [String]() var imagesFromItemDescription: [NSURL]! { if let itemDescription = self.itemDescription? { return itemDescription.imageLinksFromHTMLString } return [NSURL]() } var imagesFromContent: [NSURL]! { if let content = self.content? { return content.imageLinksFromHTMLString } return [NSURL]() } override init() { super.init() } // MARK: NSCoding required init(coder aDecoder: NSCoder) { super.init() title = aDecoder.decodeObjectForKey("title") as? String link = aDecoder.decodeObjectForKey("link") as? NSURL guid = aDecoder.decodeObjectForKey("guid") as? String pubDate = aDecoder.decodeObjectForKey("pubDate") as? NSDate itemDescription = aDecoder.decodeObjectForKey("description") as? NSString content = aDecoder.decodeObjectForKey("content") as? NSString commentsLink = aDecoder.decodeObjectForKey("commentsLink") as? NSURL commentsCount = aDecoder.decodeObjectForKey("commentsCount") as? Int commentRSSLink = aDecoder.decodeObjectForKey("commentRSSLink") as? NSURL author = aDecoder.decodeObjectForKey("author") as? String categories = aDecoder.decodeObjectForKey("categories") as? [String] } func encodeWithCoder(aCoder: NSCoder) { if let title = self.title? { aCoder.encodeObject(title, forKey: "title") } if let link = self.link? { aCoder.encodeObject(link, forKey: "link") } if let guid = self.guid? { aCoder.encodeObject(guid, forKey: "guid") } if let pubDate = self.pubDate? { aCoder.encodeObject(pubDate, forKey: "pubDate") } if let itemDescription = self.itemDescription? { aCoder.encodeObject(itemDescription, forKey: "description") } if let content = self.content? { aCoder.encodeObject(content, forKey: "content") } if let commentsLink = self.commentsLink? { aCoder.encodeObject(commentsLink, forKey: "commentsLink") } if let commentsCount = self.commentsCount? { aCoder.encodeObject(commentsCount, forKey: "commentsCount") } if let commentRSSLink = self.commentRSSLink? { aCoder.encodeObject(commentRSSLink, forKey: "commentRSSLink") } if let author = self.author? { aCoder.encodeObject(author, forKey: "author") } aCoder.encodeObject(categories, forKey: "categories") } }
0
// // AddItemViewController.swift // ToDoList // // Created by Alex Paul on 1/9/19. // Copyright © 2019 Alex Paul. All rights reserved. // import UIKit class AddItemViewController: UIViewController { @IBOutlet weak var titleTextView: UITextView! @IBOutlet weak var descriptionTextView: UITextView! private let titleTextViewPlaceholder = "Title" private let descriptionTextViewPlaceholder = "Item Description" override func viewDidLoad() { super.viewDidLoad() titleTextView.delegate = self descriptionTextView.delegate = self titleTextView.textColor = .lightGray titleTextView.text = titleTextViewPlaceholder descriptionTextView.textColor = .lightGray descriptionTextView.text = descriptionTextViewPlaceholder } @IBAction func cancel(_ sender: UIBarButtonItem) { dismiss(animated: true, completion: nil) } @IBAction func addItem(_ sender: UIBarButtonItem) { guard let itemTitle = titleTextView.text, let itemDescription = descriptionTextView.text else { // handle case return } // create an instance of the Item object let date = Date() let isoDateFormatter = ISO8601DateFormatter() isoDateFormatter.formatOptions = [.withInternetDateTime, .withFullDate, .withFullTime, .withDashSeparatorInDate, .withTimeZone] let timestamp = isoDateFormatter.string(from: date) let item = Item(title: itemTitle, description: itemDescription, createdAt: timestamp) // save to disk ItemsModel.saveItem(item: item) dismiss(animated: true, completion: nil) } } extension AddItemViewController: UITextViewDelegate { func textViewDidBeginEditing(_ textView: UITextView) { if textView.text == titleTextViewPlaceholder || textView.text == descriptionTextViewPlaceholder { textView.textColor = .black textView.text = "" } } func textViewDidEndEditing(_ textView: UITextView) { if textView == titleTextView { if textView.text == "" { textView.textColor = .lightGray textView.text = titleTextViewPlaceholder } } else if textView == descriptionTextView { if textView.text == "" { textView.textColor = .lightGray textView.text = descriptionTextViewPlaceholder } } } }
0
// // Cache+Switch.swift // George Tsifrikas // // Created by George Tsifrikas on 12/06/2017. // Copyright © 2017 George Tsifrikas. All rights reserved. // import Foundation public enum CacheSwitchResult { /// The first Cache of the switch case cacheA /// The second Cache of the switch case cacheB } public func switchCache<A: Cache, B: Cache>(cacheA: A, cacheB: B, switchClosure: @escaping (_ key: A.Key) -> CacheSwitchResult) -> CompositeCache<A.Key, A.Value> where A.Key == B.Key, A.Value == B.Value { return CompositeCache( get: { key in switch switchClosure(key) { case .cacheA: return cacheA.get(key) case .cacheB: return cacheB.get(key) } }, set: { (value, key) in switch switchClosure(key) { case .cacheA: return cacheA.set(value, for: key) case .cacheB: return cacheB.set(value, for: key) } }, clear: { cacheA.clear() cacheB.clear() } ) }
0
// // RegisterViewController.swift // register_login_template // // Created by Sarvad shetty on 1/18/18. // Copyright © 2018 Sarvad shetty. All rights reserved. // import UIKit import Firebase class RegisterViewController: UIViewController { //MARK: Outlets @IBOutlet weak var regButton: UIButton! @IBOutlet weak var emailId: UITextField! @IBOutlet weak var password: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } //MARK: Registering.. @IBAction func regPressed(_ sender: Any) { regButton.isEnabled = false Auth.auth().createUser(withEmail: emailId.text!, password: password.text!) { (user, error) in if error != nil { print("error registering , \(error!)") } else{ print("registration successfull") self.performSegue(withIdentifier: "goToChat", sender: self) self.regButton.isEnabled = true } } } }
0
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// public protocol NIOHTTP2Error: Equatable, Error { } /// Errors that NIO raises when handling HTTP/2 connections. public enum NIOHTTP2Errors { /// NIO's upgrade handler encountered a successful upgrade to a protocol that it /// does not recognise. public struct InvalidALPNToken: NIOHTTP2Error { public init() { } } /// An attempt was made to issue a write on a stream that does not exist. public struct NoSuchStream: NIOHTTP2Error { /// The stream ID that was used that does not exist. public var streamID: HTTP2StreamID public init(streamID: HTTP2StreamID) { self.streamID = streamID } } /// A stream was closed. public struct StreamClosed: NIOHTTP2Error { /// The stream ID that was closed. public var streamID: HTTP2StreamID /// The error code associated with the closure. public var errorCode: HTTP2ErrorCode public init(streamID: HTTP2StreamID, errorCode: HTTP2ErrorCode) { self.streamID = streamID self.errorCode = errorCode } } public struct BadClientMagic: NIOHTTP2Error { public init() {} } /// A stream state transition was attempted that was not valid. public struct BadStreamStateTransition: NIOHTTP2Error { public init() { } } /// An attempt was made to change the flow control window size, either via /// SETTINGS or WINDOW_UPDATE, but this change would move the flow control /// window size out of bounds. public struct InvalidFlowControlWindowSize: NIOHTTP2Error { /// The delta being applied to the flow control window. public var delta: Int /// The size of the flow control window before the delta was applied. public var currentWindowSize: Int public init(delta: Int, currentWindowSize: Int) { self.delta = delta self.currentWindowSize = currentWindowSize } } /// A frame was sent or received that violates HTTP/2 flow control rules. public struct FlowControlViolation: NIOHTTP2Error { public init() { } } /// A SETTINGS frame was sent or received with an invalid setting. public struct InvalidSetting: NIOHTTP2Error { /// The invalid setting. public var setting: HTTP2Setting public init(setting: HTTP2Setting) { self.setting = setting } } /// An attempt to perform I/O was made on a connection that is already closed. public struct IOOnClosedConnection: NIOHTTP2Error { public init() { } } /// A SETTINGS frame was received that is invalid. public struct ReceivedBadSettings: NIOHTTP2Error { public init() { } } /// A violation of SETTINGS_MAX_CONCURRENT_STREAMS occurred. public struct MaxStreamsViolation: NIOHTTP2Error { public init() { } } /// An attempt was made to use a stream ID that is too small. public struct StreamIDTooSmall: NIOHTTP2Error { public init() { } } /// An attempt was made to send a frame without having previously sent a connection preface! public struct MissingPreface: NIOHTTP2Error { public init() { } } /// An attempt was made to create a stream after a GOAWAY frame has forbidden further /// stream creation. public struct CreatedStreamAfterGoaway: NIOHTTP2Error { public init() { } } /// A peer has attempted to create a stream with a stream ID it is not permitted to use. public struct InvalidStreamIDForPeer: NIOHTTP2Error { public init() { } } /// An attempt was made to send a new GOAWAY frame whose lastStreamID is higher than the previous value. public struct RaisedGoawayLastStreamID: NIOHTTP2Error { public init() { } } /// The size of the window increment is invalid. public struct InvalidWindowIncrementSize: NIOHTTP2Error { public init() { } } /// An attempt was made to push a stream, even though the settings forbid it. public struct PushInViolationOfSetting: NIOHTTP2Error { public init() { } } /// An attempt was made to use a currently unsupported feature. public struct Unsupported: NIOHTTP2Error { public var info: String public init(info: String) { self.info = info } } public struct UnableToSerializeFrame: NIOHTTP2Error { public init() { } } public struct UnableToParseFrame: NIOHTTP2Error { public init() { } } } /// This enum covers errors that are thrown internally for messaging reasons. These should /// not leak. internal enum InternalError: Error { case attemptedToCreateStream case codecError(code: HTTP2ErrorCode) }
0
// // Selfinfo.swift // FeedMyFit // // Created by 祁汝鑫 on 2020/8/6. // import Foundation // MARK: - Request // Id=xxxxxxx&Token=xxxxxxx // MARK: - Return struct Selfinfo: Codable { var Phonenumber: String var Avatar: String? var Username: String var Sex: String var Height: Double var Weight: Double var BirthDate: String? var City: String var SkinType: Int var HeatQuantityDemand: Int var ProteinDemand: Int var CarbohydratesDemand: Int var FatDemand: Int var VitaminADemand: Int var VitaminB1Demand: Int var VitaminB2Demand: Int var VitaminB6Demand: Int var VitaminB12Demand: Int var VitaminCDemand: Int var VitaminDDemand: Int var VitaminEDemand: Int var VitaminKDemand: Int }
0
// // StringEx.swift // AppSpawnKey // // Created by TKOxff on 2021/03/14. // import Foundation extension String { // App Name.app -> App Name var splitedAppName : String { let substrings = self.split(separator: ".") return String(substrings.first ?? "") } }
0
// // storage.swift // NebulaeCommission // // Created by Mayur.Patel.653 on 07/07/21. // import Foundation public class Storage{ static let shared = Storage() private let defaults = UserDefaults.standard var notificationToken : String? = nil // func setConnectionMode(cMode :ConnectionMode){ // let encoder = JSONEncoder() // if let encoded = try? encoder.encode(cMode) { // // defaults.set(encoded, forKey: "ConnectionMode") // } // } // // func getConnectionMode() -> ConnectionMode?{ // if let cMode = defaults.object(forKey: "ConnectionMode") as? Data { // // let decoder = JSONDecoder() // if let cMode = try? decoder.decode(ConnectionMode.self, from: cMode) { // // return cMode // } // } // return nil // } // // func setNetworkInfo(networkInfo :NetworkInfo){ // let encoder = JSONEncoder() // if let encoded = try? encoder.encode(networkInfo) { // // defaults.set(encoded, forKey: "NetworkInfo") // } // } // // func getNetworkInfo() -> NetworkInfo?{ // if let cMode = defaults.object(forKey: "NetworkInfo") as? Data { // // let decoder = JSONDecoder() // if let networkInfo = try? decoder.decode(NetworkInfo.self, from: cMode) { // // return networkInfo // } // } // return nil // } // // // // func clearAllStorage(){ // // //defaults.removeObject(forKey: "SLEEPDATE") // defaults.removeObject(forKey: "ConnectionMode") // } }
0
// // ATHMPurchaseResponse.swift // athmovil-checkout // // Created by Hansy Enrique on 7/19/20. // Copyright © 2020 Evertec. All rights reserved. // import Foundation @objc(ATHMPaymentResponse) final public class ATHMPaymentResponse: NSObject { /// Current payment, it is the same object that the client have been sent in the request @objc public let payment: ATHMPayment /// Status of the payment completed, expired o cancelled and other purchase's properties @objc public let status: ATHMPaymentStatus /// ATH Móvil's customer @objc public let customer: ATHMCustomer @objc public override var description: String { """ Response: \n \(payment.description) \n \(customer.description) \n \(status.description) """ } required init(payment: ATHMPayment, status: ATHMPaymentStatus, customer: ATHMCustomer) { self.payment = payment self.customer = customer self.status = status } }
0
import Foundation import Shared public struct SPM { public struct Package: Decodable { public static func load() throws -> Self { let shell = Shell() let jsonString = try shell.exec(["swift", "package", "describe", "--type", "json"], stderr: false) guard let jsonData = jsonString.data(using: .utf8) else { throw PeripheryError.packageError(message: "Failed to read swift package description.") } let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase return try decoder.decode(Package.self, from: jsonData) } public let name: String public let path: String public let targets: [Target] public var swiftTargets: [Target] { targets.filter { $0.moduleType == "SwiftTarget" } } } public struct Target: Decodable { public let name: String public let path: String public let sources: [String] public let moduleType: String func build() throws { let shell = Shell() try shell.exec(["swift", "build", "--enable-test-discovery", "--target", name]) } } }
0
// // ViewController.swift // TwilioTest // // Created by fawad on 22/01/2017. // Copyright © 2017 fawad. All rights reserved. // import UIKit import Alamofire class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } @IBAction func availableNumbersButtonAciton(_ sender: Any) { print("availableNumbersButtonAciton") TwilioManager.shared.availableNumbers(countryISO: "US", areaCode: "510", inRegion: nil) { (phoneNumbers, errorMsg) in print(phoneNumbers ?? "no numbers") } } @IBAction func IncomingNumbersButtonAciton(_ sender: Any) { print("IncomingNumbersButtonAciton") TwilioManager.shared.IncomingNumbers { (phoneNumbers, errorMsg) in print(phoneNumbers ?? "no numbers") } } @IBAction func sendMessageButtonAciton(_ sender: Any) { print("sendMessageButtonAciton") TwilioManager.shared.sendMessage(from: "+17606643093", to: "+14156105816", body: "Hello from Twilio, Rishi") { (response, errorMsg) in //print("error: \(success)") print("response: \(response)") } } @IBAction func buyNumberButtonAciton(_ sender: Any) { print("buyNumberButtonAciton") // TODO: USE TwilioManager // let url = "https://api.twilio.com/2010-04-01/Accounts/\(K.Twilio.SID)/IncomingPhoneNumbers.json" // // let params = ["AreaCode": "510"] // //let params = ["PhoneNumber": "+15103691691"] // // postRequest(url: url, method: .post, params: params) } @IBAction func messageListOutgoingButtonAciton(_ sender: Any) { TwilioManager.shared.messageList(phoneNo: myTwilioNumber,phoneDirection: .to) { (messageHistoryList, errorMsg) in guard let histories = messageHistoryList else { print("Error") return } print(histories) } } @IBAction func messageListIncomingButtonAciton(_ sender: Any) { TwilioManager.shared.messageList(phoneNo: myTwilioNumber,phoneDirection: .from) { (messageHistoryList, errorMsg) in guard let histories = messageHistoryList else { print("Error") return } print(histories) } } }
0
import UIKit class GameView: UIView { weak var delegate: GameViewDelegate? init() { super.init(frame: .zero) backgroundColor = UIColor(color: .darkPurple383357) addSubviews() setupLayout() configurePauseButtonAction() configureRestartButtonAction() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func update(score: Int) { scoreNumberLabel.text = "\(score)" } // MARK: Actions func configurePauseButtonAction() { pauseButton.buttonActionClosure = { [weak self] in guard let sself = self else { return } sself.delegate?.gameViewDidTapPause(sself) } } func configureRestartButtonAction() { restartButton.buttonActionClosure = { [weak self] in guard let sself = self else { return } sself.delegate?.gameViewDidTapRestart(sself) } } // MARK: Subviews private func addSubviews() { addSubview(topView) topView.addSubview(pauseButton) topView.addSubview(restartButton) topView.addSubview(scoreView) scoreView.addSubview(scoreTextLabel) scoreView.addSubview(scoreNumberLabel) addSubview(boardContainerView) } private let topView: UIView = { let view = UIView(frame: .zero) view.backgroundColor = .clear return view }() private let pauseButton = Button(image: UIImage(asset: .pause)) private let restartButton = Button(image: UIImage(asset: .restartIcon)) private let scoreView: UIView = { let view = UIView(frame: .zero) view.backgroundColor = .clear return view }() private let scoreTextLabel: UILabel = { let label = UILabel(frame: .zero) label.text = score.localized label.font = UIFont(font: FontFamily.BebasNeue.bold, size: 17) label.textColor = UIColor(color: .lightPurple7D75C7) return label }() private let scoreNumberLabel: UILabel = { let label = UILabel(frame: .zero) label.text = "0" label.font = UIFont(font: FontFamily.BebasNeue.bold, size: 46) label.adjustsFontSizeToFitWidth = true label.minimumScaleFactor = 0.5 label.textColor = UIColor(color: .white) return label }() let boardContainerView: UIView = { let view = UIView(frame: .zero) view.backgroundColor = .clear return view }() var boardView: GameBoardView? { didSet { if let oldValue = oldValue { oldValue.removeFromSuperview() } if let boardView = boardView { configureBoardView(boardView) } } } // MARK: Layout private func setupLayout() { topView.snp.makeConstraints { guard let topViewSuperview = topView.superview else { return } $0.top.equalTo(20) $0.left.equalTo(16) $0.right.equalTo(-16) $0.height.greaterThanOrEqualTo(72) $0.height.equalTo(topViewSuperview).multipliedBy(0.15).priority(.low) } pauseButton.snp.makeConstraints { $0.left.equalToSuperview() $0.centerYWithinMargins.equalToSuperview() } pauseButton.setContentCompressionResistancePriority(UILayoutPriorityRequired, for: .horizontal) scoreView.snp.makeConstraints { $0.centerWithinMargins.equalToSuperview() $0.left.greaterThanOrEqualTo(pauseButton.snp.right).offset(16) $0.right.lessThanOrEqualTo(restartButton.snp.left).offset(-16) } scoreNumberLabel.snp.makeConstraints { $0.top.equalToSuperview() $0.centerXWithinMargins.equalToSuperview() $0.left.greaterThanOrEqualTo(0) $0.right.lessThanOrEqualTo(0) } scoreTextLabel.snp.makeConstraints { $0.top.equalTo(scoreNumberLabel.snp.bottom) $0.centerXWithinMargins.equalToSuperview() $0.left.greaterThanOrEqualTo(0) $0.right.lessThanOrEqualTo(0) $0.bottom.equalToSuperview() } restartButton.snp.makeConstraints { $0.right.equalToSuperview() $0.centerYWithinMargins.equalToSuperview() } restartButton.setContentCompressionResistancePriority(UILayoutPriorityRequired, for: .horizontal) boardContainerView.snp.makeConstraints { $0.top.equalTo(topView.snp.bottom) $0.left.equalTo(16) $0.right.equalTo(-16) $0.bottom.equalTo(-16) } } private func configureBoardView(_ boardView: GameBoardView) { boardView.delegate = self boardContainerView.addSubview(boardView) boardView.snp.makeConstraints { $0.edges.equalToSuperview() } } }
0
// // AppDelegate.swift // AppStoreReviews // // Created by Dmitrii Ivanov on 21/07/2020. // Copyright © 2020 ING. All rights reserved. // import Foundation struct Review: Codable { let author: String let version: String let rating: Int let title: String let id: String let content: String func ratingVersionText() -> String { return "\(String(repeating:"⭐️", count: rating)) (ver: \(version))" } } extension Review: CustomStringConvertible { var description: String { return title + " " + content } } extension Review { init(entry: Entry) { self.init(author: entry.author.name.label, version: entry.imVersion.label, rating: Int(entry.imRating.label)!, title: entry.title.label, id: entry.id.label, content: entry.content.label) } }
0
// // SelectionTypeModule.swift // UsbongKit // // Created by Chris Amanse on 26/05/2016. // Copyright © 2016 Usbong Social Systems, Inc. All rights reserved. // import Foundation /// Protocol for selection type public protocol SelectionTypeModule: Module { var selectedIndices: [Int] { get } func selectIndex(_ index: Int) func deselectIndex(_ index: Int) func toggleIndex(_ index: Int) }
0
// // ChartAxisValuesGeneratorNice.swift // SwiftCharts // // Created by ischuetz on 04/08/16. // Copyright © 2016 ivanschuetz. All rights reserved. // import UIKit open class ChartAxisValuesGeneratorNice: ChartAxisGeneratorMultiplier { open override var first: Double? { return Double(minValue) } open override var last: Double? { return Double(maxValue) } fileprivate var minValue: Double fileprivate var maxValue: Double fileprivate let minSpace: CGFloat fileprivate let preferredDividers: Int fileprivate let maxTextSize: CGFloat public init(minValue: Double, maxValue: Double, preferredDividers: Int, minSpace: CGFloat, maxTextSize: CGFloat, multiplierUpdateMode: ChartAxisGeneratorMultiplierUpdateMode = .halve) { self.minValue = minValue self.maxValue = maxValue self.preferredDividers = preferredDividers self.minSpace = minSpace self.maxTextSize = maxTextSize super.init(DBL_MAX, multiplierUpdateMode: multiplierUpdateMode) } func niceRangeAndMultiplier(_ dividers: Int) -> (minValue: Double, maxValue: Double, multiplier: Double) { let niceLength = ChartNiceNumberCalculator.niceNumber(maxValue - minValue, round: true) let niceMultiplier = ChartNiceNumberCalculator.niceNumber(niceLength / (Double(dividers) - 1), round: true) let niceMinValue = floor(minValue / niceMultiplier) * niceMultiplier let niceMaxValue = ceil(maxValue / niceMultiplier) * niceMultiplier return (niceMinValue, niceMaxValue, niceMultiplier) } open override func axisInitialized(_ axis: ChartAxis) { var dividers = preferredDividers var cont = true while dividers > 1 && cont { let nice = niceRangeAndMultiplier(dividers) if requiredLengthForDividers(dividers) < axis.screenLength { minValue = nice.minValue maxValue = nice.maxValue multiplier = nice.multiplier cont = false } else { dividers -= 1 } } } fileprivate func requiredLengthForDividers(_ dividers: Int) -> CGFloat { return minSpace + ((maxTextSize + minSpace) * CGFloat(dividers)) } }
0
import XCTest @testable import WordPress class DashboardStatsViewModelTests: XCTestCase { func testReturnCorrectDataFromAPIResponse() { // Given let statsData = BlogDashboardRemoteEntity.BlogDashboardStats(views: 1, visitors: 2, likes: 3, comments: 0) let apiResponse = BlogDashboardRemoteEntity(posts: nil, todaysStats: statsData) let viewModel = DashboardStatsViewModel(apiResponse: apiResponse) // When & Then XCTAssertEqual(viewModel.todaysViews, "1") XCTAssertEqual(viewModel.todaysVisitors, "2") XCTAssertEqual(viewModel.todaysLikes, "3") } func testReturnedDataIsFormattedCorrectly() { // Given let statsData = BlogDashboardRemoteEntity.BlogDashboardStats(views: 10000, visitors: 200000, likes: 3000000, comments: 0) let apiResponse = BlogDashboardRemoteEntity(posts: nil, todaysStats: statsData) let viewModel = DashboardStatsViewModel(apiResponse: apiResponse) // When & Then XCTAssertEqual(viewModel.todaysViews, "10,000") XCTAssertEqual(viewModel.todaysVisitors, "200.0K") XCTAssertEqual(viewModel.todaysLikes, "3.0M") } func testReturnZeroIfAPIResponseIsEmpty() { // Given let statsData = BlogDashboardRemoteEntity.BlogDashboardStats(views: nil, visitors: nil, likes: nil, comments: nil) let apiResponse = BlogDashboardRemoteEntity(posts: nil, todaysStats: statsData) let viewModel = DashboardStatsViewModel(apiResponse: apiResponse) // When & Then XCTAssertEqual(viewModel.todaysViews, "0") XCTAssertEqual(viewModel.todaysVisitors, "0") XCTAssertEqual(viewModel.todaysLikes, "0") } func testReturnTrueIfAllTodaysStatsAreZero() { // Given let statsData = BlogDashboardRemoteEntity.BlogDashboardStats(views: 0, visitors: 0, likes: 0, comments: 0) let apiResponse = BlogDashboardRemoteEntity(posts: nil, todaysStats: statsData) let viewModel = DashboardStatsViewModel(apiResponse: apiResponse) // When & Then XCTAssertEqual(viewModel.shouldDisplayNudge, true) } func testReturnFalseIfNotAllTodaysStatsAreZero() { // Given let statsData = BlogDashboardRemoteEntity.BlogDashboardStats(views: 1, visitors: 0, likes: 0, comments: 0) let apiResponse = BlogDashboardRemoteEntity(posts: nil, todaysStats: statsData) let viewModel = DashboardStatsViewModel(apiResponse: apiResponse) // When & Then XCTAssertEqual(viewModel.shouldDisplayNudge, false) } }
0
/// The declaration of a nominal type. public protocol NominalTypeDecl: NamedDecl { /// The semantic type represented by the declaration. var type: BareType? { get } }
0
// // Foundation+Tips.swift // RxTips // // Created by Yu Sugawara on 2019/11/07. // Copyright © 2019 Yu Sugawara. All rights reserved. // import Foundation import Then extension JSONEncoder: Then {} extension JSONEncoder { static var `default`: JSONEncoder { return JSONEncoder().then { $0.dateEncodingStrategy = .iso8601 } } } extension JSONDecoder: Then {} extension JSONDecoder { static var `default`: JSONDecoder { return JSONDecoder().then { $0.dateDecodingStrategy = .iso8601 } } }
0
// // GenericProtocolTest.swift // Cuckoo // // Created by Matyáš Kříž on 26/11/2018. // import XCTest import Cuckoo private class GenericProtocolConformerClass<C: AnyObject, V>: GenericProtocol { let readOnlyPropertyC: C var readWritePropertyV: V let constant: Int = 0 var optionalProperty: V? required init(theC: C, theV: V) { readOnlyPropertyC = theC readWritePropertyV = theV } func callSomeC(theC: C) -> Int { return 1 } func callSomeV(theV: V) -> Int { switch theV { case let int as Int: return int case let string as String: return Int(string) ?? 8008135 default: return 0 } } func compute(classy: C, value: V) -> C { guard let testyClassy = classy as? TestedClass else { return classy } switch value { case let int as Int: testyClassy.readWriteProperty = int case _ as String: testyClassy.optionalProperty = nil default: break } return testyClassy as! C } func noReturn() {} } private struct GenericProtocolConformerStruct<C: AnyObject, V>: GenericProtocol { let readOnlyPropertyC: C var readWritePropertyV: V let constant: Int = 0 var optionalProperty: V? init(theC: C, theV: V) { readOnlyPropertyC = theC readWritePropertyV = theV } func callSomeC(theC: C) -> Int { return 1 } func callSomeV(theV: V) -> Int { return 0 } func compute(classy: C, value: V) -> C { return classy } func noReturn() {} } class GenericProtocolTest: XCTestCase { private func createMock<V>(value: V) -> MockGenericProtocol<MockTestedClass, V> { let classy = MockTestedClass() return MockGenericProtocol(theC: classy, theV: value) } func testReadOnlyProperty() { let mock = createMock(value: 10) stub(mock) { mock in when(mock.readOnlyPropertyC.get).thenReturn(MockTestedClass()) } _ = mock.readOnlyPropertyC verify(mock).readOnlyPropertyC.get() } func testReadWriteProperty() { let mock = createMock(value: 10) stub(mock) { mock in when(mock.readWritePropertyV.get).then { 11 } when(mock.readWritePropertyV.set(anyInt())).thenDoNothing() } mock.readWritePropertyV = 42 XCTAssertEqual(mock.readWritePropertyV, 11) verify(mock).readWritePropertyV.get() verify(mock).readWritePropertyV.set(42) } func testOptionalProperty() { let mock = createMock(value: false) var called = false stub(mock) { mock in when(mock.optionalProperty.get).thenReturn(true) when(mock.optionalProperty.set(any())).then { _ in called = true } when(mock.optionalProperty.set(isNil())).then { _ in called = true } } mock.optionalProperty = nil mock.optionalProperty = false XCTAssertTrue(mock.optionalProperty == true) XCTAssertTrue(called) verify(mock).optionalProperty.get() verify(mock).optionalProperty.set(equal(to: false)) verify(mock, times(2)).optionalProperty.set(any()) verify(mock).optionalProperty.set(isNil()) } func testNoReturn() { let mock = createMock(value: "Hello. Sniffing through tests? If you're having trouble with Cuckoo, shoot us a message!") var called = false stub(mock) { mock in when(mock.noReturn()).then { _ in called = true } } mock.noReturn() XCTAssertTrue(called) verify(mock).noReturn() } func testModification() { let mock = createMock(value: ["EXTERMINATE!": "EXTERMINATE!!", "EXTERMINATE!!!": "EXTERMINATE!!!!"]) let original = GenericProtocolConformerClass(theC: MockTestedClass(), theV: ["Sir, may I help you?": "Nope, just lookin' 👀"]) mock.enableDefaultImplementation(original) original.readWritePropertyV["Are you sure?"] = "Yeah, I'm just waiting for my wife." XCTAssertEqual(mock.readWritePropertyV, ["Sir, may I help you?": "Nope, just lookin' 👀", "Are you sure?": "Yeah, I'm just waiting for my wife."]) original.readWritePropertyV["Alright, have a nice weekend!"] = "Thanks, you too." XCTAssertEqual(mock.readWritePropertyV, ["Sir, may I help you?": "Nope, just lookin' 👀", "Are you sure?": "Yeah, I'm just waiting for my wife.", "Alright, have a nice weekend!": "Thanks, you too."]) verify(mock, times(2)).readWritePropertyV.get() } // the next two test cases show using a struct as the default implementation and changing its state: // - NOTE: This only applies for `struct`s, not `class`es. // using: `enableDefaultImplementation(mutating:)` reflects the original's state at all times func testStructModification() { let mock = createMock(value: ["EXTERMINATE!": "EXTERMINATE!!", "EXTERMINATE!!!": "EXTERMINATE!!!!"]) var original = GenericProtocolConformerStruct(theC: MockTestedClass(), theV: ["Sir, may I help you?": "Nope, just lookin' 👀"]) mock.enableDefaultImplementation(mutating: &original) original.readWritePropertyV["Are you sure?"] = "Yeah, I'm just waiting for my wife." XCTAssertEqual(mock.readWritePropertyV, ["Sir, may I help you?": "Nope, just lookin' 👀", "Are you sure?": "Yeah, I'm just waiting for my wife."]) original.readWritePropertyV["Alright, have a nice weekend!"] = "Thanks, you too." XCTAssertEqual(mock.readWritePropertyV, ["Sir, may I help you?": "Nope, just lookin' 👀", "Are you sure?": "Yeah, I'm just waiting for my wife.", "Alright, have a nice weekend!": "Thanks, you too."]) verify(mock, times(2)).readWritePropertyV.get() } // using: `enableDefaultImplementation(_:)` reflects the original's state at the time of enabling default implementation with the struct // func testStructNonModification() { let mock = createMock(value: ["EXTERMINATE!": "EXTERMINATE!!", "EXTERMINATE!!!": "EXTERMINATE!!!!"]) var original = GenericProtocolConformerStruct(theC: MockTestedClass(), theV: ["Sir, may I help you?": "Nope, just lookin' 👀"]) mock.enableDefaultImplementation(original) original.readWritePropertyV["Are you sure?"] = "Yeah, I'm just waiting for my wife." XCTAssertEqual(mock.readWritePropertyV, ["Sir, may I help you?": "Nope, just lookin' 👀"]) XCTAssertEqual(original.readWritePropertyV, ["Sir, may I help you?": "Nope, just lookin' 👀", "Are you sure?": "Yeah, I'm just waiting for my wife."]) original.readWritePropertyV["Alright, have a nice weekend!"] = "Thanks, you too." XCTAssertEqual(mock.readWritePropertyV, ["Sir, may I help you?": "Nope, just lookin' 👀"]) XCTAssertEqual(original.readWritePropertyV, ["Sir, may I help you?": "Nope, just lookin' 👀", "Are you sure?": "Yeah, I'm just waiting for my wife.", "Alright, have a nice weekend!": "Thanks, you too."]) verify(mock, times(2)).readWritePropertyV.get() } }
0
import UIKit extension String { public var CGColor: CGColorRef { return self.CGColor(1) } public var UIColor: UIKit.UIColor { return self.UIColor(1) } public func CGColor (alpha: CGFloat) -> CGColorRef { return self.UIColor(alpha).CGColor } public func UIColor (alpha: CGFloat) -> UIKit.UIColor { var hex = self if hex.hasPrefix("#") { // Strip leading "#" if it exists hex = hex.substringFromIndex(hex.startIndex.successor()) } switch hex.characters.count { case 1: // Turn "f" into "ffffff" hex = hex._repeat(6) case 2: // Turn "ff" into "ffffff" hex = hex._repeat(3) case 3: // Turn "123" into "112233" hex = hex[0]._repeat(2) + hex[1]._repeat(2) + hex[2]._repeat(2) default: break } assert(hex.characters.count == 6, "Invalid hex value") var r: UInt32 = 0 var g: UInt32 = 0 var b: UInt32 = 0 NSScanner(string: "0x" + hex[0...1]).scanHexInt(&r) NSScanner(string: "0x" + hex[2...3]).scanHexInt(&g) NSScanner(string: "0x" + hex[4...5]).scanHexInt(&b) let red = CGFloat(Int(r)) / CGFloat(255.0) let green = CGFloat(Int(g)) / CGFloat(255.0) let blue = CGFloat(Int(b)) / CGFloat(255.0) return UIKit.UIColor(red: red, green: green, blue: blue, alpha: alpha) } } private extension String { func _repeat (count: Int) -> String { return "".stringByPaddingToLength((self as NSString).length * count, withString: self, startingAtIndex:0) } subscript (i: Int) -> String { return String(Array(arrayLiteral: self)[i]) } subscript (r: Range<Int>) -> String { return substringWithRange(Range(start: startIndex.advancedBy(r.startIndex), end: startIndex.advancedBy(r.endIndex))) } }
0
// // PieChartView.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import UIKit /// View that represents a pie chart. Draws cake like slices. open class PieChartView: PieRadarChartViewBase { /// rect object that represents the bounds of the piechart, needed for drawing the circle fileprivate var _circleBox = CGRect() /// array that holds the width of each pie-slice in degrees fileprivate var _drawAngles = [CGFloat]() /// array that holds the absolute angle in degrees of each slice fileprivate var _absoluteAngles = [CGFloat]() public override init(frame: CGRect) { super.init(frame: frame) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } internal override func initialize() { super.initialize() renderer = PieChartRenderer(chart: self, animator: _animator, viewPortHandler: _viewPortHandler) } open override func draw(_ rect: CGRect) { super.draw(rect) if (_dataNotSet) { return } let context = UIGraphicsGetCurrentContext()! renderer!.drawData(context: context) if (valuesToHighlight()) { renderer!.drawHighlighted(context: context, indices: _indicesToHightlight) } renderer!.drawExtras(context: context) renderer!.drawValues(context: context) _legendRenderer.renderLegend(context: context) drawDescription(context: context) } internal override func calculateOffsets() { super.calculateOffsets() // prevent nullpointer when no data set if (_dataNotSet) { return } let radius = diameter / 2.0 let c = centerOffsets // create the circle box that will contain the pie-chart (the bounds of the pie-chart) _circleBox.origin.x = c.x - radius _circleBox.origin.y = c.y - radius _circleBox.size.width = radius * 2.0 _circleBox.size.height = radius * 2.0 } internal override func calcMinMax() { super.calcMinMax() calcAngles() } open override func getMarkerPosition(entry: ChartDataEntry, highlight: ChartHighlight) -> CGPoint { /// PieChart does not support MarkerView return CGPoint(x: 0.0, y: 0.0) } /// calculates the needed angles for the chart slices fileprivate func calcAngles() { _drawAngles = [CGFloat]() _absoluteAngles = [CGFloat]() _drawAngles.reserveCapacity(_data.yValCount) _absoluteAngles.reserveCapacity(_data.yValCount) var dataSets = _data.dataSets var cnt = 0 for i in 0 ..< _data.dataSetCount { let set = dataSets[i] var entries = set.yVals for j in 0 ..< entries.count { _drawAngles.append(calcAngle(abs(entries[j].value))) if (cnt == 0) { _absoluteAngles.append(_drawAngles[cnt]) } else { _absoluteAngles.append(_absoluteAngles[cnt - 1] + _drawAngles[cnt]) } cnt += 1 } } } /// checks if the given index in the given DataSet is set for highlighting or not open func needsHighlight(xIndex: Int, dataSetIndex: Int) -> Bool { // no highlight if (!valuesToHighlight() || dataSetIndex < 0) { return false } for i in 0 ..< _indicesToHightlight.count { // check if the xvalue for the given dataset needs highlight if (_indicesToHightlight[i].xIndex == xIndex && _indicesToHightlight[i].dataSetIndex == dataSetIndex) { return true } } return false } /// calculates the needed angle for a given value fileprivate func calcAngle(_ value: Double) -> CGFloat { return CGFloat(value) / CGFloat(_data.yValueSum) * 360.0 } open override func indexForAngle(_ angle: CGFloat) -> Int { // take the current angle of the chart into consideration let a = ChartUtils.normalizedAngleFromAngle(angle - self.rotationAngle) for i in 0 ..< _absoluteAngles.count { if (_absoluteAngles[i] > a) { return i } } return -1; // return -1 if no index found } /// Returns the index of the DataSet this x-index belongs to. open func dataSetIndexForIndex(_ xIndex: Int) -> Int { var dataSets = _data.dataSets for i in 0 ..< dataSets.count { if (dataSets[i].entryForXIndex(xIndex) !== nil) { return i } } return -1 } /// returns an integer array of all the different angles the chart slices /// have the angles in the returned array determine how much space (of 360°) /// each slice takes open var drawAngles: [CGFloat] { return _drawAngles } /// returns the absolute angles of the different chart slices (where the /// slices end) open var absoluteAngles: [CGFloat] { return _absoluteAngles } /// Sets the color for the hole that is drawn in the center of the PieChart (if enabled). /// NOTE: Use holeTransparent with holeColor = nil to make the hole transparent. open var holeColor: UIColor? { get { return (renderer as! PieChartRenderer).holeColor! } set { (renderer as! PieChartRenderer).holeColor = newValue setNeedsDisplay() } } /// Set the hole in the center of the PieChart transparent open var holeTransparent: Bool { get { return (renderer as! PieChartRenderer).holeTransparent } set { (renderer as! PieChartRenderer).holeTransparent = newValue setNeedsDisplay() } } /// Returns true if the hole in the center of the PieChart is transparent, false if not. open var isHoleTransparent: Bool { return (renderer as! PieChartRenderer).holeTransparent } /// true if the hole in the center of the pie-chart is set to be visible, false if not open var drawHoleEnabled: Bool { get { return (renderer as! PieChartRenderer).drawHoleEnabled } set { (renderer as! PieChartRenderer).drawHoleEnabled = newValue setNeedsDisplay() } } /// - returns: true if the hole in the center of the pie-chart is set to be visible, false if not open var isDrawHoleEnabled: Bool { get { return (renderer as! PieChartRenderer).drawHoleEnabled } } /// the text that is displayed in the center of the pie-chart. By default, the text is "Total value + sum of all values" open var centerText: String! { get { return (renderer as! PieChartRenderer).centerText } set { (renderer as! PieChartRenderer).centerText = newValue setNeedsDisplay() } } /// true if drawing the center text is enabled open var drawCenterTextEnabled: Bool { get { return (renderer as! PieChartRenderer).drawCenterTextEnabled } set { (renderer as! PieChartRenderer).drawCenterTextEnabled = newValue setNeedsDisplay() } } /// - returns: true if drawing the center text is enabled open var isDrawCenterTextEnabled: Bool { get { return (renderer as! PieChartRenderer).drawCenterTextEnabled } } internal override var requiredBottomOffset: CGFloat { return _legend.font.pointSize * 2.0 } internal override var requiredBaseOffset: CGFloat { return 0.0 } open override var radius: CGFloat { return _circleBox.width / 2.0 } /// returns the circlebox, the boundingbox of the pie-chart slices open var circleBox: CGRect { return _circleBox } /// returns the center of the circlebox open var centerCircleBox: CGPoint { return CGPoint(x: _circleBox.midX, y: _circleBox.midY) } /// Sets the font of the center text of the piechart. open var centerTextFont: UIFont { get { return (renderer as! PieChartRenderer).centerTextFont } set { (renderer as! PieChartRenderer).centerTextFont = newValue setNeedsDisplay() } } /// Sets the color of the center text of the piechart. open var centerTextColor: UIColor { get { return (renderer as! PieChartRenderer).centerTextColor } set { (renderer as! PieChartRenderer).centerTextColor = newValue setNeedsDisplay() } } /// the radius of the hole in the center of the piechart in percent of the maximum radius (max = the radius of the whole chart) /// :default: 0.5 (50%) (half the pie) open var holeRadiusPercent: CGFloat { get { return (renderer as! PieChartRenderer).holeRadiusPercent } set { (renderer as! PieChartRenderer).holeRadiusPercent = newValue setNeedsDisplay() } } /// the radius of the transparent circle that is drawn next to the hole in the piechart in percent of the maximum radius (max = the radius of the whole chart) /// :default: 0.55 (55%) -> means 5% larger than the center-hole by default open var transparentCircleRadiusPercent: CGFloat { get { return (renderer as! PieChartRenderer).transparentCircleRadiusPercent } set { (renderer as! PieChartRenderer).transparentCircleRadiusPercent = newValue setNeedsDisplay() } } /// set this to true to draw the x-value text into the pie slices open var drawSliceTextEnabled: Bool { get { return (renderer as! PieChartRenderer).drawXLabelsEnabled } set { (renderer as! PieChartRenderer).drawXLabelsEnabled = newValue setNeedsDisplay() } } /// - returns: true if drawing x-values is enabled, false if not open var isDrawSliceTextEnabled: Bool { get { return (renderer as! PieChartRenderer).drawXLabelsEnabled } } /// If this is enabled, values inside the PieChart are drawn in percent and not with their original value. Values provided for the ValueFormatter to format are then provided in percent. open var usePercentValuesEnabled: Bool { get { return (renderer as! PieChartRenderer).usePercentValuesEnabled } set { (renderer as! PieChartRenderer).usePercentValuesEnabled = newValue setNeedsDisplay() } } /// - returns: true if drawing x-values is enabled, false if not open var isUsePercentValuesEnabled: Bool { get { return (renderer as! PieChartRenderer).usePercentValuesEnabled } } /// the line break mode for center text. /// note that different line break modes give different performance results - Clipping being the fastest, WordWrapping being the slowst. open var centerTextLineBreakMode: NSLineBreakMode { get { return (renderer as! PieChartRenderer).centerTextLineBreakMode } set { (renderer as! PieChartRenderer).centerTextLineBreakMode = newValue setNeedsDisplay() } } /// the rectangular radius of the bounding box for the center text, as a percentage of the pie hole open var centerTextRadiusPercent: CGFloat { get { return (renderer as! PieChartRenderer).centerTextRadiusPercent } set { (renderer as! PieChartRenderer).centerTextRadiusPercent = newValue setNeedsDisplay() } } }
0
// // InfoView.swift // Pods // // Created by Anatoliy Voropay on 5/11/16. // // import UIKit /** Position of arrow in a view - Parameter None: View will be without arrow - Parameter Automatic: We will try to select most suitable position - Parameter Left, Right, Top, Bottom: Define view side that will contain an errow */ public enum InfoViewArrowPosition { case None case Automatic case Left, Right, Top, Bottom } /** Appearance animation - Parameter None: View will appear without animation - Parameter FadeIn: FadeIn animation will happen - Parameter FadeInAndScale: FadeIn and Scale animation will happen */ public enum InfoViewAnimation { case None case FadeIn case FadeInAndScale } /** Delegate that can handle events from InfoView appearance. */ @objc public protocol InfoViewDelegate { optional func infoViewWillShow(view: InfoView) optional func infoViewDidShow(view: InfoView) optional func infoViewWillHide(view: InfoView) optional func infoViewDidHide(view: InfoView) } /** View to show small text information blocks with arrow pointed to another view. In most cases it will be a button that was pressed. **Simple appearance** ``` let infoView = InfoView(text: "Your information here") infoView.show(onView: view, centerView: button) ``` **Delegation** You can set a delegate and get events when view ill appear/hide: ``` infoView.delegate = self // In your delegate class func infoViewDidShow(view: InfoView) { print("Now visible") } ``` **Customization** Set arrow position: ``` infoView.arrowPosition = .Left ``` Set animation: ``` infoView.animation = InfoViewAnimation.None // Without animation infoView.animation = InfoViewAnimation.FadeIn // FadeIn animation infoView.animation = InfoViewAnimation.FadeInAndScale // FadeIn and Scale animation ``` Set custom font: ``` infoView.font = UIFont(name: "AvenirNextCondensed-Regular", size: 16) ``` Set custom text color: ``` infoView.textColor = UIColor.grayColor() ``` Set custom background color: ``` infoView.backgroundColor = UIColor.blackColor() ``` Set custom layer properties: ``` infoView.layer.shadowColor = UIColor.whiteColor().CGColor infoView.layer.cornerRadius = 15 infoView.layer.shadowRadius = 5 infoView.layer.shadowOffset = CGPoint(x: 2, y: 2) infoView.layer.shadowOpacity = 0.5 ``` **Auto hide** Hide InfoView after delay automatically ``` infoView.hideAfterDelay = 2 ``` */ public class InfoView: UIView { /// Arrow position public var arrowPosition: InfoViewArrowPosition = .Automatic /// Animation public var animation: InfoViewAnimation = .FadeIn /// InfoViewDelegate delegate public weak var delegate: InfoViewDelegate? /// Text message public var text: String? /// Autohide after delay public var hideAfterDelay: CGFloat? { didSet { if let hideAfterDelay = hideAfterDelay { timer = NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(hideAfterDelay), target: self, selector: #selector(InfoView.hide), userInfo: nil, repeats: false) } else { timer?.invalidate() timer = nil } } } /// Text padding public var textInsets: UIEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) /// Text label font public var font: UIFont? /// Text label color public var textColor: UIColor? private lazy var label: UILabel = { let label = UILabel() label.numberOfLines = 0 self.backgroundView.insertSubview(label, aboveSubview: self.placeholderView) return label }() private lazy var placeholderView: PlaceholderView = { let placeholderView = PlaceholderView() placeholderView.color = self.backgroundColor self.backgroundView.addSubview(placeholderView) return placeholderView }() private lazy var backgroundView: BackgroundView = { let backgroundView = BackgroundView() backgroundView.backgroundColor = .clearColor() backgroundView.autoresizingMask = [ .FlexibleWidth, .FlexibleHeight ] backgroundView.delegate = self return backgroundView }() override public var autoresizingMask: UIViewAutoresizing { didSet { placeholderView.autoresizingMask = autoresizingMask label.autoresizingMask = autoresizingMask } } private weak var onView: UIView? private weak var centerView: UIView? private var timer: NSTimer? // MARK: Lifecycle override init(frame: CGRect) { super.init(frame: frame) customizeAppearance() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) customizeAppearance() } public convenience init(text: String, delegate: InfoViewDelegate) { self.init(text: text, arrowPosition: .Automatic, animation: .FadeIn, delegate: delegate) } public convenience init(text: String) { self.init(text: text, arrowPosition: .Automatic, animation: .FadeIn, delegate: nil) } public init(text: String, arrowPosition: InfoViewArrowPosition, animation: InfoViewAnimation, delegate: InfoViewDelegate?) { super.init(frame: CGRect.zero) self.text = text self.animation = animation self.arrowPosition = arrowPosition self.delegate = delegate customizeAppearance() } // MARK: Appearance public func show(onView view: UIView, centerView: UIView) { self.onView = view self.centerView = centerView var (suitableRect, suitableOffset) = self.suitableRect() var labelRect = CGRect(x: suitableRect.origin.x + textInsets.left, y: suitableRect.origin.y + textInsets.top, width: suitableRect.width - textInsets.left - textInsets.right, height: suitableRect.height - textInsets.bottom - textInsets.top) switch correctArrowPosition() { case .Left: labelRect.size.width -= PlaceholderView.Constants.TriangleSize.height labelRect.origin.x += PlaceholderView.Constants.TriangleSize.height case .Right: labelRect.size.width -= PlaceholderView.Constants.TriangleSize.height labelRect.origin.x -= PlaceholderView.Constants.TriangleSize.height suitableRect.origin.x -= PlaceholderView.Constants.TriangleSize.height case .Top: labelRect.size.height -= PlaceholderView.Constants.TriangleSize.height labelRect.origin.y += PlaceholderView.Constants.TriangleSize.height case .Bottom: labelRect.size.height -= PlaceholderView.Constants.TriangleSize.height labelRect.origin.y -= PlaceholderView.Constants.TriangleSize.height suitableRect.origin.y -= PlaceholderView.Constants.TriangleSize.height default: break } backgroundView.frame = view.bounds placeholderView.frame = suitableRect placeholderView.triangleOffset = suitableOffset placeholderView.arrowPosition = correctArrowPosition() placeholderView.color = backgroundColor placeholderView.layer.cornerRadius = self.layer.cornerRadius placeholderView.layer.shadowColor = self.layer.shadowColor placeholderView.layer.shadowRadius = self.layer.shadowRadius placeholderView.layer.shadowOffset = self.layer.shadowOffset placeholderView.layer.shadowOpacity = self.layer.shadowOpacity placeholderView.alpha = 0 label.frame = labelRect label.text = text label.font = font label.textColor = textColor label.textAlignment = textAlignment() label.alpha = 0 view.addSubview(backgroundView) animateAppearance() } func hide() { timer?.invalidate() timer = nil animateDisappearance() } // MARK: Animation private func animateAppearance() { delegate?.infoViewWillShow?(self) switch self.animation { case .FadeInAndScale: placeholderView.transform = scaleTransform(placeholderView.transform) label.transform = scaleTransform(label.transform) default: break } UIView.animateWithDuration(duration(), animations: { self.label.alpha = 1 self.placeholderView.alpha = 1 switch self.animation { case .FadeInAndScale: self.placeholderView.transform = CGAffineTransformIdentity self.label.transform = CGAffineTransformIdentity default: break } }, completion: { (complete) in self.delegate?.infoViewDidShow?(self) }) } private func animateDisappearance() { self.delegate?.infoViewWillHide?(self) UIView.animateWithDuration(duration(), animations: { self.label.alpha = 0 self.placeholderView.alpha = 0 switch self.animation { case .FadeIn, .None: break case .FadeInAndScale: self.placeholderView.transform = self.scaleTransform(self.placeholderView.transform) self.label.transform = self.scaleTransform(self.label.transform) } }, completion: { (complete) in self.backgroundView.removeFromSuperview() self.delegate?.infoViewDidHide?(self) }) } private func duration() -> NSTimeInterval { return animation == .None ? 0 : 0.2 } private func scaleTransform(t: CGAffineTransform) -> CGAffineTransform { return CGAffineTransformScale(t, 0.5, 0.5) } // MARK: Helpers /// Return correct arrow position. It will detect correct position for Automatic also. private func correctArrowPosition() -> InfoViewArrowPosition { if arrowPosition == .Automatic { guard let view = onView else { return .Left } guard let centerView = centerView else { return .Left } let centerRect = view.convertRect(centerView.frame, toView: view) let width1 = view.frame.width let height1 = centerRect.origin.y let width2 = view.frame.width - centerRect.origin.x - centerRect.size.width let height2 = view.frame.height let width3 = view.frame.width let height3 = view.frame.height - centerRect.origin.y - centerRect.size.height let width4 = centerRect.origin.x let height4 = view.frame.height let area1: CGFloat = width1 * height1 let area2: CGFloat = width2 * height2 let area3: CGFloat = width3 * height3 let area4: CGFloat = width4 * height4 let max: CGFloat = CGFloat(fmaxf(fmaxf(Float(area1), Float(area2)), fmaxf(Float(area3), Float(area4)))) if max == area1 { return .Bottom } else if max == area2 { return .Left } else if max == area3 { return .Top } else { return .Right } } else { return arrowPosition } } private func textAlignment() -> NSTextAlignment { switch correctArrowPosition() { case .Left: return .Left case .Right: return .Right case .Top, .Bottom, .Automatic, .None: return .Center } } /// Return customized label with settings private func customizedLabel() -> UILabel { let label = UILabel() label.text = text label.font = font label.textColor = textColor label.numberOfLines = 0 return label } } // MARK: Discover best rect to show view extension InfoView { /// Return maximum allowed rect according to preferences private func visibleRect() -> CGRect { guard let view = onView else { return CGRect.zero } guard let centerView = centerView else { return CGRect.zero } let centerRect = view.convertRect(centerView.frame, toView: view) var visibleRect = CGRect.zero switch correctArrowPosition() { case .Left: visibleRect = CGRect(origin: CGPoint(x: centerRect.origin.x + centerRect.size.width, y: 0), size: CGSize(width: view.frame.width - centerRect.origin.x - centerRect.size.width, height: view.frame.height)) case .Right: visibleRect = CGRect(origin: CGPoint.zero, size: CGSize(width: centerRect.origin.x, height: view.frame.height)) case .Bottom: visibleRect = CGRect(origin: CGPoint.zero, size: CGSize(width: view.frame.width, height: centerRect.origin.y)) case .Top: visibleRect = CGRect(origin: CGPoint(x: 0, y: centerRect.origin.y + centerRect.size.height), size: CGSize(width: view.frame.width, height: view.frame.height - centerRect.origin.y - centerRect.size.height)) default: break } return visibleRect } /// Return allowed rect for final label according with textInsets private func allowedRect(inRect rect: CGRect) -> CGRect { let size = CGSize(width: rect.width - textInsets.left - textInsets.right, height: rect.height - textInsets.bottom - textInsets.top) let origin = CGPoint(x: rect.origin.x + textInsets.left, y: rect.origin.y + textInsets.top) return CGRect(origin: origin, size: size) } /// Return suitable rect for final label private func labelRect(inRect rect: CGRect) -> CGRect { var allowedRect = self.allowedRect(inRect: rect) allowedRect.size.height = CGFloat.max allowedRect.size.width *= ( UIDevice.currentDevice().userInterfaceIdiom == .Pad ? 0.5 : 0.8 ) let label = customizedLabel() label.frame = allowedRect label.sizeToFit() return label.frame } /// Return final rect for our placeholderView /// CGPoint is offset for triangle private func suitableRect() -> (CGRect, CGPoint) { guard let view = onView else { return (CGRect.zero, CGPoint.zero) } guard let centerView = centerView else { return (CGRect.zero, CGPoint.zero) } let visibleRect = self.visibleRect() let centerRect = view.convertRect(centerView.frame, toView: view) var finalRect = labelRect(inRect: visibleRect) var finalOffset = CGPoint.zero switch correctArrowPosition() { case .Left: finalRect.origin.y = centerRect.origin.y + centerView.frame.size.height / 2 - finalRect.size.height / 2 finalRect.origin.x = visibleRect.origin.x + textInsets.left finalRect.size.width += PlaceholderView.Constants.TriangleSize.height case .Right: finalRect.origin.y = centerRect.origin.y + centerView.frame.size.height / 2 - finalRect.size.height / 2 finalRect.origin.x = centerRect.origin.x - finalRect.size.width - textInsets.right finalRect.size.width += PlaceholderView.Constants.TriangleSize.height case .Top: finalRect.origin.x = centerRect.origin.x + centerView.frame.size.width / 2 - finalRect.size.width / 2 finalRect.origin.y = centerRect.origin.y + centerRect.size.height + textInsets.top finalRect.size.height += PlaceholderView.Constants.TriangleSize.height case .Bottom: finalRect.origin.x = centerRect.origin.x + centerView.frame.size.width / 2 - finalRect.size.width / 2 finalRect.origin.y = centerRect.origin.y - finalRect.size.height - textInsets.bottom finalRect.size.height += PlaceholderView.Constants.TriangleSize.height default: break } finalRect.origin.x -= textInsets.left finalRect.origin.y -= textInsets.top finalRect.size.width += textInsets.left + textInsets.right finalRect.size.height += textInsets.top + textInsets.bottom let borderOffset: CGFloat = 5 if finalRect.origin.x < 0 { finalOffset.x = finalRect.origin.x - borderOffset finalRect.origin.x = borderOffset } else if finalRect.origin.x + finalRect.size.width > view.frame.width { finalOffset.x = (finalRect.origin.x + finalRect.size.width) - view.frame.width + borderOffset finalRect.origin.x -= finalOffset.x } else if finalRect.origin.y < 0 { finalOffset.y = finalRect.origin.y - borderOffset finalRect.origin.y = borderOffset } else if finalRect.origin.y + finalRect.size.height > view.frame.height { finalOffset.y = (finalRect.origin.y + finalRect.size.height) - view.frame.height + borderOffset finalRect.origin.y -= finalOffset.y } return (finalRect, finalOffset) } } // MARK: Appearance customization extension InfoView { private func customizeAppearance() { font = .systemFontOfSize(14) textColor = .blackColor() backgroundColor = .whiteColor() layer.cornerRadius = 5 layer.shadowOpacity = 0.5 layer.shadowColor = UIColor.blackColor().CGColor layer.shadowRadius = 2 layer.shadowOffset = CGSize(width: 0, height: 0) } } extension InfoView: BackgroundViewDelegate { func pressedBackgorund(view: BackgroundView) { hide() } }
0
// swift-tools-version:5.5 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "nickdonald-boilerplate", platforms: [ .macOS(.v12) ], products: [ // Products define the executables and libraries a package produces, and make them visible to other packages. .library( name: "nickdonald-boilerplate", targets: ["nickdonald-boilerplate"]), ], dependencies: [ // Dependencies declare other packages that this package depends on. // .package(url: /* package url */, from: "1.0.0"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages this package depends on. .target( name: "nickdonald-boilerplate", dependencies: []), // .testTarget( // name: "nickdonald-boilerplateTests", // dependencies: ["nickdonald-boilerplate"]), ] )
0
// // Objects.swift // Notes // // Created by Eric Saba on 1/31/16. // Copyright © 2016 Eric Saba. All rights reserved. // import Foundation import MapKit import QuartzCore let ACCENT_COLOR: UIColor = UIColor(red: 14.0 / 255, green: 127.0 / 255, blue: 255.0 / 255, alpha: 1.0) let SCENERY_COLOR: UIColor = UIColor(red: 12.0 / 255, green: 208.0 / 255, blue: 0, alpha: 1.0) let CAUTION_COLOR: UIColor = UIColor(red: 255.0 / 255, green: 5.0 / 255, blue: 34.0 / 255, alpha: 1.0) let PERSONAL_COLOR: UIColor = UIColor(red: 130.0 / 255, green: 52.0 / 255, blue: 255.0 / 255, alpha: 1.0) let RESTAURANT_COLOR: UIColor = UIColor(red: 255.0 / 255, green: 255.0 / 255, blue: 0, alpha: 1.0) let FIND_RADIUS: Double = 50.0 let CAMERA_ZOOM: Float = 19.8 let BUTTON_SIZE: CGFloat = 60.0 let TYPE_SIZE: CGFloat = 40.0 let Y_INSET: CGFloat = 80.0 let POPOVER_INSET: CGFloat = 20.0 class Note: NSObject { var noteObj: PFObject? var lat: Double? var long: Double? var text: String? var dist: Double? var dir: Double? var image: UIImage? var type: String? var username: String = "" init(noteObj: PFObject, userLat: Double, userLong: Double) { super.init() self.noteObj = noteObj lat = (noteObj.objectForKey("location") as! PFGeoPoint).latitude long = (noteObj.objectForKey("location") as! PFGeoPoint).longitude text = noteObj.objectForKey("note") as? String type = noteObj.objectForKey("type") as? String dist = CallHandler().findDistance(userLat, long1: userLong, lat2: lat!, long2: long!) dir = CallHandler().findDirection(userLat, long1: userLong, lat2: lat!, long2: long!) } func setNoteUsername(completion: (reload: Bool, selfPosted: Bool) -> Void) { if username == "" { CallHandler().getUserForNote(self.noteObj!, completion: { (success, username) in if success { if self.type == "personal" { self.username = username completion(reload: true, selfPosted: false) } else if username == PFUser.currentUser()?.username { self.username = username completion(reload: true, selfPosted: true) } else { completion(reload: false, selfPosted: false) } } else { completion(reload: false, selfPosted: false) } }) } else { if self.username == PFUser.currentUser()?.username { completion(reload: true, selfPosted: true) } else { completion(reload: true, selfPosted: false) } } } // init(note: String, latitude: Double, longitude: Double, userLat: Double, userLong: Double, noteType: String) { // super.init() // text = note // lat = latitude // long = longitude // dist = CallHandler().findDistance(userLat, long1: userLong, lat2: latitude, long2: longitude) // dir = CallHandler().findDirection(userLat, long1: userLong, lat2: latitude, long2: longitude) // type = noteType // } func getDistText() -> String { return String(format: "%.0f", dist!) } func getDirText() -> String { var ret = "" if (dir > 292.5 || dir <= 67.5) { ret.appendContentsOf("N") } if (dir > 112.5 && dir <= 247.5) { ret.appendContentsOf("S") } if (dir > 22.5 && dir <= 157.5) { ret.appendContentsOf("E") } if (dir > 202.5 && dir <= 337.5) { ret.appendContentsOf("W") } return ret } func setLocation(latitude: Double, longitude: Double) { lat = latitude long = longitude } func setNote(note: String) { text = note } func updateDistance(userLat: Double, userLong: Double) { dist = CallHandler().findDistance(userLat, long1: userLong, lat2: lat!, long2: long!) dir = CallHandler().findDirection(userLat, long1: userLong, lat2: lat!, long2: long!) } func setNoteType(noteType: String) { type = noteType } } class MapNote: NSObject, MKAnnotation { let title: String? let coordinate: CLLocationCoordinate2D init(title: String, coordinate: CLLocationCoordinate2D) { self.title = title self.coordinate = coordinate super.init() } var subtitle: String? { return "" } } class Contact: NSObject { let name: String? let user: PFUser? var requested: Bool = false init(name: String, user: PFUser) { self.name = name self.user = user super.init() } } class Update: NSObject { let title: String let desc: String let seen: Bool init(title: String, desc: String, seen: Bool) { self.title = title self.desc = desc self.seen = seen super.init() } override init() { self.title = "" self.desc = "" self.seen = true super.init() } } class SegueFromLeft: UIStoryboardSegue { override func perform() { let src: UIViewController = self.sourceViewController let dst: UIViewController = self.destinationViewController let transition: CATransition = CATransition() let timeFunc : CAMediaTimingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) transition.duration = 0.25 transition.timingFunction = timeFunc transition.type = kCATransitionPush transition.subtype = kCATransitionFromLeft if (src.isMemberOfClass(ListTableViewController)) { transition.subtype = kCATransitionFromRight } src.navigationController!.view.layer.addAnimation(transition, forKey: kCATransition) src.navigationController!.pushViewController(dst, animated: false) } } class SegueFromRight: UIStoryboardSegue { override func perform() { let src: UIViewController = self.sourceViewController let dst: UIViewController = self.destinationViewController let transition: CATransition = CATransition() let timeFunc : CAMediaTimingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) transition.duration = 0.25 transition.timingFunction = timeFunc transition.type = kCATransitionPush transition.subtype = kCATransitionFromRight if (src.isMemberOfClass(ListTableViewController)) { transition.subtype = kCATransitionFromRight } src.navigationController!.view.layer.addAnimation(transition, forKey: kCATransition) src.navigationController!.pushViewController(dst, animated: false) } }
0
import XCTest import Combine @testable import Bitkub final class BitkubTests: XCTestCase { var cancellables: Set<AnyCancellable> = Set<AnyCancellable>() func testLoadCoins() { let expectation = XCTestExpectation(description: "Coin values recovered from Bitkub") let controller = BitkubController() controller.loadCoins() controller.$coins.drop(while: { $0.count == 0 }).sink { (coins) in expectation.fulfill() } .store(in: &cancellables) wait(for: [expectation], timeout: 5) } func testLoadBalance() { let key = ProcessInfo.processInfo.environment["KEY"] let secret = ProcessInfo.processInfo.environment["SECRET"] XCTAssertNotNil(key) XCTAssertNotNil(secret) let controller = BitkubController(apiKey: key!, secret: secret!) let expectation = XCTestExpectation(description: "Balance retrieved from Bitkub") try! controller.loadBalance() controller.$balances.drop(while: {$0.count == 0}).sink { (balances) in expectation.fulfill() } .store(in: &cancellables) wait(for: [expectation], timeout: 5) } func testWrongCredentials() { let key = "abcd" let secret = "efgh" let controller = BitkubController(apiKey: key, secret: secret) let expectation = XCTestExpectation(description: "Credentials are marked as invalid") try! controller.loadBalance() controller.$validCredentials.drop(while: { $0 }).sink { (validCredentials) in if validCredentials == false { expectation.fulfill() } }.store(in: &cancellables) wait(for: [expectation], timeout: 5) } func testLoadBalanceThrowsWithoutCredentials() { let controller = BitkubController() XCTAssertThrowsError(try controller.loadBalance()) { error in XCTAssertEqual(error as! BitkubError, BitkubError.missingCredentials) } } static var allTests = [ ("testLoadCoins", testLoadCoins), ] }
0
// // FVRecognitionTrainController.swift // FaceTrainerPackageDescription // // Created by Arman Galstyan on 12/17/17. // import Foundation import LASwift import AppKit public final class FVPerson { private var _faceID: String! public var faceID: String { return _faceID } public init(id: String) { self._faceID = id } } public final class FVRecognitionTrainController { typealias MeanValuesVector = Vector private let normalEigensPercenteage: Int = 15 private var facesBitArraysCollection = [TrainFaceBitArray]() private var meanValuesVector = MeanValuesVector() private var averageVectors: Matrix! private var transposeOfAverageVectors: Matrix! private var transposeOfCovarianseMatrix: Matrix! private var eigenVectors: Matrix! private var eigensMatrixTranspose: Matrix! private var porjectionMatrix: Matrix! private var personsList = [FVPerson]() public init() { } public func startTrain() { self.countMeanValuesVector() self.countAverageVectors() self.countCovariance() self.findEigens() } public func appendFace(forImage faceImage: NSImage) throws -> FVPerson { do { let recognitionImageBitsArray = try FVRecognitionImage(image: faceImage).getBitArray() self.facesBitArraysCollection.append(recognitionImageBitsArray) let person = FVPerson(id: UUID().uuidString) personsList.append(person) return person } catch (let error) { throw error } } private func countMeanValuesVector() { let faceCollectionCount = facesBitArraysCollection.count meanValuesVector = sum(Matrix(facesBitArraysCollection.map({ $0.bitArray })),.Column) meanValuesVector = rdivide(meanValuesVector, Double(faceCollectionCount)) } private func countAverageVectors() { transposeOfAverageVectors = Matrix(facesBitArraysCollection.map({ $0.bitArray - meanValuesVector })) averageVectors = transpose(transposeOfAverageVectors) } private func countCovariance() { transposeOfCovarianseMatrix = mtimes(transposeOfAverageVectors, averageVectors) } private func findEigens() { let temporaryEigens = eigen(transposeOfCovarianseMatrix) let normalCount = getNormalEigensCount(fromCount: temporaryEigens.count) print(normalCount) var sortedEigens = temporaryEigens.sorted(by: >) let normalEigens = sortedEigens[0..<normalCount] let eigensArray = normalEigens.map({ mtimes(averageVectors, $0.vectorMatrix)[col: 0] }) let normalizedEigensArray = eigensArray.map({ $0.normalized() }) self.eigensMatrixTranspose = Matrix(normalizedEigensArray) self.eigensMatrixTranspose = plus(eigensMatrixTranspose, meanValuesVector) self.porjectionMatrix = mtimes(self.eigensMatrixTranspose, averageVectors) } private func getNormalEigensCount(fromCount count: Int) -> Int { let normalCount = Double((count * normalEigensPercenteage)) / 100.0 if Int(normalCount) > 0 { return Int(normalCount) } return count } public func verify(face: FVRecognitionImage) -> FVPerson { let faceBitMap = face.getBitArray().bitArray var faceMatrix = zeros(faceBitMap.count, 1) faceMatrix = insert(faceMatrix, col: faceBitMap - meanValuesVector, at: 0) let weightMatrix = mtimes(eigensMatrixTranspose, faceMatrix) let weightVector = weightMatrix[col: 0] ////// var trainFaceVectors = [Vector]() for colIndex in 0..<self.porjectionMatrix.cols { trainFaceVectors.append(self.porjectionMatrix[col: colIndex]) } let dividingVectors = trainFaceVectors.map({ sum(abs($0 - weightVector))}) let personIndex = mini(dividingVectors) print("personindex \(personIndex)") return personsList[personIndex] } }
0
/*: # Closures Closures are self-contained blocks of functionality that can be passed around and used in your code. Functions are actually special cases of closures. Closures take one of three forms: - Global functions are closures that **have a name** and do not capture any values. - Nested functions are closures that _have a name_ and can **capture values** from their enclosing function. - Closure expressions are **unnamed closures** written in a lightweight syntax that can capture values from their surrounding context. */ /*: ## The type of functions and closures */ func add(_ a: Int, _ b: Int) -> Int { return a + b } func multiply(_ a: Int, _ b: Int) -> Int { return a * b } /*: This above example defines two simple mathematical functions called `add` and `multiply`. These functions take two `Int` values, and return an `Int` value. So the type of these functions is `(Int, Int) -> Int`. This can be read as: “A function type that has two parameters, both of type Int, and that returns a value of type Int.” */ let someArithmeticFunction: (Int, Int) -> Int = add(_:_:) someArithmeticFunction(1, 2) /*: ## Use function as arguments */ func reduce(numbers: [Int], reducer: (Int, Int) -> Int) -> Int? { guard !numbers.isEmpty else { return nil } // This array is not empty, so it’s okay to use `!` to get the first element as result. var result = numbers.first! // Then, enumerate the rest part of this array for number in numbers[1..<numbers.count] { result = reducer(result, number) } return result } reduce(numbers: [1, 2, 3, 4], reducer: add(_:_:)) reduce(numbers: [1, 2, 3, 4], reducer: multiply(_:_:)) reduce(numbers: [2, 3, 4, 5], reducer: +) //: > Yes, operatos are functions in Swift. //: -------------------------------------------------------------------------------------------------------------------- /*: ## Use closure as anonymous functions In the above example, each time when I use the `reduce(numbers:reducer:)` function, I have to create a reducer function first, and then pass the function as the argument. Closures can make the syntax of this pattern easier, like: */ reduce(numbers: [1, 2, 3, 4], reducer: { (a: Int, b: Int) -> Int in return (a + b) * 2 }) /*: Closure expression syntax has the following general form: ``` { (<parameter1>: <Type1>, <parameter2>: <Type2>, ...) -> <ReturnType> in <closure body> } ``` And it can be simplified as following syntaxes: */ // The full form reduce(numbers: [1, 2, 3, 4], reducer: { (a: Int, b: Int) -> Int in return a + b }) // Inferring Type From Context reduce(numbers: [1, 2, 3, 4], reducer: { a, b in return a + b }) // Shorthand Argument Names reduce(numbers: [1, 2, 3, 4], reducer: { return $0 + $1 }) // Implicit Returns from Single-Expression Closures reduce(numbers: [1, 2, 3, 4], reducer: { a, b in a + b }) reduce(numbers: [1, 2, 3, 4], reducer: { a, b in a + b }) reduce(numbers: [1, 2, 3, 4], reducer: { $0 + $1 }) reduce(numbers: [1, 2, 3, 4], reducer: { $0 + $1 }) /*: ## Trailing Closures If you need to pass a closure expression to a function as the function's final argument and the closure expression is long, it can be useful to write it as a trailing closure instead. A trailing closure is written after the function call's parentheses, even though it is still an argument to the function. When you use the trailing closure syntax, you don’t write the argument label for the closure as part of the function call. */ reduce(numbers: [1, 2, 3, 4]) { (a: Int, b: Int) -> Int in return a + b } // Or even ... reduce(numbers: [1, 2, 3, 4]) { a, b in return a + b } reduce(numbers: [1, 2, 3, 4]) { return $0 + $1 } reduce(numbers: [1, 2, 3, 4]) { $0 + $1 } //: -------------------------------------------------------------------------------------------------------------------- /*: ## Capturing Values A closure can capture constants and variables from the surrounding context in which it is defined. The closure can then refer to and modify the values of those constants and variables from within its body, even if the original scope that defined the constants and variables no longer exists. */ func makeIncrementer(forIncrement amount: Int) -> (() -> Int) { var runningTotal = 0 func incrementer() -> Int { runningTotal += amount return runningTotal } return incrementer } let oneStepIncrementer = makeIncrementer(forIncrement: 1) let tenStepsIncrementer = makeIncrementer(forIncrement: 10) oneStepIncrementer() oneStepIncrementer() oneStepIncrementer() tenStepsIncrementer() oneStepIncrementer() tenStepsIncrementer() /*: We can find that there are different `runningTotal` vairables **captured** by the two incremeneter. So their value are separated and won't affect each other. And also, although the scope of `runnintTotal` is end, but it still avaialbe inside the incremeneter closure. _(Because it has been captured by closures.)_ */ //: --- //: //: [<- Previous](@previous) | [Next ->](@next) //:
0
import UIKit import LoyaltyStation class ViewController: UIViewController { @IBOutlet weak var views: UIView! @IBAction func open(_ sender: Any) { LoyaltyStation.open(on: self) } @IBAction func login(_ sender: Any) { LoyaltyStation.login(user: User(id: "test-id", firstName: "Riyad", lastName: "Yahya", country: nil, referral: nil, hash: "237ccb1812cf2c893e341788921ec62515ca6d0507d7e4577055b25b794f831c")) } }
0
import UIKit import StorageKit import RxSwift public class Kit { private static let supportedCurrencies = [ Currency(code: "AUD", symbol: "A$", decimal: 2), Currency(code: "BRL", symbol: "R$", decimal: 2), Currency(code: "CAD", symbol: "C$", decimal: 2), Currency(code: "CHF", symbol: "₣", decimal: 2), Currency(code: "CNY", symbol: "¥", decimal: 2), Currency(code: "EUR", symbol: "€", decimal: 2), Currency(code: "GBP", symbol: "£", decimal: 2), Currency(code: "HKD", symbol: "HK$", decimal: 2), Currency(code: "ILS", symbol: "₪", decimal: 2), Currency(code: "JPY", symbol: "¥", decimal: 2), Currency(code: "RUB", symbol: "₽", decimal: 2), Currency(code: "SGD", symbol: "S$", decimal: 2), Currency(code: "USD", symbol: "$", decimal: 2), Currency(code: "BTC", symbol: "₿", decimal: 8), Currency(code: "ETH", symbol: "Ξ", decimal: 8), Currency(code: "BNB", symbol: "BNB", decimal: 8), ] private let currencyManager: CurrencyManager public init(localStorage: ILocalStorage) { currencyManager = CurrencyManager(currencies: Kit.supportedCurrencies, localStorage: localStorage) } } extension Kit { public var baseCurrency: Currency { get { currencyManager.baseCurrency } set { currencyManager.baseCurrency = newValue } } public var currencies: [Currency] { currencyManager.currencies } public var baseCurrencyUpdatedObservable: Observable<Currency> { currencyManager.baseCurrencyUpdatedObservable } public static func currencyIcon(code: String) -> UIImage? { CurrencyKit.image(named: code) } }
0
// // AppDelegate.swift // HaroldExample // // Created by Lacy Rhoades on 6/28/17. // Copyright © 2017 Lacy Rhoades. All rights reserved. // import UIKit import Harold @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var scanner: Harold? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. self.scanner = Harold() if let mainMenu = self.window?.rootViewController as? ViewController { self.scanner?.loggingDelegate = mainMenu self.scanner?.addListener(mainMenu) } 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. scanner?.pauseScanning() } 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. scanner?.startScanning() } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
0
// // BaseController.swift // NewToday // // Created by 吴腾通 on 2020/3/2. // Copyright © 2020 FL SMART. All rights reserved. // import UIKit class BaseController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { view.endEditing(true) } } extension BaseController { // 重写 当调用模态视图时,展示全屏 override func present(_ viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)? = nil) { viewControllerToPresent.modalPresentationStyle = .fullScreen super .present(viewControllerToPresent, animated: flag, completion: completion) } }
0
extension PhotoEditorController: UITextViewDelegate { public func textViewDidChange(_ textView: UITextView) { let rotation = atan2(textView.transform.b, textView.transform.a) if rotation == 0 { let oldFrame = textView.frame let sizeToFit = textView.sizeThatFits(CGSize(width: oldFrame.width, height: CGFloat.greatestFiniteMagnitude)) textView.frame.size = CGSize(width: oldFrame.width, height: sizeToFit.height) } } public func textViewDidBeginEditing(_ textView: UITextView) { isTyping = true activeTextView = textView textView.superview?.bringSubviewToFront(textView) textView.font = UIFont.systemFont(ofSize: 24) } public func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { if text == "\n" { doneButtonTapped() editedSomething = true return true } return true } public func textViewDidEndEditing(_ textView: UITextView) { activeTextView = nil } private func doneButtonTapped() { view.endEditing(true) canvasImageView.isUserInteractionEnabled = true isTyping = false } @objc func onKeyboardHide() { view.endEditing(true) canvasImageView.isUserInteractionEnabled = true isTyping = false } }
0
// // AppDelegate.swift // YiMaiPatient // // Created by ios-dev on 16/8/13. // Copyright © 2016年 yimai. All rights reserved. // import UIKit import CoreData import UMSocialCore import UMSocialNetwork @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, WXApiDelegate { var window: UIWindow? var NotifyCationProcession = false func RegisterNotification(app: UIApplication) { let types = UIUserNotificationType(rawValue: UIUserNotificationType.Badge.rawValue | UIUserNotificationType.Sound.rawValue | UIUserNotificationType.Alert.rawValue) let notificationSetting = UIUserNotificationSettings(forTypes: types, categories: nil) app.registerUserNotificationSettings(notificationSetting) } func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) { YMVar.DeviceToken = deviceToken.description.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "<>")) YMVar.DeviceToken = YMVar.DeviceToken.stringByReplacingOccurrencesOfString(" ", withString: "") UMessage.registerDeviceToken(deviceToken) print("remote push register success \(YMVar.DeviceToken)") } func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) { print("remote push register failed") } func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) { completionHandler(UIBackgroundFetchResult.NewData) UMessage.setAutoAlert(false) if(0 == YMVar.MyInfo.count) { application.applicationIconBadgeNumber = 0 return } let action = userInfo["action"] as? String if(nil == action) { application.applicationIconBadgeNumber = 0 return } let ctrl = window?.rootViewController as? UINavigationController if(nil == ctrl) { application.applicationIconBadgeNumber = 0 return } if(application.applicationState != UIApplicationState.Active) { YMNotificationHandler.HandlerMap[action!]?(ctrl!, userInfo) completionHandler(UIBackgroundFetchResult.NewData) } else { completionHandler(UIBackgroundFetchResult.NoData) } application.applicationIconBadgeNumber = 0 } func GoToBroadCast() { // if(NotifyCationProcession) { // return // } if(0 == YMVar.MyInfo.count) { return } // // NotifyCationProcession = true // if(YMCommonStrings.CS_PAGE_INDEX_NAME != YMCurrentPage.CurrentPage) { // YMDelay(0.5, closure: { // self.GoToBroadCast() // }) // } // NotifyCationProcession = false let ctrl = window?.rootViewController as? UINavigationController PageJumpActions(navController: ctrl).DoJump(YMCommonStrings.CS_PAGE_SYS_BROADCAST) } func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. YMCoreDataEngine.EngineInitialize() WXApi.registerApp("wx2097e8b109f9dc35", withDescription: "YiMaiPatient-1.0") UMessage.startWithAppkey("amgk5dbz4onk136msjkax7e3og4kadqz", launchOptions: launchOptions) UMessage.registerForRemoteNotifications() UMessage.setLogEnabled(true) // RegisterNotification(application) application.applicationIconBadgeNumber = 0 UMSocialManager.defaultManager().openLog(true) UMSocialManager.defaultManager().umSocialAppkey = "58073c2ae0f55a4ac00023e4" UMSocialManager.defaultManager().setPlaform(UMSocialPlatformType.WechatSession, appKey: "wx2097e8b109f9dc35", appSecret: "9zbnr31s8rijwrn5676ll9xhz8k56brn", redirectURL: "https://www.medi-link.cn") UMSocialManager.defaultManager().setPlaform(UMSocialPlatformType.Sina, appKey: "1075290971", appSecret: "ebd03c962864546d7b5e854f2b4a8dc1", redirectURL: "https://www.medi-link.cn") UIDevice.currentDevice() return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.yimai.patient.YiMaiPatient" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("YiMaiPatient", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } func application(app: UIApplication, openURL url: NSURL, options: [String : AnyObject]) -> Bool { print("openURL:\(url.absoluteString)") if (url.scheme == "wx2097e8b109f9dc35") { return WXApi.handleOpenURL(url, delegate: self) } return false } //wx pay callback func onResp(resp: BaseResp!) { let ctrl = window?.rootViewController as? UINavigationController let targetCtrl = ctrl?.viewControllers.last if resp.isKindOfClass(PayResp) { switch resp.errCode { case 0 : targetCtrl?.YMUpdateStateFromWXPay() default: targetCtrl?.YMShowErrorFromWXPay() } } } } func YMDelay(delay:Double, closure:()->()) { dispatch_after( dispatch_time( DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)) ), dispatch_get_main_queue(), closure) }
0
// // TriggerActionHandler.swift // // Created by ToKoRo on 2017-09-03. // import HomeKit protocol TriggerActionHandler { func handleRemove(_ trigger: HMTrigger) }
0
// // HighlightableRoundedButtonTests.swift // AHDownloadButton_Tests // // Created by Amer Hukic on 28/01/2019. // Copyright © 2019 CocoaPods. All rights reserved. // import XCTest @testable import AHDownloadButton class HighlightableRoundedButtonTests: XCTestCase { var highlightableRoundedButton: HighlightableRoundedButton! override func setUp() { highlightableRoundedButton = HighlightableRoundedButton() } override func tearDown() { highlightableRoundedButton = nil } func testSettingIsHighlightedShouldUpdateButtonColors() { highlightableRoundedButton.isHighlighted = true XCTAssertTrue(highlightableRoundedButton.backgroundColor == highlightableRoundedButton.highlightedBackgroundColor) XCTAssertTrue(highlightableRoundedButton.titleColor(for: .normal) == highlightableRoundedButton.highlightedTitleColor) highlightableRoundedButton.isHighlighted = false XCTAssertTrue(highlightableRoundedButton.backgroundColor == highlightableRoundedButton.nonhighlightedBackgroundColor) XCTAssertTrue(highlightableRoundedButton.titleColor(for: .normal) == highlightableRoundedButton.nonhighlightedTitleColor) } func testLayoutSubviewsShouldUpdateCornerRadius() { highlightableRoundedButton.layoutSubviews() XCTAssertTrue(highlightableRoundedButton.layer.cornerRadius == highlightableRoundedButton.frame.height / 2) } }
0
// // CreateContestCoordinator.swift // lily // // Created by Nathan Chan on 9/13/17. // Copyright © 2017 Nathan Chan. All rights reserved. // import UIKit protocol CreateContestCoordinatorDelegate: class { func createContestCoordinatorDelegateDidCancel(_ createContestCoordinator: CreateContestCoordinator) func createContestCoordinator(_ createContestCoordinator: CreateContestCoordinator, didCreateContest contest: Contest) } class CreateContestCoordinator: NavigationCoordinator { var navigationController: UINavigationController var childCoordinators: [Coordinator] = [] weak var delegate: CreateContestCoordinatorDelegate? var createContestViewModel: CreateContestViewModel required init(navigationController: UINavigationController) { self.navigationController = navigationController createContestViewModel = CreateContestViewModel() } func start() { showCreateContestSelectMediaViewController() } private func showCreateContestSelectMediaViewController() { let createContestSelectMediaViewController = CreateContestSelectMediaViewController(viewModel: createContestViewModel) createContestViewModel.delegate = self self.navigationController.pushViewController(createContestSelectMediaViewController, animated: true) } fileprivate func showCreateContestViewController(_ media: Media) { let createContestViewController = CreateContestViewController(viewModel: createContestViewModel) createContestViewModel.delegate = self createContestViewModel.selectedMedia = media self.navigationController.pushViewController(createContestViewController, animated: true) } } extension CreateContestCoordinator: CreateContestViewModelDelegate { func createContestViewDidClickCancel(_ createContestViewModel: CreateContestViewModel) { self.delegate?.createContestCoordinatorDelegateDidCancel(self) } func createContestView(_ createContestViewModel: CreateContestViewModel, didSelectMedia media: Media) { showCreateContestViewController(media) } func createContestView(_ createContestViewModel: CreateContestViewModel, didCreateContest contest: Contest) { self.delegate?.createContestCoordinator(self, didCreateContest: contest) } func createContestView(_ createContestViewModel: CreateContestViewModel, didClickViewOnIG media: Media) { self.openMedia(media) } }
0
// // Utils.swift // App // // Created by Luis Vasquez on 19/05/20. // Copyright © 2020 Cisco. All rights reserved. // import UIKit class Utils: NSObject { static func showAlert(controller: UIViewController, title: String, message: String){ let alert = UIAlertController(title: "Network Error", message: "Not able to access the internet. Please check your network connectivity", preferredStyle: UIAlertController.Style.alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil)) controller.present(alert, animated: true, completion: nil) } static func showNetworkAlertError(controller: UIViewController){ showAlert(controller: controller, title: "Network Error", message: "Not able to access the internet. Please check your network connectivity") } }
0
// // SCDefinitionDisplayView.swift // AussieDataHelper // // Created by Stephen Cao on 29/6/19. // Copyright © 2019 Stephencao Cao. All rights reserved. // import UIKit protocol SCDefinitionDisplayViewDelegate: NSObjectProtocol { func didClickKeyboardSearchKey(view: SCDefinitionDisplayView) func didScrollToBottom(view: SCDefinitionDisplayView) func didSelectedCell(view: SCDefinitionDisplayView, definitionText: String?) } private let reuseIdentifier = "definitions_cell" class SCDefinitionDisplayView: UIView { weak var delegate: SCDefinitionDisplayViewDelegate? var viewModel: SCDefinitionsViewModel? @IBOutlet weak var tableView: UITableView! @IBOutlet weak var textField: UITextField! var currentPage = 1 var shouldPullUp: Bool = false class func displayView()->SCDefinitionDisplayView{ let nib = UINib(nibName: "SCDefinitionDisplayView", bundle: nil) let v = nib.instantiate(withOwner: self, options: nil)[0] as! SCDefinitionDisplayView v.frame = UIScreen.main.bounds return v } override func awakeFromNib() { super.awakeFromNib() textField.delegate = self textField.returnKeyType = .search tableView.estimatedRowHeight = 140 tableView.rowHeight = UITableView.automaticDimension tableView.delegate = self tableView.dataSource = self tableView.register(UINib(nibName: "SCDefinitionsTableViewCell", bundle: nil), forCellReuseIdentifier: reuseIdentifier) } @IBAction func clickClearTextFieldButton(_ sender: Any) { textField.text?.removeAll() textField.resignFirstResponder() } } extension SCDefinitionDisplayView: UITextFieldDelegate{ func textFieldShouldReturn(_ textField: UITextField) -> Bool { delegate?.didClickKeyboardSearchKey(view: self) return false } } extension SCDefinitionDisplayView: UITableViewDelegate, UITableViewDataSource{ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { tableView.separatorStyle = (viewModel?.definitionsData?.content?.count ?? 0) > 0 ? UITableViewCell.SeparatorStyle.singleLine : .none return viewModel?.definitionsData?.content?.count ?? 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) as! SCDefinitionsTableViewCell cell.cententItem = viewModel?.definitionsData?.content?[indexPath.row].content return cell } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { let row = indexPath.row // let currentSection == indexPath.section let section = tableView.numberOfSections - 1 if row < 0 || section < 0{ return } let rowCount = tableView.numberOfRows(inSection: section) // && currentSection == section if row == (rowCount - 1) && !shouldPullUp{ shouldPullUp = true currentPage += 1 delegate?.didScrollToBottom(view: self) } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { delegate?.didSelectedCell(view: self, definitionText: viewModel?.definitionsData?.content?[indexPath.row].content?.definition) } }
0
// The MIT License (MIT) // Copyright © 2017 Ivan Vorobei (vvkpx@example.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit class SPPermissionDialogView: UIView { let titleLabel = UILabel() let subtitleLabel = UILabel() var views: [SPPermissionDialogLineView] = [] let descriptionLabel = UILabel() var layoutWidth: CGFloat = 0 { didSet { self.setWidth(self.layoutWidth) self.layoutSubviews() } } var layoutHeight: CGFloat = 0 var sideInset: CGFloat { return 22 } init() { super.init(frame: .zero) self.commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.commonInit() } private func commonInit() { self.backgroundColor = SPNativeStyleKit.Colors.white self.layer.cornerRadius = 17 self.subtitleLabel.text = "".uppercased() self.subtitleLabel.numberOfLines = 0 self.subtitleLabel.textColor = SPNativeStyleKit.Colors.gray self.subtitleLabel.font = UIFont.system(type: .DemiBold, size: 15) self.addSubview(self.subtitleLabel) self.titleLabel.text = "" self.titleLabel.numberOfLines = 0 self.titleLabel.textColor = SPNativeStyleKit.Colors.black self.titleLabel.font = UIFont.system(type: .Bold, size: 27) self.addSubview(self.titleLabel) self.descriptionLabel.text = "" self.descriptionLabel.numberOfLines = 0 self.descriptionLabel.textColor = SPNativeStyleKit.Colors.gray self.descriptionLabel.font = UIFont.system(type: .Regular, size: 11) self.addSubview(self.descriptionLabel) } func add(view: SPPermissionDialogLineView) { view.updateStyle() self.addSubview(view) self.views.append(view) } override func layoutSubviews() { super.layoutSubviews() self.subtitleLabel.frame = CGRect.init(x: self.sideInset, y: 0, width: self.layoutWidth - self.sideInset * 2, height: 0) self.subtitleLabel.sizeToFit() if SPDevice.Orientation.isPortrait { self.subtitleLabel.frame.origin.y = 27 } else { self.subtitleLabel.frame.origin.y = 17 } self.titleLabel.frame = CGRect.init(x: self.sideInset, y: self.subtitleLabel.frame.bottomYPosition + 2, width: self.frame.width - self.sideInset * 2, height: 0) self.titleLabel.sizeToFit() var currentYPosition: CGFloat = 0 if SPDevice.Orientation.isPortrait { currentYPosition = self.titleLabel.frame.bottomYPosition + 20 } else { currentYPosition = self.titleLabel.frame.bottomYPosition - 2 } for view in self.views { view.frame = CGRect.init(x: self.sideInset, y: currentYPosition, width: self.layoutWidth - sideInset * 2, height: 10) view.layoutSubviews() currentYPosition += view.frame.height } if let view = self.views.last { view.separatorView.isHidden = true } if SPDevice.Orientation.isPortrait { self.descriptionLabel.frame = CGRect.init(x: self.sideInset, y: currentYPosition + 20, width: self.layoutWidth - self.sideInset * 2, height: 0) self.descriptionLabel.sizeToFit() SPAnimation.animate(0.2, animations: { self.descriptionLabel.alpha = 1 }) self.layoutHeight = self.descriptionLabel.frame.bottomYPosition + 22 } else { SPAnimation.animate(0.2, animations: { self.descriptionLabel.alpha = 0 }) self.layoutHeight = currentYPosition + 2 } let shadowPath = UIBezierPath.init( roundedRect: CGRect.init(x: 0, y: 9, width: self.layoutWidth, height: self.layoutHeight), cornerRadius: self.layer.cornerRadius ) self.layer.shadowColor = UIColor.black.cgColor self.layer.shadowOffset = CGSize.zero self.layer.shadowOpacity = Float(0.07) self.layer.shadowRadius = 17 self.layer.masksToBounds = false self.layer.shadowPath = shadowPath.cgPath } } class SPPermissionDialogLineView: UIView { let titleLabel = UILabel() let subtitleLabel = UILabel() var iconView: SPGolubevIconView = SPGolubevIconView.init() var imageView = UIImageView() var button = SPAppStoreActionButton() var separatorView = UIView() var permission: SPPermissionType private var allowTitle: String private var allowedTitle: String init(permission: SPPermissionType, title: String, subtitle: String, allowTitle: String, allowedTitle: String, image: UIImage? = nil) { self.permission = permission self.allowTitle = allowTitle self.allowedTitle = allowedTitle super.init(frame: .zero) self.titleLabel.text = title self.subtitleLabel.text = subtitle self.imageView.isHidden = true if let image = image { self.imageView.contentMode = .scaleAspectFit self.imageView.image = image self.iconView.isHidden = true self.imageView.isHidden = false } else { switch permission { case .calendar: self.iconView.type = .calendar case .camera: self.iconView.type = .camera case .contacts: self.iconView.type = .book case .microphone: self.iconView.type = .micro case .notification: self.iconView.type = .ball case .photoLibrary: self.iconView.type = .photoLibrary case .reminders: self.iconView.type = .calendar case .speech: self.iconView.type = .micro case .locationWhenInUse: self.iconView.type = .compass case .locationAlways: self.iconView.type = .compass case .locationWithBackground: self.iconView.type = .compass case .mediaLibrary: self.iconView.type = .headphones } } self.commonInit() } required init?(coder aDecoder: NSCoder) { self.permission = .notification self.allowTitle = "Allow" self.allowedTitle = "Allowed" super.init(coder: aDecoder) self.commonInit() } private func commonInit() { self.backgroundColor = SPNativeStyleKit.Colors.white self.addSubview(self.imageView) self.addSubview(self.iconView) self.titleLabel.numberOfLines = 1 self.titleLabel.textColor = SPNativeStyleKit.Colors.black self.titleLabel.font = UIFont.system(type: .DemiBold, size: 15) self.addSubview(self.titleLabel) self.subtitleLabel.numberOfLines = 2 self.subtitleLabel.textColor = SPNativeStyleKit.Colors.gray self.subtitleLabel.font = UIFont.system(type: .Regular, size: 13) self.addSubview(self.subtitleLabel) self.button.setTitle(self.allowTitle) self.button.style = .base self.addSubview(self.button) self.separatorView.backgroundColor = SPNativeStyleKit.Colors.gray.withAlphaComponent(0.3) self.addSubview(self.separatorView) } func updateStyle() { if SPPermission.isAllow(self.permission) { SPAnimation.animate(0.2, animations: { self.button.setTitle(self.allowedTitle) self.button.style = .main self.button.sizeToFit() }) } else { SPAnimation.animate(0.2, animations: { self.button.setTitle(self.allowTitle) self.button.style = .base self.button.sizeToFit() }) } } override func layoutSubviews() { super.layoutSubviews() self.setHeight(79) self.iconView.frame = CGRect.init(x: 0, y: 0, width: 45, height: 45) self.iconView.center.y = self.frame.height / 2 self.imageView.frame = self.iconView.frame self.button.sizeToFit() self.button.frame.bottomXPosition = self.frame.width self.button.center.y = self.frame.height / 2 let titleInset: CGFloat = 15 let titlesWidth: CGFloat = self.button.frame.origin.x - self.iconView.frame.bottomXPosition - titleInset * 2 self.titleLabel.frame = CGRect.init(x: 0, y: 8, width: titlesWidth, height: 0) self.titleLabel.sizeToFit() self.titleLabel.setWidth(titlesWidth) self.titleLabel.frame.origin.x = self.iconView.frame.bottomXPosition + titleInset self.subtitleLabel.frame = CGRect.init(x: self.titleLabel.frame.origin.x + titleInset, y: 0, width: titlesWidth, height: 0) self.subtitleLabel.sizeToFit() self.subtitleLabel.setWidth(titlesWidth) self.subtitleLabel.frame.origin.x = self.iconView.frame.bottomXPosition + titleInset let allHeight = self.titleLabel.frame.height + 2 + self.subtitleLabel.frame.height self.titleLabel.frame.origin.y = (self.frame.height - allHeight) / 2 self.subtitleLabel.frame.origin.y = self.titleLabel.frame.bottomYPosition + 2 self.separatorView.frame = CGRect.init(x: self.subtitleLabel.frame.origin.x, y: self.frame.height - 0.7, width: self.button.frame.bottomXPosition - self.subtitleLabel.frame.origin.x, height: 0.7) self.separatorView.round() /*self.setHeight(75) self.iconView.frame = CGRect.init(x: 0, y: 0, width: 45, height: 45) self.iconView.center.y = self.frame.width / 2 self.button.sizeToFit() self.button.frame.bottomXPosition = self.frame.width self.button.center.y = self.frame.height / 2 let titleInset: CGFloat = 15 let titlesWidth: CGFloat = self.button.frame.origin.x - self.iconView.frame.bottomXPosition - titleInset * 2 self.titleLabel.frame = CGRect.init(x: self.iconView.frame.bottomXPosition + titleInset, y: 8, width: titlesWidth, height: 0) self.titleLabel.sizeToFit() self.subtitleLabel.frame = CGRect.init(x: self.iconView.frame.bottomXPosition + titleInset, y: self.titleLabel.frame.bottomYPosition + 2, width: titlesWidth, height: 0) self.subtitleLabel.setHeight(self.frame.height - 12 - self.subtitleLabel.frame.origin.y) //self.subtitleLabel.sizeToFit() //let height = (self.iconView.frame.bottomYPosition + 12) > (self.subtitleLabel.frame.bottomYPosition + 12) ? self.iconView.frame.bottomYPosition + 12 : self.subtitleLabel.frame.bottomYPosition + 12 //self.setHeight(75) self.separatorView.frame = CGRect.init(x: self.subtitleLabel.frame.origin.x, y: self.frame.height - 0.7, width: self.button.frame.bottomXPosition - self.subtitleLabel.frame.origin.x, height: 0.7) self.separatorView.round()*/ } }
0
// // SceneDelegate.swift // BetterReads // // Created by Ciara Beitel on 4/16/20. // Copyright © 2020 Labs23. All rights reserved. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` // to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be // initialized and attached to the scene. // This delegate does not imply the connecting scene or session are // new (see `application:configurationForConnectingSceneSession` instead). guard let _ = (scene as? UIWindowScene) else { return } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not neccessarily // 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. } }
0
// // ModifierMatchController.swift // MonTennis // // Created by Thomas Luquet on 01/07/2015. // Copyright (c) 2015 Thomas Luquet. All rights reserved. // import UIKit class ModifierMatchController: UITableViewController { internal var match: Match! internal var id: Int! override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return 2 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. var rows : Int switch section { case 0: rows = 4 case 1: rows = 3 default: rows = 0 } return rows } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell : UITableViewCell switch indexPath.section { case 0: cell = tableView.dequeueReusableCellWithIdentifier("detailModifier", forIndexPath: indexPath) switch indexPath.row { case 0: cell.textLabel?.text = "Résultat" if(match.resultat){ cell.detailTextLabel?.text = "Victoire" }else{ cell.detailTextLabel?.text="Défaite" } case 1: cell.textLabel?.text = "WO" if(match.wo){ cell.detailTextLabel?.text = "Oui" }else{ cell.detailTextLabel?.text = "Non" } case 2: cell.textLabel?.text = "Format" if(match.coef == 1.0){ cell.detailTextLabel?.text = "Normal" }else{ cell.detailTextLabel?.text = "Court" } case 3: cell.textLabel?.text = "Bonus championnat" if(match.bonus){ cell.detailTextLabel?.text = "Oui" }else{ cell.detailTextLabel?.text = "Non" } default: cell.textLabel?.text = "" cell.detailTextLabel?.text = "" } case 1: switch indexPath.row { case 0: cell = tableView.dequeueReusableCellWithIdentifier("detailModifierText", forIndexPath: indexPath) cell.textLabel?.text = "Nom" cell.detailTextLabel?.text = match.lastName case 1: cell = tableView.dequeueReusableCellWithIdentifier("detailModifierText", forIndexPath: indexPath) cell.textLabel?.text = "Prénom" cell.detailTextLabel?.text = match.firstName case 2: cell = tableView.dequeueReusableCellWithIdentifier("detailModifier", forIndexPath: indexPath) cell.textLabel?.text = "Classement" cell.detailTextLabel?.text = match.classement.string default: cell = tableView.dequeueReusableCellWithIdentifier("detailModifier", forIndexPath: indexPath) cell.textLabel?.text = "" cell.detailTextLabel?.text = "" } default: cell = tableView.dequeueReusableCellWithIdentifier("detailModifier", forIndexPath: indexPath) cell.textLabel?.text = "" cell.detailTextLabel?.text = "" } return cell } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { var title = "" switch section { case 0: title = "Match" case 1: title = "Infos Adversaire" default: title = "" } return title } @IBAction func saveMatchChanges(segue:UIStoryboardSegue){ self.tableView.reloadData() } // 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. if let cell = sender as? UITableViewCell { if(segue.identifier == "modifierChoix"){ let controller = segue.destinationViewController as! ModifierChoixController controller.choixType = cell.textLabel?.text controller.match = match controller.id = id } else if(segue.identifier == "modifierText"){ let controller = segue.destinationViewController as! ModifierTextController controller.textValue = cell.detailTextLabel?.text controller.textType = cell.textLabel?.text controller.match = match controller.id = id } } else if(segue.identifier == "deleteMatch"){ if(match.resultat){ barCtrl.user.victoires.removeAtIndex(id) }else{ barCtrl.user.defaites.removeAtIndex(id) } barCtrl.clearCoreData() barCtrl.fillCoreData() } } }
0
// // AUParamsApp // AudioUnitViewController.swift // // last build: macOS 10.13, Swift 4.0 // // Created by Gene De Lisa on 5/25/18. // Copyright ©(c) 2018 Gene De Lisa. All rights reserved. // // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. // // In addition: // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // 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 CoreAudioKit public class AudioUnitViewController: AUViewController, AUAudioUnitFactory { /* When this view controller is instantiated within the Containing App, its audio unit is created independently, and passed to the view controller here. */ public var audioUnit: AUAudioUnit? { didSet { /* We may be on a dispatch worker queue processing an XPC request at this time, and quite possibly the main queue is busy creating the view. To be thread-safe, dispatch onto the main queue. It's also possible that we are already on the main queue, so to protect against deadlock in that case, dispatch asynchronously. */ NSLog("got the audio unit \(String(describing: audioUnit))")// DispatchQueue.main.async { if self.isViewLoaded { self.connectUIToAudioUnit() } } } } var intervalAUParameter: AUParameter? var parameterObserverToken: AUParameterObserverToken? @IBOutlet weak var intervalSegmentedControl: UISegmentedControl! @IBOutlet weak var intervalLabel: UILabel! public override func viewDidLoad() { super.viewDidLoad() NSLog("\(#function)") if audioUnit == nil { return } connectUIToAudioUnit() } public func createAudioUnit(with componentDescription: AudioComponentDescription) throws -> AUAudioUnit { NSLog("\(#function)") audioUnit = try AUParamsPresetsAudioUnit(componentDescription: componentDescription, options: []) // Check if the UI has been loaded // if self.isViewLoaded { // NSLog("\(#function) connecting UI in create audio unit") // connectUIToAudioUnit() // } return audioUnit! } func connectUIToAudioUnit() { NSLog("\(#function)") guard let paramTree = audioUnit?.parameterTree else { NSLog("The audio unit has no parameters!") return } // get the parameter self.intervalAUParameter = paramTree.value(forKey: "intervalParameter") as? AUParameter NSLog("interauparameter \(String(describing: intervalAUParameter))"); // or // if let theUnit = audioUnit as? AUParamsPresetsAudioUnit { // if let param = theUnit.parameterTree?.parameter(withAddress: AUParameterAddress(intervalParameter)) { // NSLog("connectUIToAudioUnit intervalParam: \(String(describing: param))") // self.intervalAUParameter = param // // DispatchQueue.main.async { [weak self] in // guard let strongSelf = self else { return } // NSLog("connectUIToAudioUnit new value: \(param.value) will sub 1") // strongSelf.intervalSegmentedControl.selectedSegmentIndex = Int(param.value - 1) // strongSelf.intervalLabel.text = strongSelf.intervalAUParameter!.string(fromValue: nil) // } // } // } parameterObserverToken = paramTree.token(byAddingParameterObserver: { [weak self] address, value in guard let strongSelf = self else { NSLog("self is nil; returning") return } DispatchQueue.main.async { if address == strongSelf.intervalAUParameter!.address { NSLog("connectUIToAudioUnit2 observed new value: \(value)") strongSelf.intervalSegmentedControl.selectedSegmentIndex = Int(value - 1) strongSelf.intervalLabel.text = strongSelf.intervalAUParameter!.string(fromValue: nil) } } }) self.intervalLabel.text = self.intervalAUParameter!.string(fromValue: nil) self.intervalSegmentedControl.selectedSegmentIndex = Int(self.intervalAUParameter!.value - 1) } // if I had a slider @IBAction func intervalSliderValueChangedAction(_ sender: UISlider) { guard let theAudioUnit = audioUnit as? AUParamsPresetsAudioUnit, let intervalParameter = theAudioUnit.parameterTree?.parameter(withAddress: AUParameterAddress(intervalParameter)) else { NSLog("could not get the audio unit or the parameter in \(#function)") return } intervalParameter.setValue(sender.value, originator: parameterObserverToken) } @IBAction func intervalValueChanged(_ sender: UISegmentedControl) { var interval: AUValue = 0 switch sender.selectedSegmentIndex { case 0: interval = 1 case 1: interval = 2 case 2: interval = 3 case 3: interval = 4 case 4: interval = 5 case 5: interval = 6 case 6: interval = 7 case 7: interval = 8 case 8: interval = 9 case 9: interval = 10 case 10: interval = 11 case 11: interval = 12 default: break } //or self.intervalAUParameter?.value = interval self.intervalAUParameter?.setValue(interval, originator: parameterObserverToken) // just debugging if let p = self.intervalAUParameter { NSLog("intervalParam: \(String(describing: p))") let s = p.string(fromValue: &p.value) NSLog("value string: \(s)") NSLog("final value: \(p.value)") } else { NSLog("oops self.intervalAUParameter is nil") } } }

Dataset Card for "swift"

More Information needed

Downloads last month
53
Edit dataset card