text
stringlengths
8
1.32M
// // BabyRadioItems.swift // MASSDK_Swift // // Created by Big Shark on 15/03/2017. // Copyright © 2017 MasterApp. All rights reserved. // import Foundation class BabyRadioItems{ static func getAllItems() -> [FloatingItemModel]{ var result : [FloatingItemModel] = [] var item = FloatingItemModel() item.item_title = "Washing machine" item.item_type = Constants.BABY_RADIO_SOUND item.item_audiosource = Constants.AUDIO_SOURCE_ASSET result.append(item) item = FloatingItemModel() item.item_title = "Vacuum cleaner" item.item_type = Constants.BABY_RADIO_SOUND item.item_audiosource = Constants.AUDIO_SOURCE_ASSET result.append(item) item = FloatingItemModel() item.item_title = "Jukebox" item.item_type = Constants.BABY_RADIO_MUSIC item.item_audiosource = Constants.AUDIO_SOURCE_ASSET result.append(item) item = FloatingItemModel() item.item_title = "Chimes" item.item_type = Constants.BABY_RADIO_MUSIC item.item_audiosource = Constants.AUDIO_SOURCE_ASSET result.append(item) item = FloatingItemModel() item.item_title = "Mom's heartbeat" item.item_type = Constants.BABY_RADIO_SOUND item.item_audiosource = Constants.AUDIO_SOURCE_ASSET result.append(item) item = FloatingItemModel() item.item_title = "Fan" item.item_type = Constants.BABY_RADIO_SOUND item.item_audiosource = Constants.AUDIO_SOURCE_ASSET result.append(item) item = FloatingItemModel() item.item_title = "Forest" item.item_type = Constants.BABY_RADIO_SOUND item.item_audiosource = Constants.AUDIO_SOURCE_ASSET result.append(item) item = FloatingItemModel() item.item_title = "Cat purr" item.item_type = Constants.BABY_RADIO_SOUND item.item_audiosource = Constants.AUDIO_SOURCE_ASSET result.append(item) item = FloatingItemModel() item.item_title = "Violin" item.item_type = Constants.BABY_RADIO_MUSIC item.item_audiosource = Constants.AUDIO_SOURCE_ASSET result.append(item) item = FloatingItemModel() item.item_title = "Wind" item.item_type = Constants.BABY_RADIO_SOUND item.item_audiosource = Constants.AUDIO_SOURCE_ASSET result.append(item) item = FloatingItemModel() item.item_title = "Air conditioning" item.item_type = Constants.BABY_RADIO_SOUND item.item_audiosource = Constants.AUDIO_SOURCE_ASSET result.append(item) item = FloatingItemModel() item.item_title = "Piano" item.item_type = Constants.BABY_RADIO_MUSIC item.item_audiosource = Constants.AUDIO_SOURCE_ASSET result.append(item) item = FloatingItemModel() item.item_title = "Sax" item.item_type = Constants.BABY_RADIO_MUSIC item.item_audiosource = Constants.AUDIO_SOURCE_ASSET result.append(item) item = FloatingItemModel() item.item_title = "Dishwasher" item.item_type = Constants.BABY_RADIO_SOUND item.item_audiosource = Constants.AUDIO_SOURCE_ASSET result.append(item) item = FloatingItemModel() item.item_title = "Lorry" item.item_type = Constants.BABY_RADIO_SOUND item.item_audiosource = Constants.AUDIO_SOURCE_ASSET result.append(item) item = FloatingItemModel() item.item_title = "Flute" item.item_type = Constants.BABY_RADIO_MUSIC item.item_audiosource = Constants.AUDIO_SOURCE_ASSET result.append(item) item = FloatingItemModel() item.item_title = "White noise" item.item_type = Constants.BABY_RADIO_SOUND result.append(item) item = FloatingItemModel() item.item_title = "Rain" item.item_type = Constants.BABY_RADIO_SOUND item.item_audiosource = Constants.AUDIO_SOURCE_ASSET result.append(item) item = FloatingItemModel() item.item_title = "Xylophone" item.item_type = Constants.BABY_RADIO_MUSIC item.item_audiosource = Constants.AUDIO_SOURCE_ASSET result.append(item) item = FloatingItemModel() item.item_title = "Harp" item.item_type = Constants.BABY_RADIO_MUSIC item.item_audiosource = Constants.AUDIO_SOURCE_ASSET result.append(item) item = FloatingItemModel() item.item_title = "Wipers" item.item_type = Constants.BABY_RADIO_SOUND item.item_audiosource = Constants.AUDIO_SOURCE_ASSET result.append(item) item = FloatingItemModel() item.item_title = "Grandfather clock" item.item_type = Constants.BABY_RADIO_SOUND item.item_audiosource = Constants.AUDIO_SOURCE_ASSET result.append(item) item = FloatingItemModel() item.item_title = "Waterfall" item.item_type = Constants.BABY_RADIO_SOUND item.item_audiosource = Constants.AUDIO_SOURCE_ASSET result.append(item) item = FloatingItemModel() item.item_title = "Train" item.item_type = Constants.BABY_RADIO_SOUND item.item_audiosource = Constants.AUDIO_SOURCE_ASSET result.append(item) item = FloatingItemModel() item.item_title = "Shower" item.item_type = Constants.BABY_RADIO_SOUND item.item_audiosource = Constants.AUDIO_SOURCE_ASSET result.append(item) item = FloatingItemModel() item.item_title = "Dolphin" item.item_type = Constants.BABY_RADIO_SOUND item.item_audiosource = Constants.AUDIO_SOURCE_ASSET result.append(item) item = FloatingItemModel() item.item_title = "Guitar" item.item_type = Constants.BABY_RADIO_MUSIC item.item_audiosource = Constants.AUDIO_SOURCE_ASSET result.append(item) item = FloatingItemModel() item.item_title = "Lyre" item.item_type = Constants.BABY_RADIO_MUSIC item.item_audiosource = Constants.AUDIO_SOURCE_ASSET result.append(item) item = FloatingItemModel() item.item_title = "Stream" item.item_type = Constants.BABY_RADIO_SOUND item.item_audiosource = Constants.AUDIO_SOURCE_ASSET result.append(item) item = FloatingItemModel() item.item_title = "Fire" item.item_type = Constants.BABY_RADIO_SOUND item.item_audiosource = Constants.AUDIO_SOURCE_ASSET result.append(item) return result } static func getSounds() -> [FloatingItemModel]{ var result : [FloatingItemModel] = [] for item in getAllItems(){ if item.item_type == Constants.BABY_RADIO_SOUND{ result.append(item) } } return result } static func getMusic() -> [FloatingItemModel]{ var result : [FloatingItemModel] = [] for item in getAllItems(){ if item.item_type == Constants.BABY_RADIO_MUSIC{ result.append(item) } } return result } }
// // MangaLink.swift // adex // // Created by Sena on 29/04/20. // Copyright © 2020 Never Mind Dev. All rights reserved. // import Foundation public struct MangaLink: Codable { public let al, ap, bw, kt: String? public let mu: String? public let amz: String? public let mal: String? }
// Generated using Sourcery 0.17.0 — https://github.com/krzysztofzablocki/Sourcery // DO NOT EDIT import Domain import RealmSwift extension Item { static func makeDefault( guid: String = "", guidIsPermaLink: Bool? = nil, title: String = "", subTitle: String? = nil, enclosure: Enclosure = Enclosure.makeDefault(), pubDate: Date? = nil, itemDescription: String? = nil, duration: Double? = nil, link: URL? = nil, artwork: URL? = nil ) -> Self { return .init( guid: guid, guidIsPermaLink: guidIsPermaLink, title: title, subTitle: subTitle, enclosure: enclosure, pubDate: pubDate, itemDescription: itemDescription, duration: duration, link: link, artwork: artwork ) } }
// // TestLocalProvider.swift // TodoAllTests // // Created by Franklin Cruz on 27-10-20. // Copyright © 2020 S.Y.Soft. All rights reserved. // import XCTest import Combine @testable import TodoAll class TestLocalProvider: XCTestCase { struct DummyData: Identifiable, Codable { var id: Int var title: String } var cancellables: Set<AnyCancellable>! override func setUpWithError() throws { UserDefaults.standard.removeObject(forKey: String(describing: DummyData.self)) LocalProvider.registerStoreName(forType: DummyData.self) cancellables = [] } override func tearDownWithError() throws { UserDefaults.standard.removeObject(forKey: String(describing: DummyData.self)) } func testCreateItem() throws { let expectation = XCTestExpectation(description: "Store a value with a Local Store provider") let provider = LocalProvider() let val = DummyData(id: 1, title: "My title") provider.create(val).sink { completion in switch completion { case .finished: print("OK") case .failure(let e): XCTFail("Unexpected failure result \(e)") } } receiveValue: { (data) in XCTAssertNotNil(data) XCTAssertEqual(data?.id, val.id) expectation.fulfill() }.store(in: &cancellables) wait(for: [expectation], timeout: 1.0) } func testListItems() throws { let expectation = XCTestExpectation(description: "Read all the stored values") let provider = LocalProvider() provider.create(DummyData(id: 1, title: "My title")) .flatMap({ _ in provider.create(DummyData(id: 2, title: "My title 2")) }) .flatMap({ _ -> Future<[DummyData], ServiceError> in provider.list() }) .sink { completion in switch completion { case .finished: print("OK") case .failure(let e): XCTFail("Unexpected failure result \(e)") } } receiveValue: { data in XCTAssertNotNil(data) XCTAssertEqual(data.count, 2) XCTAssertNotNil(data.first) XCTAssertNotNil(data.last) XCTAssertEqual(data.first?.id, 1) XCTAssertEqual(data.last?.id, 2) expectation.fulfill() }.store(in: &cancellables) wait(for: [expectation], timeout: 1.0) } func testEmptyList() throws { let expectation = XCTestExpectation(description: "Read store when no value have been saved") let provider = LocalProvider() provider.list() .sink { completion in switch completion { case .finished: print("OK") case .failure(let e): XCTFail("Unexpected failure result \(e)") } } receiveValue: { (data: [DummyData]) in XCTAssertNotNil(data) XCTAssertEqual(data.count, 0) XCTAssertNil(data.first) expectation.fulfill() }.store(in: &cancellables) wait(for: [expectation], timeout: 1.0) } func testGetItem() throws { let expectation = XCTestExpectation(description: "Get an item by id") let provider = LocalProvider() let val = DummyData(id: 1, title: "My title") provider.create(val) .flatMap({_ -> Future<DummyData?, ServiceError> in provider.get(byId: 1) }) .sink { completion in switch completion { case .finished: print("OK") case .failure(let e): XCTFail("Unexpected failure result \(e)") } } receiveValue: { (data) in XCTAssertNotNil(data) XCTAssertEqual(data?.id, val.id) expectation.fulfill() }.store(in: &cancellables) wait(for: [expectation], timeout: 1.0) } func testGetItemNotCreated() throws { let expectation = XCTestExpectation(description: "Get an item that does not exists") let provider = LocalProvider() provider.get(byId: 1) .sink { completion in switch completion { case .finished: print("OK") case .failure(let e): XCTFail("Unexpected failure result \(e)") } } receiveValue: { (data: DummyData?) in XCTAssertNil(data) expectation.fulfill() }.store(in: &cancellables) wait(for: [expectation], timeout: 1.0) } func testUpdateItem() throws { let expectation = XCTestExpectation(description: "Update an item by id") let provider = LocalProvider() let val = DummyData(id: 1, title: "My title") provider.create(val) .flatMap({_ -> Future<DummyData?, ServiceError> in let modified = DummyData(id: 1, title: "New Title") return provider.update(modified) }) .sink { completion in switch completion { case .finished: print("OK") case .failure(let e): XCTFail("Unexpected failure result \(e)") } } receiveValue: { (data) in XCTAssertNotNil(data) XCTAssertEqual(data?.id, val.id) XCTAssertEqual(data?.title, "New Title") expectation.fulfill() }.store(in: &cancellables) wait(for: [expectation], timeout: 1.0) } func testDeleteItem() throws { let expectation = XCTestExpectation(description: "Delete an item then try to get it") let provider = LocalProvider() let val = DummyData(id: 1, title: "My title") provider.create(val) .flatMap({ _ -> Future<DummyData?, ServiceError> in provider.delete(byId: 1) }) .flatMap({_ -> Future<DummyData?, ServiceError> in provider.get(byId: 1) }) .sink { completion in switch completion { case .finished: print("OK") case .failure(let e): XCTFail("Unexpected failure result \(e)") } } receiveValue: { (data) in XCTAssertNil(data) expectation.fulfill() }.store(in: &cancellables) wait(for: [expectation], timeout: 1.0) } }
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // RUN: %target-run-simple-swift // REQUIRES: executable_test // REQUIRES: objc_interop import Foundation #if FOUNDATION_XCTEST import XCTest class TestDateIntervalSuper : XCTestCase { } #else import StdlibUnittest class TestDateIntervalSuper { } #endif class TestDateInterval : TestDateIntervalSuper { func dateWithString(_ str: String) -> Date { let formatter = DateFormatter() if #available(iOS 9, *){ formatter.calendar = Calendar(identifier: .gregorian)! }else{ formatter.calendar = Calendar(calendarIdentifier: .gregorian)! } formatter.locale = Locale(localeIdentifier: "en_US") formatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z" return formatter.date(from: str)! as Date } func test_compareDateIntervals() { if #available(iOS 10.10, OSX 10.12, tvOS 10.0, watchOS 3.0, *) { let start = dateWithString("2010-05-17 14:49:47 -0700") let duration: TimeInterval = 10000000.0 let testInterval1 = DateInterval(start: start, duration: duration) let testInterval2 = DateInterval(start: start, duration: duration) expectEqual(testInterval1, testInterval2) expectEqual(testInterval2, testInterval1) expectEqual(testInterval1.compare(testInterval2), ComparisonResult.orderedSame) let testInterval3 = DateInterval(start: start, duration: 10000000000.0) expectTrue(testInterval1 < testInterval3) expectTrue(testInterval3 > testInterval1) let earlierStart = dateWithString("2009-05-17 14:49:47 -0700") let testInterval4 = DateInterval(start: earlierStart, duration: duration) expectTrue(testInterval4 < testInterval1) expectTrue(testInterval1 > testInterval4) } } func test_isEqualToDateInterval() { if #available(iOS 10.10, OSX 10.12, tvOS 10.0, watchOS 3.0, *) { let start = dateWithString("2010-05-17 14:49:47 -0700") let duration = 10000000.0 let testInterval1 = DateInterval(start: start, duration: duration) let testInterval2 = DateInterval(start: start, duration: duration) expectEqual(testInterval1, testInterval2) let testInterval3 = DateInterval(start: start, duration: 100.0) expectNotEqual(testInterval1, testInterval3) } } func test_checkIntersection() { if #available(iOS 10.10, OSX 10.12, tvOS 10.0, watchOS 3.0, *) { let start1 = dateWithString("2010-05-17 14:49:47 -0700") let end1 = dateWithString("2010-08-17 14:49:47 -0700") let testInterval1 = DateInterval(start: start1, end: end1) let start2 = dateWithString("2010-02-17 14:49:47 -0700") let end2 = dateWithString("2010-07-17 14:49:47 -0700") let testInterval2 = DateInterval(start: start2, end: end2) expectTrue(testInterval1.intersects(testInterval2)) let start3 = dateWithString("2010-10-17 14:49:47 -0700") let end3 = dateWithString("2010-11-17 14:49:47 -0700") let testInterval3 = DateInterval(start: start3, end: end3) expectFalse(testInterval1.intersects(testInterval3)) } } func test_validIntersections() { if #available(iOS 10.10, OSX 10.12, tvOS 10.0, watchOS 3.0, *) { let start1 = dateWithString("2010-05-17 14:49:47 -0700") let end1 = dateWithString("2010-08-17 14:49:47 -0700") let testInterval1 = DateInterval(start: start1, end: end1) let start2 = dateWithString("2010-02-17 14:49:47 -0700") let end2 = dateWithString("2010-07-17 14:49:47 -0700") let testInterval2 = DateInterval(start: start2, end: end2) let start3 = dateWithString("2010-05-17 14:49:47 -0700") let end3 = dateWithString("2010-07-17 14:49:47 -0700") let testInterval3 = DateInterval(start: start3, end: end3) let intersection1 = testInterval2.intersection(with: testInterval1) expectNotEmpty(intersection1) expectEqual(testInterval3, intersection1) let intersection2 = testInterval1.intersection(with: testInterval2) expectNotEmpty(intersection2) expectEqual(intersection1, intersection2) } } func test_containsDate() { if #available(iOS 10.10, OSX 10.12, tvOS 10.0, watchOS 3.0, *) { let start = dateWithString("2010-05-17 14:49:47 -0700") let duration = 10000000.0 let testInterval = DateInterval(start: start, duration: duration) let containedDate = dateWithString("2010-05-17 20:49:47 -0700") expectTrue(testInterval.contains(containedDate)) let earlierStart = dateWithString("2009-05-17 14:49:47 -0700") expectFalse(testInterval.contains(earlierStart)) } } } #if !FOUNDATION_XCTEST var DateIntervalTests = TestSuite("TestDateInterval") DateIntervalTests.test("test_compareDateIntervals") { TestDateInterval().test_compareDateIntervals() } DateIntervalTests.test("test_isEqualToDateInterval") { TestDateInterval().test_isEqualToDateInterval() } DateIntervalTests.test("test_checkIntersection") { TestDateInterval().test_checkIntersection() } DateIntervalTests.test("test_validIntersections") { TestDateInterval().test_validIntersections() } runAllTests() #endif
// // Error Manager.swift // WeatherApp // // Created by MacBook on 26/09/2019. // Copyright © 2019 MacBook. All rights reserved. // import Foundation public let ODNetworkingErrorDomain = "ru.OlgaDakhel.WeatherApp.NetworkingError" public let MissingHTTPResponseError = 100 public let UnexpectedResponseError = 200
// // SocketListner.swift // Hippo // // Created by Arohi Sharma on 21/10/20. // Copyright © 2020 CL-macmini-88. All rights reserved. // import Foundation fileprivate struct EventCallback { let uuid: UUID? let handler: (Any) -> Void } class SocketListner { private var eventCallbacks = [String: EventCallback]() init() { NotificationCenter.default.addObserver(self, selector: #selector(socketConnected), name: .socketConnected, object: nil) } func startListening(event: String, callback: @escaping (Any?) -> Void) { let uuid = SocketClient.shared.on(event: event) { (dataArray) in let data = dataArray.first callback(data) } eventCallbacks[event] = EventCallback(uuid: uuid, handler: callback) } func stopListening(event: String) { SocketClient.shared.offEvent(for: event) } @objc private func socketConnected() { for (event, callback) in eventCallbacks { startListening(event: event, callback: callback.handler) } } private func removeAllCallbacks() { for event in eventCallbacks { stopListening(event: event.key) } } deinit { //removeAllCallbacks() NotificationCenter.default.removeObserver(self) } }
import UIKit @IBDesignable class Button3D: UIControl { @IBInspectable var title: String? { didSet { content.setTitle(title) } } @IBInspectable var fontSizeIPhone: CGFloat = 30 { didSet { content.setFontSize(valueFor(iPhone: fontSizeIPhone, iPad: fontSizeIPad)) } } @IBInspectable var fontSizeIPad: CGFloat = 40 { didSet { content.setFontSize(valueFor(iPhone: fontSizeIPhone, iPad: fontSizeIPad)) } } @IBInspectable var numberOfLines: Int = 1 { didSet { content.setNumberOfLines(numberOfLines) } } @IBInspectable var isShadowEnabled: Bool = true { didSet { isShadowEnabledDidChange() } } //MARK: UIControl overwritten properties override var isHighlighted: Bool { didSet { isHighlightedDidChange() } } override var isEnabled: Bool { didSet { isEnabledDidChange() } } private var layout: Button3DLayout! private var content: Button3DContent! private var colors: Button3DColors! override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder: NSCoder) { super.init(coder: coder) setup() } func setLayout(_ layout: Button3DLayout) { self.layout = layout removeAllSubviews() addSubviewToBounds(layout) } func setContent(_ content: Button3DContent) { self.content = content layout.setContent(content) } func setColors(_ colors: Button3DColors) { self.colors = colors layout.setColors(getColorForCurrentState()) } private func setup() { setupDefaultLayout() setupDefaultContent() setupDefaultColors() isEnabled = true isShadowEnabled = true backgroundColor = .clear } private func setupDefaultLayout() { setLayout(Button3DRectangularLayout()) } private func setupDefaultContent() { setContent(Button3DContentWithImageAndLabel(contentSize: .normal)) } private func setupDefaultColors() { setColors(.aqua) } private func isShadowEnabledDidChange() { layout.setShadowEnabled(isShadowEnabled) } private func isHighlightedDidChange() { layout.showAsPressed(isHighlighted) } private func isEnabledDidChange() { layout.setColors(getColorForCurrentState()) } private func getColorForCurrentState() -> Button3DColors { return isEnabled ? colors : .disabled } } extension Button3D { override func prepareForInterfaceBuilder() { setNeedsLayout() layoutIfNeeded() layout.setNeedsLayout() layout.layoutIfNeeded() backgroundColor = .clear } }
// // Location.swift // Quick Tour // // Created by quanganh on 3/1/20. // Copyright © 2020 quanganh. All rights reserved. // import Foundation class Location{ var Name: String? var id: String? var description: String? var rating: Int? var image: String? var comment: DICT? var district: String? init(name: String ,dict: DICT) { let id = dict["id"] as? String ?? "" let description = dict["Description"] as? String ?? "" let image = dict["image"] as? String ?? "" let rating = dict["Rating"] as? Int ?? 0 let comment = dict["Comment"] as? DICT ?? [:] let district = dict["district"] as? String ?? "" self.district = district self.comment = comment self.id = id self.Name = name self.description = description self.rating = rating self.image = image } }
// // MyTabBarViewController.swift // oneone // // Created by levi.luo on 2017/10/10. // Copyright © 2017年 levi.luo. All rights reserved. // import UIKit import SwiftyJSON class MyTabBarViewController: UITabBarController { let defaults = UserDefaults.standard var items = ["reply","like","focus","msg"] override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.white let defaults = UserDefaults.standard initNoreads() if defaults.integer(forKey: "memberId") != 0 { let socket = DSSocket.sharedInstance() socket.connectSever() socket.socket.on(clientEvent: .connect) {data, ack in socket.socket.emit("setName", defaults.string(forKey: "memberId")!) socket.socket.on("notice") { (result, ack) in print(result) let type = String(describing: ((result as! NSArray)[0] as! Dictionary<String,Any>)["ntype"]!) let currentView = UIViewController.currentViewController() for item in self.items{ if type == item{ if currentView is NoticesTableViewController && (currentView as! NoticesTableViewController).type == item{ NotificationCenter.default.post(name: Notification.Name(rawValue: item), object: nil,userInfo:result[0] as! [String : Any]) return } if type == "msg" && currentView is ChatViewController{ NotificationCenter.default.post(name: Notification.Name(rawValue: item), object: nil,userInfo:result[0] as! [String : Any]) return } defaults.set(defaults.integer(forKey: item) + 1, forKey: item) break } } if (self.tabBar.selectedItem! != self.tabBar.items![1]){ if self.tabBar.items![1].badgeValue != nil{ self.tabBar.items![1].badgeValue = String(Int(self.tabBar.items![1].badgeValue!)! + 1) }else{ self.tabBar.items![1].badgeValue = "1" } }else{ NotificationCenter.default.post(name: NotificationHelper.noRead, object: nil,userInfo:[:]) } } } } } override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) { if item == self.tabBar.items![0]{ if UIViewController.currentViewController() is HomeUpdatesTableViewController{ // print("点击首页刷新") let vc = (UIViewController.currentViewController() as! HomeUpdatesTableViewController) UIView.animate(withDuration: 0.2, animations: { vc.navigationController?.isNavigationBarHidden = false vc.tableView.contentOffset.y = 0 }, completion: { (res) in vc.header.beginRefresh() }) } } } func initNoreads(){ NetService.request(api: "/noReadMessages", params: nil, options: nil, isLoading: false) { (res) in print(res) if res == JSON.null{ return } var total = 0 for item in self.items{ if let count = res[item].int{ self.defaults.set(count, forKey: item) total += count } } if total != 0{ DispatchQueue.main.async { self.tabBar.items![1].badgeValue = String(total) } } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } public func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool{ print("测试切换tab") return true } // public func tabBarController(_ tabBarController: UITabBarController, animationControllerForTransitionFrom fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning?{ //// return true // } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
// // UILabel.swift // NLBKlik // // Created by Sukov on 10/8/16. // Copyright © 2016 WF | Gorjan Shukov. All rights reserved. // import Foundation extension UILabel { public func enableCopyMenu() { userInteractionEnabled = true addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(UILabel.showMenu(_:)))) } func showMenu(sender: AnyObject?) { becomeFirstResponder() let menu = UIMenuController.sharedMenuController() if !menu.menuVisible { menu.setTargetRect(bounds, inView: self) menu.setMenuVisible(true, animated: true) } } override public func copy(sender: AnyObject?) { let board = UIPasteboard.generalPasteboard() board.string = text?.toDigits() let menu = UIMenuController.sharedMenuController() menu.setMenuVisible(false, animated: true) } override public func canBecomeFirstResponder() -> Bool { return true } override public func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool { if action == #selector(copy(_:)) { return true } return false } }
// // ViewController.swift // RPNCalc // // Created by cyroxin on 25.3.2021. // import UIKit import Foundation class ViewController: UIViewController { let stack = IntStack() @IBOutlet weak var mem4: UILabel! // Top @IBOutlet weak var mem3: UILabel! @IBOutlet weak var mem2: UILabel! @IBOutlet weak var mem1: UILabel! @IBOutlet weak var main: UILabel! // Bottom @IBAction func onClickNumber(_ sender: UIButton) { if let val = stack.pop() { stack.push(Int(String(val) + sender.currentTitle!)!) } else { stack.push(Int(sender.currentTitle!)!) } draw() } @IBAction func onClickSign() { if let val = stack.pop() { stack.push(-val) draw() } } @IBAction func onClickDelete() { if let val = stack.pop() { stack.push( Int( String(String(val).dropLast(1)) ) ?? 0 ) draw() } } @IBAction func onClickClear() { if(stack.pop() == nil) { stack.push(0) } draw() } @IBAction func onClickClearEverything() { while stack.hasTwo() { _ = stack.pop() } _ = stack.pop() stack.push(0) draw() } @IBAction func onClickEnter() { stack.push(0) draw() } @IBAction func onClickExp() { let val1 = Double(stack.pop() ?? 0) let val2 = Double(stack.pop() ?? 0) stack.push(Int(pow(val2,val1))) draw() } @IBAction func onClickDiv() { let val1 = stack.pop() if(val1 == nil) { return } else if(val1 == 0) { stack.push(0) return } let val2 = stack.pop() if(val2 == nil) { stack.push(val1!) return } stack.push(val2! / val1!) draw() } @IBAction func onClickMul() { let val1 = (stack.pop() ?? 0) let val2 = (stack.pop() ?? 0) stack.push(val2 * val1) draw() } @IBAction func onClickSub() { let val1 = (stack.pop() ?? 0) let val2 = (stack.pop() ?? 0) stack.push(val2 - val1) draw() } @IBAction func onClickAdd() { let val1 = (stack.pop() ?? 0) let val2 = (stack.pop() ?? 0) stack.push(val2 + val1) draw() } func draw() { // Clear old main.text = "" mem1.text = "" mem2.text = "" mem3.text = "" mem4.text = "" // Take new if let val = stack.pop() { print("mem1: ",val) main.text = String(val) } if let val = stack.pop() { print("mem2: ",val) mem1.text = String(val) } if let val = stack.pop() { print("mem3: ",val) mem2.text = String(val) } if let val = stack.pop() { print("mem4: ",val) mem3.text = String(val) } if let val = stack.pop() { print("mem5: ",val) mem4.text = String(val) } // Restore stack if let text = mem4.text { if let mem = Int(text) { stack.push(mem) } } if let text = mem3.text { if let mem = Int(text) { stack.push(mem) } } if let text = mem2.text { if let mem = Int(text) { stack.push(mem) } } if let text = mem1.text { if let mem = Int(text) { stack.push(mem) } } if let text = main.text { if let mem = Int(text) { stack.push(mem) } } } override func viewDidLoad() { super.viewDidLoad() stack.push(0) } }
// // TransactionCardDashedLineCell.swift // WavesWallet-iOS // // Created by rprokofev on 12/03/2019. // Copyright © 2019 Waves Platform. All rights reserved. // import Foundation import UIKit import Extensions private struct Constants { static let padding: CGFloat = 14 } final class TransactionCardDashedLineCell: UITableViewCell, Reusable, ViewConfiguration { enum Model { case topPadding case bottomPadding case nonePadding } private var model: Model? @IBOutlet var topLayoutConstaint: NSLayoutConstraint! @IBOutlet var bottomLayoutConstaint: NSLayoutConstraint! override func updateConstraints() { guard let model = model else { return } switch model { case .bottomPadding: self.topLayoutConstaint.constant = 0 self.bottomLayoutConstaint.constant = Constants.padding case .topPadding: self.topLayoutConstaint.constant = Constants.padding self.bottomLayoutConstaint.constant = 0 case .nonePadding: self.topLayoutConstaint.constant = 0 self.bottomLayoutConstaint.constant = 0 } super.updateConstraints() } func update(with model: TransactionCardDashedLineCell.Model) { self.model = model needsUpdateConstraints() } }
// // HighlightedString.swift // // // Created by Vladislav Fitc on 13.03.2020. // import Foundation public struct HighlightedString: Codable, Hashable { public static var preTag = "<em>" public static var postTag = "</em>" public let taggedString: TaggedString public init(string: String) { self.taggedString = TaggedString(string: string, preTag: HighlightedString.preTag, postTag: HighlightedString.postTag, options: [.caseInsensitive, .diacriticInsensitive]) } public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() let decodedString = try container.decode(String.self) self.init(string: decodedString) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(taggedString.input) } }
// // NewLandmarkViewController.swift // Landmark Remark // // Created by Jun Xiu Chan on 1/4/18. // Copyright © 2018 Brickoapps. All rights reserved. // import UIKit import MapKit class NewLandmarkViewController: UIViewController { @IBOutlet private weak var textView: UITextView! @IBOutlet private weak var mapView: MKMapView! @IBOutlet private weak var locationNameLabel: UILabel! @IBOutlet private weak var locationCoordinateLabel: UILabel! var location: CLLocation! } extension NewLandmarkViewController { override func viewDidLoad() { super.viewDidLoad() // Observe keyboard events let notificationCenter = NotificationCenter.default notificationCenter.addObserver( self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil ) } override func viewDidAppear(_ animated: Bool) { super.viewWillAppear(animated) textView.becomeFirstResponder() reverseGeolocation(self.location) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) view.endEditing(true) } private func reverseGeolocation(_ location: CLLocation) { // Reverse geolocation from the user location provided by LandmarkTableViewController CLGeocoder().reverseGeocodeLocation(location, completionHandler: { [weak self] (placemarks, error) -> Void in guard let placemark = placemarks?.last, let strongSelf = self else { return } UIView.animate(withDuration: 0.35, animations: { strongSelf.locationNameLabel.text = placemark.name let coordinate = placemark.location?.coordinate let lat = coordinate?.latitude ?? 0 let lng = coordinate?.longitude ?? 0 strongSelf.locationCoordinateLabel.text = "\(lat), \(lng)" }) let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude) let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01)) strongSelf.mapView.setRegion(region, animated: true) }) } } extension NewLandmarkViewController: UITextViewDelegate { func textViewDidChange(_ textView: UITextView) { navigationItem.rightBarButtonItem?.isEnabled = !textView.text.isEmpty } } extension NewLandmarkViewController { @IBAction func doneTapped(_ sender: UIBarButtonItem) { // User cannot send an empty message. guard let loginedUser = UserService.loginedUser(), let text = textView.text, !text.isEmpty else { return } let landmarkService = LandmarkService() let newLandmark = Landmark(user: loginedUser, message: Message(text: text), coordinate: location.coordinate) landmarkService.addLandmark(newLandmark) dismiss(animated: true, completion: nil) } @IBAction func cancelTapped(_ sender: UIBarButtonItem) { dismiss(animated: true, completion: nil) } } extension NewLandmarkViewController { @objc func keyboardWillShow(_ notification: NSNotification) { if let keyboardFrame: NSValue = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue { let keyboardRectangle = keyboardFrame.cgRectValue let keyboardHeight = keyboardRectangle.height textView.contentInset.bottom = keyboardHeight } } }
// Copyright 2017 IBM RESEARCH. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ============================================================================= import Foundation final class NumUtilities { private init() { } static func identityComplex(_ n: Int) -> [[Complex]] { return (0...n).map { let row = $0 return (0...n).map { return row == $0 ? Complex(real: 1.0) : Complex() } } } static func zeroComplex(_ rows: Int,_ cols: Int) -> [[Complex]] { return (0...rows).map {_ in return (0...cols).map {_ in return Complex() } } } static func kronComplex(_ a: [[Complex]], _ b: [[Complex]]) -> [[Complex]] { let m = a.count let n = a.isEmpty ? 0 : a[0].count let p = b.count let q = b.isEmpty ? 0 : b[0].count var ab = NumUtilities.zeroComplex(m * p, n * q) for i in 0..<m { for j in 0..<n { let da = a[i][j] for k in 0..<p { for l in 0..<q { let db = b[k][l] ab[p*i + k][q*j + l] = da * db } } } } return ab } static func dotComplex(_ a: [[Complex]], _ b: [[Complex]]) -> [[Complex]] { let m = a.count let n = a.isEmpty ? 0 : a[0].count let q = b.isEmpty ? 0 : b[0].count var ab = NumUtilities.zeroComplex(m,q) for i in 0..<m { for j in 0..<q { for k in 0..<n { ab[i][j] += a[i][k] * b[k][j] } } } return ab } }
// // UIColor.swift // ShapeApp // // Created by Sam on 15/09/2016. // Copyright © 2016 Sam Payne. All rights reserved. // import UIKit public extension UIColor { static func colorWithCSS(css:String) -> UIColor { let hashSet:CharacterSet = CharacterSet(charactersIn: "#") let formattedCSS = "#" + css.trimmingCharacters(in:hashSet) return UIColor(rgba: formattedCSS) } convenience init(css:String) { let hashSet = CharacterSet(charactersIn: "#") let formattedCSS = "#" + css.trimmingCharacters(in:hashSet) self.init(rgba:formattedCSS) } convenience init(red: UInt, green: UInt, blue: UInt, alphaVal:CGFloat = 1) { self.init(red: CGFloat(red)/255.0, green:CGFloat(green)/255.0, blue: CGFloat(blue)/255.0, alpha: alphaVal) } static func defaultBackgroundColor() -> UIColor { return UIColor.white } static func defaultTextColor() -> UIColor { return UIColor.darkGray } }
// // MemoryCell.swift // HappyDays // // Created by Eric Rado on 2/13/18. // Copyright © 2018 Eric Rado. All rights reserved. // import UIKit class MemoryCell: UICollectionViewCell { @IBOutlet weak var imageView: UIImageView! }
// // IlkGiris7.swift // LearningSwiftUI // // Created by Metin HALILOGLU on 5/2/21. // import SwiftUI struct IlkGiris7: View { var body: some View { VStack(spacing: 20) { Text("ŞEKİLLER").font(.largeTitle) Text("Köşeleri yuvarla") .multilineTextAlignment(.center) .frame(width: 100, height: 100) .padding() .foregroundColor(.white) .background(RoundedRectangle(cornerRadius: 20).foregroundColor(Color.blue)) Image("apple") .cornerRadius(120) .background(Color.blue) } } } struct IlkGiris7_Previews: PreviewProvider { static var previews: some View { IlkGiris7() } }
// Playground - noun: a place where people can play import UIKit extension String { subscript (i: Int) -> String { return String(Array(self)[i]) } subscript (r: Range<Int>) -> String { return String(Array(self)[r]) } } func isInterleave(s1: String, s2: String, s3: String) -> Bool { let strlen1 = count(s1), strlen2 = count(s2), strlen3 = count(s3) if strlen3 != strlen1+strlen2 { return false } if strlen1 == 0 || strlen2 == 0 { return true } var opt = [[Bool]](count: strlen1, repeatedValue: [Bool](count: strlen2, repeatedValue: false)) for var i=0; i<strlen1; i++ { for var j=0; j<strlen2; j++ { opt[i][j] = (i==0 ? true : opt[i-1][j]) && s1[i] == s3[i+j+1] || (j==0 ? true : opt[i][j-1]) && s2[j] == s3[i+j+1] // println("s1[\(i)]: \(s1[i]) s2[\(j)]: \(s2[j]) s3[\(i+j+1)]: \(s3[i+j+1]) opt[\(i)][\(j)]: \(opt[1][j])") } } return opt.last!.last! } isInterleave("aabcc", "dbbca", "aadbbcbcac") isInterleave("aabcc", "dbbca", "aadbbbaccc") isInterleave("101", "011", "011011") isInterleave("101", "011", "110110") // aadbbcbcac // aa bc c // db bca //0,0, 1,0, 1,1, 2,1, 3,1, 3,2 3,3, 3,4, 4,4 /*: Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. For example, Given: s1 = ”aabcc”, s2 = ”dbbca”, When s3 = ”aadbbcbcac”, return true. When s3 = ”aadbbbaccc”, return false. */
import Foundation @testable import HAP @testable import KituraNet import XCTest class EndpointTests: XCTestCase { static var allTests : [(String, (EndpointTests) -> () throws -> Void)] { return [ ("testAccessories", testAccessories), ("testGetCharacteristics", testGetCharacteristics), ("testPutBoolAndIntCharacteristics", testPutBoolAndIntCharacteristics), ("testPutDoubleAndEnumCharacteristics", testPutDoubleAndEnumCharacteristics), ("testLinuxTestSuiteIncludesAllTests", testLinuxTestSuiteIncludesAllTests), ] } func testAccessories() { let lamp = Accessory.Lightbulb(info: .init(name: "Night stand left")) let device = Device(name: "Test", pin: "123-44-321", storage: MemoryStorage(), accessories: [lamp]) let application = accessories(device: device) let response = application(MockConnection(), MockRequest.get(path: "/accessories")) let jsonObject = try! JSONSerialization.jsonObject(with: response.body!, options: []) as! [String: [[String: Any]]] guard let accessory = jsonObject["accessories"]?.first else { return XCTFail("No accessory") } XCTAssertEqual(accessory["aid"] as? Int, 1) guard let services = accessory["services"] as? [[String: Any]] else { return XCTFail("No services") } guard let metaService = services.first(where: { ($0["type"] as? String) == "3E" }) else { return XCTFail("No meta") } XCTAssertEqual(metaService["iid"] as? Int, 1) XCTAssertEqual((metaService["characteristics"] as? [Any])?.count, 5) guard let lampService = services.first(where: { ($0["type"] as? String) == "43" }) else { return XCTFail("No lamp") } XCTAssertEqual(lampService["iid"] as? Int, 7) guard let lampCharacteristics = lampService["characteristics"] as? [[String: Any]] else { return XCTFail("No lamp characteristics") } XCTAssertEqual(lampCharacteristics.count, 4) } /// This test assumes that 1.3 and 1.5 are respectively `manufacturer` and /// `name`. This does not need to be the case. func testGetCharacteristics() { let lamp = Accessory.Lightbulb(info: .init(name: "Night stand left", manufacturer: "Bouke")) let device = Device(name: "Test", pin: "123-44-321", storage: MemoryStorage(), accessories: [lamp]) let application = characteristics(device: device) let response = application(MockConnection(), MockRequest.get(path: "/characteristics?id=1.3,1.5")) guard let jsonObject = (try? JSONSerialization.jsonObject(with: response.body!, options: [])) as? [String: [[String: Any]]] else { return XCTFail("Could not decode") } guard let characteristics = jsonObject["characteristics"] else { return XCTFail("No characteristics") } guard let manufacturerCharacteristic = characteristics.first(where: { $0["iid"] as? Int == 3 }) else { return XCTFail("No manufacturer") } XCTAssertEqual(manufacturerCharacteristic["value"] as? String, "Bouke") guard let nameCharacteristic = characteristics.first(where: { $0["iid"] as? Int == 5 }) else { return XCTFail("No name") } XCTAssertEqual(nameCharacteristic["value"] as? String, "Night stand left") } /// This test assumes that 1.3 and 1.5 are respectively `manufacturer` and /// `name`. This does not need to be the case. func testPutBoolAndIntCharacteristics() { let lamp = Accessory.Lightbulb(info: .init(name: "Night stand left", manufacturer: "Bouke")) let device = Device(name: "Test", pin: "123-44-321", storage: MemoryStorage(), accessories: [lamp]) let application = characteristics(device: device) lamp.lightbulb.on.value = false lamp.lightbulb.brightness.value = 0 // turn lamp on do { let jsonObject: [String: [[String: Any]]] = [ "characteristics": [ [ "aid": 1, "iid": 8, "value": 1 ] ] ] let body = try! JSONSerialization.data(withJSONObject: jsonObject, options: []) let response = application(MockConnection(), MockRequest(method: "PUT", path: "/characteristics", body: body)) XCTAssertEqual(response.status, .noContent) XCTAssertEqual(lamp.lightbulb.on.value, true) } // 50% brightness do { let jsonObject: [String: [[String: Any]]] = [ "characteristics": [ [ "aid": 1, "iid": 9, "value": Double(50) ] ] ] let body = try! JSONSerialization.data(withJSONObject: jsonObject, options: []) let response = application(MockConnection(), MockRequest(method: "PUT", path: "/characteristics", body: body)) XCTAssertEqual(response.status, .noContent) XCTAssertEqual(lamp.lightbulb.brightness.value, 50) } // 100% brightness do { let jsonObject: [String: [[String: Any]]] = [ "characteristics": [ [ "aid": 1, "iid": 9, "value": Double(100) ] ] ] let body = try! JSONSerialization.data(withJSONObject: jsonObject, options: []) let response = application(MockConnection(), MockRequest(method: "PUT", path: "/characteristics", body: body)) XCTAssertEqual(response.status, .noContent) XCTAssertEqual(lamp.lightbulb.brightness.value, 100) } } /// This test assumes that 1.3 and 1.5 are respectively `manufacturer` and /// `name`. This does not need to be the case. func testPutDoubleAndEnumCharacteristics() { let thermostat = Accessory.Thermostat(info: .init(name: "Thermostat", manufacturer: "Bouke")) let device = Device(name: "Test", pin: "123-44-321", storage: MemoryStorage(), accessories: [thermostat]) let application = characteristics(device: device) thermostat.thermostat.currentHeatingCoolingState.value = .off thermostat.thermostat.currentTemperature.value = 18 thermostat.thermostat.targetHeatingCoolingState.value = .off thermostat.thermostat.targetTemperature.value = 15 // turn up the heat do { let jsonObject: [String: [[String: Any]]] = [ "characteristics": [ [ "aid": 1, "iid": 11, "value": 19.5 ], [ "aid": 1, "iid": 9, "value": TargetHeatingCoolingState.auto.rawValue ] ] ] let body = try! JSONSerialization.data(withJSONObject: jsonObject, options: []) let response = application(MockConnection(), MockRequest(method: "PUT", path: "/characteristics", body: body)) XCTAssertEqual(response.status, .noContent) XCTAssertEqual(thermostat.thermostat.targetTemperature.value, 19.5) XCTAssertEqual(thermostat.thermostat.targetHeatingCoolingState.value, .auto) } // turn up the heat some more (value is an Int on Linux, needs to be cast to Double) do { let jsonObject: [String: [[String: Any]]] = [ "characteristics": [ [ "aid": 1, "iid": 11, "value": 20 ] ] ] let body = try! JSONSerialization.data(withJSONObject: jsonObject, options: []) let response = application(MockConnection(), MockRequest(method: "PUT", path: "/characteristics", body: body)) XCTAssertEqual(response.status, .noContent) XCTAssertEqual(thermostat.thermostat.targetTemperature.value, 20) } // turn off do { let jsonObject: [String: [[String: Any]]] = [ "characteristics": [ [ "aid": 1, "iid": 9, "value": TargetHeatingCoolingState.off.rawValue ] ] ] let body = try! JSONSerialization.data(withJSONObject: jsonObject, options: []) let response = application(MockConnection(), MockRequest(method: "PUT", path: "/characteristics", body: body)) XCTAssertEqual(response.status, .noContent) XCTAssertEqual(thermostat.thermostat.targetHeatingCoolingState.value, .off) } } // from: https://oleb.net/blog/2017/03/keeping-xctest-in-sync/#appendix-code-generation-with-sourcery func testLinuxTestSuiteIncludesAllTests() { #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) let thisClass = type(of: self) let linuxCount = thisClass.allTests.count let darwinCount = Int(thisClass .defaultTestSuite().testCaseCount) XCTAssertEqual(linuxCount, darwinCount, "\(darwinCount - linuxCount) tests are missing from allTests") #endif } }
// // HomeViewController.swift // theBestQuestion // // Created by DHIKA ADITYA ARE on 27/04/21. // import UIKit import CoreData class HomeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableCategory: UITableView! let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext var arrayOfCategory = [Category]() override func viewDidLoad() { super.viewDidLoad() tableCategory.delegate = self tableCategory.dataSource = self viewHome() getCategoryFromCoreData() } func viewHome(){ tableCategory.backgroundColor = UIColor.clear } func getCategoryFromCoreData(){ // do { // self.arrayOfCategory = try context.fetch(Category.fetchRequest()) // DispatchQueue.main.async { // self.tableCategory.reloadData() // } // } catch { // } do{ arrayOfCategory = try context.fetch(Category.fetchRequest()) }catch{ } do { try context.save() } catch { } } //MARK: Setting table func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return arrayOfCategory.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "kategoriCell", for: indexPath) let data = self.arrayOfCategory[indexPath.row] cell.textLabel?.text = data.listOfCategory return cell } //MARK: Klik table (delegate methode) func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { performSegue(withIdentifier: "goToStory", sender: self) //MARK: Navigation // let vc = StoryQuestViewController() // vc.navigationItem.largeTitleDisplayMode = .never } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if(segue.identifier=="goToStory"){ let destinationVC = segue.destination as! StoryQuestViewController if let indexPath = tableCategory.indexPathForSelectedRow{ destinationVC.selectedCategory = arrayOfCategory[indexPath.row] //destinationVC.kategoriApetu = String(arrayOfCategory[indexPath.row]) } } } }
// // PatterListDefaultService.swift // Patter // // Created by Maksim Ivanov on 14/06/2019. // Copyright © 2019 Maksim Ivanov. All rights reserved. // import Foundation import RealmSwift final class PatterListDefaultService: PatterListService { private let realm = try! Realm() private var notificationToken: NotificationToken? private var entities: Results<RealmPatter>! init() { self.entities = getDefaultScope() setObservation() } deinit { removeObservation() } // MARK: - Public API weak var delegate: PatterListServiceDelegate? func getDataEntities() -> [PatterData] { return entities.map { $0.transferData } } func filterByName(_ name: String) { removeObservation() if name.isEmpty { entities = getDefaultScope() } else { entities = getDefaultScope().filter("name CONTAINS[cd] '\(name)'") } setObservation() } // MARK: - Private private func setObservation() { notificationToken = entities.observe { (changes: RealmCollectionChange<Results<RealmPatter>>) in if case .initial(_) = changes { self.delegate?.reloadEntities() } if case let .update(_, deletions, insertions, modifications) = changes { self.delegate?.changed(deletions: deletions, insertions: insertions, modifications: modifications) } } } private func removeObservation() { notificationToken?.invalidate() } private func getDefaultScope() -> Results<RealmPatter> { return realm.objects(RealmPatter.self).sorted(byKeyPath: "createdAt") } }
// // CityViewController.swift // Countries(CoreData) // // Created by Tomas Sukys on 2020-09-03. // Copyright © 2020 Tomas Sukys.lt. All rights reserved. // import CoreData import UIKit class CityViewController: UIViewController { @IBOutlet weak var cityInputLabel: UITextField! @IBOutlet weak var visitsInputLabel: UITextField! @IBOutlet weak var updateButtonLabel: UIButton! var cityName = "" let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext var city:[City] = [] override func viewDidLoad() { super.viewDidLoad() title = cityName updateButtonLabel.layer.cornerRadius = 10 fetchCity() cityInputLabel.text = city[0].name visitsInputLabel.text = String(city[0].visits) hideKeyboardWhenTappedAround() } func fetchCity() { do { let request = City.fetchRequest() as NSFetchRequest<City> let pred = NSPredicate(format: "name Contains '\(cityName)'") request.predicate = pred city = try context.fetch(request) try self.context.save() } catch { print("Cound not find city") } } @IBAction func updateButtonTapped(_ sender: Any) { do { city[0].name = cityInputLabel.text! city[0].visits = Int64(visitsInputLabel.text!)! try self.context.save() navigationController?.popViewController(animated: true) } catch { print("Data can not be saved") } } }
// // CustomHeadingUILabel.swift // tictactoe // // Created by Chirag Chaplot on 4/9/21. // import Foundation import UIKit class CustomHeadingUILabel: UILabel { init(title:String) { super.init(frame: .zero) self.text = title self.translatesAutoresizingMaskIntoConstraints = false self.adjustsFontForContentSizeCategory = true } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
/* * Copyright (c) 2012-2020 MIRACL UK Ltd. * * This file is part of MIRACL Core * (see https://github.com/miracl/core). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // // rand.swift // // Created by Michael Scott on 17/06/2015. // Copyright (c) 2015 Michael Scott. All rights reserved. // // Cryptographic strong random number generator /* Marsaglia & Zaman Random number generator constants */ public struct RAND { private static let NK:Int=21 private static let NJ:Int=6 private static let NV:Int=8 private var ira=[UInt32](repeating: 0,count: NK) private var rndptr:Int=0 private var borrow:UInt32=0 private var pool_ptr:Int=0 private var pool=[UInt8](repeating: 0,count: 32) public mutating func clean() { pool_ptr=0 rndptr=0 for i in 0 ..< 32 {pool[i]=0} for i in 0 ..< RAND.NK {ira[i]=0} borrow=0; } public init() {clean()} private mutating func sbrand() -> UInt32 { /* Marsaglia & Zaman random number generator */ rndptr+=1; if rndptr<RAND.NK {return ira[rndptr]} rndptr=0; var k=RAND.NK-RAND.NJ for i in 0 ..< RAND.NK { if k==RAND.NK {k=0} let t=ira[k]; let pdiff=t &- ira[i] &- borrow if pdiff<t {borrow=0} if pdiff>t {borrow=1} ira[i]=pdiff k += 1; } return ira[0] } mutating func sirand(_ seed: UInt32) { var m:UInt32=1 var s:UInt32=seed borrow=0; rndptr=0 ira[0]^=s for i in 1 ..< RAND.NK { /* fill initialisation vector */ let ipn=(RAND.NV*i)%RAND.NK ira[ipn]^=m let t=m m=s &- m s=t } for _ in 0 ..< 10000 {_ = sbrand()} } private mutating func fill_pool() { var sh=HASH256() for _ in 0 ..< 128 {sh.process(UInt8(sbrand()&0xff))} pool=sh.hash() pool_ptr=0 } private mutating func pack(_ b: [UInt8]) -> UInt32 { var r=UInt32(b[3])<<24 r |= UInt32(b[2])<<16 r |= UInt32(b[1])<<8 r |= UInt32(b[0]) return r //return (UInt32(b[3])<<24)|(UInt32(b[2])<<16)|(UInt32(b[1])<<8)|(UInt32(b[0])) } /* Initialize RNG with some real entropy from some external source */ public mutating func seed(_ rawlen: Int,_ raw: [UInt8]) { /* initialise from at least 128 byte string of raw random entropy */ var digest=[UInt8]() var b=[UInt8](repeating: 0, count: 4) var sh=HASH256() pool_ptr=0 for i in 0 ..< RAND.NK {ira[i]=0} if rawlen>0 { for i in 0 ..< rawlen {sh.process(raw[i])} digest=sh.hash() for i in 0 ..< 8 { b[0]=digest[4*i]; b[1]=digest[4*i+1]; b[2]=digest[4*i+2]; b[3]=digest[4*i+3] sirand(pack(b)) } } fill_pool() } public mutating func getByte() -> UInt8 { let r=pool[pool_ptr]; pool_ptr+=1 if pool_ptr>=32 {fill_pool()} return r } }
// // CommitNO.swift // SwipeTabBarController // // Created by Vadim Zhydenko on 27.05.2020. // Copyright © 2020 Vadym Zhydenko. All rights reserved. // import Foundation struct CommitNO: Decodable { enum RootKeys: String, CodingKey { case sha, commit, url = "html_url" } enum CommitKeys: String, CodingKey { case message case committer enum CommitterKeys: String, CodingKey { case date, name } } let date: Date let message: String let sha: String let url: String let author: AuthorNO init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: RootKeys.self) sha = try container.decode(String.self, forKey: .sha) url = try container.decode(String.self, forKey: .url) let commitContainer = try container.nestedContainer(keyedBy: CommitKeys.self, forKey: .commit) message = try commitContainer.decode(String.self, forKey: .message) let committerContainer = try commitContainer.nestedContainer(keyedBy: CommitKeys.CommitterKeys.self, forKey: .committer) date = try committerContainer.decode(Date.self, forKey: .date) author = try commitContainer.decode(AuthorNO.self, forKey: .committer) } }
// // WeakBox.swift // JatApp-Utils // // Created by Developer on 3/20/19. // Copyright © 2019 JatApp. All rights reserved. // import Foundation /// Using WeakBox we can turn any strong reference into a weak one /// public final class WeakBox<T>: NSObject { private weak var weakObject: AnyObject? private let memoryAddress: Int public var object: T? { return weakObject as? T } public init(_ object: T) { self.memoryAddress = unsafeBitCast(object as AnyObject, to: Int.self) self.weakObject = object as AnyObject super.init() } public override var hash: Int { return memoryAddress } public override func isEqual(_ object: Any?) -> Bool { if let reference = object as? WeakBox { return self.memoryAddress == reference.memoryAddress } return false } }
// // GradientView.swift // SocialBannersApp // // Created by Ruslan Timchenko on 02.06.17. // Copyright © 2017 Ruslan Timchenko. All rights reserved. // import Cocoa class GradientView: NSView { var gradientLayer = CAGradientLayer() override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) setBackgroundLayer() // Drawing code here. } func setBackgroundLayer() { let firstGradientColor = CGColor.init(red: 0.10196078, green: 0.83921569, blue: 0.99215686, alpha: 1.0) let secondDradientColor = CGColor.init(red: 0.11372549, green: 0.38431373, blue: 0.94117647, alpha: 1) gradientLayer = createGradientLayer(withFirstColor: firstGradientColor, secondColor: secondDradientColor, andFrame: self.bounds) self.layer?.addSublayer(gradientLayer) } }
import Foundation public protocol Callback: AnyObject { associatedtype C : Context associatedtype E : Entities /** Called when a successful response has been returned from server. -Parameter response: object representation of successful json response. */ func success(response: StreamResponse<C,E>) /** See VoysisError for different possible error responses. -Parameter error: provides VoysisError. */ func failure(error: VoysisError) /** Called when microphone is turned on and recording begins. */ func recordingStarted() /** Called when successful connection is made to server. -Parameter queryResponse: contains information about the connection. */ func queryResponse(queryResponse: QueryResponse) /** Called when recording finishes. -Parameter reason: enum explaining why recording finished. */ func recordingFinished(reason: FinishedReason) /** Audio data recorded from microphone. -Parameter buffer: containing audio data. */ func audioData(data: Data) } public extension Callback { func audioData(data: Data) { //no implementation } func recordingStarted() { //no implementation } func queryResponse(queryResponse: QueryResponse) { //no implementation } func recordingFinished(reason: FinishedReason) { //no implementation } }
// // CustomCollectionViewCell.swift // journal // // Created by Diqing Chang on 17.02.18. // Copyright © 2018 Diqing Chang. All rights reserved. // import UIKit class CustomCollectionViewCell: UICollectionViewCell { @IBOutlet weak var filterIcon: UIImageView! @IBOutlet weak var filterLabel: UILabel! func displayContent(image: UIImage, title: String){ filterIcon.image = image filterLabel.text = title } }
// // result.swift // MotionVisualize // // Created by 合田 和馬 on 2017/01/15. // Copyright © 2017年 Project. All rights reserved. // import UIKit class result: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func backTop(_ sender: AnyObject) { let targetView = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "title") targetView.modalTransitionStyle = UIModalTransitionStyle.crossDissolve self.present(targetView, animated: true, completion: nil) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
// // CoreDataManager.swift // CleanSwiftTest // // Created by Davron on 26.05.2021. // import Foundation import CoreData import UIKit //CoreDataManager protocol protocol CoreDataManagerProtocol { func saveContext() func fetchData() -> [Places] func deleteItem(item: Places) -> Bool } //CoreDataManager class CoreDataManager: CoreDataManagerProtocol { static let shared = CoreDataManager() private init() {} lazy var persistentContainer: NSPersistentContainer = { let container = NSPersistentContainer(name: "CleanSwiftTest") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() func saveContext () { let context = CoreDataManager.shared.persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } func fetchData() -> [Places] { do { let context = persistentContainer.viewContext let items = try context.fetch(Places.fetchRequest()) as! [Places] return items } catch { return [] } } func deleteItem(item: Places) -> Bool { let context = persistentContainer.viewContext context.delete(item) do { try context.save() return true } catch { return false } } func createItems() { let items = CoreDataManager.shared.fetchData() let context = CoreDataManager.shared.persistentContainer.viewContext if items.count == 0 { for i in 0...4 { let newItem = Places(context: context) newItem.titile = "TestCity \(i)" newItem.detail = "TestDescrition \(i)" newItem.url = "https://images.unsplash.com/photo-1480714378408-67cf0d13bc1b?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=2250&q=80" } saveContext() } } }
// // Game.swift // Apple Pie // // Created by Range, Noah H on 11/4/19. // Copyright © 2019 Range, Noah H. All rights reserved. // import Foundation struct Game{ var word:String var guessedLetters:[Character] var formattedWord:String{ var guessedWord = "" for letter in word{ if guessedLetters.contains(letter){ guessedWord += "\(letter) " }else{ guessedWord += "_ " } } return guessedWord } mutating func appendLetter(letter : Character){ guessedLetters.append(letter) } }
import POSIX import XCTest class SpawnTests: XCTestCase { func testSpawn() { let process = try! POSIX.spawn(["/usr/bin/true"]) let status = try! process.wait() XCTAssertEqual(status.exitstatus, 0) } func testSpawnEnvVar() { let (rd, wr) = try! IO.pipe() let process = try! POSIX.spawn(["/bin/sh", "-c", "echo $FOO"], environment: ["FOO": "1"], fileActions: [ .Dup2(wr.fd, 1), .Close(rd.fd) ]) try! wr.close() let status = try! process.wait() XCTAssertEqual(status.exitstatus, 0) XCTAssertEqual(try! rd.read(encoding: NSUTF8StringEncoding), "1\n") } }
// // ApplicationObserver.swift // // Copyright © 2017-2022 Doug Russell. All rights reserved. // import Asynchrone import Cocoa public actor ApplicationObserver<ObserverType: Observer>: Observer where ObserverType.ObserverElement: Hashable { public typealias ObserverElement = ObserverType.ObserverElement private let observer: ObserverType private var streams: [Key:ObserverAsyncSequence] = [:] public init(observer: ObserverType) { self.observer = observer } public func start() async throws { try await observer.start() } public func stop() async throws { try await observer.stop() } public func stream( element: ObserverType.ObserverElement, notification: NSAccessibility.Notification ) async throws -> ObserverAsyncSequence { let key = Key( element: element, notification: notification ) if let stream = streams[key] { return stream } else { let stream = try await observer.stream( element: element, notification: notification ) streams[key] = stream return stream } } } extension ApplicationObserver { fileprivate struct Key: Hashable { let element: ObserverElement let notification: NSAccessibility.Notification } }
// // PlayerActionAdapterTests.swift // SailingThroughHistoryTests // // Created by Herald on 20/4/19. // Copyright © 2019 Sailing Through History Team. All rights reserved. // import XCTest @testable import SailingThroughHistory class PlayerActionAdapterTests: XCTestCase { func testProcess() { let state = GameVariable<TurnSystemNetwork.State>( value: TurnSystemNetwork.State.invalid) let networkInfo = TestClasses.createNetworkInfo() let data = TestClasses.createTestState(numPlayers: 2) let adapter = PlayerActionAdapter( stateVariable: state, networkInfo: networkInfo, data: data) let player = data.gameState.getPlayers()[0] let otherPlayer = data.gameState.getPlayers()[1] guard let location = data.gameState.map.getNodes().filter({ $0.identifier != player.node?.identifier }).first else { XCTFail("There should be 2 connected nodes on the test map") return } let playerAction = PlayerAction.move(toNodeId: location.identifier, isEnd: false) state.value = .invalid moveFail(adapter: adapter, playerAction: playerAction, player: player) state.value = .evaluateMoves(for: player) moveFail(adapter: adapter, playerAction: playerAction, player: otherPlayer) do { // not checking result _ = try adapter.process(action: playerAction, for: player) } catch { XCTFail("Player's move unable to be evaluated, wrong phase") } } private func moveFail(adapter: PlayerActionAdapter, playerAction: PlayerAction, player: GenericPlayer) { do { _ = try adapter.process(action: playerAction, for: player) } catch { return } XCTFail("Player 2 should not be able to move!") } // not testing the other functionality }
// // NoticeModel.swift // Jup-Jup // // Created by 조주혁 on 2021/03/07. // import Foundation struct NoticeModel: Codable { let success: Bool let list: [NoticeList] } struct NoticeList: Codable { let title: String let content: String }
// // TokenRefreshRequest.swift // Slidecoin // // Created by Oleg Samoylov on 19.12.2019. // Copyright © 2019 Oleg Samoylov. All rights reserved. // import Foundation import Toolkit final class TokenRefreshRequest: BasePostRequest { init() { let endpoint = "\(RequestFactory.endpointRoot)token/refresh" super.init(endpoint: endpoint) } override public var urlRequest: URLRequest? { var request = super.urlRequest guard let refreshToken = Global.refreshToken else { return request } request?.setValue("Bearer \(refreshToken)", forHTTPHeaderField: "Authorization") return request } }
import Vapor public class HTTPSRedirectMiddleware: Middleware { let allowedHosts: [String]? public init(allowedHosts: [String]? = nil) { self.allowedHosts = allowedHosts } public func respond(to request: Request, chainingTo next: Responder) -> EventLoopFuture<Response> { if request.application.environment == .development { return next.respond(to: request) } let proto = request.headers.first(name: "X-Forwarded-Proto") ?? request.url.scheme ?? "http" guard proto == "https" else { guard let host = request.headers.first(name: .host) else { return request.eventLoop.makeFailedFuture(Abort(.badRequest)) } if let allowedHosts = allowedHosts { guard allowedHosts.contains(host) else { return request.eventLoop.makeFailedFuture(Abort(.badRequest)) } } let httpsURL = "https://" + host + "\(request.url)" return request.redirect(to: "\(httpsURL)", redirectType: .permanent).encodeResponse(for: request) } return next.respond(to: request) } }
// // datePickerClass.swift // MariCab // // Created by Brainstorm on 1/6/17. // Copyright © 2017 Brainstorm. All rights reserved. // import UIKit class datePickerClass: UIViewController { //MARK:- Outlet @IBOutlet weak var btnDatePickerDone: UIButton! @IBOutlet weak var btnDatePickerCancel: UIButton! @IBOutlet weak var lblDatePikerHeader: UILabel! @IBOutlet weak var datePicker: UIDatePicker! var fromWhere: String = "" var objRoster: setRosterClass! var objSeeker: regSeekerGInfo! var objSeekerProfile: myProfileSeeker! var strForDateOrTime: String = "" var minimumDates: Date! var custObj : customClassViewController = customClassViewController() //MARK:- View Cycle override func viewDidLoad() { super.viewDidLoad() if fromWhere == "roster" { if minimumDates != nil { datePicker.minimumDate = minimumDates as Date? datePicker.date = minimumDates } if strForDateOrTime == "date" { datePicker.datePickerMode = UIDatePickerMode.date } else { //datePicker.locale = NSLocale(localeIdentifier: "en_GB") as Locale //datePicker.locale = NSLocale(localeIdentifier: "en_US") as Locale datePicker.datePickerMode = UIDatePickerMode.time } } else if fromWhere == "seekerReg" || fromWhere == "seekerProfile" { datePicker.maximumDate = Date().addingTimeInterval(-(60*60*24*365)*16) datePicker.maximumDate = datePicker.maximumDate?.addingTimeInterval(-60*60*24*4) if strForDateOrTime == "date" { datePicker.datePickerMode = UIDatePickerMode.date } else { datePicker.datePickerMode = UIDatePickerMode.time //datePicker.locale = NSLocale(localeIdentifier: "en_US") as Locale //datePicker.locale = NSLocale(localeIdentifier: "en_GB") as Locale } } else if fromWhere == "seekerProfileHistroy" { datePicker.maximumDate = Date() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } //MARK:- Action Zone @IBAction func btnDatePickerDone(_ sender: Any) { let df: DateFormatter = DateFormatter() if fromWhere == "roster" { print(df.string(from: datePicker.date)) if strForDateOrTime == "date" { df.dateFormat = "dd/MM/yyyy" objRoster.txtToDate.text = "" } else { df.dateFormat = "hh:mm a" //datePicker.locale = NSLocale(localeIdentifier: "en_US") as Locale // let strTime: String = df.string(from: datePicker.date) // if !strTime.lowercased().contains("A".lowercased()) // { // objRoster.tempTextField.text = API.convertDateToString(strDate: df.string(from: datePicker.date), fromFormat: "HH:mm", toFormat: "hh:mm a") // } // else // { // objRoster.tempTextField.text = df.string(from: datePicker.date) // } } objRoster.tempTextField.text = df.string(from: datePicker.date) if objRoster.tempTextField == objRoster.txtDate || objRoster.tempTextField == objRoster.txtFromDate { objRoster.txtDate.text = df.string(from: datePicker.date) objRoster.txtFromDate.text = df.string(from: datePicker.date) objRoster.txtStartTime.text = "" } objRoster.calculatePirce() } else if fromWhere == "seekerReg" { if strForDateOrTime == "date" { let year: Int = Date().yearss(from: datePicker.date) if year < 16 { custObj.alertMessage("Oops..something went wrong! Check your DOB") return } df.dateFormat = "dd/MM/yyyy" } else { df.dateFormat = "hh:mm a" } objSeeker.txtDOB.text = df.string(from: datePicker.date) } else if fromWhere == "seekerProfile" { if strForDateOrTime == "date" { let year: Int = Date().yearss(from: datePicker.date) if year < 16 { custObj.alertMessage("Oops..something went wrong! Check your DOB") return } df.dateFormat = "dd/MM/yyyy" } else { df.dateFormat = "hh:mm a" } objSeekerProfile.txtDOB.text = df.string(from: datePicker.date) } else if fromWhere == "seekerProfileHistroy" { df.dateFormat = "dd/MM/yyyy" objSeekerProfile.tempTextField.text = df.string(from: datePicker.date) } self.dismiss(animated: true, completion: nil) } @IBAction func btnDatePickerCancel(_ sender: Any) { self.dismiss(animated: true, completion: nil) } @IBAction func btnDismiss(_ sender: Any) { self.dismiss(animated: true, completion: nil) } } extension Date { /// Returns the amount of years from another date func yearss(from date: Date) -> Int { return Calendar.current.dateComponents([.year], from: date, to: self).year ?? 0 } /// Returns the amount of months from another date func months(from date: Date) -> Int { return Calendar.current.dateComponents([.month], from: date, to: self).month ?? 0 } /// Returns the amount of weeks from another date func weeks(from date: Date) -> Int { return Calendar.current.dateComponents([.weekOfYear], from: date, to: self).weekOfYear ?? 0 } /// Returns the amount of days from another date func days(from date: Date) -> Int { return Calendar.current.dateComponents([.day], from: date, to: self).day ?? 0 } /// Returns the amount of hours from another date func hours(from date: Date) -> Int { return Calendar.current.dateComponents([.hour], from: date, to: self).hour ?? 0 } /// Returns the amount of minutes from another date func minutes(from date: Date) -> Int { return Calendar.current.dateComponents([.minute], from: date, to: self).minute ?? 0 } /// Returns the amount of seconds from another date func seconds(from date: Date) -> Int { return Calendar.current.dateComponents([.second], from: date, to: self).second ?? 0 } /// Returns the a custom time interval description from another date func offset(from date: Date) -> String { if yearss(from: date) > 0 { return "\(yearss(from: date))y" } if months(from: date) > 0 { return "\(months(from: date))M" } if weeks(from: date) > 0 { return "\(weeks(from: date))w" } if days(from: date) > 0 { return "\(days(from: date))d" } if hours(from: date) > 0 { return "\(hours(from: date))h" } if minutes(from: date) > 0 { return "\(minutes(from: date))m" } if seconds(from: date) > 0 { return "\(seconds(from: date))s" } return "" } }
// // APIError.swift // FaMulan // // Created by Bia Plutarco on 18/07/20. // Copyright © 2020 Bia Plutarco. All rights reserved. // import Foundation enum APIError: Error { case noData case invalidJSON case unknown } extension APIError: LocalizedError { public var errorDescription: String? { switch self { case .unknown: return self.localizedDescription case .noData: return "Sem resposta" case .invalidJSON: return "Erro ao parsear o retorno da API." } } }
// // ImageTaskDownloadedDelegate.swift // MarvelHeroes // // Created by RafaelAlmeida on 15/07/19. // Copyright © 2019 RafaelAlmeida. All rights reserved. // import UIKit protocol ImageTaskDownloadedDelegate { func imageDownloaded(position: Int) }
// // CharacterComponent.swift // Pods // // Created by Alexander Skorulis on 19/8/18. // import GameplayKit class CharacterComponent: BaseEntityComponent { let character:CharacterModel let playerNumber:Int var killCount:Int = 0 var deathCount:Int = 0 init(character:CharacterModel,playerNumber:Int) { self.character = character self.playerNumber = playerNumber super.init() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func sprite() -> SimpleBeingNode { let sprite = entity?.component(ofType: GKSCNNodeComponent.self)?.node as? SimpleBeingNode return sprite! } func takeDamage(damage:Int) { let wastedDamage = max(damage - character.health.valueInt,0) character.health -= damage sprite().updateHealthBar(pct:character.health.fullPercentage) events()?.receivedDamage(amount: damage) events()?.wastedDamage(amount: wastedDamage) } func takeMana(amount:Int) { character.mana -= amount sprite().updateManaBar(pct: character.mana.fullPercentage) events()?.spendMana(amount: amount) } func heal(amount:Float) { character.health += amount sprite().updateHealthBar(pct:character.health.fullPercentage) } func addMana(amount:Float) { character.mana += amount sprite().updateManaBar(pct: character.mana.fullPercentage) } func hasMana(cost:Int) -> Bool { return character.mana.valueInt >= cost } override func update(deltaTime seconds: TimeInterval) { let manaBefore = character.mana.value character.mana += Float(seconds) * 2 //Don't do an update if nothing has changed if (manaBefore != character.mana.value) { sprite().updateManaBar(pct: character.mana.fullPercentage) } } func reset() { character.mana.setToMax() character.health.setToMax() sprite().updateManaBar(pct: character.mana.fullPercentage) sprite().updateHealthBar(pct:character.health.fullPercentage) } override func didAddToEntity() { //sprite().updateManaBar(pct: character.mana.fullPercentage) //sprite().updateHealthBar(pct:character.health.fullPercentage) } func isDead() -> Bool { return self.character.health.value == 0 } func addBuff(buff:BuffModel) { self.character.buffs.append(buff) } }
../../Tests/RxSwiftTests/RxAtomic+Overrides.swift
// // SignupInfoTests.swift // PrinCraigslist // // Created by Kirill Kudaev on 4/19/17. // Copyright © 2017 Parse. All rights reserved. // import XCTest @testable import PrinCraigslist class SignupInfoTests: XCTestCase { var emptyString = "" var email = "email@email" var password = "password" var firstName = "firstName" var lastName = "lastName" var shortPassword = "short" var longString = "longlonglonglonglonglonglonglonglonglonglonglong" override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testSUT_NoEmail() { let signupInfo = SignupInfo(email: emptyString, password: password, firstName: firstName, lastName: lastName) XCTAssertEqual(signupInfo.error, true) XCTAssertEqual(signupInfo.errorMessage, "Please enter an email") } func testSUT_NoPassword() { let signupInfo = SignupInfo(email: email, password: emptyString, firstName: firstName, lastName: lastName) XCTAssertEqual(signupInfo.error, true) XCTAssertEqual(signupInfo.errorMessage, "Please enter a password") } func testSUT_NoFirstName() { let signupInfo = SignupInfo(email: email, password: password, firstName: emptyString, lastName: lastName) XCTAssertEqual(signupInfo.error, true) XCTAssertEqual(signupInfo.errorMessage, "Please enter First Name") } func testSUT_NoLastName() { let signupInfo = SignupInfo(email: email, password: password, firstName: firstName, lastName: emptyString) XCTAssertEqual(signupInfo.error, true) XCTAssertEqual(signupInfo.errorMessage, "Please enter Last Name") } func testSUT_ShortPassword() { let signupInfo = SignupInfo(email: email, password: shortPassword, firstName: firstName, lastName: lastName) XCTAssertEqual(signupInfo.error, true) XCTAssertEqual(signupInfo.errorMessage, "Password has to be at least 8 characters") } func testSUT_LongPassword() { let signupInfo = SignupInfo(email: email, password: longString, firstName: firstName, lastName: lastName) XCTAssertEqual(signupInfo.error, true) XCTAssertEqual(signupInfo.errorMessage, "Password has to be less then 35 characters") } func testSUT_LongFirstName() { let signupInfo = SignupInfo(email: email, password: password, firstName: longString, lastName: lastName) XCTAssertEqual(signupInfo.error, true) XCTAssertEqual(signupInfo.errorMessage, "First Name has to be less then 35 characters") } func testSUT_LongLastName() { let signupInfo = SignupInfo(email: email, password: password, firstName: firstName, lastName: longString) XCTAssertEqual(signupInfo.error, true) XCTAssertEqual(signupInfo.errorMessage, "Last Name has to be less then 35 characters") } }
// // ViewController.swift // CuratedPlansDetailScreen // // Created by Jatin on 02/09/21. // import UIKit class ViewController: UIViewController { let viewModel = ScrollableStickyHeaderViewModel() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) let setting = ScrollableStickyHeaderCollectionViewSetting(title: "15 day plan for Your Knees - Phase 1", backgroundColor: UIColor(named: "EBD4D9")!) let controller = ScrollableStickyHeaderCollectionViewController(with: setting, dataSource: viewModel) viewModel.set(delegate: controller) self.navigationController?.pushViewController(controller, animated: true) } }
// // RecommendationsOptions.swift // // // Created by Vladislav Fitc on 01/09/2021. // import Foundation public struct RecommendationsOptions: Codable { /// Name of the index to target public let indexName: IndexName /// The recommendation model to use public let model: RecommendationModel /// The objectID to get recommendations for public let objectID: ObjectID /// The threshold to use when filtering recommendations by their score public let threshold: Int /// The maximum number of recommendations to retrieve public let maxRecommendations: Int? /// Search parameters to filter the recommendations public let queryParameters: Query? /// Search parameters to use as fallback when there are no recommendations public let fallbackParameters: Query? /** - parameter indexName: Name of the index to target - parameter model: The recommendation model to use - parameter objectID: The objectID to get recommendations for - parameter threshold: The threshold to use when filtering recommendations by their score - parameter maxRecommendations: The maximum number of recommendations to retrieve - parameter queryParameters: Search parameters to filter the recommendations - parameter fallbackParameters: Search parameters to use as fallback when there are no recommendations */ public init(indexName: IndexName, model: RecommendationModel, objectID: ObjectID, threshold: Int = 0, maxRecommendations: Int? = nil, queryParameters: Query? = nil, fallbackParameters: Query? = nil) { self.indexName = indexName self.model = model self.objectID = objectID self.threshold = threshold self.maxRecommendations = maxRecommendations self.queryParameters = queryParameters self.fallbackParameters = fallbackParameters } } public struct FrequentlyBoughtTogetherOptions { internal let recommendationsOptions: RecommendationsOptions /** - parameter indexName: Name of the index to target - parameter objectID: The objectID to get recommendations for - parameter threshold: The threshold to use when filtering recommendations by their score - parameter maxRecommendations: The maximum number of recommendations to retrieve - parameter queryParameters: Search parameters to filter the recommendations */ public init(indexName: IndexName, objectID: ObjectID, threshold: Int = 0, maxRecommendations: Int? = nil, queryParameters: Query? = nil) { recommendationsOptions = .init(indexName: indexName, model: .boughtTogether, objectID: objectID, threshold: threshold, maxRecommendations: maxRecommendations, queryParameters: queryParameters, fallbackParameters: nil) } } public struct RelatedProductsOptions { internal let recommendationsOptions: RecommendationsOptions /** - parameter indexName: Name of the index to target - parameter objectID: The objectID to get recommendations for - parameter threshold: The threshold to use when filtering recommendations by their score - parameter maxRecommendations: The maximum number of recommendations to retrieve - parameter queryParameters: Search parameters to filter the recommendations - parameter fallbackParameters: Search parameters to use as fallback when there are no recommendations */ public init(indexName: IndexName, objectID: ObjectID, threshold: Int = 0, maxRecommendations: Int? = nil, queryParameters: Query? = nil, fallbackParameters: Query? = nil) { recommendationsOptions = .init(indexName: indexName, model: .relatedProducts, objectID: objectID, threshold: threshold, maxRecommendations: maxRecommendations, queryParameters: queryParameters, fallbackParameters: fallbackParameters) } }
import RxSwift class StepViewModel: ViewModel { let stepVariable = Variable<String>(String()) var step: Observable<String> { return stepSubject.asObservable() } var isDataProvided: Observable<Bool> { return stepVariable.asObservable().map { !$0.isEmpty } } var addDidTap: AnyObserver<Void> { return AnyObserver { [weak self] event in switch event { case .next: self?.addStep() default: break } } } private let stepSubject = PublishSubject<String>() // MARK: - Private private func addStep() { stepSubject.onNext(stepVariable.value) } }
// // MovieReminderController.swift // PopUpCorn // // Created by Elias Paulino on 08/06/19. // Copyright © 2019 Elias Paulino. All rights reserved. // import Foundation import UserNotifications import EventKit class MovieReminderController: MovieFormatterProtocol { weak public var delegate: MovieReminderControllerDelegate? { didSet { delegate?.reloadReminderButton() } } var movieDAO = MovieCoreDataDAO() func needRemindMovie(_ movie: DetailableMovie) { let realMovie = toMovie(from: movie) guard realMovie.id != nil && realMovie.releaseDate != nil, let releaseDate = movie.release else { return } guard !movieHasReminder(movie) else { if !movieDAO.delete(element: realMovie) { delegate?.needShowError(message: "A Error Happend While Deleting the Reminder.") } else { removeNotification(forMovie: movie) } delegate?.reloadReminderButton() delegate?.needRemoveMovie(movie: movie) return } if movieDAO.save(element: realMovie) == nil { delegate?.needShowError(message: "A Error Happend While Saving the Reminder.") } else if releaseDate > Date() { setNotification(forMovie: movie) setCalendarReminder(forMovie: movie) delegate?.reminderWasAdded(inReminders: true) } else { delegate?.reminderWasAdded(inReminders: false) } delegate?.reloadReminderButton() } private func removeNotification(forMovie movie: DetailableMovie) { guard let movieID = movie.id else { return } let notificationCenter = UNUserNotificationCenter.current() notificationCenter.removePendingNotificationRequests(withIdentifiers: [String(movieID)]) } private func setCalendarReminder(forMovie movie: DetailableMovie) { let eventStore = EKEventStore() switch EKEventStore.authorizationStatus(for: .reminder) { case .authorized: addReminderToCalendar(store: eventStore, andMovie: movie) case .notDetermined: eventStore.requestAccess(to: .reminder) { [weak self] (acessPermitted, error) in guard error == nil, acessPermitted else { return } self?.addReminderToCalendar(store: eventStore, andMovie: movie) } default: break } } private func addReminderToCalendar(store: EKEventStore, andMovie movie: DetailableMovie) { let defaultCalendar = store.defaultCalendarForNewReminders() ?? store.calendars(for: .reminder).first let calendarFormatter = Calendar.current guard let calendar = defaultCalendar, let movieReleaseDate = movie.release, let startDate = calendarFormatter.date(byAdding: .day, value: -1, to: movieReleaseDate) else { return } let reminder = EKReminder(eventStore: store) reminder.calendar = calendar reminder.title = "\(movie.title ?? "movie") Release" reminder.isCompleted = false let startDateComponents = calendarFormatter.dateComponents([.minute, .hour, .day, .month, .year], from: startDate) reminder.startDateComponents = startDateComponents do { try store.save(reminder, commit: true) } catch { print(error) } } private func setNotification(forMovie movie: DetailableMovie) { guard let movieDate = movie.release, let movieID = movie.id else { return } let notificationCenter = UNUserNotificationCenter.current() notificationCenter.requestAuthorization(options: [.alert, .sound, .badge]) { [weak self] (userAccepeted, error) in guard error == nil, userAccepeted else { return } let notificationContent = UNMutableNotificationContent() notificationContent.title = "\(movie.title ?? "no title") release is today" notificationContent.body = movie.overview ?? "no overview" notificationContent.sound = UNNotificationSound.default notificationContent.badge = 1 let notificationTrigger = UNCalendarNotificationTrigger( dateMatching: Calendar.current.dateComponents( [.year, .month, .day, .minute, .second, .hour], from: movieDate ), repeats: false ) let notificationRequest = UNNotificationRequest( identifier: String(movieID), content: notificationContent, trigger: notificationTrigger ) notificationCenter.add(notificationRequest, withCompletionHandler: { [weak self] (error) in if error != nil { self?.delegate?.needShowError(message: "A Error Happend While Setting the Notification") } }) } } func mustShowReminderButton(forMovie movie: DetailableMovie) -> Bool { return true } private func releaseToDate(_ release: String) -> Date? { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" guard let date = dateFormatter.date(from: release) else { return nil } return date } func controllerWillAppear() { delegate?.reloadReminderButton() } func movieHasReminder(_ movie: DetailableMovie) -> Bool { guard let movieID = movie.id, movieDAO.get(elementWithID: movieID) != nil else { return false } return true } }
// // CompositeBinaryTree.swift // Algorithms&DataStructures // // Created by Paul Kraft on 22.08.16. // Copyright © 2016 pauljohanneskraft. All rights reserved. // // swiftlint:disable trailing_whitespace public struct CompositeBinaryTree<Element: Equatable>: Tree { public func contains(_ data: Element) -> Bool { return root.contains(data) } public mutating func insert(_ data: Element) throws { try push(data) } public mutating func remove(_ data: Element) throws { root = try root.remove(data) } public mutating func removeAll() { root = Leaf(order: order) } public var count: UInt { return root.count } public typealias DataElement = Element var root: Node public init(order: @escaping (Element, Element) -> Bool) { self.root = Leaf(order: order) } public var array: [Element] { get { return root.array } set { root = Leaf(order: order) newValue.forEach { try? insert($0) } } } public var order: (Element, Element) -> Bool { return root.order } public mutating func push(_ data: Element) throws { root = try root.push(data) } public mutating func pop() -> Element? { let ret = root.pop() self.root = ret.node return ret.data } class Node { let order: (Element, Element) -> Bool var count: UInt { return 0 } init(order: @escaping (Element, Element) -> Bool) { self.order = order } var array: [Element] { return [] } func push(_ data: Element) throws -> Node { return InnerNode(data: data, order: order) } func remove(_ data: Element) throws { throw DataStructureError.notIn } func pop() -> (data: Element?, node: Node) { return (nil, self) } func remove(_ data: Element) throws -> Node { throw DataStructureError.notIn } func contains(_ data: Element) -> Bool { return false } func removeLast() -> (data: Element?, node: Node) { return (nil, self) } } final class InnerNode: Node, BinaryTreeNodeProtocol { var left: Node var right: Node var data: Element init(data: Element, order: @escaping (Element, Element) -> Bool) { self.data = data self.left = Leaf(order: order) self.right = Leaf(order: order) super.init(order: order) } override var array: [Element] { return left.array + [data] + right.array } override func push(_ newData: Element) throws -> Node { guard data != newData else { throw DataStructureError.alreadyIn } if order(newData, data) { left = try left.push(newData) } else { right = try right.push(newData) } return self } override func remove(_ data: Element) throws -> Node { if data == self.data { let leftPop = left.removeLast() left = leftPop.node if let data = leftPop.data { self.data = data return self } return right } else if order(data, self.data) { left = try left.remove(data) } else { right = try right.remove(data) } return self } override func removeLast() -> (data: Element?, node: CompositeBinaryTree.Node) { let remLast = right.removeLast() right = remLast.node guard let element = remLast.data else { return (self.data, left) } return (element, self) } override func pop() -> (data: Element?, node: Node) { if left is Leaf { return (self.data, right) } let (data, newLeft) = left.pop() left = newLeft return (data, self) } override func contains(_ data: Element) -> Bool { if data == self.data { return true } else if order(data, self.data) { return left.contains(data) } else { return right.contains(data) } } override var count: UInt { return left.count + right.count + 1 } } final class Leaf: Node { } }
// // SwiftchainMessage.swift // Swiftchain // // Created by Albertino Padin on 4/1/17. // Copyright © 2017 Albertino Padin. All rights reserved. // import Foundation public class SwiftchainMessage { var type: MessageType var data: Data? init(type: MessageType) { self.type = type self.data = nil } init(type: MessageType, data: Data) { self.type = type self.data = data } }
// // 257_二叉树的所有路径.swift // algorithm.swift // // Created by yaoning on 6/1/20. // Copyright © 2020 yaoning. All rights reserved. // import Foundation class Solution257 { public class TreeNode { public var val: Int public var left: TreeNode? public var right: TreeNode? public init(_ val: Int) { self.val = val self.left = nil self.right = nil } } func construct_path(root: TreeNode?, path: String, paths: inout [String]) { guard let r = root else { return } var p = path.appending(String(r.val)) if r.left == nil && r.right == nil { paths.append(p) } else { p = p.appending("->") construct_path(root: r.left, path: p, paths: &paths) construct_path(root: r.right, path: p, paths: &paths) } } func binaryTreePaths(_ root: TreeNode?) -> [String] { let path = "" var paths: [String] = [] construct_path(root: root, path: path, paths: &paths) return [] } }
// // SendModalViewController.swift // Piicto // // Created by OkuderaYuki on 2018/01/23. // Copyright © 2018年 SmartTech Ventures Inc. All rights reserved. // import UIKit final class SendModalViewController: UIViewController { @IBOutlet private var panGestureRecognizer: UIPanGestureRecognizer! @IBOutlet private weak var scrollView: UIScrollView! @IBOutlet weak var imageView: UIImageView! // swiftlint:disable:this private_outlet private let sendModalViewStatusBar = SendModalViewStatusBar() private var imageSlideOutTransition = ImageSlideOutTransition() private var interactiveTransitionController: UIPercentDrivenInteractiveTransition? private var isTransitioning = false private var image = UIImage() private var imageName = "" // MARK: - Factory class func make(with image: UIImage, name: String) -> SendModalViewController { let vcName = SendModalViewController.className guard let sendModalVC = UIStoryboard.viewController( storyboardName: vcName, identifier: vcName) as? SendModalViewController else { fatalError("SendViewController is nil.") } sendModalVC.image = image sendModalVC.imageName = name return sendModalVC } // MARK: - Life cycle override func viewDidLoad() { super.viewDidLoad() setup() } private func setup() { setNeedsStatusBarAppearanceUpdate() sendModalViewStatusBar.setStatusBarBackgroundColor(newColor: #colorLiteral(red: 1, green: 0.5294117647, blue: 0.4705882353, alpha: 1)) imageView.image = image self.transitioningDelegate = self panGestureRecognizer.delegate = self } override var prefersStatusBarHidden: Bool { return false } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } // MARK: - Actions @IBAction func didTapBack(_ sender: UIButton) { guard let piictoNC = presentingViewController as? PiictoNavigationController, let sendVC = piictoNC.viewControllers.last as? SendViewController else { return } sendVC.sendStatus = .willBack dismiss(animated: false) { self.sendModalViewStatusBar.setStatusBarBackgroundColor(newColor: nil) piictoNC.popViewController(animated: true) } } } extension SendModalViewController: UIViewControllerTransitioningDelegate { func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return imageSlideOutTransition } func interactionControllerForDismissal( using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { return self.interactiveTransitionController } } extension SendModalViewController: UIGestureRecognizerDelegate { func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { if otherGestureRecognizer.isKind(of: UIPinchGestureRecognizer.self) { return false } else { return true } } } extension SendModalViewController { // MARK: - Selectors @IBAction func pan(_ sender: UIPanGestureRecognizer) { if scrollView.zoomScale > 1.0 || scrollView.contentOffset.x != 0 { return } switch sender.state { case .began: // ジェスチャの開始。遷移を開始・上下方向を決定する。 panBegan(sender: sender) case .cancelled: // ジェスチャキャンセル。遷移をキャンセルする endTransitioning() cancelInteractiveTransition() case .changed: // ジェスチャ中。遷移の進行度を更新する panChanged(sender: sender) case .ended: // ジェスチャの正常完了。遷移を実行させるかキャンセルする。 endTransitioning() guard let interactiveTransitionController = interactiveTransitionController else { break } // 進行度0.5以上なら遷移実行へ if interactiveTransitionController.percentComplete >= CGFloat(0.5) { finishInteractiveTransition() break } // スワイプの勢いが一定以上なら遷移実行へ determineTheSwipeSpeed(sender: sender) case .failed: // ジェスチャの失敗。遷移をキャンセルする。 panFailed() default: break } } private func panBegan(sender: UIPanGestureRecognizer) { isTransitioning = true scrollView.isScrollEnabled = false interactiveTransitionController = UIPercentDrivenInteractiveTransition() if sender.translation(in: scrollView).y > 0 { imageSlideOutTransition.isScrolledUp = false } else { imageSlideOutTransition.isScrolledUp = true } dismiss(animated: true, completion: nil) updateTransitionProgress(sender: sender) } private func panChanged(sender: UIPanGestureRecognizer) { if isTransitioning { // 方向が変更される場合、一旦キャンセルして初期化し直す if imageSlideOutTransition.isScrolledUp && sender.translation(in: scrollView).y > 0 { reInitDismiss(isScrolledUp: false) } else if !imageSlideOutTransition.isScrolledUp && sender.translation(in: scrollView).y < 0 { reInitDismiss(isScrolledUp: true) } updateTransitionProgress(sender: sender) } } private func determineTheSwipeSpeed(sender: UIPanGestureRecognizer) { let velocityinView = sender.velocity(in: scrollView).y print("velocityinView: \(fabs(velocityinView))") if fabs(velocityinView) > 1000 { if imageSlideOutTransition.isScrolledUp && velocityinView < 0 { finishInteractiveTransition() } else if !imageSlideOutTransition.isScrolledUp && velocityinView > 0 { // 下へスクロールした場合は、キャンセル cancelInteractiveTransition() } else { cancelInteractiveTransition() } } else { cancelInteractiveTransition() } } private func panFailed() { endTransitioning() cancelInteractiveTransition() } } extension SendModalViewController { /// 遷移の進行度を更新する private func updateTransitionProgress(sender: UIPanGestureRecognizer) { let transitionProgress: CGFloat = sender.translation(in: scrollView).y / view.frame.size.height interactiveTransitionController?.update(fabs(transitionProgress)) } /// 遷移フラグを折って、スクロールビューのスクロールを許可する private func endTransitioning() { isTransitioning = false scrollView.isScrollEnabled = true } /// 方向が変更される場合、一旦キャンセルして初期化し直す private func reInitDismiss(isScrolledUp: Bool) { interactiveTransitionController?.cancel() interactiveTransitionController = UIPercentDrivenInteractiveTransition() imageSlideOutTransition.isScrolledUp = isScrolledUp dismiss(animated: true, completion: nil) } /// 画面遷移を実行する private func finishInteractiveTransition() { guard let piictoNC = presentingViewController as? PiictoNavigationController, let sendVC = piictoNC.viewControllers.last as? SendViewController else { return } sendVC.sendStatus = .willSend interactiveTransitionController?.finish() interactiveTransitionController = nil } /// 画面遷移を実行しない private func cancelInteractiveTransition() { interactiveTransitionController?.cancel() interactiveTransitionController = nil } }
// // CommentViewController.swift // Instagram // // Created by saito-takumi on 2018/01/06. // Copyright © 2018年 saito-takumi. All rights reserved. // import Foundation import UIKit import Floaty import Parse class CommentViewController: UIViewController { @IBOutlet weak var tableView: UITableView! var post: Post? var comments = [Comment]() { didSet { tableView.reloadData() } } override func viewDidLoad() { super.viewDidLoad() navigationController?.navigationBar.tintColor = UIColor.white navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor as NSAttributedStringKey: UIColor.white] navigationController?.navigationBar.barTintColor = #colorLiteral(red: 0.1019607843, green: 0.137254902, blue: 0.4941176471, alpha: 1) let postNib = UINib(nibName: "PostInCommentTableViewCell", bundle: nil) tableView.register(postNib, forCellReuseIdentifier: "postInCommentCell") let commentNib = UINib(nibName: "CommentTableViewCell", bundle: nil) tableView.register(commentNib, forCellReuseIdentifier: "commentCell") tableView.estimatedRowHeight = 400 tableView.rowHeight = UITableViewAutomaticDimension tableView.dataSource = self let floaty = Floaty() floaty.fabDelegate = self self.view.addSubview(floaty) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) fetchComment() let center = NotificationCenter.default center.addObserver(forName: Notification.Name.newCommentSent, object: nil, queue: OperationQueue.main) { (notification) in if let newComment = notification.userInfo?["newCommentObject"] as? Comment { if !self.postWasDisplayed(newComment: newComment) { self.comments.insert(newComment, at: self.comments.count) } } } } // MARK: Method override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "new comment composer" { let navigationController = segue.destination as! UINavigationController let newCommentViewController = navigationController.childViewControllers.first as! NewCommentViewController newCommentViewController.post = post } } func postWasDisplayed(newComment: Comment) -> Bool { return self.comments.contains(newComment) } func fetchComment() { let commentQuery = PFQuery(className: Comment.parseClassName()) commentQuery.whereKey("postID", equalTo: post?.objectId) commentQuery.order(byAscending: "updatedAt") commentQuery.cachePolicy = .cacheThenNetwork commentQuery.includeKey("user") commentQuery.findObjectsInBackground { (objects, error) in if error == nil { if let objects = objects { if objects.count > 0 { self.comments = objects.map({ (pfObject) -> Comment in return pfObject as! Comment }) } } } else { print(error) } } } } // MARK: UITableViewDataSource extension CommentViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return comments.count + 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.row == 0 { let cell = tableView.dequeueReusableCell(withIdentifier: "postInCommentCell", for: indexPath) as! PostInCommentTableViewCell cell.post = post return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: "commentCell", for: indexPath) as! CommentTableViewCell cell.comment = comments[indexPath.row-1] return cell } } } // MARK: FloatyDelegate extension CommentViewController: FloatyDelegate { func emptyFloatySelected(_ floaty: Floaty){ print("tapped") self.performSegue(withIdentifier: "new comment composer", sender: self) } }
// // Ticker.swift // Cryptohopper-iOS-SDK // // Created by Kaan Baris Bayrak on 04/11/2020. // import Foundation public class Ticker : Codable { public private(set) var currencyPair : String? public private(set) var last : String? public private(set) var lowestAsk : String? public private(set) var highestBid : String? public private(set) var percentChange : String? public private(set) var baseVolume : String public private(set) var quoteVolume : String? public private(set) var isFrozen : Int? public private(set) var oneDayHigh : String? public private(set) var oneDayLow : String? private enum CodingKeys: String, CodingKey { case currencyPair = "currencyPair" case last = "last" case lowestAsk = "lowestAsk" case highestBid = "highestBid" case percentChange = "percentChange" case baseVolume = "baseVolume" case quoteVolume = "quoteVolume" case isFrozen = "isFrozen" case oneDayHigh = "24hrHigh" case oneDayLow = "24hrLow" } }
// // AddressListVM.swift // MyLoqta // // Created by Ashish Chauhan on 26/07/18. // Copyright © 2018 AppVenturez. All rights reserved. // import Foundation import ObjectMapper typealias Address = (title: String, value: String) protocol AddressListVModeling { func getAddressList(completion: @escaping (_ arrayAddress: [ShippingAddress])-> Void) func getAddAddressDataSource(address: ShippingAddress?) -> [Address] func addAddress(param: [String: AnyObject], completion: @escaping (_ success: Bool, _ address: ShippingAddress)-> Void) func removeAddress(addressId: Int, completion: @escaping (_ success: Bool)-> Void) func updateAddress(param: [String: AnyObject], completion: @escaping (_ success: Bool)-> Void) func getCityList(param: [String: AnyObject], completion: @escaping (_ arrayCategory: [[String: Any]]) ->Void) func validateData(_ arrModel: [Address]) -> Bool func getCountryList() -> [[String: Any]] func getCityList() -> [[String: Any]] } class AddressListVM: BaseModeling, AddressListVModeling { func getAddAddressDataSource(address: ShippingAddress?) -> [Address] { var array = [Address]() // Title var title = Address(title: "Title".localize(), value: "") if let strTitle = address?.title { title.value = strTitle } array.append(title) // Country var country = Address(title: "Country".localize(), value: "Kuwait".localize()) if let value = address?.country { country.value = value } array.append(country) // City var city = Address(title: "City".localize(), value: "") if let value = address?.city { city.value = value } array.append(city) // Block No. var blockNo = Address(title: "Block No.".localize(), value: "") if let value = address?.blockNo { blockNo.value = value } array.append(blockNo) // Street var street = Address(title: "Street".localize(), value: "") if let value = address?.street { street.value = value } array.append(street) // Avenue No. (optional) var avenueNo = Address(title: "Avenue No. (optional)".localize(), value: "") if let value = address?.avenueNo { avenueNo.value = value } array.append(avenueNo) // Building No. var buildingNo = Address(title: "Building No.".localize(), value: "") if let value = address?.buildingNo { buildingNo.value = value } array.append(buildingNo) // PACI No. (optional) var paciNo = Address(title: "PACI No. (optional)".localize(), value: "") if let value = address?.paciNo { paciNo.value = value } array.append(paciNo) return array } func getAddressList(completion: @escaping (_ arrayAddress: [ShippingAddress])-> Void) { let userId = UserSession.sharedSession.getUserId() self.apiManagerInstance()?.request(apiRouter: APIRouter.init(endpoint: .addressList(userId: userId)), completionHandler: { (response, success) in if success, let array = response as? [[String: Any]] { let arrayShipping = ShippingAddress.getArray(array: array) completion(arrayShipping) } }) } func addAddress(param: [String: AnyObject], completion: @escaping (_ success: Bool, _ address: ShippingAddress)-> Void) { self.apiManagerInstance()?.request(apiRouter: APIRouter.init(endpoint: .addAddress(param: param)), completionHandler: { (response, success) in print(response) if success, let result = response as? [String: Any] { if let shippingAdd = Mapper<ShippingAddress>().map(JSON: result) { completion(success, shippingAdd) } } }) } func removeAddress(addressId: Int, completion: @escaping (_ success: Bool)-> Void) { let param = ["id": addressId as AnyObject] apiManagerInstance()?.request(apiRouter: APIRouter.init(endpoint: .removeAddress(param: param)), completionHandler: { (_, success) in completion(success) }) } func updateAddress(param: [String: AnyObject], completion: @escaping (_ success: Bool)-> Void) { apiManagerInstance()?.request(apiRouter: APIRouter.init(endpoint: .editAddress(param: param)), completionHandler: { (_, success) in completion(success) }) } func getCityList(param: [String: AnyObject], completion: @escaping (_ arrayCategory: [[String: Any]]) ->Void) { self.apiManagerInstance()?.request(apiRouter: APIRouter.init(endpoint: .getCityList(param: param)), completionHandler: { (response, success) in print(response) if success, let result = response as? [[String: Any]] { completion(result) } }) } func getCountryList() -> [[String: Any]] { let countryOne = ["countryName": "Kuwait"] let arrCountry = [countryOne] return arrCountry } func getCityList() -> [[String: Any]] { let cityOne = ["cityName": "Kuwait City"] let arrCity = [cityOne] return arrCity } func validateData(_ arrModel: [Address]) -> Bool { var isValid = true let home = arrModel[0].value let country = arrModel[1].value let city = arrModel[2].value let blockNo = arrModel[3].value let street = arrModel[4].value let buildingNo = arrModel[6].value if home.isEmpty { Alert.showOkAlert(title: ConstantTextsApi.AppName.localizedString, message: "Please enter title".localizedString()) isValid = false } else if country.isEmpty { Alert.showOkAlert(title: ConstantTextsApi.AppName.localizedString, message: "Please select your country".localizedString()) isValid = false } else if city.isEmpty { Alert.showOkAlert(title: ConstantTextsApi.AppName.localizedString, message: "Please select your city".localizedString()) isValid = false } else if blockNo.isEmpty { Alert.showOkAlert(title: ConstantTextsApi.AppName.localizedString, message: "Please enter Block No.".localizedString()) isValid = false } else if street.isEmpty { Alert.showOkAlert(title: ConstantTextsApi.AppName.localizedString, message: "Please enter Street".localizedString()) isValid = false } else if buildingNo.isEmpty { Alert.showOkAlert(title: ConstantTextsApi.AppName.localizedString, message: "Please enter Building No.".localizedString()) isValid = false } return isValid } }
// // UITextView+Properties.swift // Fugu // // Created by Gagandeep Arora on 15/06/17. // Copyright © 2017 Socomo Technologies Private Limited. All rights reserved. // import Foundation import UIKit protocol HippoMessageTextViewImageDelegate: class { func imagePasted() } class HippoMessageTextView: UITextView { // MARK: - Properties weak var imagePasteDelegate: HippoMessageTextViewImageDelegate? var privateText: NSAttributedString = NSAttributedString(string: "") var normalText: NSAttributedString = NSAttributedString(string: "") var isPrivateMode: Bool = false { didSet { updateDataAsPerMode() } } // MARK: - View Life Cycle override func awakeFromNib() { super.awakeFromNib() textAlignment = .left contentInset.top = 12 contentInset.bottom = 0 text = "" } private func updateDataAsPerMode() { isPrivateMode ? setPropertyForPrivateMode() : setPropertyForNormalMode() } private func setPropertyForPrivateMode() { // normalText = attributedText attributedText = privateText } private func setPropertyForNormalMode() { // privateText = attributedText attributedText = normalText } // MARK: - Methods override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { if action == #selector(paste(_:)) && UIPasteboard.general.hasImages { return true } return super.canPerformAction(action, withSender: sender) } override func paste(_ sender: Any?) { if UIPasteboard.general.hasImages { imagePasteDelegate?.imagePasted() } else { super.paste(sender) } } }
// // File.swift // BUDDHA // // Created by 片山義仁 on 2020/01/27. // Copyright © 2020 Neeza. All rights reserved. // import Foundation
// // TMFeedbackRatingLayout.swift // consumer // // Created by Vladislav Zagorodnyuk on 3/24/17. // Copyright © 2017 Human Ventures Co. All rights reserved. // import UIKit /// Used for a status layout type where a width must be defined to set correct insets. protocol TMFeedbackRatingLayoutProtocol { var ratingViews: [TMFeedbackRatingView] { get set } } /// Layout to assemble a request cell. struct TMFeedbackRatingLayout: Layout { /// Image of product. var views: [Layout] init(views: [Layout]) { self.views = views } /// Will layout image and content for request cell.. /// /// - Parameter rect: Rect of main content. Image will use the top half of the rect and other info will be near the bottom. mutating func layout(in rect: CGRect) { var feedbackLayout = HorizontalLayout(contents: views, horizontalSeperatingSpace: 0) feedbackLayout.layout(in: rect) } }
// Create your Whale Talk program below: var input: String = "hello therey" var output: String = "" for char in input { let lowerChar = char.lowercased() switch lowerChar { case "a", "i", "o": output += lowerChar.uppercased() case "e": output += "EE" case "u": output += "UU" case "y": output += "YYYY" default: continue } } print(output)
// // ViewController.swift // Duck Racer // // Created by Gerardo Gallegos on 12/17/16. // Copyright © 2016 Gerardo Gallegos. All rights reserved. // // // Duck = Pekins // Fox = Mallard //correct score limit // import UIKit import SwiftySound import GoogleMobileAds import Firebase class ViewController: UIViewController, GADInterstitialDelegate { //google admob var interstitial: GADInterstitial! @IBOutlet weak var duckCount: UILabel! @IBOutlet weak var foxCount: UILabel! @IBOutlet weak var foxButton: UIButton! @IBOutlet weak var duckButton: UIButton! @IBOutlet weak var scoreLabel: UILabel! @IBOutlet weak var playAgainOutlet: UIButton! @IBOutlet weak var startOverOutlet: UIButton! @IBOutlet weak var timerLabel: UILabel! @IBOutlet weak var startGameOutlet: UIButton! //create image view let duckView = UIImageView(image: UIImage(named: "Duck1.png")!) let foxView = UIImageView(image: UIImage(named: "Duck2.png")!) let finishView = UIImageView(image: UIImage(named: "finish.png")!) //variables var foxC: Int = 0 var duckC: Int = 0 var x1: Int = 286 var y1: Int = 217 var x2: Int = 286 var y2: Int = 355 var edgeWidth:Int! var edgeHeight:Int! var screenWidth:Int = Int(UIScreen.main.bounds.width) var screenHeight:Int = Int(UIScreen.main.bounds.height) var screenRatio: Int! var screenRatioH: Int! var tcount = 3 var timer = Timer() var cpuTimer = Timer() var scoreLimit = 10 var isTwoPlayer: Bool! var diff: Int! //viewDidLoad override func viewDidLoad() { super.viewDidLoad() interstitial = createAndLoadInterstitial() //GOOGLE ADS //interstitial = GADInterstitial(adUnitID: "ca-app-pub-6937210582976662/6485839035") //let request = GADRequest() //request.testDevices = [ kGADSimulatorID, "041d6da59580f2493337b3844055eb8a" ]; // device ID for testing //interstitial.load(request) /* bannerView = GADBannerView(adSize: kGADAdSizeSmartBannerPortrait) bannerView.delegate = self self.view.addSubview(bannerView) //banner adUnitId "ca-app-pub-6937210582976662/1177923684" bannerView.rootViewController = self bannerView.load(GADRequest()) /////////////////////// */ //rotate fox button foxButton.transform = CGAffineTransform(rotationAngle: CGFloat.pi) //change x and y corrdinates edgeWidth = screenWidth - 80 //screen ratio for width screenRatio = edgeWidth / 5 //screen ratio detect if UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad { screenRatioH = screenHeight / 10//10 for ipad } else { screenRatioH = screenHeight / 8 //8 for iphone } //starting positions x1 = edgeWidth x2 = edgeWidth y1 = (screenHeight / 2) - screenRatioH y2 = (screenHeight / 2) + screenRatioH //load images & re orientate duckView.transform = CGAffineTransform(rotationAngle: -CGFloat.pi/2) self.duckView.frame = CGRect(x: self.x1, y: self.y1, width: 68, height: 68) self.view.addSubview(self.duckView) foxView.transform = CGAffineTransform(rotationAngle: -CGFloat.pi/2) self.foxView.frame = CGRect(x: self.x2, y: self.y2, width: 68, height: 68) self.view.addSubview(self.foxView) //draw finishline self.finishView.frame = CGRect(x: edgeWidth, y: (screenHeight/2), width: 136, height: 30)//136x60 self.view.addSubview(self.finishView) scoreLabel.text = (" ") timerLabel.text = "" preGameClean() startGame() //Sound.play(file: "DuckRacerSound", fileExtension: "aif", numberOfLoops: -1) print("Game Page: .\(isTwoPlayer), .\(diff)") }// //GOOGLE ADMOB/////////////////////////////////////////////// func displayAd() { if self.interstitial.isReady { self.interstitial.present(fromRootViewController: self) } else { print("Ad wasn't ready") } } func createAndLoadInterstitial() -> GADInterstitial { let interstitial = GADInterstitial(adUnitID: "ca-app-pub-6937210582976662/6485839035") interstitial.delegate = self interstitial.load(GADRequest()) return interstitial } func interstitialDidDismissScreen(_ ad: GADInterstitial) { interstitial = createAndLoadInterstitial() } //determine if ads should be shown, show ads when rand is not 1 func rollForAds() { let rand = random(lo: 0, hi: 3) if (rand != 1) { self.displayAd() //ads are shown print("yes ad \(rand)") }else { //no ads print("no ad \(rand)") } } /* BANNER VIEW AD func adViewDidReceiveAd(_ bannerView: GADBannerView) { view.addSubview(bannerView) print("adViewDidReceiveAd") } /// Tells the delegate an ad request failed. func adView(_ bannerView: GADBannerView, didFailToReceiveAdWithError error: GADRequestError) { print("adView:didFailToReceiveAdWithError: \(error.localizedDescription)") } */ ////////////////////////////////////////////////////////////// func random(lo: Int, hi: Int) -> Int { return lo + Int(arc4random_uniform(UInt32(hi - lo + 1))) } @objc func updateTimer(){ if(tcount > 0){ timerLabel.text = String(tcount) tcount -= 1 }else if (tcount == 0){ timerLabel.text = "Go!" tcount -= 1 if isTwoPlayer{ //un freeze butons foxButton.isEnabled = true duckButton.isEnabled = true }else { var cpuSpeed: Double! if diff == 1{ cpuSpeed = 0.18 }else if diff == 2{ cpuSpeed = 0.093 }else{ cpuSpeed = 0.075 } //start cpu duck and only unfreeze player cpuTimer = Timer.scheduledTimer(timeInterval: cpuSpeed, target: self, selector: #selector(ViewController.cpuDuck), userInfo: nil, repeats: true) duckButton.isEnabled = true } }else { timerLabel.isHidden = true } } //called at very begining removes everything off screen func preGameClean() { timerLabel.isHidden = false timerLabel.text = "" startOverOutlet.isEnabled = true startOverOutlet.isHidden = false duckButton.setTitle("Pekin", for: .normal) //freeze butons foxButton.isEnabled = false duckButton.isEnabled = false startOverOutlet.isHidden = false startOverOutlet.isEnabled = true duckCount.isHidden = true foxCount.isHidden = true } func startGame() { //start timer //set up timer tcount = 3 timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: (#selector(ViewController.updateTimer)), userInfo: nil, repeats: true) updateTimer() if !isTwoPlayer { duckCount.text = "You: 0" } duckCount.isHidden = false foxCount.isHidden = false startOverOutlet.isEnabled = false startOverOutlet.isHidden = true startGameOutlet.isHidden = true startGameOutlet.isEnabled = false } //plus one button press @IBAction func buttonPress(_ sender: AnyObject) { //detect edge of screen(sort of) if(x1 == edgeWidth && y1 > 10){ y1 -= screenRatioH duckView.transform = CGAffineTransform(rotationAngle: -CGFloat.pi/2) } else if(x1 > 30 && y1 < 20){ x1 -= screenRatio duckView.transform = CGAffineTransform(rotationAngle: CGFloat.pi) }else if(x1 <= 30 && y1 < (screenHeight - 150)){ y1 += screenRatioH duckView.transform = CGAffineTransform(rotationAngle: CGFloat.pi/2) }else { x1 += screenRatio duckView.transform = CGAffineTransform(rotationAngle: 0) } //animate and draw images UIView.animate(withDuration: 0.2, animations: ({ self.duckView.frame = CGRect(x: self.x1, y: self.y1, width: 68, height: 68) self.view.addSubview(self.duckView) })) collDetectDuck() keepScore() }// //fox button @IBAction func foxButtonPress(_ sender: Any) { //detect edge of screen(sort of) if(x2 < edgeWidth && y2 <= 10){ x2 += screenRatio foxView.transform = CGAffineTransform(rotationAngle: CGFloat.pi) } else if(x2 == edgeWidth && y2 < (screenHeight - 150)){ y2 += screenRatioH foxView.transform = CGAffineTransform(rotationAngle: -CGFloat.pi/2) }else if(x2 > 10 && y2 > (screenHeight - 150)){ x2 -= screenRatio foxView.transform = CGAffineTransform(rotationAngle: 0) }else { y2 -= screenRatioH foxView.transform = CGAffineTransform(rotationAngle: CGFloat.pi/2) } //animate and draw images UIView.animate(withDuration: 0.2, animations: ({ self.foxView.frame = CGRect(x: self.x2, y: self.y2, width: 68, height: 68) self.view.addSubview(self.foxView) })) //call collision detection collDetectFox() keepScore() }// //collsion detetcion Fox func collDetectFox(){ if (foxView.frame.intersects(finishView.frame)){ foxC += 1 //playSound() foxCount.text = "Mallard: " + String(foxC) Sound.play(file: "quack.wav") } }// //collsion detetcion Duck func collDetectDuck(){ if (duckView.frame.intersects(finishView.frame)){ duckC += 1 if isTwoPlayer{ duckCount.text = "Pekin: \(duckC)" } else { duckCount.text = "You: \(duckC)" } Sound.play(file: "quack.wav") } }// //reset everything @IBAction func playAgainReset(_ sender: Any) { foxC = 0 duckC = 0 x1 = edgeWidth y1 = (screenHeight / 2) - screenRatioH x2 = edgeWidth y2 = (screenHeight / 2) + screenRatioH //reset labels foxCount.text = "Mallard: " + String(foxC) duckCount.text = "Pekin: " + String(duckC) //re enable buttons foxButton.isEnabled = true duckButton.isEnabled = true //play again button playAgainOutlet.setTitle("Play Again", for: .normal) playAgainOutlet.isHidden = true playAgainOutlet.isEnabled = false startGameOutlet.isHidden = false startGameOutlet.isEnabled = true scoreLabel.text = (" ") //re orientate duck duckView.transform = CGAffineTransform(rotationAngle: -CGFloat.pi/2) //draw duck self.duckView.frame = CGRect(x: self.x1, y: self.y1, width: 68, height: 68) self.view.addSubview(self.duckView) //re orientate fox foxView.transform = CGAffineTransform(rotationAngle: -CGFloat.pi/2) //re draw fox self.foxView.frame = CGRect(x: self.x2, y: self.y2, width: 68, height: 68) self.view.addSubview(self.foxView) timer.fire() preGameClean() rollForAds() } @IBAction func startGameAction(_ sender: Any) { startGame() } //keep score and end game func keepScore(){ if(foxC == scoreLimit || duckC == scoreLimit){ //disable butons when game is over foxButton.isEnabled = false duckButton.isEnabled = false //show play again button playAgainOutlet.isHidden = false playAgainOutlet.isEnabled = true //show start over startOverOutlet.isEnabled = true startOverOutlet.isHidden = false timer.invalidate() cpuTimer.invalidate() //display winner when score is achieved if(foxC == scoreLimit){ //single player lose message if !isTwoPlayer{ scoreLabel.text = ("Game Over! \n You Lose!") Sound.play(file: "lose.wav") } else { //two player message scoreLabel.text = ("Game Over! \n Mallard Wins!") Sound.play(file: "victory.wav") } }else if(duckC == scoreLimit){ //two player winner message if isTwoPlayer{ scoreLabel.text = ("Game Over! \n Pekins Wins!") }else { //single player win message scoreLabel.text = ("Game Over! \n You Win!") } Sound.play(file: "victory.wav") } } } @objc func cpuDuck(){ self.foxButtonPress(UIControlEvents.touchUpInside) } /// Tells the delegate an ad request succeeded. func interstitialDidReceiveAd(_ ad: GADInterstitial) { print("interstitialDidReceiveAd") } /// Tells the delegate an ad request failed. func interstitial(_ ad: GADInterstitial, didFailToReceiveAdWithError error: GADRequestError) { print("interstitial:didFailToReceiveAdWithError: \(error.localizedDescription)") } }
// // TablePinsViewController.swift // On The Map // // Created by Luis Vazquez on 23.05.2020. // Copyright © 2020 Alortechs. All rights reserved. // import UIKit class TablePinsViewController: UIViewController { //IBOutlets @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() //Set datasource and delegate of tableview tableView.dataSource = self tableView.delegate = self } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) //Reload data when view will appear tableView.reloadData() } //MARK: - showAlert: Create an alert with dynamic titles according to the type of error func showAlert(ofType type: AlertNotification.ofType, message: String){ let alertVC = UIAlertController(title: type.getTitles.ofController, message: message, preferredStyle: .alert) alertVC.addAction(UIAlertAction(title: type.getTitles.ofAction, style: .default, handler: nil)) present(alertVC, animated: true) } //MARK: - refresh: Refresh data from new retrieved user locations public func refresh(){ if let tableView = tableView{ tableView.reloadData() } } } extension TablePinsViewController: UITableViewDataSource, UITableViewDelegate { // MARK: - UITableViewDelegate, UITableViewDataSource func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return StudentsLocation.data.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "pinCell", for: indexPath) let studentInfo = StudentsLocation.data[indexPath.row] cell.textLabel?.text = "\(studentInfo.firstName) \(studentInfo.lastName)" cell.imageView?.image = UIImage(named: "icon_pin") return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let mediaURL = StudentsLocation.data[indexPath.row].mediaURL tableView.deselectRow(at: indexPath, animated: true) //Check if the URL format is correct if not set an alert if mediaURL.contains("https"){ if let mediaURL = URL(string: mediaURL){ UIApplication.shared.open(mediaURL, options: [:], completionHandler: nil) } } else { showAlert(ofType: .incorrectURLFormat, message: "Media contains a wrong URL format") } } }
@testable import TMDb import XCTest final class MovieServiceTests: XCTestCase { var service: MovieService! var apiClient: MockAPIClient! var locale: Locale! override func setUp() { super.setUp() apiClient = MockAPIClient() locale = Locale(identifier: "en_GB") service = MovieService(apiClient: apiClient, localeProvider: { [unowned self] in locale }) } override func tearDown() { apiClient = nil locale = nil service = nil super.tearDown() } func testDetailsReturnsMovie() async throws { let expectedResult = Movie.thorLoveAndThunder let movieID = expectedResult.id apiClient.result = .success(expectedResult) let result = try await service.details(forMovie: movieID) XCTAssertEqual(result, expectedResult) XCTAssertEqual(apiClient.lastPath, MoviesEndpoint.details(movieID: movieID).path) } func testCreditsReturnsCredits() async throws { let expectedResult = ShowCredits.mock() let movieID = expectedResult.id apiClient.result = .success(expectedResult) let result = try await service.credits(forMovie: movieID) XCTAssertEqual(result, expectedResult) XCTAssertEqual(apiClient.lastPath, MoviesEndpoint.credits(movieID: movieID).path) } func testReviewsWithDefaultParametersReturnsReviews() async throws { let movieID = Int.randomID let expectedResult = ReviewPageableList.mock() apiClient.result = .success(expectedResult) let result = try await service.reviews(forMovie: movieID) XCTAssertEqual(result, expectedResult) XCTAssertEqual(apiClient.lastPath, MoviesEndpoint.reviews(movieID: movieID).path) } func testReviewsReturnsReviews() async throws { let movieID = Int.randomID let expectedResult = ReviewPageableList.mock() apiClient.result = .success(expectedResult) let result = try await service.reviews(forMovie: movieID, page: nil) XCTAssertEqual(result, expectedResult) XCTAssertEqual(apiClient.lastPath, MoviesEndpoint.reviews(movieID: movieID).path) } func testReviewsWithPageReturnsReviews() async throws { let movieID = Int.randomID let expectedResult = ReviewPageableList.mock() let page = expectedResult.page apiClient.result = .success(expectedResult) let result = try await service.reviews(forMovie: movieID, page: page) XCTAssertEqual(result, expectedResult) XCTAssertEqual(apiClient.lastPath, MoviesEndpoint.reviews(movieID: movieID, page: page).path) } func testImagesReturnsImageCollection() async throws { let expectedResult = ImageCollection.mock() let movieID = expectedResult.id apiClient.result = .success(expectedResult) let result = try await service.images(forMovie: movieID) XCTAssertEqual(result, expectedResult) XCTAssertEqual( apiClient.lastPath, MoviesEndpoint.images(movieID: movieID, languageCode: locale.languageCode).path ) } func testVideosReturnsVideoCollection() async throws { let expectedResult = VideoCollection.mock() let movieID = expectedResult.id apiClient.result = .success(expectedResult) let result = try await service.videos(forMovie: movieID) XCTAssertEqual(result, expectedResult) XCTAssertEqual( apiClient.lastPath, MoviesEndpoint.videos(movieID: movieID, languageCode: locale.languageCode).path ) } func testRecommendationsWithDefaultParametersReturnsMovies() async throws { let movieID = 1 let expectedResult = MoviePageableList.mock() apiClient.result = .success(expectedResult) let result = try await service.recommendations(forMovie: movieID) XCTAssertEqual(result, expectedResult) XCTAssertEqual(apiClient.lastPath, MoviesEndpoint.recommendations(movieID: movieID).path) } func testRecommendationsReturnsMovies() async throws { let movieID = 1 let expectedResult = MoviePageableList.mock() apiClient.result = .success(expectedResult) let result = try await service.recommendations(forMovie: movieID, page: nil) XCTAssertEqual(result, expectedResult) XCTAssertEqual(apiClient.lastPath, MoviesEndpoint.recommendations(movieID: movieID).path) } func testRecommendationsWithPageReturnsMovies() async throws { let movieID = 1 let expectedResult = MoviePageableList.mock() let page = expectedResult.page apiClient.result = .success(expectedResult) let result = try await service.recommendations(forMovie: movieID, page: page) XCTAssertEqual(result, expectedResult) XCTAssertEqual(apiClient.lastPath, MoviesEndpoint.recommendations(movieID: movieID, page: page).path) } func testSimilarWithDefaultParametersReturnsMovies() async throws { let movieID = 1 let expectedResult = MoviePageableList.mock() apiClient.result = .success(expectedResult) let result = try await service.similar(toMovie: movieID) XCTAssertEqual(result, expectedResult) XCTAssertEqual(apiClient.lastPath, MoviesEndpoint.similar(movieID: movieID).path) } func testSimilarReturnsMovies() async throws { let movieID = 1 let expectedResult = MoviePageableList.mock() apiClient.result = .success(expectedResult) let result = try await service.similar(toMovie: movieID, page: nil) XCTAssertEqual(result, expectedResult) XCTAssertEqual(apiClient.lastPath, MoviesEndpoint.similar(movieID: movieID).path) } func testSimilarWithPageReturnsMovies() async throws { let movieID = 1 let expectedResult = MoviePageableList.mock() let page = expectedResult.page apiClient.result = .success(expectedResult) let result = try await service.similar(toMovie: movieID, page: page) XCTAssertEqual(result, expectedResult) XCTAssertEqual(apiClient.lastPath, MoviesEndpoint.similar(movieID: movieID, page: page).path) } func testNowPlayingWithDefaultParametersReturnsMovies() async throws { let expectedResult = MoviePageableList.mock() apiClient.result = .success(expectedResult) let result = try await service.nowPlaying() XCTAssertEqual(result, expectedResult) XCTAssertEqual(apiClient.lastPath, MoviesEndpoint.nowPlaying().path) } func testNowPlayingReturnsMovies() async throws { let expectedResult = MoviePageableList.mock() apiClient.result = .success(expectedResult) let result = try await service.nowPlaying(page: nil) XCTAssertEqual(result, expectedResult) XCTAssertEqual(apiClient.lastPath, MoviesEndpoint.nowPlaying().path) } func testNowPlayingWithPageReturnsMovies() async throws { let expectedResult = MoviePageableList.mock() let page = expectedResult.page apiClient.result = .success(expectedResult) let result = try await service.nowPlaying(page: page) XCTAssertEqual(result, expectedResult) XCTAssertEqual(apiClient.lastPath, MoviesEndpoint.nowPlaying(page: page).path) } func testPopularWithDefaultParametersReturnsMovies() async throws { let expectedResult = MoviePageableList.mock() apiClient.result = .success(expectedResult) let result = try await service.popular() XCTAssertEqual(result, expectedResult) XCTAssertEqual(apiClient.lastPath, MoviesEndpoint.popular().path) } func testPopularReturnsMovies() async throws { let expectedResult = MoviePageableList.mock() apiClient.result = .success(expectedResult) let result = try await service.popular(page: nil) XCTAssertEqual(result, expectedResult) XCTAssertEqual(apiClient.lastPath, MoviesEndpoint.popular().path) } func testPopularWithPageReturnsMovies() async throws { let expectedResult = MoviePageableList.mock() let page = expectedResult.page apiClient.result = .success(expectedResult) let result = try await service.popular(page: page) XCTAssertEqual(result, expectedResult) XCTAssertEqual(apiClient.lastPath, MoviesEndpoint.popular(page: page).path) } func testTopRatedWithDefaultParametersReturnsMovies() async throws { let expectedResult = MoviePageableList.mock() apiClient.result = .success(expectedResult) let result = try await service.topRated() XCTAssertEqual(result, expectedResult) XCTAssertEqual(apiClient.lastPath, MoviesEndpoint.topRated().path) } func testTopRatedReturnsMovies() async throws { let expectedResult = MoviePageableList.mock() apiClient.result = .success(expectedResult) let result = try await service.topRated(page: nil) XCTAssertEqual(result, expectedResult) XCTAssertEqual(apiClient.lastPath, MoviesEndpoint.topRated().path) } func testTopRatedWithPageReturnsMovies() async throws { let expectedResult = MoviePageableList.mock() let page = expectedResult.page apiClient.result = .success(expectedResult) let result = try await service.topRated(page: page) XCTAssertEqual(result, expectedResult) XCTAssertEqual(apiClient.lastPath, MoviesEndpoint.topRated(page: page).path) } func testUpcomingWithDefaultParametersReturnsMovies() async throws { let expectedResult = MoviePageableList.mock() apiClient.result = .success(expectedResult) let result = try await service.upcoming() XCTAssertEqual(result, expectedResult) XCTAssertEqual(apiClient.lastPath, MoviesEndpoint.upcoming().path) } func testUpcomingReturnsMovies() async throws { let expectedResult = MoviePageableList.mock() apiClient.result = .success(expectedResult) let result = try await service.upcoming(page: nil) XCTAssertEqual(result, expectedResult) XCTAssertEqual(apiClient.lastPath, MoviesEndpoint.upcoming().path) } func testUpcomingWithPageReturnsMovies() async throws { let expectedResult = MoviePageableList.mock() let page = expectedResult.page apiClient.result = .success(expectedResult) let result = try await service.upcoming(page: page) XCTAssertEqual(result, expectedResult) XCTAssertEqual(apiClient.lastPath, MoviesEndpoint.upcoming(page: page).path) } }
// // VisitUserHeader.swift // Instagram // // Created by Fahad Almehawas on 7/4/17. // Copyright © 2017 Fahad Almehawas. All rights reserved. // // protocol VisitUserHeaderDelegate { func didTapUnfollowUser(userId: String, cell: VisitUserHeader) func didTapFollowersList() func didTapFollowingList() } import UIKit import Firebase class VisitUserHeader: UICollectionViewCell { override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .white setupviews() } var delegate: VisitUserHeaderDelegate? var user: Users? { didSet { userFullNameLabel.text = user?.userName guard let profilePhoto = user?.userProfileImageUrl else {return} userProfileImageView.loadImage(urlString: profilePhoto) checkIfFollowingUser() updatePostCount() updateFollowersLabel() updatefollowingLabel() } } let userProfileImageView: CustomImageView = { let imageView = CustomImageView() imageView.contentMode = .scaleAspectFill imageView.clipsToBounds = true imageView.layer.masksToBounds = true imageView.backgroundColor = .red return imageView }() let userFullNameLabel: UILabel = { let label = UILabel() label.text = "Testing username" label.font = UIFont.boldSystemFont(ofSize: 14) return label }() lazy var followProfileButton: UIButton = { let button = UIButton(type: .system) button.setTitleColor(.white, for: .normal) button.layer.borderWidth = 1 button.layer.cornerRadius = 5 button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 15) button.backgroundColor = UIColor.rgb(red: 80, green: 151, blue: 233) button.layer.borderColor = UIColor.clear.cgColor button.addTarget(self, action: #selector(handleFollow), for: .touchUpInside) return button }() let notificationsId = Database.database().reference().childByAutoId().key @objc func handleFollow() { guard let userid = user?.uid else {return} guard let currentUserUID = Auth.auth().currentUser?.uid else {return} let DatabaseRef = Database.database().reference().child("user").child(userid).child("followers") let value: [String: Any] = [currentUserUID: "follower"] DatabaseRef.updateChildValues(value) let followingValues = [userid: "following"] Database.database().reference().child("user").child(currentUserUID).child("following").updateChildValues(followingValues) self.followProfileButton.setTitle("Message", for: .normal) self.followProfileButton.setTitleColor(.black, for: .normal) self.followProfileButton.backgroundColor = UIColor.white self.followProfileButton.layer.borderColor = UIColor.lightGray.cgColor self.settingsButtons.backgroundColor = UIColor.white self.settingsButtons.tintColor = .black self.settingsButtons.layer.borderColor = UIColor.lightGray.cgColor let databaseNotificationRef = Database.database().reference().child("Notifications").child(userid).child(notificationsId) let notifValues = ["text": "Just followed you", "uid": currentUserUID, "notificationType": "Gained a Follower", "NotificationId": notificationsId] databaseNotificationRef.updateChildValues(notifValues) } func checkIfFollowingUser() { guard let userid = user?.uid else {return} guard let currentUserUID = Auth.auth().currentUser?.uid else {return} let DatabaseRef = Database.database().reference().child("user").child(userid).child("followers") DatabaseRef.observeSingleEvent(of: .value, with: { (snapshot) in if snapshot.hasChild(currentUserUID) { self.followProfileButton.setTitle("Message", for: .normal) self.followProfileButton.setTitleColor(.black, for: .normal) self.followProfileButton.backgroundColor = UIColor.white self.followProfileButton.layer.borderColor = UIColor.lightGray.cgColor self.settingsButtons.backgroundColor = UIColor.white self.settingsButtons.tintColor = .black self.settingsButtons.layer.borderColor = UIColor.lightGray.cgColor } else { self.followProfileButton.setTitle("Follow", for: .normal) self.followProfileButton.setTitleColor(.white, for: .normal) self.followProfileButton.layer.borderWidth = 1 self.followProfileButton.layer.cornerRadius = 5 self.followProfileButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: 15) self.followProfileButton.backgroundColor = UIColor.rgb(red: 80, green: 151, blue: 233) self.followProfileButton.layer.borderColor = UIColor.clear.cgColor self.settingsButtons.tintColor = .white self.settingsButtons.layer.borderWidth = 1 self.settingsButtons.layer.cornerRadius = 5 self.settingsButtons.layer.borderColor = UIColor.clear.cgColor self.settingsButtons.backgroundColor = UIColor.rgb(red: 80, green: 151, blue: 233) } }) { (err) in print("failed to follow user", err.localizedDescription) } } lazy var settingsButtons: UIButton = { let button = UIButton(type: .system) button.setImage(#imageLiteral(resourceName: "triangular-arrow-pointing-down").withRenderingMode(.alwaysTemplate), for: .normal) button.tintColor = .white button.layer.borderWidth = 1 button.layer.cornerRadius = 5 button.layer.borderColor = UIColor.clear.cgColor button.backgroundColor = UIColor.rgb(red: 80, green: 151, blue: 233) button.addTarget(self, action: #selector(self.handleUnfollowUser), for: .touchUpInside) return button }() let postLabel: UILabel = { let label = UILabel() label.text = "11\npost" label.numberOfLines = 0 label.font = UIFont.systemFont(ofSize: 14) label.textAlignment = .center return label }() lazy var followersLabel: UILabel = { let label = UILabel() label.text = "11\nfollowers" label.numberOfLines = 0 label.font = UIFont.systemFont(ofSize: 14) label.textAlignment = .center let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleNavigateToFollowers)) label.addGestureRecognizer(tapGesture) label.isUserInteractionEnabled = true return label }() lazy var followingLabel: UILabel = { let label = UILabel() label.text = "11\nfollowing" label.numberOfLines = 0 label.textAlignment = .center label.font = UIFont.systemFont(ofSize: 14) let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleNavigateToFollowing)) label.addGestureRecognizer(tapGesture) label.isUserInteractionEnabled = true return label }() let bioTextField: UITextView = { let textview = UITextView() textview.isEditable = false textview.isScrollEnabled = false textview.text = "Testing caption and stuff" return textview }() let gridButton: UIButton = { let button = UIButton(type: .system) button.setImage(#imageLiteral(resourceName: "menu").withRenderingMode(.alwaysTemplate), for: .normal) button.tintColor = UIColor.rgb(red: 80, green: 151, blue: 233) return button }() let listButton: UIButton = { let button = UIButton(type: .system) button.setImage(#imageLiteral(resourceName: "list").withRenderingMode(.alwaysTemplate), for: .normal) button.tintColor = .lightGray return button }() let bookMarkButton: UIButton = { let button = UIButton(type: .system) button.setImage(#imageLiteral(resourceName: "small-bookmark").withRenderingMode(.alwaysOriginal), for: .normal) return button }() let tagButton: UIButton = { let button = UIButton(type: .system) return button }() let bottomLineDivider: UIView = { let line = UIView() line.backgroundColor = .lightGray return line }() let topLineDivider: UIView = { let line = UIView() line.backgroundColor = .lightGray return line }() @objc func handleUnfollowUser() { if followProfileButton.title(for: .normal) == "Message" { guard let userId = user?.uid else {return} delegate?.didTapUnfollowUser(userId: userId, cell: self) } } func updatePostCount() { guard let uid = user?.uid else {return} let ref = Database.database().reference().child("posts").child(uid) ref.observe(.value, with: { (snapshot) in let postsCount: Int = Int(snapshot.childrenCount) let bookAttributedText = NSMutableAttributedString(string: "\(String(postsCount)) \n", attributes: [NSAttributedStringKey.foregroundColor : UIColor.black, NSAttributedStringKey.font : UIFont.boldSystemFont(ofSize: 14)]) bookAttributedText.append(NSMutableAttributedString(string: "posts", attributes: [NSAttributedStringKey.foregroundColor : UIColor.gray, NSAttributedStringKey.font: UIFont.systemFont(ofSize: 12)])) self.postLabel.attributedText = bookAttributedText }) } func updateFollowersLabel() { guard let uid = user?.uid else {return} guard let currentLoggedInUserId = Auth.auth().currentUser?.uid else {return} let followers: String = "followers" let ref = Database.database().reference().child("user").child(uid).child(followers) ref.observe(.value, with: { (snapshot) in let followersCount: Int = Int(snapshot.childrenCount) self.followersLabel.textColor = .white let bookAttributedText = NSMutableAttributedString(string: "\(String(followersCount)) \n", attributes: [NSAttributedStringKey.foregroundColor : UIColor.black, NSAttributedStringKey.font : UIFont.boldSystemFont(ofSize: 14)]) bookAttributedText.append(NSMutableAttributedString(string: "followers", attributes: [NSAttributedStringKey.foregroundColor : UIColor.gray, NSAttributedStringKey.font: UIFont.systemFont(ofSize: 12)])) self.followersLabel.attributedText = bookAttributedText }) } func updatefollowingLabel() { guard let uid = user?.uid else {return} let followers: String = "following" let ref = Database.database().reference().child("user").child(uid).child(followers) ref.observe(.value, with: { (snapshot) in let followersCount: Int = Int(snapshot.childrenCount) self.followingLabel.textColor = .white let bookAttributedText = NSMutableAttributedString(string: "\(String(followersCount)) \n", attributes: [NSAttributedStringKey.foregroundColor : UIColor.black, NSAttributedStringKey.font : UIFont.boldSystemFont(ofSize: 14)]) bookAttributedText.append(NSMutableAttributedString(string: "following", attributes: [NSAttributedStringKey.foregroundColor : UIColor.gray, NSAttributedStringKey.font: UIFont.systemFont(ofSize: 12)])) self.followingLabel.attributedText = bookAttributedText }) } @objc func handleNavigateToFollowers() { delegate?.didTapFollowersList() } @objc func handleNavigateToFollowing() { delegate?.didTapFollowingList() } func setupviews() { addSubview(userProfileImageView) addSubview(userFullNameLabel) addSubview(bioTextField) addSubview(bottomLineDivider) addSubview(topLineDivider) userProfileImageView.anchor(top: topAnchor, left: leftAnchor, bottom: nil, right: nil, paddingTop: 20, paddingLeft: 8, paddingBottom: 0, paddingRight: 0, width: 80, height: 80) userProfileImageView.layer.cornerRadius = 80 / 2 userFullNameLabel.anchor(top: userProfileImageView.bottomAnchor, left: userProfileImageView.leftAnchor, bottom: nil, right: nil, paddingTop: 8, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 0, height: 15) bioTextField.anchor(top: userFullNameLabel.bottomAnchor, left: userFullNameLabel.leftAnchor, bottom: nil, right: rightAnchor, paddingTop: 8, paddingLeft: 0, paddingBottom: 0, paddingRight: 4, width: 0, height: 0) setupInPutTextFields() } func setupInPutTextFields() { let stackview = UIStackView(arrangedSubviews: [postLabel, followersLabel, followingLabel]) let gridListStackView = UIStackView(arrangedSubviews: [gridButton, listButton, bookMarkButton]) stackview.axis = .horizontal stackview.spacing = 10 addSubview(stackview) addSubview(followProfileButton) addSubview(settingsButtons) addSubview(gridListStackView) addSubview(topLineDivider) addSubview(bottomLineDivider) stackview.anchor(top: userProfileImageView.topAnchor, left: userProfileImageView.rightAnchor, bottom: nil, right: rightAnchor, paddingTop: 0, paddingLeft: 8, paddingBottom: 0, paddingRight: 8, width: 0, height: 0) stackview.translatesAutoresizingMaskIntoConstraints = false followProfileButton.anchor(top: stackview.bottomAnchor, left: stackview.leftAnchor, bottom: nil, right: settingsButtons.leftAnchor, paddingTop: 8, paddingLeft: 0, paddingBottom: 0, paddingRight: 5, width: 0, height: 30) settingsButtons.anchor(top: followProfileButton.topAnchor, left: followProfileButton.rightAnchor, bottom: followProfileButton.bottomAnchor, right: rightAnchor, paddingTop: 0, paddingLeft: 8, paddingBottom: 0, paddingRight: 4, width: 40, height: 0) gridListStackView.axis = .horizontal gridListStackView.spacing = 10 gridListStackView.distribution = .fillEqually gridListStackView.anchor(top: nil, left: bioTextField.leftAnchor, bottom: bottomAnchor, right: bioTextField.rightAnchor, paddingTop: 0, paddingLeft: 10, paddingBottom: 0, paddingRight: 10, width: 0, height: 40) topLineDivider.anchor(top: nil, left: leftAnchor, bottom: gridListStackView.topAnchor, right: rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 2, paddingRight: 0, width: 0, height: 1) bottomLineDivider.anchor(top: gridListStackView.bottomAnchor, left: leftAnchor, bottom: nil, right: rightAnchor, paddingTop: 2, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 0, height: 1) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
// // MathUtils.swift // Prototipo1TFG // // Created by Arancha Ferrero Ortiz de Zárate on 26/6/18. // Copyright © 2018 Arancha Ferrero Ortiz de Zárate. All rights reserved. // import Foundation import CoreGraphics func + (firstPoint: CGPoint, secondPoint: CGPoint) -> CGPoint { return CGPoint(x: firstPoint.x + secondPoint.x, y: firstPoint.y + secondPoint.y) } func += (firstPoint: inout CGPoint, secondPoint: CGPoint) { firstPoint = firstPoint + secondPoint } func - (firstPoint: CGPoint, secondPoint: CGPoint) -> CGPoint { return CGPoint(x: firstPoint.x - secondPoint.x, y: firstPoint.y - secondPoint.y) } func -= (firstPoint: inout CGPoint, secondPoint: CGPoint) { firstPoint = firstPoint - secondPoint } func * (firstPoint: CGPoint, secondPoint: CGPoint) -> CGPoint { return CGPoint(x: firstPoint.x * secondPoint.x, y: firstPoint.y * secondPoint.y) } func *= (firstPoint: inout CGPoint, secondPoint: CGPoint) { firstPoint = firstPoint * secondPoint } func * (firstPoint: CGPoint, scalar: CGFloat) -> CGPoint { return CGPoint(x: firstPoint.x * scalar, y: firstPoint.y * scalar) } func *= (firstPoint: inout CGPoint, scalar: CGFloat) { firstPoint = firstPoint * scalar } func / (firstPoint: CGPoint, secondPoint: CGPoint) -> CGPoint { return CGPoint(x: firstPoint.x / secondPoint.x, y: firstPoint.y / secondPoint.y) } func /= (firstPoint: inout CGPoint, secondPoint: CGPoint) { firstPoint = firstPoint / secondPoint } func / (firstPoint: CGPoint, scalar: CGFloat) -> CGPoint { return CGPoint(x: firstPoint.x / scalar, y: firstPoint.y / scalar) } func /= (firstPoint: inout CGPoint, scalar: CGFloat) { firstPoint = firstPoint / scalar } // Solo se ejecuta si la app corre en 32 bits #if !(arch(x86_64) || arch(arm64)) func atan2(y: CGFloat, x: CGFloat) -> CGFloat { return CGFloat(atan2f(Float(y), Float(x))) } func sqrt(a: CGFloat) -> CGFloat { return CGFloat(sqrtf(Float(a))) } #endif extension CGPoint { func length() -> CGFloat { return sqrt(x*x+y*y) } func normalize() -> CGPoint { return self / length() } var angle : CGFloat { return atan2(y,x) } }
// // APITests.swift // Video Club AppTests // // Created by Rodrigo Camargo on 5/16/21. // import XCTest @testable import Video_Club_App class APITests: XCTestCase { func test_Api_Movies_ReturnsNotNil(){ var movieManager = MovieManager() movieManager.getMovies { (result, error) in XCTAssert(result!.movies.count > 0) XCTAssertNotNil(result) XCTAssertNil(error) } } func test_Api_Genres_ReturnsNotNil() { var genreManager = GenreManager() genreManager.getGenres { (result, error) in XCTAssertTrue(result!.genres.count > 0) XCTAssertNotNil(result) XCTAssertNil(error) } } func test_Api_MovieReviews_ReturnsNotNil() { var reviewManager = ReviewManager() reviewManager.getReviews("460465") { (result, error) in XCTAssertNotNil(result) XCTAssertNil(error) } } func test_Api_MovieReviews_ReturnsNil() { var reviewManager = ReviewManager() reviewManager.getReviews("1") { (result, error) in XCTAssertNil(result) XCTAssertNotNil(error) } } }
// // EventCreationRouter.swift // ChessAggregator // // Created by Administrator on 05.12.2020. // // import UIKit import SafariServices final class EventCreationRouter: BaseRouter { } extension EventCreationRouter: EventCreationRouterInput { func showRules() { let url = URL(string: "https://handbook.fide.com/chapter/E012018") ?? URL(string: "https://handbook.fide.com")! let rulesVC = SFSafariViewController(url: url) navigationController?.present(rulesVC, animated: true) } func closeCreation() { navigationController?.popToRootViewController(animated: true) } }
// // ImageCell.swift // Questions // // Created by 文川术 on 15/9/8. // Copyright (c) 2015年 xiaoyao. All rights reserved. // import UIKit class ImageCell: UITableViewCell { @IBOutlet weak var iconView: UIImageView! @IBOutlet weak var meanLabel: UILabel! func configureForImageCell(knowledge: Knowledge) { iconView.image = knowledge.Image meanLabel.textColor = UIColor.grayColor() meanLabel.text = knowledge.title } }
// // TestModels.swift // LocalizeWizTests // // Created by John Warmann on 2020-01-22. // Copyright © 2020 LocalizeWiz. All rights reserved. // import XCTest @testable import LocalizeWiz class TestModels: XCTestCase { var reader: FileReader! var decoder: JSONDecoder! var encoder: JSONEncoder! var bundle: Bundle! override func setUp() { decoder = JSONDecoder.wizDecoder encoder = JSONEncoder() reader = FileReader() bundle = Bundle(for: type(of: self)) // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testCreateProject() { let data = reader.readFile(fileName: "Project", ofType: "json", in: bundle)! let project = try! decoder.decode(Project.self, from: data) XCTAssertNotNil(project) } func testCreateProjectWithDetails() { let data = reader.readFile(fileName: "ProjectWithDetails", ofType: "json", in: bundle)! let project = try! decoder.decode(Project.self, from: data) XCTAssertNotNil(project) } func testCreateWorkspace() { let data = reader.readFile(fileName: "Workspace", ofType: "json", in: bundle)! let workspace = try! decoder.decode(Workspace.self, from: data) XCTAssertNotNil(workspace) } func testCreateLanguage() { let data = reader.readFile(fileName: "Language", ofType: "json", in: bundle)! let language = try! decoder.decode(Language.self, from: data) XCTAssertNotNil(language) } func testLocalizedStringEnvelope() { let data = reader.readFile(fileName: "LocalizedStringEnvelope", ofType: "json", in: bundle)! let envelope = try! decoder.decode(LocalizedStringEnvelope.self, from: data) XCTAssertNotNil(envelope) } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
// // Chapter3SetofStacks.swift // CtCI // // Created by Jordan Doczy on 2/19/21. // import Foundation class Chapter3SetofStacks { static func test() -> Bool { var stackSet = StackSet<Int>(threshold: 5) stackSet.push(LinkedNode(data: 1)) stackSet.push(LinkedNode(data: 2)) stackSet.push(LinkedNode(data: 3)) stackSet.push(LinkedNode(data: 4)) stackSet.push(LinkedNode(data: 5)) stackSet.push(LinkedNode(data: 6)) stackSet.push(LinkedNode(data: 7)) stackSet.push(LinkedNode(data: 8)) stackSet.push(LinkedNode(data: 9)) stackSet.push(LinkedNode(data: 10)) stackSet.push(LinkedNode(data: 11)) stackSet.push(LinkedNode(data: 12)) print(stackSet.stringValue) print("-pop-") while stackSet.isEmpty == false { _ = stackSet.pop() print(stackSet.stringValue) print("-pop-") } return true } } struct StackSet<T: Hashable & Comparable>: StackProtocol { private var stacks: [Stack<T>] = [] private var itemCount: Int = 0 private var topStackIndex: Int { return stacks.count - 1 } let threshold: Int var isEmpty: Bool { return stacks.isEmpty } var stringValue: String { var result = "" for i in 0..<stacks.count { result += "stacks[\(i)]= \(stacks[i].stringValue)\r" } return result } init(threshold: Int) { self.threshold = threshold } func peek() -> T? { return stacks[topStackIndex].peek() } mutating func pop() -> T? { let value = stacks[topStackIndex].pop() if stacks[topStackIndex].isEmpty { stacks.remove(at: topStackIndex) } itemCount = itemCount > 1 ? itemCount - 1 : 0 return value } // mutating func pop(at subStackIndex: Int) -> T? { // guard subStackIndex < stacks.count else { // return // } // let value = stacks[subStackIndex].pop() // return value // } mutating func push(_ node: LinkedNode<T>) { itemCount += 1 if Double(itemCount) / Double(threshold) > Double(stacks.count) { stacks.append(Stack<T>()) } stacks[topStackIndex].push(node) } }
// // FlashcardDetailViewController.swift // flashcards // // Created by Bryan Workman on 7/18/20. // Copyright © 2020 Bryan Workman. All rights reserved. // import UIKit import VisionKit class FlashcardDetailViewController: UIViewController, UINavigationControllerDelegate, UITextViewDelegate { //MARK: - Outlets @IBOutlet weak var frontTextView: UITextView! @IBOutlet weak var frontImageView: UIImageView! @IBOutlet weak var frontSelectImageLabel: UIButton! @IBOutlet weak var frontTextButtonOutlet: UIButton! @IBOutlet weak var frontPictureButtonOutlet: UIButton! @IBOutlet weak var frontPencilButtonOutlet: UIButton! @IBOutlet weak var backTextView: UITextView! @IBOutlet weak var backImageView: UIImageView! @IBOutlet weak var backSelectImageLabel: UIButton! @IBOutlet weak var backTextButtonOutlet: UIButton! @IBOutlet weak var backPictureButtonOutlet: UIButton! @IBOutlet weak var backPencilButtonOutlet: UIButton! @IBOutlet weak var frontPencilKitImageView: UIImageView! @IBOutlet weak var backPencilKitImageView: UIImageView! @IBOutlet weak var frontDrawSomethingButton: UIButton! @IBOutlet weak var backDrawSomethingButton: UIButton! @IBOutlet weak var frontViewView: UIView! @IBOutlet weak var backViewView: UIView! @IBOutlet weak var saveButton: UIBarButtonItem! //MARK: - Properties var flashcard: Flashcard? var flashpile: Flashpile? var frontTextIsSelected = false var frontPictureIsSelected = false var frontPencilIsSelected = false var backTextIsSelected = false var backPictureIsSelected = false var backPencilIsSelected = false var frontImagePickerSelected = true var isFrontPencil = true var frontPKImageSelected = false var backPKImageSelected = false var frontImg = UIImage() { didSet { frontPencilIsSelected = true frontPKImageSelected = true } } var backImg = UIImage() { didSet { backPencilIsSelected = true backPKImageSelected = true } } //MARK: - Lifecycles override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = .bgTan saveButton.isEnabled = true let tap = UITapGestureRecognizer(target: self.view, action: #selector(UIView.endEditing)) view.addGestureRecognizer(tap) if let flashcard = flashcard { updateViews(flashcard: flashcard) } else { frontTextSelected() backTextSelected() } setupTextViews() } override func viewDidLayoutSubviews() { frontViewView.layer.cornerRadius = 15.0 frontViewView.clipsToBounds = true backViewView.layer.cornerRadius = 15.0 backViewView.clipsToBounds = true frontViewView.layer.shadowColor = UIColor.gray.cgColor frontViewView.layer.shadowOffset = CGSize(width: 0, height: 2.0) frontViewView.layer.shadowRadius = 2.0 frontViewView.layer.shadowOpacity = 1.0 frontViewView.layer.masksToBounds = false frontViewView.layer.shadowPath = UIBezierPath(roundedRect: frontViewView.bounds, cornerRadius: frontViewView.layer.cornerRadius).cgPath backViewView.layer.shadowColor = UIColor.gray.cgColor backViewView.layer.shadowOffset = CGSize(width: 0, height: 2.0) backViewView.layer.shadowRadius = 2.0 backViewView.layer.shadowOpacity = 1.0 backViewView.layer.masksToBounds = false backViewView.layer.shadowPath = UIBezierPath(roundedRect: backViewView.bounds, cornerRadius: backViewView.layer.cornerRadius).cgPath frontViewView.layer.borderWidth = 2.0 frontViewView.layer.cornerRadius = 15.0 //guard let canvaBlue = UIColor.canvaBlue else {return} frontViewView.layer.borderColor = UIColor.canvaBlue.cgColor backViewView.layer.borderWidth = 2.0 backViewView.layer.cornerRadius = 15.0 backViewView.layer.borderColor = UIColor.canvaBlue.cgColor } //MARK: - Actions @IBAction func unwindToDetail(_ sender: UIStoryboardSegue) { if isFrontPencil { frontPencilKitImageView.image = frontImg frontDrawSomethingButton.setTitle("", for: .normal) } else { backPencilKitImageView.image = backImg backDrawSomethingButton.setTitle("", for: .normal) } } @IBAction func saveButtonTapped(_ sender: Any) { guard let flashpile = flashpile else {return} saveButton.isEnabled = false var frontString: String? var backString: String? var frontPhoto: UIImage? var backPhoto: UIImage? var frontIsPKImage: Bool = frontPKImageSelected var backIsPKImage: Bool = backPKImageSelected if frontTextIsSelected { guard let frontText = frontTextView.text, !frontText.isEmpty else {return} frontString = frontText frontIsPKImage = false } else if frontPictureIsSelected { guard let frontImage = frontImageView.image else {return} frontPhoto = frontImage frontIsPKImage = false } else { guard let frontImage = frontPencilKitImageView.image else {return} frontPhoto = frontImage frontIsPKImage = true } if backTextIsSelected { guard let backText = backTextView.text, !backText.isEmpty else {return} backString = backText backIsPKImage = false } else if backPictureIsSelected { guard let backImage = backImageView.image else {return} backPhoto = backImage backIsPKImage = false } else { guard let backImage = backPencilKitImageView.image else {return} backPhoto = backImage backIsPKImage = true } if let flashcard = flashcard { FlashcardController.shared.updateFlashcard(flashcard: flashcard, frontString: frontString, backString: backString, frontIsPKImage: frontIsPKImage, backIsPKImage: backIsPKImage, frontPhoto: frontPhoto, backPhoto: backPhoto) { (result) in DispatchQueue.main.async { switch result { case .success(_): self.navigationController?.popViewController(animated: true) case .failure(let error): print("There was an error updating the flashcard -- \(error) -- \(error.localizedDescription)") } } } } else { FlashcardController.shared.createFlashcard(frontString: frontString, backString: backString, frontIsPKImage: frontIsPKImage, backIsPKImage: backIsPKImage, frontPhoto: frontPhoto, backPhoto: backPhoto, flashpile: flashpile) { (result) in DispatchQueue.main.async { switch result { case .success(let flashcard): flashpile.flashcards.append(flashcard) FlashcardController.shared.totalFlashcards.append(flashcard) self.navigationController?.popViewController(animated: true) case .failure(let error): print("There was an error creating flashcard -- \(error) -- \(error.localizedDescription)") } } } } } @IBAction func cancelButtonTapped(_ sender: Any) { self.navigationController?.popViewController(animated: true) } @IBAction func frontTextButtonTapped(_ sender: Any) { frontTextSelected() } @IBAction func frontPictureButtonTapped(_ sender: Any) { frontPictureSelected() } @IBAction func frontPencilButtonTapped(_ sender: Any) { frontPencilSelected() } @IBAction func backTextButtonTapped(_ sender: Any) { backTextSelected() } @IBAction func backPictureButtonTapped(_ sender: Any) { backPictureSelected() } @IBAction func backPencilButtonTapped(_ sender: Any) { backPencilSelected() } @IBAction func frontDrawSomethingTapped(_ sender: Any) { isFrontPencil = true } @IBAction func backDrawSomethingTapped(_ sender: Any) { isFrontPencil = false } @IBAction func frontSelectImageTapped(_ sender: Any) { frontImagePickerSelected = true let alertController = UIAlertController(title: "Select an image", message: "From where would you like to select an image?", preferredStyle: .alert) let cameraAction = UIAlertAction(title: "Camera", style: .default) { (_) in let imagePickerController = UIImagePickerController() imagePickerController.delegate = self imagePickerController.sourceType = .camera self.present(imagePickerController, animated: true, completion: nil) } let libraryAction = UIAlertAction(title: "Photo Library", style: .default) { (_) in let imagePickerController = UIImagePickerController() imagePickerController.delegate = self imagePickerController.sourceType = .photoLibrary self.present(imagePickerController, animated: true, completion: nil) } let scanDocAction = UIAlertAction(title: "Scan Document", style: .default) { (_) in let scanningDocumentVC = VNDocumentCameraViewController() scanningDocumentVC.delegate = self self.present(scanningDocumentVC, animated: true, completion: nil) } let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) alertController.addAction(cameraAction) alertController.addAction(libraryAction) alertController.addAction(scanDocAction) alertController.addAction(cancelAction) present(alertController, animated: true) } @IBAction func backSelectImageTapped(_ sender: Any) { frontImagePickerSelected = false let alertController = UIAlertController(title: "Select an image", message: "From where would you like to select an image?", preferredStyle: .alert) let cameraAction = UIAlertAction(title: "Camera", style: .default) { (_) in let imagePickerController = UIImagePickerController() imagePickerController.delegate = self imagePickerController.sourceType = .camera self.present(imagePickerController, animated: true, completion: nil) } let libraryAction = UIAlertAction(title: "Photo Library", style: .default) { (_) in let imagePickerController = UIImagePickerController() imagePickerController.delegate = self imagePickerController.sourceType = .photoLibrary self.present(imagePickerController, animated: true, completion: nil) } let scanDocAction = UIAlertAction(title: "Scan Document", style: .default) { (_) in let scanningDocumentVC = VNDocumentCameraViewController() scanningDocumentVC.delegate = self self.present(scanningDocumentVC, animated: true, completion: nil) } let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) alertController.addAction(cameraAction) alertController.addAction(libraryAction) alertController.addAction(scanDocAction) alertController.addAction(cancelAction) present(alertController, animated: true) } //MARK: - Helper Methods func updateViews(flashcard: Flashcard) { if let frontString = flashcard.frontString { frontTextSelected() frontTextView.text = frontString } else if let frontPhoto = flashcard.frontPhoto { if flashcard.frontIsPKImage == false { frontPictureSelected() frontSelectImageLabel.setTitle("", for: .normal) frontImageView.image = frontPhoto } else { frontImg = frontPhoto frontPencilSelected() frontPencilKitImageView.image = frontPhoto frontDrawSomethingButton.setTitle("", for: .normal) } } if let backString = flashcard.backString { backTextSelected() backTextView.text = backString } else if let backPhoto = flashcard.backPhoto { if flashcard.backIsPKImage == false { backPictureSelected() backSelectImageLabel.setTitle("", for: .normal) backImageView.image = backPhoto } else { backImg = backPhoto backPencilSelected() backPencilKitImageView.image = backPhoto backDrawSomethingButton.setTitle("", for: .normal) } } } func setupTextViews() { frontTextView.delegate = self backTextView.delegate = self if frontTextView.text.isEmpty { frontTextView.text = "front text..." frontTextView.textColor = UIColor.lightGray } if backTextView.text.isEmpty { backTextView.text = "back text..." backTextView.textColor = UIColor.lightGray } } func textViewDidBeginEditing(_ textView: UITextView) { if textView.textColor == UIColor.lightGray { textView.text = nil textView.textColor = UIColor.black } } func textViewDidEndEditing(_ textView: UITextView) { if textView.text.isEmpty { if textView == frontTextView { textView.text = "front text..." } else if textView == backTextView { textView.text = "back text..." } textView.textColor = UIColor.lightGray } } func frontTextSelected() { frontTextIsSelected = true frontPictureIsSelected = false frontPencilIsSelected = false frontPKImageSelected = false frontTextView.isHidden = false frontImageView.isHidden = true frontSelectImageLabel.isHidden = true frontPencilKitImageView.isHidden = true frontDrawSomethingButton.isHidden = true frontTextButtonOutlet.tintColor = #colorLiteral(red: 0.09019608051, green: 0, blue: 0.3019607961, alpha: 1) frontTextButtonOutlet.setPreferredSymbolConfiguration(.init(pointSize: 25.0, weight: .bold), forImageIn: .normal) frontPictureButtonOutlet.tintColor = .systemBlue frontPictureButtonOutlet.setPreferredSymbolConfiguration(.init(pointSize: 21.0, weight: .unspecified), forImageIn: .normal) frontPencilButtonOutlet.tintColor = .systemBlue frontPencilButtonOutlet.setPreferredSymbolConfiguration(.init(pointSize: 22.0, weight: .unspecified), forImageIn: .normal) } func frontPictureSelected() { frontTextIsSelected = false frontPictureIsSelected = true frontPencilIsSelected = false frontPKImageSelected = false frontTextView.isHidden = true frontImageView.isHidden = false frontSelectImageLabel.isHidden = false frontPencilKitImageView.isHidden = true frontDrawSomethingButton.isHidden = true frontTextButtonOutlet.tintColor = .systemBlue frontTextButtonOutlet.setPreferredSymbolConfiguration(.init(pointSize: 22.0, weight: .unspecified), forImageIn: .normal) frontPictureButtonOutlet.tintColor = #colorLiteral(red: 0.1215686277, green: 0.01176470611, blue: 0.4235294163, alpha: 1) frontPictureButtonOutlet.setPreferredSymbolConfiguration(.init(pointSize: 25.0, weight: .bold), forImageIn: .normal) frontPencilButtonOutlet.tintColor = .systemBlue frontPencilButtonOutlet.setPreferredSymbolConfiguration(.init(pointSize: 22.0, weight: .unspecified), forImageIn: .normal) } func frontPencilSelected() { frontTextIsSelected = false frontPictureIsSelected = false frontPencilIsSelected = true frontPKImageSelected = true frontTextView.isHidden = true frontImageView.isHidden = true frontSelectImageLabel.isHidden = true frontPencilKitImageView.isHidden = false frontDrawSomethingButton.isHidden = false frontTextButtonOutlet.tintColor = .systemBlue frontTextButtonOutlet.setPreferredSymbolConfiguration(.init(pointSize: 22.0, weight: .unspecified), forImageIn: .normal) frontPictureButtonOutlet.tintColor = .systemBlue frontPictureButtonOutlet.setPreferredSymbolConfiguration(.init(pointSize: 21.0, weight: .unspecified), forImageIn: .normal) frontPencilButtonOutlet.tintColor = #colorLiteral(red: 0.1215686277, green: 0.01176470611, blue: 0.4235294163, alpha: 1) frontPencilButtonOutlet.setPreferredSymbolConfiguration(.init(pointSize: 25.0, weight: .bold), forImageIn: .normal) } func backTextSelected() { backTextIsSelected = true backPictureIsSelected = false backPencilIsSelected = false backPKImageSelected = false backTextView.isHidden = false backImageView.isHidden = true backSelectImageLabel.isHidden = true backPencilKitImageView.isHidden = true backDrawSomethingButton.isHidden = true backTextButtonOutlet.tintColor = #colorLiteral(red: 0.09019608051, green: 0, blue: 0.3019607961, alpha: 1) backTextButtonOutlet.setPreferredSymbolConfiguration(.init(pointSize: 25.0, weight: .bold), forImageIn: .normal) backPictureButtonOutlet.tintColor = .systemBlue backPictureButtonOutlet.setPreferredSymbolConfiguration(.init(pointSize: 21.0, weight: .unspecified), forImageIn: .normal) backPencilButtonOutlet.tintColor = .systemBlue backPencilButtonOutlet.setPreferredSymbolConfiguration(.init(pointSize: 22.0, weight: .unspecified), forImageIn: .normal) } func backPictureSelected() { backTextIsSelected = false backPictureIsSelected = true backPencilIsSelected = false backPKImageSelected = false backTextView.isHidden = true backImageView.isHidden = false backSelectImageLabel.isHidden = false backPencilKitImageView.isHidden = true backDrawSomethingButton.isHidden = true backTextButtonOutlet.tintColor = .systemBlue backTextButtonOutlet.setPreferredSymbolConfiguration(.init(pointSize: 22.0, weight: .unspecified), forImageIn: .normal) backPictureButtonOutlet.tintColor = #colorLiteral(red: 0.1215686277, green: 0.01176470611, blue: 0.4235294163, alpha: 1) backPictureButtonOutlet.setPreferredSymbolConfiguration(.init(pointSize: 25.0, weight: .bold), forImageIn: .normal) backPencilButtonOutlet.tintColor = .systemBlue backPencilButtonOutlet.setPreferredSymbolConfiguration(.init(pointSize: 22.0, weight: .unspecified), forImageIn: .normal) } func backPencilSelected() { backTextIsSelected = false backPictureIsSelected = false backPencilIsSelected = true backPKImageSelected = true backTextView.isHidden = true backImageView.isHidden = true backSelectImageLabel.isHidden = true backPencilKitImageView.isHidden = false backDrawSomethingButton.isHidden = false backTextButtonOutlet.tintColor = .systemBlue backTextButtonOutlet.setPreferredSymbolConfiguration(.init(pointSize: 22.0, weight: .unspecified), forImageIn: .normal) backPictureButtonOutlet.tintColor = .systemBlue backPictureButtonOutlet.setPreferredSymbolConfiguration(.init(pointSize: 21.0, weight: .unspecified), forImageIn: .normal) backPencilButtonOutlet.tintColor = #colorLiteral(red: 0.1215686277, green: 0.01176470611, blue: 0.4235294163, alpha: 1) backPencilButtonOutlet.setPreferredSymbolConfiguration(.init(pointSize: 25.0, weight: .bold), forImageIn: .normal) } //MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "toPencilKitView" { guard let destinationVC = segue.destination as? PencilViewController else {return} destinationVC.isFrontPencil = isFrontPencil } } } //End of class extension FlashcardDetailViewController: UIImagePickerControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { guard let selectedImage = info[.originalImage] as? UIImage else {return} if frontImagePickerSelected { frontSelectImageLabel.setTitle("", for: .normal) frontImageView.image = selectedImage } else { backSelectImageLabel.setTitle("", for: .normal) backImageView.image = selectedImage } dismiss(animated: true, completion: nil) } } //End of extension extension FlashcardDetailViewController: VNDocumentCameraViewControllerDelegate { func documentCameraViewController(_ controller: VNDocumentCameraViewController, didFinishWith scan: VNDocumentCameraScan) { for pageNumber in 0..<scan.pageCount { let image = scan.imageOfPage(at: pageNumber) if frontImagePickerSelected { frontSelectImageLabel.setTitle("", for: .normal) frontImageView.image = image } else { backSelectImageLabel.setTitle("", for: .normal) backImageView.image = image } } controller.dismiss(animated: true, completion: nil) } } //End of extension
import Foundation struct JSONCodingKeys: CodingKey { var stringValue: String init?(stringValue: String) { self.stringValue = stringValue } var intValue: Int? init?(intValue: Int) { self.init(stringValue: "\(intValue)") self.intValue = intValue } } extension KeyedDecodingContainer { func decode(_ type: [String: Any].Type, forKey key: K) throws -> [String: Any] { let container = try nestedContainer(keyedBy: JSONCodingKeys.self, forKey: key) return try container.decode(type) } func decodeIfPresent(_ type: [String: Any].Type, forKey key: K) throws -> [String: Any]? { guard contains(key) else { return nil } guard try decodeNil(forKey: key) == false else { return nil } return try decode(type, forKey: key) } func decode(_ type: [Any].Type, forKey key: K) throws -> [Any] { var container = try nestedUnkeyedContainer(forKey: key) return try container.decode(type) } func decodeIfPresent(_ type: [Any].Type, forKey key: K) throws -> [Any]? { guard contains(key) else { return nil } guard try decodeNil(forKey: key) == false else { return nil } return try decode(type, forKey: key) } func decode(_: [String: Any].Type) throws -> [String: Any] { var dictionary = [String: Any]() for key in allKeys { if let boolValue = try? decode(Bool.self, forKey: key) { dictionary[key.stringValue] = boolValue } else if let stringValue = try? decode(String.self, forKey: key) { dictionary[key.stringValue] = stringValue } else if let intValue = try? decode(Int.self, forKey: key) { dictionary[key.stringValue] = intValue } else if let doubleValue = try? decode(Double.self, forKey: key) { dictionary[key.stringValue] = doubleValue } else if let nestedDictionary = try? decode([String: Any].self, forKey: key) { dictionary[key.stringValue] = nestedDictionary } else if let nestedArray = try? decode([Any].self, forKey: key) { dictionary[key.stringValue] = nestedArray } } return dictionary } } extension UnkeyedDecodingContainer { mutating func decode(_: [Any].Type) throws -> [Any] { var array: [Any] = [] while isAtEnd == false { // See if the current value in the JSON array is `null` first and prevent infite recursion with nested arrays. if try decodeNil() { continue } else if let value = try? decode(Bool.self) { array.append(value) } else if let value = try? decode(Double.self) { array.append(value) } else if let value = try? decode(String.self) { array.append(value) } else if let nestedDictionary = try? decode([String: Any].self) { array.append(nestedDictionary) } else if let nestedArray = try? decode([Any].self) { array.append(nestedArray) } } return array } mutating func decode(_ type: [String: Any].Type) throws -> [String: Any] { let nestedContainer = try self.nestedContainer(keyedBy: JSONCodingKeys.self) return try nestedContainer.decode(type) } } extension KeyedEncodingContainerProtocol where Key == JSONCodingKeys { mutating func encode(_ value: [String: Any]) throws { try value.forEach { key, value in if let key = JSONCodingKeys(stringValue: key) { switch value { case let value as Bool: try encode(value, forKey: key) case let value as Int: try encode(value, forKey: key) case let value as String: try encode(value, forKey: key) case let value as Double: try encode(value, forKey: key) case let value as [String: Any]: try encode(value, forKey: key) case let value as [Any]: try encode(value, forKey: key) // case Any?.none: // try encodeNil(forKey: key) default: throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: codingPath + [key], debugDescription: "Invalid JSON value")) } } } } } public extension KeyedEncodingContainerProtocol { mutating func encode(_ value: [String: Any]?, forKey key: Key) throws { if value != nil { var container = nestedContainer(keyedBy: JSONCodingKeys.self, forKey: key) try container.encode(value!) } } mutating func encode(_ value: [Any]?, forKey key: Key) throws { if value != nil { var container = nestedUnkeyedContainer(forKey: key) try container.encode(value!) } } } public extension UnkeyedEncodingContainer { mutating func encode(_ value: [Any]) throws { try value.enumerated().forEach { index, value in switch value { case let value as Bool: try encode(value) case let value as Int: try encode(value) case let value as String: try encode(value) case let value as Double: try encode(value) case let value as [String: Any]: try encode(value) case let value as [Any]: try encode(value) // case Any?.none: // try encodeNil() default: let keys = JSONCodingKeys(intValue: index).map { [$0] } ?? [] throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: codingPath + keys, debugDescription: "Invalid JSON value")) } } } mutating func encode(_ value: [String: Any]) throws { var nestedContainer = self.nestedContainer(keyedBy: JSONCodingKeys.self) try nestedContainer.encode(value) } } extension UserDefaults { func set<T: Encodable>(encodable: T, forKey key: String) { if let data = try? JSONEncoder().encode(encodable) { set(data, forKey: key) } } func value<T: Decodable>(_ type: T.Type, forKey key: String) -> T? { if let data = object(forKey: key) as? Data, let value = try? JSONDecoder().decode(type, from: data) { return value } return nil } }
import Combine protocol CharacterStorable { func fetchCharacters() -> AnyPublisher<[Character], Never> } class CharacterStore: CharacterStorable { private let service: CharacterServiceable init(service: CharacterServiceable) { self.service = service } func fetchCharacters() -> AnyPublisher<[Character], Never> { service.fetchCharacters() } }
// // SignInViewController.swift // ToDoBackend // // Created by siddharth on 14/02/19. // Copyright © 2019 clarionTechnologies. All rights reserved. // import UIKit import Firebase class SignInViewController: UIViewController { @IBOutlet weak var usernameField: UITextField! @IBOutlet weak var passwordField: UITextField! @IBOutlet weak var signInButton: UIButton! @IBOutlet weak var viewBelowUsername: UIView! @IBOutlet weak var viewBelowPassword: UIView! @IBOutlet weak var forgotPasswordButton: UIButton! override func viewDidLoad() { super.viewDidLoad() setRoundedFields() addImageToTextField() } @IBAction func signInButton(_ sender: Any) { loginUser() } @IBAction func forgotPasswordButton(_ sender: Any) { setupForgotPasswordPrompt() } } extension SignInViewController { func loginUser(){ let email = usernameField.text let password = passwordField.text Auth.auth().signIn(withEmail: email!, password: password!, completion: { (user, error) in guard let _ = user else { if let error = error { if let errCode = AuthErrorCode(rawValue: error._code) { switch errCode { case .userNotFound: self.showAlert("User account not found. Try registering") case .wrongPassword: self.showAlert("Incorrect username/password combination") default: self.showAlert("Error: \(error.localizedDescription)") } } } assertionFailure("user and error are nil") return } self.signIn() }) } func setupForgotPasswordPrompt() { let prompt = UIAlertController(title: "ToDo App", message: "Email:", preferredStyle: .alert) let okaction = UIAlertAction(title: "Okay", style: .default) { (action) in let userInputs = prompt.textFields![0].text if (userInputs!.isEmpty) { return } Auth.auth().sendPasswordReset(withEmail: userInputs!, completion: {(error) in if let error = error { if let errCode = AuthErrorCode(rawValue: error._code) { switch errCode { case .userNotFound: DispatchQueue.main.async { self.showAlert("User account not found. Try registering") } default: DispatchQueue.main.async { self.showAlert("Error: \(error.localizedDescription)") } } } return } else { DispatchQueue.main.async { self.showAlert("You'll receive an email shortly to reset your password.") } } }) } prompt.addTextField(configurationHandler: nil) prompt.addAction(okaction) present(prompt, animated: true, completion: nil) } func showAlert(_ message: String) { let alertController = UIAlertController(title: "To Do App", message: message, preferredStyle: UIAlertController.Style.alert) alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertAction.Style.default,handler: nil)) self.present(alertController, animated: true, completion: nil) } func signIn() { performSegue(withIdentifier: "signInFromSignInSegue", sender: nil) } } extension SignInViewController { func setRoundedFields(){ usernameField.clipsToBounds = true usernameField.layer.cornerRadius = 15 passwordField.clipsToBounds = true passwordField.layer.cornerRadius = 15 viewBelowUsername.clipsToBounds = true viewBelowUsername.layer.cornerRadius = 15 viewBelowPassword.clipsToBounds = true viewBelowPassword.layer.cornerRadius = 15 signInButton.clipsToBounds = true signInButton.layer.cornerRadius = 15 viewBelowUsername.backgroundColor = UIColor.white.withAlphaComponent(0.45) viewBelowPassword.backgroundColor = UIColor.white.withAlphaComponent(0.45) } func addImageToTextField(){ addImageToPasswordField() addImageToUsernameField() } func addImageToUsernameField(){ let imageView = UIImageView() let image = UIImage(named: "email") imageView.image = image imageView.frame = CGRect(x: 0, y: 0, width: 50, height: 17) imageView.contentMode = .scaleAspectFit usernameField.leftViewMode = UITextField.ViewMode.always usernameField.leftView = imageView usernameField.addSubview(imageView) } func addImageToPasswordField(){ let imageView = UIImageView() let image = UIImage(named: "password") imageView.image = image imageView.frame = CGRect(x: 0, y: 0, width: 50, height: 17) imageView.contentMode = .scaleAspectFit passwordField.leftViewMode = UITextField.ViewMode.always passwordField.leftView = imageView passwordField.addSubview(imageView) } }
// // BasketTotalTableViewCell.swift // eDairy // // Created by Daniel Bolivar herrera on 4/10/17. // Copyright © 2017 R3PI. All rights reserved. // import UIKit public let basketTotalCellId = "basketTotalCellId" class BasketTotalTableViewCell: UITableViewCell { @IBOutlet weak var totalPrice: UILabel! @IBOutlet weak var checkOutButton: UIButton! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
// // GameOfLife.swift // GameOfLife // // Created by Mattias Jähnke on 2015-07-27. // Copyright © 2015 nearedge. All rights reserved. // import Foundation protocol GameOfLifeMatrix: Equatable { var width: Int { get } var height: Int { get } var activeCells: Set<Point> { get } var isEmpty: Bool { get } init(width: Int, height: Int, active: Set<Point>) subscript(point: Point) -> Bool { get set } } struct Point: Hashable, Equatable { let x: Int, y: Int init(x: Int = 0, y: Int = 0) { self.x = x self.y = y } var hashValue: Int { return "\(x.hashValue)\(y.hashValue)".hashValue } } func ==(lhs: Point, rhs: Point) -> Bool { return lhs.hashValue == rhs.hashValue } extension GameOfLifeMatrix { func contains(_ point: Point) -> Bool { return point.x >= 0 && point.y >= 0 && point.x <= width - 1 && point.y <= height - 1 } subscript(x: Int, y: Int) -> Bool { get { return self[Point(x: x, y: y)] } set { self[Point(x: x, y: y)] = newValue } } } extension GameOfLifeMatrix { func incrementedGeneration() -> Self { var next = Self.init(width: width, height: height, active: []) var processed = Set<Point>() for cell in activeCells { next[cell] = fate(cell) // Determine the fate for the the "inactive" neighbours for inactive in cell.adjecentPoints.filter({ self.contains($0) && !self[$0] }) { guard !processed.contains(inactive) else { continue } next[inactive] = fate(inactive) processed.insert(inactive) } } return next } fileprivate func fate(_ point: Point) -> Bool { let activeNeighbours = point.adjecentPoints.filter { self.contains($0) && self[$0] }.count switch activeNeighbours { case 3 where self[point] == false: // Dead cell comes alive return true case 2..<4 where self[point] == true: // Lives on return true default: // Under- or over-population, dies return false } } } // Move private extension Point { var adjecentPoints: Set<Point> { return [left, leftUp, up, rightUp, right, rightDown, down, leftDown] } var left: Point { return Point(x: x - 1, y: y) } var leftUp: Point { return Point(x: x - 1, y: y - 1) } var up: Point { return Point(x: x, y: y - 1) } var rightUp: Point { return Point(x: x + 1, y: y - 1) } var right: Point { return Point(x: x + 1, y: y) } var rightDown: Point { return Point(x: x + 1, y: y + 1) } var down: Point { return Point(x: x, y: y + 1) } var leftDown: Point { return Point(x: x - 1, y: y + 1) } }
// // UINavigationController+Ext.swift // Umbrella // // Created by Lucas Correa on 14/01/2019. // Copyright © 2019 Security First. All rights reserved. // import UIKit extension UINavigationController { func removeAnyViewControllers(ofKind kind: AnyClass) { self.viewControllers = self.viewControllers.filter { !$0.isKind(of: kind)} } func containsViewController(ofKind kind: AnyClass) -> Bool { return self.viewControllers.contains(where: { $0.isKind(of: kind) }) } }
// // weatherDetailVC.swift // PTJ3_Weather_Practice // // Created by mong on 08/02/2019. // Copyright © 2019 mong. All rights reserved. // import Foundation import UIKit class WeatherDatilVC: UIViewController { var rain: String = "" var temp: String = "" var state: String = "" var city: String = "" var stateNum: Int? var weather: UIImage? @IBOutlet var weather_img: UIImageView! @IBOutlet var weather_lb: UILabel! @IBOutlet var temp_lb: UILabel! @IBOutlet var rain_lb: UILabel! func selectWeather(_ state: Int) -> String{ switch state { case 10: return "맑음" case 11: return "흐림" case 12: return "비" case 13: return "눈" default: return "불러올 수 없음!" } } override func viewDidLoad() { rain_lb.text = rain temp_lb.text = temp weather_img.image = weather weather_lb.text = selectWeather(stateNum!) navigationItem.title = city } }
// // DeveloperTableViewCell.swift // Rent A Dev // // Created by Dharmendra Valiya on 05/12/20. // Copyright © 2020 Dharmendra Valiya All rights reserved. // import UIKit class DeveloperTableViewCell: UITableViewCell { @IBOutlet weak var avatarImageView: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var expertiseLabel: UILabel! override func layoutSubviews() { super.layoutSubviews() avatarImageView.contentMode = UIView.ContentMode.scaleAspectFit avatarImageView.clipsToBounds = true } func bindData(with developer:Developer) { avatarImageView.image = developer.avatarImg nameLabel.text = developer.name expertiseLabel.text = developer.expertise } }
// // UImageViewExtension.swift // PasswordStorage // // Created by João Paulo dos Anjos on 02/02/18. // Copyright © 2018 Joao Paulo Cavalcante dos Anjos. All rights reserved. // import UIKit import Kingfisher extension UIImageView { func loadImageWithAuthorization(url: String) { let url = URL(string: "https://dev.people.com.ai/mobile/api/v2/logo/\(url)") let modifier = AnyModifier { request in var r = request r.setValue(User.logged.token!, forHTTPHeaderField: "authorization") return r } self.kf.setImage(with: url, options: [.requestModifier(modifier)]) { (image, error, type, url) in if error == nil && image != nil { DispatchQueue.main.async { self.image = image } } else { DispatchQueue.main.async { self.image = UIImage(named: "ic_image_galery") } } } } }
// // TableCellHeightProtocol.swift // AppExtension // // Created by ZJaDe on 2018/12/7. // Copyright © 2018 ZJaDe. All rights reserved. // import Foundation public enum CellHeightLayoutType { case neverLayout case hasLayout case resetLayout var isNeedLayout: Bool { self != .hasLayout } } /** ZJaDe: 使用item来存储高度 如果改成用tableView根据indexPath来存储高度,刷新时需要清空高度缓存,不可取 */ protocol TableCellHeightProtocol: AssociatedObjectProtocol { /// ZJaDe: 计算高度 func calculateCellHeight(_ tableView: UITableView, wait: Bool) func updateHeight(_ closure: (() -> Void)?) } private var cellHeightKey: UInt8 = 0 extension TableCellHeightProtocol { var tempCellHeight: CGFloat { associatedObject(&cellHeightKey, createIfNeed: 0) } func changeTempCellHeight(_ newValue: CGFloat) { setAssociatedObject(&cellHeightKey, newValue) } var cellHeightLayoutType: CellHeightLayoutType { switch self.tempCellHeight { case 0: return .neverLayout case ..<0: return .resetLayout case _: return .hasLayout } } func _setNeedResetCellHeight() { self.changeTempCellHeight(-1) } }
// // PersonalGroupsTableViewController.swift // SocialApp // // Created by Дима Давыдов on 02.10.2020. // import UIKit import RealmSwift import os.log class FriendsTableViewController: UITableViewController { @IBOutlet weak var searchBar: UISearchBar! var userFriends: Results<FriendsRealmModel>? var indexedUsers = [[FriendsRealmModel]]() var sections = [String]() private var notificationToken: NotificationToken? override func viewDidLoad() { super.viewDidLoad() tableView.delaysContentTouches = false searchBar.delegate = self fetchUserFollowers() } private func fetchUserFollowers() { userFriends = FriendsDataProvider.shared.getData() notificationToken = userFriends?.observe(on: .main, { [weak self] (collectionChange) in switch collectionChange { case .initial(let results): self?.indexUsers(results, searchString: nil) self?.tableView.reloadData() os_log(.info, "Realm - Initial notification") case .error(let error): os_log(.info, "Realm - error notification: \(error.localizedDescription)") case let .update(results, _, _, _): os_log(.info, "Realm - Updated notification") self?.indexUsers(results, searchString: nil) self?.tableView.reloadData() } }) } private func indexUsers(_ results: Results<FriendsRealmModel>?, searchString: String?) { let userFriendsResults = results != nil ? results : userFriends guard let results = userFriendsResults else { return } indexedUsers = [[FriendsRealmModel]]() var searchText: String? if let searchString = searchString, searchString.count > 0 { searchText = searchString } for user in results { if let st = searchText { if !user.fullName.contains(st) { continue } } let firstLetter = String(user.fullName.first!) let indexOfLetter = sections.firstIndex(of: firstLetter) if indexOfLetter == nil { sections.append(firstLetter) indexedUsers.append([user]) continue } indexedUsers[indexOfLetter!].append(user) } } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return sections[section] } override func numberOfSections(in tableView: UITableView) -> Int { return indexedUsers.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return indexedUsers[section].count } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let selectedUser = indexedUsers[indexPath.section][indexPath.row] let vc = UserCollectionViewController(userModel: selectedUser) show(vc, sender: self) } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "UserCell", for: indexPath) as? UserTableCell else { fatalError("The dequeued cell is not an instance of UserTableCell.") } let user = indexedUsers[indexPath.section][indexPath.row] cell.user = user cell.name.text = user.fullName cell.avatarView.loadFrom(url: URL(string: user.avatar)!) return cell } // override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // // let destintaion = segue.destination as! UserCollectionViewController // // let selectedIndexPath = self.tableView.indexPathForSelectedRow! // let selectedUser = indexedUsers[selectedIndexPath.section][selectedIndexPath.row] // destintaion.user = selectedUser // } } extension FriendsTableViewController: UISearchBarDelegate { func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { sections = [String]() indexedUsers = [[FriendsRealmModel]]() indexUsers(nil, searchString: searchText) self.tableView.reloadData() } }
// // ShowsListCell.swift // ScreenLifeMaze // // Created by Felipe Lobo on 15/09/21. // import UIKit final class ShowsListCell: UITableViewCell { let coverImageView: UIImageView = { let imageView = UIImageView() imageView.translatesAutoresizingMaskIntoConstraints = false imageView.backgroundColor = .gray return imageView }() let titleLabel: UILabel = { let titleLabel = UILabel() titleLabel.translatesAutoresizingMaskIntoConstraints = false titleLabel.numberOfLines = 0 return titleLabel }() override init(style: CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupSubviews() setupLayout() } required init?(coder aDecoder: NSCoder) { preconditionFailure("Please do not instantiate this view controller with init?(coder:)") } private func setupSubviews() { contentView.addSubview(coverImageView) contentView.addSubview(titleLabel) } private func setupLayout() { contentView.addConstraints([ coverImageView.topAnchor.constraint(equalTo: contentView.topAnchor), coverImageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor), coverImageView.widthAnchor.constraint(equalTo: coverImageView.heightAnchor, multiplier: 3 / 4), contentView.bottomAnchor.constraint(equalTo: coverImageView.bottomAnchor), titleLabel.leadingAnchor.constraint(equalTo: coverImageView.trailingAnchor, constant: 16), titleLabel.topAnchor.constraint(equalTo: contentView.topAnchor), contentView.bottomAnchor.constraint(equalTo: titleLabel.bottomAnchor), contentView.trailingAnchor.constraint(equalTo: titleLabel.trailingAnchor), ]) let heightConstraint = contentView.heightAnchor.constraint(equalToConstant: 80) heightConstraint.priority = UILayoutPriority(rawValue: 900) heightConstraint.isActive = true } }
// // MovieRequest.swift // MoviesApi // // Created by Kenan Mazalovic on 10/1/20. // import Foundation enum MovieError:Error { case noDataAvailable case canNotProcessData } struct MovieRequest { let resourceURL:URL init(movieName: String, page: Int) { let resourceString = "https://api.themoviedb.org/3/search/movie?api_key=2696829a81b1b5827d515ff121700838&query=\(movieName)&page=\(page)" guard let resourceURL = URL(string: resourceString) else {fatalError()} self.resourceURL = resourceURL } mutating func getMovies (completion: @escaping(Result<[MovieDetail], MovieError>) -> Void) { let dataTask = URLSession.shared.dataTask(with: resourceURL) {data, _, _ in guard let jsonData = data else{ print("ERrror") completion(.failure((.noDataAvailable))) return } do { let decoder = JSONDecoder() let moviesResponse = try decoder.decode(MovieResponse.self, from: jsonData) let movieDetails = moviesResponse.results if moviesResponse.total_results > 0 { completion(.success(movieDetails)) } else { completion(.failure(.noDataAvailable)) } }catch{ completion(.failure(.canNotProcessData)) } } dataTask.resume() } mutating func getTotalpages (completion: @escaping(Result<Int , MovieError>) -> Void) { let dataTask = URLSession.shared.dataTask(with: resourceURL) {data, _, _ in guard let jsonData = data else{ print("Error") completion(.failure((.noDataAvailable))) return } do { let decoder = JSONDecoder() let moviesResponse = try decoder.decode(MovieResponse.self, from: jsonData) let movieDetails = moviesResponse.total_pages completion(.success(movieDetails)) }catch{ completion(.failure(.canNotProcessData)) } } dataTask.resume() } }
// // FoodView.swift // SwiftUIApp // // Created by Artem Pecherukin on 09.03.2020. // Copyright © 2020 pecherukin. All rights reserved. // import SwiftUI struct FoodView: View { let foodName: String let description: String var body: some View { ScrollView { EmptyView() Text(description) .padding(EdgeInsets(top: 16, leading: 16, bottom: 0, trailing: 16)) } .navigationBarTitle(foodName) } }
// // SupermarketTVC.swift // BuySwift // // Created by CoffeeWu on 16/2/6. // Copyright © 2016年 CoffeeWu. All rights reserved. // import UIKit class SupermarketTVC: UITableViewController { var specialsItems = [ Specials(name: "西梅", brand: "超达", category: .food, price: 2.8, originalPrice: 5.3, imageName: "1"), Specials(name: "iPhone 5s", brand: "Apple",category: .mobile, price: 4188, originalPrice: 4488, imageName: "2"), Specials(name: "好多鱼", brand: "好丽友", category: .food, price: 11.8, originalPrice: 13.4, imageName: "3"), Specials(name: "天然水", brand: "农夫山泉", category: .drink, price: 26.9, originalPrice: 32.0, imageName: "4"), Specials(name: "柠檬片", brand: "鲜引力", category: .food, price: 2.9, originalPrice: 3.8, imageName: "5"), Specials(name: "杏仁露", brand: "露露", category: .drink, price: 15.9, originalPrice: 21.3, imageName: "6"), Specials(name: "小米4", brand: "小米", category: .mobile, price: 2760, originalPrice: 3200, imageName: "7"), Specials(name: "仙贝", brand: "旺旺", category: .food, price: 20.8, originalPrice: 28.2, imageName: "8"), Specials(name: "薯片", brand: "乐事", category: .food, price: 19.9, originalPrice: 23.9, imageName: "9"), Specials(name: "瓜子", brand: "正林", category: .food, price: 22.6, originalPrice: 25.2, imageName: "10"), Specials(name: "手撕牛肉", brand: "棒棒娃", category: .food, price: 26.8, originalPrice: 31.1, imageName: "11")] var categorySpecials = [Int: [Specials]]() 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() for specials in specialsItems{ if categorySpecials[specials.category.rawValue] == nil{ categorySpecials[specials.category.rawValue] = [specials] }else{ categorySpecials[specials.category.rawValue]?.append(specials) } } } 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 Incomplete implementation, return the number of sections return categorySpecials.count } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows let categorys = Array(categorySpecials.keys) return categorySpecials[categorys[section]]!.count // 用问号会报错 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier("SpecialsCell", forIndexPath: indexPath) as! SpecialsCell let categorys = Array(categorySpecials.keys) var specials = categorySpecials[categorys[indexPath.section]]![indexPath.row] cell.nameLabel.text = specials.name cell.brandLabel.text = specials.brand cell.leftImageView.image = UIImage(named: specials.imageName) return cell } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. if segue.identifier == "SpecialsDetailSegue"{ var destination: SpecialsDetailVC = segue.destinationViewController as! SpecialsDetailVC let indexPath: NSIndexPath = self.tableView.indexPathForSelectedRow! let categorys = Array(categorySpecials.keys) var specials = categorySpecials[categorys[indexPath.section]]![indexPath.row] destination.specials = specials } } }
// // DataProviderTest.swift // CCC // // Created by Karl Söderberg on 2015-11-01. // Copyright © 2015 Lemon and Lime. All rights reserved. // import XCTest import Alamofire import AlamofireImage @testable import CCCTV class DataProviderTest: XCTestCase { let provider = DataProvider.sharedInstance func testGetMainData() { let expectation = expectationWithDescription("...") provider.getMainData { (result) -> Void in switch result { case .Failure(let error): XCTAssertFalse(true, "Data retrival failed with error" + error.localizedDescription) case .Success(let episodes, _): XCTAssertGreaterThan(episodes.count, 0) } expectation.fulfill() } waitForExpectationsWithTimeout(10) { (error) -> Void in if let error = error { print("error: " + error.localizedDescription) } } } }
// // DirectionsTableViewCell.swift // AirTicket // // Created by Rauan Kussembayev on 10/6/17. // Copyright © 2017 kuzya. All rights reserved. // import UIKit import SwiftyUserDefaults protocol DirectionsTableViewCellDelegate: class { func showCities(directionType: DirectionType) func updateDirectionsCell() } enum DirectionType { case from case to } class DirectionsTableViewCell: UITableViewCell { // MARK: - Outlets @IBOutlet weak var originView: UIView! @IBOutlet weak var destinationView: UIView! @IBOutlet weak var originLabel: UILabel! @IBOutlet weak var destinationLabel: UILabel! @IBOutlet weak var bgView: UIView! // MARK: - Properties weak var delegate: DirectionsTableViewCellDelegate? var originCity: String? { didSet { setupCell() } } var destinationCity: String? { didSet { setupCell() } } override func awakeFromNib() { super.awakeFromNib() backgroundColor = .clear selectionStyle = .none bgView.backgroundColor = .clear _ = bgView.addBorder(edges: [.bottom], colour: UIColor.white.withAlphaComponent(0.25), thickness: 1) setupTapGestures() } private func setupTapGestures() { let originTap = UITapGestureRecognizer(target: self, action: #selector(self.showOrigin(_:))) originView.isUserInteractionEnabled = true originView.addGestureRecognizer(originTap) let destinationTap = UITapGestureRecognizer(target: self, action: #selector(self.showDestination(_:))) destinationView.isUserInteractionEnabled = true destinationView.addGestureRecognizer(destinationTap) } private func setupCell() { originLabel.text = originCity destinationLabel.text = destinationCity } @objc private func showOrigin(_ sender: UITapGestureRecognizer) { delegate?.showCities(directionType: .from) } @objc private func showDestination(_ sender: UITapGestureRecognizer) { delegate?.showCities(directionType: .to) } @IBAction func swipeCitiesAction(_ sender: Any) { let originCity = Defaults[.originCity] let destinationCity = Defaults[.destinationCity] Defaults[.originCity] = destinationCity Defaults[.destinationCity] = originCity delegate?.updateDirectionsCell() } }
// // HMZSplitViewController.swift // iPad-SplitViewController // // Created by 赵志丹 on 15/12/28. // Copyright © 2015年 HMZBadge. All rights reserved. // import UIKit class HMZSplitViewController: UISplitViewController { override func viewDidLoad() { super.viewDidLoad() let masterVc = childViewControllers[0].childViewControllers[0] as? HMZMasterViewController let detailVc = childViewControllers[1].childViewControllers[0] as? HMZDetailViewController masterVc?.foodTypeDelegate = detailVc delegate = detailVc //手动调用一下屏幕旋转模式 detailVc?.splitViewController(self, willChangeToDisplayMode: .PrimaryHidden) } }
// // PlantViewControllerTests.swift // BotanicalGardenTests // // Created by 黃偉勛 on 2021/4/20. // import XCTest import BotanicalGarden class PlantViewControllerTests: XCTestCase { func test_loadPlantActions_requestPlantFromViewModel() { let (sut, vm) = makeSUT() XCTAssertEqual(vm.loadPlantCallCount, 0) sut.loadViewIfNeeded() XCTAssertEqual(vm.loadPlantCallCount, 1) } // MARK: - Helpers private func makeSUT(file: StaticString = #file, line: UInt = #line) -> (sut: PlantViewController, vm: PlantViewModelSpy) { let vm = PlantViewModelSpy() let sut = PlantViewController(viewModel: (vm.inputs, vm.outputs)) trackForMemoryLeaks(sut, file: file, line: line) trackForMemoryLeaks(vm, file: file, line: line) return (sut, vm) } private class PlantViewModelSpy: ViewModel, PlantViewModelInputs, PlantViewModelOutputs { var inputs: PlantViewModelInputs { return self } var outputs: PlantViewModelOutputs { return self } var items: [PlantCellModel] = [] var didLoadPlant: (([IndexPath]) -> Void)? func loadPlant() { loadPlantCallCount += 1 } var loadPlantCallCount = 0 } }
// // TripImageCell.swift // OnTheRoadB // // Created by Cunqi.X on 11/29/14. // Copyright (c) 2014 CS9033. All rights reserved. // import UIKit class TripImageCell: UICollectionViewCell { @IBOutlet var deleteBtn: UIButton! @IBOutlet var thumbNail: UIImageView! }
// // MADWalletController.swift // MovingAD_iPhone_client // // Created by Monzy Zhang on 5/22/16. // Copyright © 2016 MonzyZhang. All rights reserved. // import UIKit class MADWalletController: UIViewController { // MARK: outlets @IBOutlet weak var cash: UILabel! // MARK: life cycle override func viewDidLoad() { super.viewDidLoad() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) setMoney() } func setMoney() { let money = MADUserInfo.currentUserInfo?.account_money ?? 0.0 cash.text = "余额: \(String.init(format: "%.3f", money)) 元" } // MARK: - actions - @IBAction func logoutButtonPressed(sender: UIBarButtonItem) { let alert = UIAlertController(title: "退出登录", message: "确认退出登录?", preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "是", style: .Destructive, handler: { (action) in MADData.sweepAllData() self.performSegueWithIdentifier("LogoutSegue", sender: self) })) alert.addAction(UIAlertAction(title: "否", style: .Cancel, handler: nil)) presentViewController(alert, animated: true, completion: nil) } @IBAction func getcashButtonPressed(sender: DesignableButton) { } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let identifier = segue.identifier { if identifier == "GetMoneySegue" { let vc = segue.destinationViewController as! MADGetMoneyViewController vc.walletVC = self } } } }
// // PeripheralsVC.swift // BLEScanner // // Created by Marian Shkurda on 3/6/19. // Copyright © 2019 Marian Shkurda. All rights reserved. // import UIKit import CoreBluetooth private extension String { static let PeripheralCellID = "PeripheralCell" static let PeripheralsToServicesSegue = "PeripheralsToServicesSegue" static let ConnectingToDeviceTitle = "Connecting to device..." } class PeripheralsVC: BluetoothSessionVC { @IBOutlet weak var table: UITableView! var logView: UITextView? var peripherals = [CBPeripheral]() override func viewDidLoad() { super.viewDidLoad() bleManager.setDidDiscoverPeripheralClosure { [weak self](peripheral) in guard let strongSelf = self else { return } if !strongSelf.peripherals.contains(peripheral){ strongSelf.peripherals.append(peripheral) strongSelf.table.reloadData() } } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let servicesVC = segue.destination as? ServicesVC, let services = sender as? [CBService] { servicesVC.services = services } } @IBAction func logPressed(_ sender: UIBarButtonItem) { if let logView = logView { logView.removeFromSuperview() self.logView = nil return } logView = UITextView(frame: CGRect(x: 0, y: 100, width: 300, height: 300)) logView!.text = Log.read() self.view.addSubview(logView!) } @IBAction func cleanLogPressed(_ sender: UIBarButtonItem) { Log.clean() } } // MARK: UITableViewDataSource conformance extension PeripheralsVC: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return peripherals.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: .PeripheralCellID, for: indexPath) let peripheral = self.peripherals[indexPath.row] cell.textLabel?.text = peripheral.name return cell } } // MARK: UITableViewDelegate conformance extension PeripheralsVC: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let peripheral = peripherals[indexPath.row] LoadingIndicatorView.show(.ConnectingToDeviceTitle) bleManager.connect(toPeripheral: peripheral) { [weak self](p, error) in if let error = error { LoadingIndicatorView.hide() self?.showAlert(title: error.localizedDescription, message: nil) return } self?.bleManager.discoverServices(completion: { (services, error) in LoadingIndicatorView.hide() if let error = error { self?.showAlert(title: error.localizedDescription, message: nil) return } if let services = services { self?.performSegue(withIdentifier: .PeripheralsToServicesSegue, sender: services) } }) } } }
// // Vehicle.swift // OnestapSDK // // Created by Munir Wanis on 22/08/17. // Copyright © 2017 Stone Payments. All rights reserved. // import Foundation public struct Vehicle { public init(licensePlate: String) { self.licensePlate = licensePlate } public internal(set) var key: String = "" public var licensePlate: String public var licensePlateCity: String? = nil public var licensePlateState: String? = nil public var licensePlateCountry: String? = nil } extension Vehicle: Encondable { func toDictionary() -> JSON { return [ "licensePlate": licensePlate, "licensePlateCity": licensePlateCity as Any, "licensePlateState": licensePlateState as Any, "licensePlateCountry": licensePlateCountry as Any ] } }
// // HighScoreData+CoreDataProperties.swift // DartsData // // Created by Dakota Raymond on 4/22/17. // Copyright © 2017 Dakota Raymond. All rights reserved. // import Foundation import CoreData extension HighScoreData { @nonobjc public class func fetchRequest() -> NSFetchRequest<HighScoreData> { return NSFetchRequest<HighScoreData>(entityName: "HighScoreData"); } @NSManaged public var game: String @NSManaged public var name: String @NSManaged public var score: Int32 }
// // AutoGravityCollectionViewController.swift // Image-Downloading // // Created by Thinh Le on 1/7/16. // Copyright © 2016 Lac Viet Inc. All rights reserved. // import UIKit private let reuseIdentifier = "MyCell" class AutoGravityCollectionViewController: UICollectionViewController { var arrayOfImageURL = Array<String>() override func viewDidLoad() { super.viewDidLoad() //do_matrix_refresh(); get_data_from_url("https://pixabay.com/api/?key=103582-ced4be9ff789b472fbfd89dd7&q=yellow+flower&image_type=photo") // https://itunes.apple.com/ca/app/english-vietnamese-guide-to/id593964156?mt=8 //do_matrix_refresh(); } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: UICollectionViewDataSource override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return arrayOfImageURL.count } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! ImageCollectionViewCell let url = NSURL(string: self.arrayOfImageURL[indexPath.row]) let contentURL = NSData(contentsOfURL: url!) let image = UIImage(data: contentURL!) cell.imageView.image = image return cell } func get_data_from_url(url:String) { let url = NSURL(string: url) let task = NSURLSession.sharedSession().dataTaskWithURL(url!) { (data, response, error) -> Void in if error != nil { print(error) } else { if data!.length > 0 { self.extract_json(data!) } else if data!.length == 0 { print("Nothing was downloaded") } } } task.resume() } func extract_json(jsonData:NSData) { do { let jsonResult = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers) if let items = jsonResult["hits"] as? NSArray { for item in items { if let previewURL = item["previewURL"] as? String { self.arrayOfImageURL.append(previewURL) //print(previewURL) } } } do_matrix_refresh(); } catch { print("JSON serialization failed") } } func do_matrix_refresh() { dispatch_async(dispatch_get_main_queue(), { self.collectionView!.reloadData() return }) } }
// // Leaf.swift // florafinder // // Created by Andrew Tokeley on 5/01/16. // Copyright © 2016 Andrew Tokeley . All rights reserved. // import Foundation import CoreData class Leaf: NSManagedObject { // Insert code here to add functionality to your managed object subclass override var description: String { var sentences = [String]() if let text = notes { sentences.append(text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) + "\n\n") } if let text = dimensions?.description { sentences.append(text) } return sentences.joinWithSeparator("") } }
// // MainSceneView.swift // gloop-drop // // Created by Fernando Fernandes on 18.09.20. // import SwiftUI import SpriteKit struct MainSceneView: View { // MARK: - Properties var body: some View { let size = CGSize(width: 1336, height: 1024) SpriteView(scene: makeScene(size: size)) } } // MARK: - Private fileprivate extension MainSceneView { func makeScene(size: CGSize) -> SKScene { MainScene(size: size) } } // MARK: - Preview struct MainSceneView_Previews: PreviewProvider { static var previews: some View { MainSceneView() } }
// // AutoLayout.swift // GForm // // Created by Kennan Trevyn Zenjaya on 01/01/21. // import LBTAComponents class CellWidthController: DatasourceController { func cellWidth() -> CGFloat{ return UIScreen.main.bounds.size.width } } let three = CellWidthController().cellWidth()/138 let four = CellWidthController().cellWidth()/103.5 let six = CellWidthController().cellWidth()/69 let eight = CellWidthController().cellWidth()/51.75 let ten = CellWidthController().cellWidth()/41.4 let twelve = CellWidthController().cellWidth()/34.5 let fourteen = CellWidthController().cellWidth()/29.57 let fifteen = CellWidthController().cellWidth()/27.6 let sixteen = CellWidthController().cellWidth()/25.87 let eighteen = CellWidthController().cellWidth()/23 let nineteen = CellWidthController().cellWidth()/21.78 let twenty = CellWidthController().cellWidth()/20.7 let twentyTwo = CellWidthController().cellWidth()/18.81 let twentyFour = CellWidthController().cellWidth()/17.25 let twentySix = CellWidthController().cellWidth()/15.92 let twentyEight = CellWidthController().cellWidth()/14.78 let thirty = CellWidthController().cellWidth()/13.8 let thirtyTwo = CellWidthController().cellWidth()/12.93 let thirtyThree = CellWidthController().cellWidth()/12.54 let thirtyFour = CellWidthController().cellWidth()/12.17 let thirtyFourPointFive = CellWidthController().cellWidth()/12 let thirtySix = CellWidthController().cellWidth()/11.5 let thirtyEight = CellWidthController().cellWidth()/10.89 let fourty = CellWidthController().cellWidth()/10.35 let fourtyTwo = CellWidthController().cellWidth()/9.85 let fourtyFive = CellWidthController().cellWidth()/9.2 let fourtySix = CellWidthController().cellWidth()/9 let fourtyEight = CellWidthController().cellWidth()/8.6 let fifty = CellWidthController().cellWidth()/8.28 let fiftyTwo = CellWidthController().cellWidth()/7.96 let fiftyFour = CellWidthController().cellWidth()/7.66 let fiftyFive = CellWidthController().cellWidth()/7.52 let fiftySix = CellWidthController().cellWidth()/7.39 let fiftyEight = CellWidthController().cellWidth()/7.13 let sixty = CellWidthController().cellWidth()/6.9 let sixtyFour = CellWidthController().cellWidth()/6.46 let sixtySix = CellWidthController().cellWidth()/6.27 let sixtyEight = CellWidthController().cellWidth()/6.088 let seventyFour = CellWidthController().cellWidth()/5.59 let seventySix = CellWidthController().cellWidth()/5.44 let seventyEight = CellWidthController().cellWidth()/5.3 let eighty = CellWidthController().cellWidth()/5.175 let eightyTwo = CellWidthController().cellWidth()/5.04 let eightyFour = CellWidthController().cellWidth()/4.92 let eightySix = CellWidthController().cellWidth()/4.81 let eightyEight = CellWidthController().cellWidth()/4.70 let ninety = CellWidthController().cellWidth()/4.6 let ninetyTwo = CellWidthController().cellWidth()/4.5 let ninetySix = CellWidthController().cellWidth()/4.31 let ninetyEight = CellWidthController().cellWidth()/4.22 let oneHundred = CellWidthController().cellWidth()/4.14 let oneZeroTwo = CellWidthController().cellWidth()/4.05 let oneZeroSix = CellWidthController().cellWidth()/3.9 let oneTen = CellWidthController().cellWidth()/3.69 let oneEighteen = CellWidthController().cellWidth()/3.5 let oneTwenty = CellWidthController().cellWidth()/3.45 let oneTwentySix = CellWidthController().cellWidth()/3.28 let oneThirty = CellWidthController().cellWidth()/3.18 let oneThirtyFour = CellWidthController().cellWidth()/3.08 let oneFourty = CellWidthController().cellWidth()/2.95 let oneFifty = CellWidthController().cellWidth()/2.76 let oneSixtyTwo = CellWidthController().cellWidth()/2.55 let oneSixtyFour = CellWidthController().cellWidth()/2.52 let oneSeventy = CellWidthController().cellWidth()/2.43 let oneEighty = CellWidthController().cellWidth()/2.3 let twoHundred = CellWidthController().cellWidth()/2.07 let twoTen = CellWidthController().cellWidth()/1.97 let twoTwenty = CellWidthController().cellWidth()/1.88 let twoThirty = CellWidthController().cellWidth()/1.8 let twoFourtyFive = CellWidthController().cellWidth()/1.68 let twoFiftyTwo = CellWidthController().cellWidth()/1.64 let twoSixty = CellWidthController().cellWidth()/1.59 let twoSixtySix = CellWidthController().cellWidth()/1.55 let twoEightFour = CellWidthController().cellWidth()/1.45 let twoNineEight = CellWidthController().cellWidth()/1.38 let threeHundred = CellWidthController().cellWidth()/1.38 let threeOneZero = CellWidthController().cellWidth()/1.33 let threeTwenty = CellWidthController().cellWidth()/1.29 let threeFourty = CellWidthController().cellWidth()/1.21 let fourHundred = CellWidthController().cellWidth()/0.9