blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
6
116
path
stringlengths
5
872
src_encoding
stringclasses
7 values
length_bytes
int64
10
4.68M
score
float64
2.52
5.63
int_score
int64
3
5
detected_licenses
listlengths
0
47
license_type
stringclasses
2 values
text
stringlengths
7
4.81M
download_success
bool
1 class
79b53b380665132c011220508ce091ff9907c026
Swift
Sowmya06/ios
/ValidationApp/ValidationApp/ViewController.swift
UTF-8
2,726
2.875
3
[]
no_license
// // ViewController.swift // ValidationApp // // Created by Sowmya Amireddy on 6/28/17. // Copyright © 2017 Sowmya Amireddy. All rights reserved. // import UIKit import SafariServices class ViewController: UIViewController{ @IBOutlet weak var button: UIButton! @IBOutlet weak var textField: UITextField! @IBOutlet weak var button1: UIButton! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func validateUrl(textField: String) -> Bool { let urlRegEx = "((https|http)://)((\\w|-)+)(([.]|[/])((\\w|-)+))+" return NSPredicate(format: "SELF MATCHES %@", urlRegEx).evaluate(with: textField) } @IBAction func safariButton(_ sender: UIButton) { let temp = textField.text let isValidUrl = validateUrl(textField: temp!) if isValidUrl{ print("valid") print(isValidUrl) let url = URL(string: temp!) if let myData = url{ let svc = SFSafariViewController(url: myData) self.present(svc, animated: true, completion: nil) } }else{ print("not valid") let alert1 = UIAlertController(title: "My ALert", message: "Please enter valid Url", preferredStyle: UIAlertControllerStyle.alert) let actionOk = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil) alert1.addAction(actionOk) self.present(alert1, animated: true, completion: nil) } } @IBAction func buttonClicked(_ sender: UIButton) { let temp = textField.text let isValidUrl = validateUrl(textField: temp!) if isValidUrl{ print("valid") print(isValidUrl) let secondView = self.storyboard?.instantiateViewController(withIdentifier: "secondView") as! SecondViewController secondView.stringUrl = temp! navigationController?.pushViewController(secondView, animated: true) }else{ let alert1 = UIAlertController(title: "My ALert", message: "Please enter valid Url", preferredStyle: UIAlertControllerStyle.alert) let actionOk = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil) alert1.addAction(actionOk) self.present(alert1, animated: true, completion: nil) } } }
true
5463d6c474a9bf5b8f81198e6e6f1e3c76285478
Swift
Leuxll/businessApp
/businessApp/Views/TabBar.swift
UTF-8
2,224
2.53125
3
[ "MIT" ]
permissive
// // TabBarController.swift // businessApp // // Created by Yue Fung Lee on 25/6/2021. // import UIKit class TabBar: UITabBarController { override func viewDidLoad() { super.viewDidLoad() setupView() } func setupView() { view.backgroundColor = ColourConstants.baseColour customTabBar() } func customTabBar() { let appearance = tabBar.standardAppearance tabBar.backgroundColor = ColourConstants.baseColour tabBar.barTintColor = ColourConstants.baseColour appearance.configureWithOpaqueBackground() appearance.shadowImage = nil appearance.shadowColor = nil tabBar.standardAppearance = appearance tabBar.layer.cornerRadius = 30 tabBar.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner] tabBar.layer.masksToBounds = true let homeView = UINavigationController(rootViewController: HomeView()) let forumView = UINavigationController(rootViewController: ForumView()) let exemplarView = UINavigationController(rootViewController: ExemplarView()) let profileView = UINavigationController(rootViewController: ProfileView()) setViewControllers([homeView, forumView, exemplarView, profileView], animated: false) guard let items = tabBar.items else { return } let icons = ["homeView", "forumView", "exemplarView", "profileView"] for x in 0..<items.count { items[x].image = UIImage(named: icons[x]) items[x].title = nil items[x].imageInsets = UIEdgeInsets(top: 15.5, left: 0, bottom: -15.5, right: 0) } } init() { super.init(nibName: nil, bundle: nil) object_setClass(self.tabBar, customTabBarHeight.self) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } class customTabBarHeight: UITabBar { override func sizeThatFits(_ size: CGSize) -> CGSize { var sizeThatFits = super.sizeThatFits(size) sizeThatFits.height = 100 return sizeThatFits } } }
true
29e0acb9006bcabfd3b10d6d4b25f2ee26c61017
Swift
KeeganFerrett/persitent-data-swift
/Persistent Data/ContentView.swift
UTF-8
942
2.90625
3
[]
no_license
// // ContentView.swift // Persistent Data // // Created by Keegan Ferrett on 2021/04/17. // import SwiftUI struct ContentView: View { let service = DataService() var body: some View { VStack { HeaderView() .frame( height: 100 ) DataListView() .frame( maxHeight: .infinity ) FooterView() .frame( maxWidth: .infinity, maxHeight: 75 ) .background( Color.white ) .shadow(color: Color.black.opacity(0.2), radius: 2, x: 0.0, y: -2) }.ignoresSafeArea(.all) .environmentObject(service) } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
true
cb9b94ab25c51629b4d02fd05af4718c9c7a31f8
Swift
wearebeatcode/POEditorSwift
/POEditorSwift/Classes/Extensions/DateFormatter.swift
UTF-8
370
2.625
3
[ "MIT" ]
permissive
// // DateFormatter.swift // POEditorSwift // // Created by Giuseppe Travasoni on 27/04/2020. // import Foundation extension DateFormatter { static var formatter: DateFormatter { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ" formatter.calendar = Calendar(identifier: .iso8601) return formatter } }
true
a2fc95a186161fc29cfe39a1d63e4634e0119aec
Swift
fconelli/reddit-client
/reddit-clientTests/reddit_clientTests.swift
UTF-8
5,619
2.5625
3
[]
no_license
// // reddit_clientTests.swift // reddit-clientTests // // Created by Francisco Conelli on 12/01/2021. // import XCTest @testable import reddit_client class reddit_clientTests: XCTestCase { //MARK: - feed tests func test_load_requestsDataFromURL() { let (sut, client) = makeSUT() let url = sut.getURL() sut.load() {_ in } XCTAssertEqual(client.requestedURL, url) } func test_load_deliversConnectivityErrorOnClientError() { let (sut, client) = makeSUT() client.error = NSError(domain: "test", code: 0) let expectedResult: Result<[FeedItem], RemoteFeedLoader.Error> = .failure(.connectivity) let exp = expectation(description: "Wait for load completion") sut.load() { switch ($0, expectedResult) { case let (.success(receivedItems), .success(expectedItems)): XCTAssertEqual(receivedItems, expectedItems) case let (.failure(receivedError as RemoteFeedLoader.Error), .failure(expectedError)): XCTAssertEqual(receivedError, expectedError) default: XCTFail("Expected result \(expectedResult) got \($0) instead") } exp.fulfill() } waitForExpectations(timeout: 0.1) } func test_load_deliversInvalidDataErrorOn200HTTPResponseWithInvalidJSON() { let (sut, client) = makeSUT() client.receivedInvalidJson = true let expectedResult: Result<[FeedItem], RemoteFeedLoader.Error> = .failure(.invalidData) let exp = expectation(description: "Wait for load completion") sut.load() { switch ($0, expectedResult) { case let (.success(receivedItems), .success(expectedItems)): XCTAssertEqual(receivedItems, expectedItems) case let (.failure(receivedError as RemoteFeedLoader.Error), .failure(expectedError)): XCTAssertEqual(receivedError, expectedError) default: XCTFail("Expected result \(expectedResult) got \($0) instead") } exp.fulfill() } waitForExpectations(timeout: 0.1) } // func test_load_deliversNoItemsOnHTTPResponseWithEmptyJSONList() { // let (sut, client) = makeSUT() // // } // MARK: - helpers private func makeSUT() -> (sut: RemoteFeedLoader, client: HTTPClientSpy) { let client = HTTPClientSpy() let sut = RemoteFeedLoader(client: client) addTeardownBlock { [weak sut] in // executes after each tests finishes XCTAssertNil(sut, "Potential memory leak!") } return (sut, client) } class HTTPClientSpy: HTTPClient { var requestedURL: URL? var error: Error? var complete: (HTTPClientResult) -> Void = {_ in } var receivedInvalidJson: Bool = false func get(from url: URL, completion: @escaping (HTTPClientResult) -> Void) { complete = completion if let error = error { complete(.failure(error)) } requestedURL = url if receivedInvalidJson { let invalidJson = Data("invalid json".utf8) self.complete(withInvalidJSON: invalidJson, completion: completion) } } func complete(withInvalidJSON json: Data, completion: @escaping (HTTPClientResult) -> Void) { if let url = requestedURL, let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: nil, headerFields: nil) { completion(.success(json, response)) } } } } class URLSessionHTTPClientTests: XCTestCase { func test_getFromURL_failsOnRequestError() { let url = URL(string: "http://any-url.com")! let error = NSError(domain: "any", code: 1) let session = URLSessionSpy() session.stub(url: url, error: error) let sut = URLSessionHTTPClient(session: session) let exp = expectation(description: "wait for completion") sut.get(from: url, completion: { result in switch result { case let .failure(receivedError): XCTAssertEqual(receivedError as NSError, error) default: XCTFail("Expected failure with error!") } exp.fulfill() }) wait(for: [exp], timeout: 1.0) } // MARK: - helpers private class URLSessionSpy: URLSession { private struct Stub { let task: URLSessionDataTask let error: Error? } private var stubs = [URL: Stub]() func stub(url: URL, task: URLSessionDataTask = FakeURLSessionDataTask(), error: Error? = nil) { stubs[url] = Stub(task: task, error: error) } override func dataTask(with url: URL, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask { if let stub = stubs[url] { completionHandler(nil, nil, stub.error) return stub.task } return FakeURLSessionDataTask() } } /// fake URLSession to avoid making real network requests during tests private class FakeURLSessionDataTask: URLSessionDataTask { override func resume() {} } }
true
7d42814b7cdf5466781614f05671d3df333ab210
Swift
Cgrau/Marvel-App
/Marvel-App/Scenes/MainScreen/MainScreenWorker.swift
UTF-8
1,437
3.015625
3
[]
no_license
// // MainScreenWorker.swift // Marvel-App // // Created by Carles Grau Galvan on 11/05/2018. // Copyright © 2018 Carles Grau Galvan. All rights reserved. // import UIKit import Alamofire import CryptoSwift class MainScreenWorker { private let apiClient = APIClient() /// Worker will get Characters starting by searchString and will call APIClient to request to Marvel API. /// /// - Parameters: /// - string: Search Characters starting by this parameter /// - Completion: /// - entity: An array of characters /// - error: - func search(string: String, completion: @escaping (_ entity: [Character]?, _ error: Error?) -> Void) { apiClient.search(string: string) { (characters, error) in if let error = error { completion(nil, error) } else { completion(characters, nil) } } } /// Request to get Comic data. /// /// - Parameters: /// - url: ComicURI /// - Completion: /// - entity: Comic thumbnail URL with extension /// - error: - func getComicThumbnailData(url: String, completion: @escaping (_ entity: String?, _ error: Error?) -> Void) { apiClient.getComicThumbnailData(url: url) { (imageURL, error) in if let error = error { completion(nil, error) } else { completion(imageURL, nil) } } } }
true
6ecf0cb876f3254c04896ab9ee081ef3685a57d8
Swift
SuyeonKim1702/Eating
/Eating_ios/Eating/Service/AddressService.swift
UTF-8
1,320
2.828125
3
[]
no_license
// // AddressService.swift // Eating // // Created by 코드잉 on 2021/03/07. // import Foundation class AddressService{ let networkManager = NetworkManager() func getAddressInfo(for keyword: String, page: Int, completion: @escaping (Result<[Place], NetworkError>) -> Void) { var urlComponents = URLComponents() urlComponents.scheme = Constant.scheme urlComponents.host = Constant.kakaoHost urlComponents.path = Constant.ApiId.kakaoAddressApi.rawValue urlComponents.queryItems = [ URLQueryItem(name: "query", value: keyword), URLQueryItem(name: "page", value: "\(page)") ] guard let urlString = urlComponents.url?.absoluteString, let url = URL(string: urlString) else { return completion(.failure(.urlError)) } networkManager.request(url, completion, parseAddress(_:), "KakaoAK \(Constant.kakaoRestApiKey)").resume() } func parseAddress(_ data: Data) -> (Result<[Place], NetworkError>) { let decoder = JSONDecoder() do { let response = try decoder.decode(Address.self, from: data) let places = response.documents return .success(places) } catch { return .failure(.decodingError) } } }
true
0be6f835ed4a1d0ebb949945d3a20b12bc046cb0
Swift
bender-io/CSBook
/Pages/Trees.xcplaygroundpage/Contents.swift
UTF-8
5,829
4.0625
4
[]
no_license
//: [Previous](@previous) import Foundation // Helper function public func example(of description: String, action: () -> Void) { print("---Example of: \(description)---") action() print() } // Queue Stacks Struct forEachLevelOrder() method public struct Queue<T> { private var leftStack: [T] = [] private var rightStack: [T] = [] public init() {} public var isEmpty: Bool { return leftStack.isEmpty && rightStack.isEmpty } public var peek: T? { return !leftStack.isEmpty ? leftStack.last : rightStack.first } @discardableResult public mutating func enqueue(_ element: T) -> Bool { rightStack.append(element) return true } public mutating func dequeue() -> T? { if leftStack.isEmpty { leftStack = rightStack.reversed() rightStack.removeAll() } return leftStack.popLast() } } // MARK: - TREES GENERAL // The tree is a data structure of profound importance. It is used to tackle many recurring challenges in software development, such as: // • Representing hierarchical relationships. // • Managing sorted data. // • Facilitating fast lookup operations. // Depth-First Traversal: // • A technique that starts at the root and visits nodes as deep as it can before backtracking. // Level-Order Traversal: // • A technique that visits each node of the tree based on the depth of the nodes. // KEY POINTS // • Trees share some similarities to linked lists, but, whereas linked-list nodes may only link to one other node, a tree node can link to infinitely many nodes. // • Be comfortable with the tree terminology such as parent, child, leaf and root. Many of these terms are common tongue for fellow programmers and will be used to help explain other tree structures. // • Traversals, such as depth-first and level-order traversals, aren't specific to the general tree. They work on other trees as well, although their implementation will be slightly different based on how the tree is structured. /// Each node is responsible for a value and holds references to all its children using an array. public class TreeNode<T> { public var value: T public var children: [TreeNode] = [] public init(_ value: T) { self.value = value } /// Adds a child node to the children array for the TreeNode public func add(_ child: TreeNode) { children.append(child) } } extension TreeNode { /// Uses simple recursion to visit every child node (depth first) public func forEachDepthFirst(visit: (TreeNode) -> Void) { visit(self) children.forEach { $0.forEachDepthFirst(visit: visit) } } } extension TreeNode { /// Uses simple recursion to visit every level node (left to right) before diving one level deeper (also left to right) public func forEachLevelOrder(visit: (TreeNode) -> Void) { visit(self) var queue = Queue<TreeNode>() children.forEach { queue.enqueue($0) } while let node = queue.dequeue() { visit(node) node.children.forEach { queue.enqueue($0) } } } } extension TreeNode where T: Equatable { public func search(_ value: T) -> TreeNode? { var result: TreeNode? forEachLevelOrder { node in if node.value == value { result = node } } return result } } // MARK: - EXAMPLES func makeBeverageTree() -> TreeNode<String> { let tree = TreeNode("Beverages:") let hot = TreeNode("Hot:") let cold = TreeNode("Cold:") let tea = TreeNode("tea") let coffee = TreeNode("coffee") let chocolate = TreeNode("cocoa") let blackTea = TreeNode("black") let greenTea = TreeNode("green") let chaiTea = TreeNode("chai") let soda = TreeNode("soda") let milk = TreeNode("milk") let gingerAle = TreeNode("ginger ale") let bitterLemon = TreeNode("bitter lemon") tree.add(hot) tree.add(cold) hot.add(tea) hot.add(coffee) hot.add(chocolate) cold.add(soda) cold.add(milk) tea.add(blackTea) tea.add(greenTea) tea.add(chaiTea) soda.add(gingerAle) soda.add(bitterLemon) return tree } let tree = makeBeverageTree() // Depth-First tree.forEachDepthFirst { print($0.value) } // Bredth-First tree.forEachLevelOrder { print($0.value) } if let searchResult1 = tree.search("ginger ale") { print("\nFound node: \(searchResult1.value)") } if let searchResult2 = tree.search("WKD Blue") { print(searchResult2.value) } else { print("Couldn't find WKD Blue") } // MARK: - CHALLENGES // Challenge 1. // Print all the values in a tree in an order based on their level. Nodes belonging in the same level should be printed in the same line. For example, consider the following tree: func makeNumberTree() -> TreeNode<Int> { let root = TreeNode(1) let secondLevel₁ = TreeNode(2) let secondLevel₂ = TreeNode(3) let secondLevel₃ = TreeNode(4) let thirdLevel₁ = TreeNode(5) let thirdLevel₂ = TreeNode(6) let thirdLevel₃ = TreeNode(7) let thirdLevel₄ = TreeNode(8) let thirdLevel₅ = TreeNode(9) let thirdLevel₆ = TreeNode(10) root.add(secondLevel₁) root.add(secondLevel₂) root.add(secondLevel₃) secondLevel₁.add(thirdLevel₁) secondLevel₁.add(thirdLevel₂) secondLevel₂.add(thirdLevel₃) secondLevel₂.add(thirdLevel₄) secondLevel₃.add(thirdLevel₅) secondLevel₃.add(thirdLevel₆) return root } example(of: "Challenge 1") { let numberTree = makeNumberTree() numberTree.forEachLevelOrder { print($0.value) } } //: [Next](@next)
true
40a187a1d6c94d5356aa098eb2c61cc4451ce24c
Swift
jordy2015/swift-design-patterns
/swift-design-patterns/Presentation/Movies/MVP/MoviesProtocol.swift
UTF-8
285
2.671875
3
[]
no_license
// // MoviesProtocol.swift // swift-design-patterns // // Created by Jordy Gonzalez on 8/05/21. // import Foundation protocol MoviesProtocol: class { func shouldDisplayActivityIndicator(_ shouldDisplay: Bool) func gotError(_ error: Error) func gotMovies(movieList: [Movie]) }
true
e48adbdd29f9a541861f4d3658498073841d4e29
Swift
richmondwatkins/HappyNashville
/HappyNashville/DetailViewModel.swift
UTF-8
3,881
2.953125
3
[]
no_license
// // DetailViewModel.swift // HappyNashville // // Created by Richmond Watkins on 4/16/15. // Copyright (c) 2015 Richmond Watkins. All rights reserved. // import UIKit protocol DetialViewModelProtocol { func scrollPageViewControllertoDay(indexPath: NSIndexPath) } class DetailViewModel: AppViewModel { var weekLookup: Array<String> = ["", "Su", "M", "T", "W", "Th", "F", "S"] var dataSource: Array<DealDay> = [] var calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian) var hasCurrentDay: Bool! var delegate:DetialViewModelProtocol? var currentDayCell: DayCollectionViewCell? var currentCellIndex: Int = Int() var originalConfigCount: Int = Int() var selectedDay: DealDay! init(dealDays: Array<DealDay>, selectedDate: DealDay?) { super.init() self.dataSource = dealDays.sort { (day1: DealDay, day2: DealDay) -> Bool in return day1.day.integerValue < day2.day.integerValue } self.selectedDay = selectedDate self.hasCurrentDay = isTodayIncluded() } func dayLabelText(dealDay: DealDay) -> String { return self.weekLookup[dealDay.day.integerValue] } func dateLabelText(indexPath: NSIndexPath) -> String { let dateComponents = NSDateComponents() let dealDay: DealDay = self.dataSource[indexPath.row] dateComponents.day = dealDay.day.integerValue - getCurrentDay() let dateForIndex: NSDate = self.calendar!.dateByAddingComponents(dateComponents, toDate: NSDate(), options: [])! let dateFormatter: NSDateFormatter = NSDateFormatter() dateFormatter.dateFormat = "MMM dd"; return dateFormatter.stringFromDate(dateForIndex) } func isTodayIncluded() -> Bool { for dealDay in self.dataSource { if dealDay.day == getCurrentDay() { return true } } return false } func setNewSelectedCell(cell: DayCollectionViewCell, index: Int) -> UIPageViewControllerNavigationDirection? { if self.currentDayCell != nil { self.currentDayCell!.selectedView.backgroundColor = .clearColor() } cell.selectedView.backgroundColor = UIColor(hexString: "3d3d3e") self.currentDayCell = cell if self.currentCellIndex < index { self.currentCellIndex = index return UIPageViewControllerNavigationDirection.Forward } else if (self.currentCellIndex > index) { self.currentCellIndex = index return UIPageViewControllerNavigationDirection.Reverse } else { return nil } } func configureSelected(cell: DayCollectionViewCell, indexPath: NSIndexPath) { if self.originalConfigCount <= self.dataSource.count { let dealDay: DealDay = self.dataSource[indexPath.row] if let selectedDealDay = self.selectedDay { if selectedDealDay.day.integerValue == dealDay.day.integerValue { cell.selectedView.backgroundColor = UIColor(hexString: "3d3d3e") delegate?.scrollPageViewControllertoDay(indexPath) self.currentDayCell = cell self.currentCellIndex = indexPath.row } else if(self.currentDayCell == cell) { cell.selectedView.backgroundColor = UIColor.clearColor() } } else if (indexPath.row == 0) { cell.selectedView.backgroundColor = .blackColor() self.currentDayCell = cell self.currentCellIndex = indexPath.row } self.originalConfigCount++ } } }
true
eb8a5810eef9df9f896c681f88aab17977fcc010
Swift
rezatakhti/Bookie---Session-Tracker
/Bookie - Session Tracker/Model/CoreDataManager.swift
UTF-8
2,031
2.953125
3
[]
no_license
// // CoreDataManager.swift // Singleton Core Data Manager // Bookie - Session Tracker // // Created by Reza Takhti on 4/9/19. // Copyright © 2019 Reza Takhti. All rights reserved. // import Foundation import CoreData import UIKit class CoreDataManager{ static let sharedManager = CoreDataManager() lazy var context = persistentContainer.viewContext private init() {} // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { let container = NSPersistentContainer(name: "DataModel") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } func saveItems() { if context.hasChanges{ do { try context.save() } catch { print("Error saving context \(error)") } } } func loadItems(with request: NSFetchRequest<CurrentSession> = CurrentSession.fetchRequest()) -> [CurrentSession]{ var sessionsArray = [CurrentSession]() do { sessionsArray = try context.fetch(request) } catch { print("error fetching data from context \(error)") } return sessionsArray } }
true
fbb94bd70ce05f76a11706c150ec3f2592fac94d
Swift
lucasongX/Vapor3Tour
/Sources/App/Models/UserInfo/UserInfo.swift
UTF-8
1,657
2.765625
3
[ "MIT" ]
permissive
// // UserInfo.swift // App // // Created by ASong on 2018/8/3. // import Foundation import Vapor struct UserInfo: BaseSQLModel { var id: Int? var userId: String var age: Int? var sex: Int? var nickName: String? var phone: String? var birthday: String? var location: String? var picName: String? init(userId: String) { self.userId = userId } } extension UserInfo { mutating func updateInfo(with user: UserInfoParam) -> UserInfo { if let age = user.age { self.age = age } if let sex = user.sex { self.sex = sex } if let nickName = user.nickName { self.nickName = nickName } if let phone = user.phone { self.phone = phone } if let birthday = user.birthday { self.birthday = birthday } if let location = user.location { self.location = location } if let picName = user.picName { self.picName = picName } return self } } struct UserInfoParam: Content { var age: Int? var sex: Int? var nickName: String? var phone: String? var birthday: String? var location: String? var picName: String? init(userInfo: UserInfo) { self.age = userInfo.age ?? 0 self.sex = userInfo.sex ?? 0 self.nickName = userInfo.nickName ?? "" self.phone = userInfo.phone ?? "" self.birthday = userInfo.birthday ?? "" self.location = userInfo.location ?? "" self.picName = userInfo.picName ?? "" } }
true
9201fb221fe73012c592ef81c2d2142705a4dc46
Swift
filiponegrao/BEPID-Rio-Projeto-Final
/FFVChat/FFVChat/AppNavigationController.swift
UTF-8
2,957
2.609375
3
[]
no_license
// // AppNavigationController.swift // FFVChat // // Created by Filipo Negrao on 29/09/15. // Copyright © 2015 FilipoNegrao. All rights reserved. // import Foundation import UIKit class AppNavigationController : UINavigationController, UIViewControllerTransitioningDelegate { var home : Home_ViewController! init() { super.init(nibName: "AppNavigationController", bundle: nil) self.home = Home_ViewController() self.viewControllers = [home] self.navigationBar.hidden = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func flowLayoutSetup() -> UICollectionViewFlowLayout { let flowLayout = UICollectionViewFlowLayout() flowLayout.scrollDirection = UICollectionViewScrollDirection.Vertical let dimension:CGFloat = self.view.frame.width * 0.23 let labelHeight:CGFloat = 30 flowLayout.itemSize = CGSize(width: dimension, height: dimension + labelHeight) flowLayout.sectionInset = UIEdgeInsets(top: 50, left: 30, bottom: 10, right: 30) flowLayout.minimumLineSpacing = 20.0 return flowLayout } //******* TRANSITIONS ******** } extension UINavigationBar { func hideBottomHairline() { let navigationBarImageView = hairlineImageViewInNavigationBar(self) navigationBarImageView!.hidden = true } func showBottomHairline() { let navigationBarImageView = hairlineImageViewInNavigationBar(self) navigationBarImageView!.hidden = false } private func hairlineImageViewInNavigationBar(view: UIView) -> UIImageView? { if view.isKindOfClass(UIImageView) && view.bounds.height <= 1.0 { return (view as! UIImageView) } let subviews = (view.subviews as [UIView]) for subview: UIView in subviews { if let imageView: UIImageView = hairlineImageViewInNavigationBar(subview) { return imageView } } return nil } } extension UIToolbar { func hideHairline() { let navigationBarImageView = hairlineImageViewInToolbar(self) navigationBarImageView!.hidden = true } func showHairline() { let navigationBarImageView = hairlineImageViewInToolbar(self) navigationBarImageView!.hidden = false } private func hairlineImageViewInToolbar(view: UIView) -> UIImageView? { if view.isKindOfClass(UIImageView) && view.bounds.height <= 1.0 { return (view as! UIImageView) } let subviews = (view.subviews as [UIView]) for subview: UIView in subviews { if let imageView: UIImageView = hairlineImageViewInToolbar(subview) { return imageView } } return nil } }
true
c385eec8e697e0d939138b7b91cea00cd8886cfb
Swift
ChangtongZhou/space_shooting
/space_shooting/GameOverScene.swift
UTF-8
2,907
2.890625
3
[]
no_license
// // GameOverScene.swift // spirte_first_try // // Created by Tianyu Ying on 7/8/16. // Copyright © 2016 Tianyu Ying. All rights reserved. // import SpriteKit class GameOverScene: SKScene { init(size: CGSize, score: Int) { super.init(size: size) self.runAction(SKAction.playSoundFileNamed("Grenade.wav", waitForCompletion: false)) backgroundColor = SKColor.whiteColor() let message = "GAME OVER" let label = SKLabelNode(fontNamed: "Chalkduster") label.text = message label.fontSize = 40 label.fontColor = SKColor.blackColor() label.position = CGPoint(x: size.width / 2, y: size.height / 3 * 2) addChild(label) let defaults = NSUserDefaults.standardUserDefaults() var highScore = 0 if let tempScore = defaults.objectForKey("high_score") { highScore = tempScore as! Int } let labelCurrScore = SKLabelNode(fontNamed: "Chalkduster") labelCurrScore.text = String(format: "YOUR SCORE: %04u", score) labelCurrScore.fontSize = 25 labelCurrScore.fontColor = SKColor.blackColor() labelCurrScore.position = CGPoint(x: size.width / 2, y: size.height / 2) addChild(labelCurrScore) let labelHighest = SKLabelNode(fontNamed: "Chalkduster") if score >= highScore { labelHighest.text = "NEW HIGH SCORE" defaults.setObject(score, forKey: "high_score") } else { labelHighest.text = String(format: "HIGH SCORE: %04u", highScore) } labelHighest.fontSize = 25 labelHighest.fontColor = SKColor.blackColor() labelHighest.position = CGPoint(x: size.width / 2, y: size.height / 3) addChild(labelHighest) let label2 = SKLabelNode(fontNamed: "Chalkduster") label2.text = "Touch to try again" label2.fontSize = 15 label2.fontColor = SKColor.blackColor() label2.position = CGPoint(x: size.width / 2, y: size.height / 5) addChild(label2) // runAction(SKAction.sequence([ // SKAction.waitForDuration(3.0), // SKAction.runBlock() { // let reveal = SKTransition.flipVerticalWithDuration(0.5) // let scene = GameScene(size: size) // self.view?.presentScene(scene, transition: reveal) // } // ])) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { let reveal = SKTransition.flipVerticalWithDuration(0.5) let scene = GameScene(size: size) self.view?.presentScene(scene, transition: reveal) } }
true
3b97eb24d9410d5e328e6d285b9704ee2e613b38
Swift
rlaguilar/TMDBClient
/MasterMoviesApp/Network Requests/APIImageConfigEndpoint.swift
UTF-8
720
2.578125
3
[]
no_license
// // APIImageConfigEndpoint.swift // MasterMoviesApp // // Created by Reynaldo Aguilar on 28/10/19. // Copyright © 2019 Reynaldo Aguilar. All rights reserved. // import Foundation public extension TMDBApi { static func imageConfig() -> Endpoint<ImageConfigParser> { return Endpoint(path: "configuration", method: .get, params: [:], parser: ImageConfigParser()) } } public struct ImageConfigParser: ResponseParser { private let configurationParser = APIReponseParser<Configuration>() public func parse(data: Data) throws -> APIImageConfig { return try configurationParser.parse(data: data).images } private struct Configuration: Codable { let images: APIImageConfig } }
true
e09887cffc72c53867e9d2caa6d2c6762d1ccf4a
Swift
cjordanball/biz-card-ui
/biz-card-ui/components/infoView.swift
UTF-8
660
2.78125
3
[]
no_license
// // infoView.swift // biz-card-ui // // Created by C. Jordan Ball III on 7/18/21. // import SwiftUI struct InfoView: View { var image: String; var insertedText: String; var body: some View { RoundedRectangle(cornerRadius: 40.0) .fill(Color.white) .frame(height: 40) .overlay( HStack { Image(systemName: image) .foregroundColor( Color(red: 0.09, green: 0.63, blue: 0.52)) Text(insertedText) } ) .foregroundColor(Color(red: 0.09, green: 0.63, blue: 0.52)) .padding(.all) } }
true
0083217283b802e97dafebbec1b1c461e2b2faab
Swift
j10l/Bluegecko-ios
/SiliconLabsApp/ViewModels/BluetoothBrowser/SILFilterBarViewModel.swift
UTF-8
1,782
2.6875
3
[ "Apache-2.0" ]
permissive
// // SILFilterBarViewModel.swift // BlueGecko // // Created by Kamil Czajka on 14.12.2020. // Copyright © 2020 SiliconLabs. All rights reserved. // import Foundation class SILFilterBarViewModel { private var currentFilter: SILBrowserFilterViewModel? var state: SILObservable<Bool> = SILObservable(initialValue: false) var filterParamters: SILObservable<String> = SILObservable(initialValue: "") func handleTap() { self.state.value = !self.state.value } func updateCurrentFilter(filter: SILBrowserFilterViewModel?) { self.currentFilter = filter self.state.value = false self.filterParamters.value = prepareParametersDescription() } private func prepareParametersDescription() -> String { var description: [String] = [] if let currentFilter = currentFilter { if !currentFilter.isFilterActive() { return "" } if currentFilter.searchByDeviceName != "" { description.append(currentFilter.searchByDeviceName) } description.append(" > \(currentFilter.dBmValue)dBm") let beaconTypes = currentFilter.beaconTypes as! [SILBrowserBeaconType] for beacon in beaconTypes { if beacon.isSelected { description.append("\(String(describing: beacon.beaconName!))") } } if currentFilter.isFavouriteFilterSet { description.append("favourites") } if currentFilter.isConnectableFilterSet { description.append("connectable") } } return description.joined(separator: ", ") } }
true
94982185868b1f570692f3198fde7cfb955ec1db
Swift
amolbombe/DynamicForm
/DynamicForms/DFCheckBoxButtonController.swift
UTF-8
1,303
2.90625
3
[]
no_license
// // DFCheckBoxButtonController.swift // DynamicForms // // Created by Softcell on 21/11/16. // Copyright © 2016 Softcell. All rights reserved. // import Foundation import UIKit protocol DFCheckBoxButtonDelegate: class { func dfButtonDidSelect(button: DFCheckButton) } class DFCheckBoxButtonController: NSObject { var buttonArray = [DFCheckButton]() var currentSelectedButton = [DFCheckButton]() var delegate: DFCheckBoxButtonDelegate? init(buttons: [DFCheckButton]) { super.init() buttonArray = buttons for button in buttons { button.addTarget(self, action: #selector(DFCheckBoxButtonController.buttonTapped(sender:)), for: UIControlEvents.touchUpInside) } } func buttonTapped(sender: DFCheckButton) { if sender.isChecked { sender.isChecked = false currentSelectedButton.remove(at: currentSelectedButton.index(of: sender)!) // sender.removeTarget(self, action: #selector(DFCheckButtonController.buttonTapped(sender:)), for: UIControlEvents.touchUpInside) } else { sender.isChecked = true currentSelectedButton.append(sender) } for button in currentSelectedButton { print(button.titleLabel?.text) } } }
true
d4d54c53cd00fa1ec80a2bac94d3a258708126d1
Swift
jpv88/CanaryPosts
/CanaryPosts/CanaryPosts/Modules/Detail/View/DefaultDetailViewController.swift
UTF-8
1,979
2.71875
3
[]
no_license
// // DefaultDetailViewController.swift // CanaryPosts // // Created by Jared Perez Vega on 29/7/21. // import UIKit class DefaultDetailViewController: BaseViewController { internal var postTitle: UILabel! internal var postBody: UILabel! internal var ownerPost: UILabel! internal var commentsTitle: UILabel! internal var tableView: UITableView! var viewModel: DetailViewModel? var tableManager: CommentsPostsTableManager? internal enum Constant { static let title = "Canary Post Detail" static let accessibilityIdentifier = "DetailView" static let commentsLabel = "Comments on Post:" static let postOwnerTitle = "Post Owner:" static let marginSeparator: CGFloat = 16 } override func viewDidLoad() { super.viewDidLoad() viewModel?.onViewDidLoad() } override func buildComponents() { super.buildComponents() buildView() } override func setUpLayout() { super.setUpLayout() layoutView() } } // MARK: HomeViewController Protocol extension DefaultDetailViewController: DetailViewController { func showThisError(error: Error) { showError(error: error) } func showPostInfo(title: String, body: String) { DispatchQueue.main.async { [weak self] in self?.postTitle.text = title self?.postBody.text = body } } func showOwnerInfo(name: String) { DispatchQueue.main.async { [weak self] in self?.ownerPost.text = "\(Constant.postOwnerTitle) \(name)" } } func showComments(input: CommentsModel) { tableManager?.set(input: input) } } // MARK: ListPostsActions Protocol extension DefaultDetailViewController: CommentsPostsActions { func updateUI() { DispatchQueue.main.async { [weak self] in self?.tableView.reloadData() } } }
true
b2e9c6170f66b9b49a0b0b3e505988091c3e1812
Swift
sandydev33/Staqo
/Staqo/Shared/Extension.swift
UTF-8
1,424
2.671875
3
[]
no_license
// // Extension.swift // // // Created by apple on 27/03/19. // Copyright © 2019 ESoft Technologies. All rights reserved. // import Foundation import UIKit extension UINavigationBar { func setGradientBackground() { var colors:[Any] = [] if #available(iOS 11.0, *) { colors = [UIColor(named: "NavGreen")?.cgColor as! CGColor, UIColor(named: "NavBlue")?.cgColor as! CGColor] } else { // Fallback on earlier versions } let gradient: CAGradientLayer = CAGradientLayer() gradient.startPoint = CGPoint(x: 0, y: 0.5) gradient.endPoint = CGPoint(x: 1, y: 0.5) var bounds = self.bounds bounds.size.height += UIApplication.shared.statusBarFrame.size.height gradient.frame = bounds gradient.colors = colors; self.setBackgroundImage(self.image(gradientLayer: gradient), for: .default) } private func image(gradientLayer: CAGradientLayer) -> UIImage? { var gradientImage:UIImage? UIGraphicsBeginImageContext(gradientLayer.frame.size) if let context = UIGraphicsGetCurrentContext() { gradientLayer.render(in: context) gradientImage = UIGraphicsGetImageFromCurrentImageContext()?.resizableImage(withCapInsets: UIEdgeInsets.zero, resizingMode: .stretch) } UIGraphicsEndImageContext() return gradientImage } }
true
5e4709a440c3225f7ee5634410633d6acd737770
Swift
gmary95/Diploma
/Diploma/UserInterface/Main/MainVIewController.swift
UTF-8
5,390
2.609375
3
[]
no_license
// // ViewController.swift // Recorder // // Created by Aurelius Prochazka, revision history on Githbub. // Copyright © 2017 Aurelius Prochazka. All rights reserved. // import Cocoa import Charts import AVFoundation class MainViewController: NSViewController { @IBOutlet weak var stopButton: NSButton! @IBOutlet weak var startButton: NSButton! @IBOutlet weak var soundChart: LineChartView! @IBOutlet weak var timeLabel: NSTextField! var audioControl: AudioControl? var meterTimer: DispatchSourceTimer? var soundData: Data? override func viewDidLoad() { super.viewDidLoad() soundChart.noDataTextColor = .white startButton.isEnabled = true stopButton.isEnabled = false } @IBAction func startRecord(_ sender: Any) { setPath() } @IBAction func stopRecord(_ sender: Any) { if self.stopButton.isEnabled { self.audioControl?.stopRecord() self.stopButton.isEnabled = false self.startButton.isEnabled = true self.meterTimer?.cancel() self.timeLabel.stringValue = "" let alert:NSAlert = NSAlert() alert.messageText = "Recording finished" alert.alertStyle = NSAlert.Style.informational alert.runModal() } } @IBAction func openFile(_ sender: Any) { let dialog = NSOpenPanel() let path = "/Users⁩/gmary⁩/Desktop/" dialog.directoryURL = NSURL.fileURL(withPath: path, isDirectory: true) dialog.title = "Choose a file" dialog.showsResizeIndicator = true dialog.showsHiddenFiles = false dialog.canChooseDirectories = true dialog.canCreateDirectories = true dialog.allowsMultipleSelection = false dialog.allowedFileTypes = ["wav"] if (dialog.runModal() == NSApplication.ModalResponse.OK) { let result = dialog.url // Pathname of the file if (result != nil) { let path = result!.path openAndRead(filePath: result!) } } else { // User clicked on "Cancel" return } } func openAndRead(filePath: URL) { do { soundData = try Data(contentsOf: filePath) startFilter() } catch { let alert:NSAlert = NSAlert() alert.messageText = "You choose incorect file or choose noone." alert.alertStyle = NSAlert.Style.informational alert.runModal() } } func record() { if startButton.isEnabled { print("start recording") self.stopButton.isEnabled = true self.startButton.isEnabled = false self.audioControl?.startRecord() setupUpdateMeter() } else { print("recording not possible. no file loaded") } } func setPath() { print("Set Path") let panel = NSSavePanel() panel.allowedFileTypes = ["wav"] let choice = panel.runModal() switch(choice) { case .OK : self.audioControl = AudioControl(path:panel.url!) record() break; case .cancel : print("canceled") break; default: print("test") break; } } func setupUpdateMeter() { self.meterTimer = DispatchSource.makeTimerSource(flags: [], queue: DispatchQueue.main) self.meterTimer?.schedule(deadline: .now(), repeating: .microseconds(100)) self.meterTimer?.setEventHandler { self.timeLabel.stringValue = "\(Float(((self.audioControl?.getTime())!*10).rounded()/10))s" } self.meterTimer?.resume() } func startFilter() { var wavcat = soundData!.subdata(in: 1024 ..< soundData!.count) let tmp = dataToInt(data: wavcat) print(tmp) representChart(timeSeries: tmp, chart: soundChart) } func dataToInt(data: Data) -> [UInt16] { var result: [UInt16] = [] for i in 0 ..< data.count / 2 { let bytes: [UInt8] = [data[i * 2], data[i * 2 + 1]] let u16 = UnsafePointer(bytes).withMemoryRebound(to: UInt16.self, capacity: 1) { $0.pointee } result.append(u16) } return result } func representChart(timeSeries: Array<UInt16>, chart: LineChartView){ let series = timeSeries.enumerated().map { x, y in return ChartDataEntry(x: Double(x), y: Double(y)) } let data = LineChartData() let dataSet = LineChartDataSet(values: series, label: "Current sound") dataSet.colors = [NSUIColor.yellow] dataSet.valueColors = [NSUIColor.white] dataSet.drawCirclesEnabled = false data.addDataSet(dataSet) chart.data = data chart.gridBackgroundColor = .red chart.legend.textColor = .white chart.xAxis.labelTextColor = .white chart.leftAxis.labelTextColor = .white chart.rightAxis.labelTextColor = .white } }
true
710bf0b04a98b7926e69c52dedcdfad270873fe1
Swift
johndpope/Soundify
/SFCoreDataManager.swift
UTF-8
4,450
2.59375
3
[]
no_license
// // SFCoreDataManager.swift // Soundify // // Created by MaahiHiten on 19/10/16. // Copyright © 2016 MaahiHiten. All rights reserved. // import UIKit import CoreData import MediaPlayer enum DatabaseErrors: Error { case itemNotExist } class SFCoreDataManager: NSObject { static let sharedInstance = SFCoreDataManager() func addOrUpdateItemsInCoreData() { //https://www.youtube.com/watch?v=-4wvf3QjHiM let allSongs = MPMediaQuery.songs().items for item in allSongs! { let existenceItems = self.existingItemsInDatabase() var existingItemsPersistenceIds : [String]? = Array.init() for (_, item) in (existenceItems?.enumerated())! { existingItemsPersistenceIds?.append(item.itemPersistenceId!) } if !(existingItemsPersistenceIds?.contains("\(item.persistentID)"))! { let recored = NSEntityDescription.insertNewObject(forEntityName: "SFItem", into: sfCoreDataStack.managedObjectContext) as! SFItem recored.isItemLiked = false recored.itemPlayedCount = 0 recored.itemLastPlayedDate = nil recored.itemPersistenceId = "\(item.persistentID)" } } sfCoreDataStack.saveContext() } func existingItemsInDatabase() -> [SFItem]?{ let fetchRequest = NSFetchRequest<SFItem>(entityName: "SFItem") do { let existingItems = try sfCoreDataStack.managedObjectContext.fetch(fetchRequest) return existingItems } catch{ NSLog("error in fetching items..!") } return nil } func itemWithPersistenceId(itemPersistenceId : String) -> SFItem? { let existenceItems : [SFItem] = self.existingItemsInDatabase()! for (_, item) in (existenceItems.enumerated()) { if item.itemPersistenceId == itemPersistenceId{ return item } } return nil } func updateLikedStateOfItem(withItemPersistenceId itemPersistenceId : String) { let existenceItems : [SFItem] = self.existingItemsInDatabase()! for (_, item) in (existenceItems.enumerated()) { if item.itemPersistenceId == itemPersistenceId{ if item.isItemLiked{ item.isItemLiked = true } else{ item.isItemLiked = false } } } sfCoreDataStack.saveContext() } func updatePlayedCountOfItem(withItemPersistenceId itemPersistenceId : String) { let existenceItems : [SFItem] = self.existingItemsInDatabase()! for (_, item) in (existenceItems.enumerated()) { if item.itemPersistenceId == itemPersistenceId{ item.itemPlayedCount += 1 } } sfCoreDataStack.saveContext() } func updateItemLastPlayedDate(withItemPersistenceId itemPersistenceId : String) { let existenceItems : [SFItem] = self.existingItemsInDatabase()! for (_, item) in (existenceItems.enumerated()) { if item.itemPersistenceId == itemPersistenceId{ item.itemLastPlayedDate = NSDate() } } sfCoreDataStack.saveContext() } // MARK: Media Items Query func allMediaItems() -> [MPMediaItem] { return MPMediaQuery.songs().items! } func allPlayLists() -> [MPMediaItemCollection] { return MPMediaQuery.playlists().collections! } func allAlbums() -> [MPMediaItemCollection] { return MPMediaQuery.albums().collections! } func allArtists() -> [MPMediaItemCollection] { return MPMediaQuery.playlists().collections! } func mediaItem(withPersistenceId itemPersistenceId : String) -> MPMediaItem? { let allMediaItems : [MPMediaItem] = self.allMediaItems() for (_, mediaItem) in (allMediaItems.enumerated()) { if "\(mediaItem.persistentID)" == itemPersistenceId{ return mediaItem } } return nil } }
true
6d918c5c4b01430ba3d7526862b647ed15a2c822
Swift
yuichirokato/RealmtTranslator
/RealmTranslator/DialogRealmModel.swift
UTF-8
1,487
2.671875
3
[]
no_license
// // DialogRealmModel.swift // RealmTranslator // // Created by TakahashiYuichirou on 2016/05/17. // Copyright © 2016年 TakahashiYuichirou. All rights reserved. // import UIKit import RealmSwift class DialogRealmModel: Object, CSVConvertible { dynamic var id: Int = 0 dynamic var dialog = "" dynamic var dialogJapanese = "" dynamic var dialogAnswer = "" dynamic var dialogAnswerJapanese = "" dynamic var wrongAnswer1 = "" dynamic var wrongAnswer2 = "" dynamic var wrongAnswer3 = "" dynamic var quesFileName = "" dynamic var answerFileName = "" dynamic var lessonId: Int = 0 override static func primaryKey() -> String? { return "id" } func convertFromCSV(row: [String]) -> Object { id = Int(row[0]) ?? -1 dialog = row[1] dialogJapanese = row[2] dialogAnswer = row[3] dialogAnswerJapanese = row[4] wrongAnswer1 = row[5] wrongAnswer2 = row[6] wrongAnswer3 = row[7] quesFileName = row[8] answerFileName = row[9] lessonId = Int(row[10]) ?? -1 return self } } class DialogLessonRealmModel: Object, CSVConvertible { dynamic var id: Int = 0 dynamic var name = "" override static func primaryKey() -> String? { return "id" } func convertFromCSV(row: [String]) -> Object { id = Int(row[0]) ?? -1 name = row[1] return self } }
true
77fc40909449325f1fcce69cc0ece5b79128bf2d
Swift
IbrahimZananiri/swifty-traveller
/Sources/App/ExpediaService/ExpediaService.swift
UTF-8
1,551
2.90625
3
[ "MIT" ]
permissive
// // OffersService.swift // travellerPackageDescription // // Created by Ibrahim Z on 10/8/17. // import Foundation import Vapor // ExpediaService for interacting with the Expedia API // This service can handle mapping and is scalable for other Offerables public class ExpediaService { // Vapor HTTP Client immutable property private let client: Responder // Initializer with a Vapor client public init(client: Responder) { self.client = client } // Possible operation errors enum public enum OpError: Error { // Thrown when bytes of Response are nil case nilBytes } // Fetch mapped OffersEnvelope by passing OfferRequest<T : Offerable> (which carries productType // and Filter instance) // Generic T is of Offerable type, e.g. HotelOffer, FlightOffer. // This method can throw. public func fetchOffersEnvelope<T>(request: OfferRequest<T>) throws -> OffersEnvelope<T> { // Ask the client to perform the request let response = try client.respond(to: request.httpRequest) guard let responseBodyBytes = response.body.bytes else { throw OpError.nilBytes } let responseBodyBytesData = Data(bytes: responseBodyBytes) // OffersEnvelope (and children properties) conform to Decodable protocol // and hence can be decoded. This is a Swift 4.0 feature. let envelope = try JSONDecoder().decode(OffersEnvelope<T>.self, from: responseBodyBytesData) return envelope } }
true
5e2f349e0243442c3557868cd09bc1c01bf5bb54
Swift
mario-deluna/Swift-imgui
/Sources/ImGuiSwift/ImGui.swift
UTF-8
1,265
2.765625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
// // ImGui.swift // Swift-imgui // // Created by Hiroaki Yamane on 5/13/17. // Copyright © 2017 Hiroaki Yamane. All rights reserved. // public class ImGui { public enum API { case metal case opengl } public static var vc: ViewControllerAlias? public class func initialize(_ api: API = .opengl, fontPath: String? = nil) { switch api { case .metal: vc = ImGuiMTKViewController(fontPath: fontPath) if let vc = vc as? ImGuiMTKViewController { if !vc.isAvailable { print("Metal API is not available, falling back to OpenGL API.") initialize(.opengl, fontPath: fontPath) } } break case .opengl: #if os(iOS) vc = ImGuiGLKViewController(fontPath: fontPath) #endif break default: break } } public class func reset() { if var vc = vc as? ImGuiViewControllerProtocol { vc.drawBlocks.removeAll() } } public class func draw(_ block: @escaping ImGuiDrawCallback) { if var vc = vc as? ImGuiViewControllerProtocol { vc.drawBlocks.append(block) } } }
true
d49c3f141d57cf9472f5873ba56a5d9439763fee
Swift
Mike-Pai/MikeOnlinGame
/MikeOnlinGame/Firsebase/StorageOfFirebase.swift
UTF-8
2,684
3.203125
3
[]
no_license
// // StorageOfFirebase.swift // MikeOnlinGame // // Created by 白謹瑜 on 2021/6/13. // import SwiftUI import Foundation import FirebaseStorage import FirebaseStorageSwift import FirebaseAuth func uploadPhoto(image: UIImage, completion: @escaping (Result<URL, Error>) -> Void) { let fileReference = Storage.storage().reference().child(UUID().uuidString + ".jpg") if let data = image.jpegData(compressionQuality: 0.9) { fileReference.putData(data, metadata: nil) { result in switch result { case .success(_): fileReference.downloadURL { result in switch result { case .success(let url): completion(.success(url)) case .failure(let error): completion(.failure(error)) } } case .failure(let error): completion(.failure(error)) } } } } func setUserPhoto(url: URL, completion: @escaping (Result<String, Error>) -> Void) { print("setUserPhoto URL: \(url)") let changeRequest = Auth.auth().currentUser?.createProfileChangeRequest() changeRequest?.photoURL = url changeRequest?.commitChanges(completion: { error in guard error == nil else { print(error?.localizedDescription) completion(.failure(error!)) return } }) completion(.success("setUserPhoto success")) } func downloadUserImage(str:String, url: URL, completion: @escaping (Result<UIImage, Error>) -> Void) { if url == URL(string: "https://www.google.com.tw/?client=safari&channel=iphone_bm")! { completion(.success(UIImage(systemName: "person")!)) } if let user = Auth.auth().currentUser { // Create a reference to the file you want to download let httpsReference = Storage.storage().reference(forURL:url.absoluteString) print("downloadUserProfileImg(\(str): \(httpsReference)") // Download in memory with a maximum allowed size of 1MB (1 * 1024 * 1024 bytes) httpsReference.getData(maxSize: 1 * 1024 * 1024) { data, error in if let error = error { // Uh-oh, an error occurred! print(error.localizedDescription) completion(.failure(error)) } else { // Data for "images/island.jpg" is returned let image = UIImage(data: data!) completion(.success(image ?? UIImage(systemName: "person")!)) } } } }
true
09c7d0648c8d0f884e67ead35bb019972f8bb68f
Swift
efremidze/Alarm
/Alarm/Views/SwitchTableViewCell.swift
UTF-8
871
2.609375
3
[ "Apache-2.0" ]
permissive
// // SwitchTableViewCell.swift // Alarm // // Created by Lasha Efremidze on 2/8/17. // Copyright © 2017 Lasha Efremidze. All rights reserved. // import UIKit class SwitchTableViewCell: UITableViewCell { lazy var switchView: UISwitch = { [unowned self] in let view = UISwitch() view.addTarget(self, action: #selector(_valueChanged), for: .valueChanged) self.accessoryView = view return view }() var valueChanged: ((UISwitch) -> Void)? @IBAction func _valueChanged(sender: UISwitch) { self.valueChanged?(sender) } override func layoutSubviews() { super.layoutSubviews() imageView?.frame.origin.x = 8 imageView?.frame.size = CGSize(width: 38, height: 38) imageView?.center.y = contentView.center.y textLabel?.frame.origin.x = 54 } }
true
6be0a7891416ce3384c2d3a9a0069f2200329d52
Swift
DhrubojyotiBis1/Quizzler
/Quizzler/Question.swift
UTF-8
341
2.640625
3
[]
no_license
// // Quesion.swift // Quizzler // // Created by Dhrubojyoti on 27/12/18. // Copyright © 2018 London App Brewery. All rights reserved. // import Foundation class Question{ let question : String let answere : Bool init(text qsn : String , correctAnswer ans :Bool){ question = qsn answere = ans } }
true
26ddddc4440f4e2b779775b5f52e8221b470ab2e
Swift
tsubbi/OpenRestaurant
/OpenRestaurant/Models/CategoryList.swift
UTF-8
2,023
3.34375
3
[]
no_license
// // CategoryList.swift // OpenRestaurant // // Created by Jamie Chen on 2021-05-26. // import Foundation struct CategoryList { private var entreesList: [MenuItem] = [] private var appetizersList: [MenuItem] = [] private var saladsList: [MenuItem] = [] private var soupsList: [MenuItem] = [] private var dessertsList: [MenuItem] = [] private var sandwichesList: [MenuItem] = [] init(dataSource: [MenuItem]) { dataSource.forEach({ addItemToList(category: $0.category, item: $0) }) } func getList(category: String) -> [MenuItem] { guard let type = CategoryListType(rawValue: category) else { return [] } switch type { case .appetizers: return appetizersList case .desserts: return dessertsList case .entrees: return entreesList case .salads: return saladsList case .sandwiches: return sandwichesList case .soups: return soupsList } } mutating func addItemToList(category: String, item: MenuItem) { guard let type = CategoryListType(rawValue: category) else { return } switch type { case .appetizers: appetizersList.append(item) case .salads: saladsList.append(item) case .soups: soupsList.append(item) case .entrees: entreesList.append(item) case .desserts: dessertsList.append(item) case .sandwiches: sandwichesList.append(item) } } func filterEmptyList() -> [[MenuItem]] { return [entreesList, appetizersList, saladsList, soupsList, dessertsList, sandwichesList].filter({ !$0.isEmpty }) } } enum CategoryListType: String, CaseIterable { case appetizers case salads case soups case entrees case desserts case sandwiches var name: String { return self.rawValue.capitalized } }
true
976151f448da3d6e9573e9cdcf37e4a87ddc7746
Swift
nickswiss/picczle_ios
/Picczle/Puzzle.swift
UTF-8
1,157
3.25
3
[]
no_license
// // Puzzle.swift // Picczle // // Created by Nick Arnold on 11/24/15. // Copyright © 2015 Swiss. All rights reserved. // import Foundation import UIKit import SwiftyJSON class Puzzle: Equatable { var id: String var title: String var imageURL: String var message: String init(id: String, title: String, imageURL: String, message: String) { self.id = id self.title = title self.imageURL = imageURL self.message = message } static func puzzlesFromJSON(json: JSON) -> [Puzzle] { var puzzles: [Puzzle] = [] for(var i = 0; i < json.count; i++) { puzzles.append(puzzleFromJSON(json[i])) } return puzzles } static func puzzleFromJSON(json: JSON) -> Puzzle { let id = json["id"].stringValue let title = json["title"].stringValue let image = json["image"].stringValue let message = json["message"].stringValue let p = Puzzle(id: id, title: title, imageURL: image, message: message) return p } } func == (lhs: Puzzle, rhs: Puzzle) -> Bool { return lhs.id == rhs.id }
true
41e3d0a781cd9172c783428f41f43961ad4ec31c
Swift
goRestart/algolia-client
/Sources/AlgoliaSearch/Core/Infrastructure/Service/Index/IndexService.swift
UTF-8
534
2.78125
3
[]
no_license
import Foundation enum IndexService { case add(object: [String: Any], index: Index) } // MARK: IndexService + ServiceTarget extension IndexService: ServiceTarget { var path: String { switch self { case let .add(object: _, index: index): return Api.v1("/indexes/\(index.name)") } } var method: Method { switch self { case .add(_ , _): return .post } } var json: [String: Any]? { switch self { case let .add(object: object, index: _): return object } } }
true
e00eeac3d6aa5793e09a6b2ef52c766ea7d58918
Swift
paultopia/gdriveWithUIExperiment
/gdriveWithUIExperiment/downloadPDF.swift
UTF-8
3,018
2.921875
3
[ "MIT" ]
permissive
// // downloadPDF.swift // gdriveWithUIExperiment // // Created by Paul Gowder on 5/26/19. // Copyright © 2019 Paul Gowder. All rights reserved. // // if you send a second file before the first is done, they both get converted but they end up with the name of the second---need coordination for this. import Foundation func makeDestinationURL() -> URL { let fileManager = FileManager.default let inURL = hackishGlobalState.chosenFile! let downloadsDirectory = FileManager.default.urls(for: .downloadsDirectory, in: .userDomainMask).first! var filename = inURL.deletingPathExtension().appendingPathExtension("pdf").lastPathComponent print(filename) var outURL = downloadsDirectory.appendingPathComponent(filename, isDirectory: false) if fileManager.fileExists(atPath: outURL.path) { print("file exists! adding UUID.") filename = outURL.deletingPathExtension().lastPathComponent + "-\(UUID().uuidString).pdf" outURL = downloadsDirectory.appendingPathComponent(filename, isDirectory: false) } return outURL } func copyTempPDF(tempFile: URL, destination: URL){ let fileManager = FileManager.default do { try fileManager.copyItem(at: tempFile, to: destination) } catch { print("file error: \(error)") } } public func createTempPDFFile(contents: Data) -> URL { let fileManager = FileManager.default let dest = fileManager.temporaryDirectory .appendingPathComponent(UUID().uuidString) .appendingPathExtension("pdf") try! contents.write(to: dest) return dest } func downloadCurrentFile(deleteOnServer: Bool = true){ let fileID = hackishGlobalState.uploadedFileID! let endpoint = "https://www.googleapis.com/drive/v3/files/\(fileID)/export" let token = accessToken.get()! let authQuery = URLQueryItem(name: "access_token", value: token) let mimeQuery = URLQueryItem(name: "mimeType", value: "application/pdf") var urlComponents = URLComponents(string: endpoint)! urlComponents.queryItems = [authQuery, mimeQuery] let address = urlComponents.url! let session = URLSession.shared let task = session.dataTask(with: address, completionHandler: {data, response, error in if error != nil || data == nil { print("Client error!") return } let resp = response as! HTTPURLResponse guard (200...299).contains(resp.statusCode) else { print("Server error: \(resp.statusCode)") print(String(data: data!, encoding: .utf8)!) print(response) return } print("success!") print("ABOUT TO PRINT DATA FILE") let temp = createTempPDFFile(contents: data!) let dest = makeDestinationURL() copyTempPDF(tempFile: temp, destination: dest) print(dest.absoluteString) if deleteOnServer { print("deleting file on server") deleteFile(fileID: fileID) } }) task.resume() }
true
7f21988caa3ef8fe32fea28a8a16940405d7ba0a
Swift
grantfogle/first_ios_playground
/Pages/Arrays.xcplaygroundpage/Contents.swift
UTF-8
1,024
3.859375
4
[]
no_license
// Collections and Control Flow // Arrays var todo: [String] = ["Finish collections course", "Buy groceries", "Respond to emails"] todo.append("Pick up dry cleaning") var numbers: [Int] = [1, 2, 3] // Concatenating two Arrays [1,2,3] + [4] todo += ["Order book online"] todo[0] todo.insert("Do stuff", at:2) todo todo.remove(at: 2) todo.count todo[todo.count-1] // //Dictionaries /* Airport Code (Key) Airport Name(Value) DIA Denver Intl Airport */ var airportCodes: [String: String] = [ "DIA": "Denver Intl Airport", "LHR": "Heathrow", "CDG": "Charles De Gaulle", "NRT": "Tokyo Narita" ] let currentWeather = ["Denver": 72] airportCodes["DIA"] // Insert a new key value pair airportCodes["SLC"] = "Salt Lake Airport" airportCodes.updateValue("Sydney Airport", forKey:"SYD") airportCodes //Removing key value pairs airportCodes["SLC"] = nil airportCodes.removeValue(forKey: "SYD") airportCodes let denverAirport = airportCodes["DIA"]
true
27bfae2220f33b4dc0dd138170a3ce0f393f733f
Swift
elveatles/Diary
/Diary/Models/Photo+CoreDataProperties.swift
UTF-8
2,438
3.078125
3
[]
no_license
// // Photo+CoreDataProperties.swift // Diary // // Created by Erik Carlson on 12/19/18. // Copyright © 2018 Round and Rhombus. All rights reserved. // // import Foundation import CoreData import UIKit extension Photo { @nonobjc public class func fetchRequest() -> NSFetchRequest<Photo> { let request = NSFetchRequest<Photo>(entityName: "Photo") let sortDescriptor = NSSortDescriptor(key: "createDate", ascending: true) request.sortDescriptors = [sortDescriptor] return request } @NSManaged public var createDate: Date @NSManaged public var imageData: NSData @NSManaged public var thumbnailData: NSData @NSManaged public var post: Post? } // MARK: - Non-generated code. extension Photo: CoreDataEntity {} extension Photo: PhotoProtocol {} extension Photo { /// Get a UIImage from imageData or set imageData with a UIImage. var image: UIImage { get { let data = imageData as Data guard let result = UIImage(data: data) else { print("Could not create UIImage from imageData.") return UIImage() } return result } set { guard let pngData = newValue.pngData() else { print("Could not create png data from UIImage.") return } imageData = pngData as NSData } } /// Get a UIImage from thumbnailData or set thumbnailData with a UIImage var thumbnailImage: UIImage { get { let data = thumbnailData as Data guard let result = UIImage(data: data) else { print("Could not create UIImage from thumbanilData.") return UIImage() } return result } set { guard let pngData = newValue.pngData() else { print("Could not create png data from thumbnailImage.") return } thumbnailData = pngData as NSData } } /** Copy attributes from a temp photo. - Parameter tempPhoto: The temp photo to copy from. */ func copy(from tempPhoto: TempPhoto) { self.createDate = tempPhoto.createDate self.image = tempPhoto.image self.thumbnailImage = tempPhoto.thumbnailImage } }
true
3a29b198f947a674f5b89e6751a0c05c3c2cc67f
Swift
ObuchiYuki/Pielotopica
/Pielotopica/SandBox/Impl/Blocks/TS_House.swift
UTF-8
1,560
2.84375
3
[]
no_license
// // TS_House.swift // Pielotopica // // Created by yuki on 2019/09/02. // Copyright © 2019 yuki. All rights reserved. // import SceneKit import UIKit class TS_House: TSBlock { // =============================================================== // // MARK: - Properties - public let color:HouseColor // =============================================================== // // MARK: - Methods - enum HouseColor { case red case green case blue } init(color: HouseColor, nodeNamed nodeName: String, index: Int) { self.color = color super.init(nodeNamed: nodeName, index: index) } override func createNode() -> SCNNode { let node = super.createNode() let image:UIImage switch color { case .green: image = UIImage(named: "TP_house_green")! case .blue: image = UIImage(named: "TP_house_blue")! case .red: image = UIImage(named: "TP_house_red")! } node.fmaterial?.diffuse.contents = image return node } override func getOriginalNodeSize() -> TSVector3 { return [2, 2, 2] } override func getHardnessLevel() -> Int { return 20 } override func isObstacle() -> Bool { return true } override func canDestroy(at point: TSVector3) -> Bool { return true } override func shouldAnimateWhenPlaced(at point: TSVector3) -> Bool { return true } }
true
6c6a384d0b6dc0ff32f1b6f7db0d0898413baa84
Swift
gmCrivelli/MovieNight
/MovieNight/Services/ColorSchemeManager.swift
UTF-8
926
3.03125
3
[ "MIT" ]
permissive
// // ColorSchemeManager.swift // MovieNight // // Created by Gustavo De Mello Crivelli on 12/11/18. // Copyright © 2018 Movile. All rights reserved. // import Foundation import UIKit class ColorSchemeManager { // Singleton Instance static let shared = ColorSchemeManager() // Properties private let userDefaults = UserDefaults.standard var currentColorScheme: ColorScheme = ColorSchemeType(rawValue: 0)!.instance() // Private initializer private init() { reloadColorScheme() } // MARK: - Methods func reloadColorScheme() { if let schemeType = ColorSchemeType(rawValue: userDefaults.integer(forKey: UserDefaults.Keys.color)) { self.currentColorScheme = schemeType.instance() } } func saveColorScheme(to schemeType: ColorSchemeType) { userDefaults.set(schemeType.rawValue, forKey: UserDefaults.Keys.color) reloadColorScheme() } }
true
bba743bb797ec3f39b0392ef8364a56d19526bcb
Swift
Mobilette/Swift-best-practices
/Mobilette.playground/Pages/Error.xcplaygroundpage/Contents.swift
UTF-8
1,810
3.5625
4
[ "MIT" ]
permissive
/*: # Error Swift 2.0 introduce a new way to handle errors and we've created a protocol that should be implmented into enums that decribing errors. You should create a enum that implements the MBError protocol as follows: enum MappingError: MBError { case CanNotMapIntoObject(String) var code: Int { switch self { case .CanNotMapIntoObject: return 3001 } } var domain: String { return "MappingDomain" } var description: String { switch self { case .CanNotMapIntoObject: return "Can not map objects." } } var reason: String { switch self { case .CanNotMapIntoObject(let JSONString): return "'\(JSONString)' can not be mapped into an object." } } } So, you should be able to throw error as follows: throw MBOAuthCredentialError.UserIdentifierMissing ## Summary 1. [Storyboard](Storyboard) 2. [API](API) 3. [Router](Router) 4. [Credential](Credential) 5. _Error_ 6. [Safe arrays](Array) */ enum MappingError: MBError { case CanNotMapIntoObject(String) var code: Int { switch self { case .CanNotMapIntoObject: return 3001 } } var domain: String { return "MappingDomain" } var description: String { switch self { case .CanNotMapIntoObject: return "Can not map objects." } } var reason: String { switch self { case .CanNotMapIntoObject(let JSONString): return "'\(JSONString)' can not be mapped into an object." } } } MappingError.CanNotMapIntoObject("{objects: []}").error
true
b55f8767048f63dbb39ed0fb1e8b0c73dabf6f30
Swift
Antonppavlov/WhereMyFriends_iOS
/WhereMyFriends/ContTableViewController.swift
UTF-8
2,117
2.796875
3
[]
no_license
// // ContactsViewController.swift // WhereMyFriends // // Created by Anton Pavlov on 01.06.17. // Copyright © 2017 Anton Pavlov. All rights reserved. // import UIKit import Contacts class ContViewController: UITableViewController{ var peoples = Array<CNContact>() override func viewDidLoad() { super.viewDidLoad() loadDateFromContactStore() } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return peoples.count } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "ListCell", for: indexPath) let contacts = peoples[indexPath.row] cell.textLabel?.text = contacts.givenName cell.detailTextLabel?.text = contacts.phoneNumbers[0].value.stringValue return cell } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete{ peoples.remove(at: indexPath.row) self.tableView.reloadData() } } //MARK: Load date from ContactStore func loadDateFromContactStore() { let store = CNContactStore() var contacts = [CNContact]() let request = CNContactFetchRequest(keysToFetch: [CNContactIdentifierKey as NSString, CNContactPhoneNumbersKey as CNKeyDescriptor , CNContactFormatter.descriptorForRequiredKeys(for: .fullName)]) do { try store.enumerateContacts(with: request) { contact, stop in contacts.append(contact) } } catch { print(error) } peoples = contacts; } }
true
edadaab77bb4385b18e224ed4921088206a2c6e2
Swift
oscarvictoria/Pursuit-Core-Persistence-Lab
/PersistenceLab/PersistenceLab/APIClient/FileManager.swift
UTF-8
3,188
3.390625
3
[]
no_license
// // FileManager.swift // PersistenceLab // // Created by Oscar Victoria Gonzalez on 1/21/20. // Copyright © 2020 Oscar Victoria Gonzalez . All rights reserved. // import Foundation enum DataPersistanceError: Error { // conforming to the Error protocol case savingError(Error) // associative value case fileDoesNotExist(String) case noData case decodingError(Error) case deletingError(Error) } class PersistanceHelper { // CRUD - create, read, update, delete private static var photos = [Hits]() private static let filename = "photos.plist" // create - save item to documents directory private static func save() throws { let url = FileManager.pathToDocumentsDirectory(with: filename) // append new event to the events array // events array will be object being converted to data // we will use the data object and write (save) it to documents directory do { // convert (serialize) the events array to Data let data = try PropertyListEncoder().encode(photos) // writes, saves, persist the data to the documents directory try data.write(to: url, options: .atomic) } catch { throw DataPersistanceError.savingError(error) } } static func save(pictures: Hits) throws { // let url = FileManager.pathToDocumentsDirectory(with: filename) // append new event to the events array photos.append(pictures) try save() do { try save() } catch { throw DataPersistanceError.savingError(error) } // events array will be object being converted to data // we will use the data object and write (save) it to documents directory } // read - load (retrieve) items from documents directory static func loadEvents() throws -> [Hits] { // we need access to the filename url that we are reading from let url = FileManager.pathToDocumentsDirectory(with: filename) // check if file exist // to convert URL to string we use .path on the url if FileManager.default.fileExists(atPath: url.path) { if let data = FileManager.default.contents(atPath: url.path) { do { photos = try PropertyListDecoder().decode([Hits].self, from: data) } catch { throw DataPersistanceError.decodingError(error) } } else { throw DataPersistanceError.noData } } else { throw DataPersistanceError.fileDoesNotExist(filename) } return photos } // update - // delete - remove items from documents directory static func delete(photos index: Int) throws { photos.remove(at: index) // save our events array to the documents directory do { try save() } catch { throw DataPersistanceError.deletingError(error) } } }
true
4a8478db8a62696b53cc4dc607deca1661c0c9c4
Swift
gjaber/hackatruck
/revisao swift/06_Funções.playground/Pages/Encerramento.xcplaygroundpage/Contents.swift
UTF-8
705
3.203125
3
[]
no_license
/*: ## Encerramento Agora você já viu como as funções podem ser usadas para agrupar códigos de forma que uma tarefa complicada possa ser realizada com uma única linha de código, mesmo se essa linha usar muitas outras formuladas em outro lugar. Você também viu que usar uma função em vez de escrever vários códigos pode facilitar as alterações. Se decidir mudar a forma como um programa funciona, você só precisará alterá-lo em um lugar. Por último, você viu como as funções são abstrações poderosas. Faça os exercícios das próximas páginas para praticar o que aprendeu. [Anterior](@previous) | página 10 de 12 | [Na sequência: Meme funcional](@next) */
true
859d1ebeb49dfc90e9107323504214d03fa185d9
Swift
sarbogast/vapor-todobackend
/App/Dao/TodoDaoImpl.swift
UTF-8
3,717
2.6875
3
[ "MIT" ]
permissive
// // TodoDaoImpl.swift // VaporApp // // Created by Sebastien Arbogast on 16/05/2016. // // import Foundation import MongoKitten import Vapor class TodoDaoImpl: TodoDao { let collectionName = "todos" private let collection:MongoKitten.Collection init() throws { if let repository = MongoRepository.sharedRepository { self.collection = repository.database[collectionName] } else { throw MongoRepositoryError.CouldNotConnect } } func createTodo(_ todo:Todo) -> Todo? { do { let documentToInsert = todo.makeBson() let todoDocument = try self.collection.insert(documentToInsert) return try Todo(fromBson:todoDocument) } catch MongoError.InsertFailure(documents: _, error: let error) { Log.error("Could not insert todo because " + (error?["errmsg"].string)!) return nil } catch { Log.error("Error converting todo to BSON") return nil } } func findAllTodos() -> [Todo]? { do { var todos = [Todo]() let resultTodos = try self.collection.find() for result in resultTodos { if let todo = try Todo(fromBson: result) { todos.append(todo) } } return todos } catch { return nil } } func deleteAllTodos() { do { try self.collection.remove(matching: [] as Document) } catch { } } func getTodoWithId(_ id: String) -> Todo? { do { if let todoDocument = try self.collection.findOne(matching: "_id" == ObjectId(id)) { return try Todo(fromBson: todoDocument) } else { return nil } } catch { return nil } } func modifyTodoWithId(_ id: String, changes: [String : Any]) -> Todo? { do { if var todoDocument = try self.collection.findOne(matching: "_id" == ObjectId(id)) { if let title = changes["title"] as? String { todoDocument["title"] = ~title } if let completed = changes["completed"] as? Bool { todoDocument["completed"] = ~completed } if let order = changes["order"] as? Int { todoDocument["order"] = ~order } try self.collection.update(matching: "_id" == ObjectId(id), to: todoDocument) if let todoDocument = try self.collection.findOne(matching: "_id" == ObjectId(id)) { return try Todo(fromBson: todoDocument) } else { return nil } } else { return nil } } catch { return nil } } func deleteTodoWithId(_ id: String) { do { try self.collection.remove(matching: "_id" == ObjectId(id)) } catch { } } func updateTodo(_ todo: Todo) -> Todo? { do { if let id = todo.id { try self.collection.update(matching: "_id" == ObjectId(id), to: todo.makeBson()) if let todoDocument = try self.collection.findOne(matching: "_id" == ObjectId(id)) { return try Todo(fromBson: todoDocument) } else { return nil } } else { return nil } } catch { return nil } } }
true
8f597c5e0523a3e5670acd4306696d49e2bdd8c2
Swift
AppStudio2015/MyArchitecture
/code/MyArchitecture/MyArchitecture/Utils/Extensions/UIScreenExtensions.swift
UTF-8
2,445
2.71875
3
[ "MIT" ]
permissive
// // UIDeviceExtension.swift // MyApp // // Created by QF on 25/02/2018. // Copyright © 2018 AutoAi Inc. All rights reserved. // import UIKit extension UIScreen { /// 当前机型相对设计机型(iPhone6)的宽度系数 static private var widthScaleFactor: CGFloat = { return min(UIScreen.main.bounds.size.width ,UIScreen.main.bounds.size.height)/375.0 }() /// 当前机型相对设计机型(iPhone6)的高度系数 static private var heightScaleFactor: CGFloat = { return max(UIScreen.main.bounds.size.width ,UIScreen.main.bounds.size.height)/667.0 }() /// 获取屏幕高度 @objc class func height() -> CGFloat { return UIScreen.main.bounds.size.height; } /// 获取屏幕宽度 @objc class func width() -> CGFloat { return UIScreen.main.bounds.size.width; } /// 获取屏幕size @objc class func size() -> CGSize { return UIScreen.main.bounds.size; } /// 获取屏幕size短边 @objc class func minSide() -> CGFloat { return fmin(UIScreen.main.bounds.size.height, UIScreen.main.bounds.size.width); } /// 获取屏幕size长边 @objc class func maxSide() -> CGFloat { return fmax(UIScreen.main.bounds.size.height, UIScreen.main.bounds.size.width); } /// 获取状态栏高度(竖屏) @objc class func statusBarHeight() -> CGFloat { return UIDevice.current.isIPhoneXSeries() ? 44.0 : 20.0 } /// 规整尺寸 以0.5为单位进行向下取整处理 /// /// - Parameter size: 原尺寸 /// - Returns: 规整后的尺寸 @objc static func normalizerSize(_ size: CGFloat) -> CGFloat { return floor(size * 2.0) * 0.5 } /// 将设计尺寸转换为在当前机型上的真实宽度 /// /// - Parameter designWidth: 设计宽度(iPhone6) /// - Returns: 真实尺寸(0.5对齐) @objc static func relativeWidth(_ designWidth: CGFloat) -> CGFloat { return self.normalizerSize(widthScaleFactor * designWidth) } /// 将设计尺寸转换为在当前机型上的真实宽度 /// /// - Parameter designHeight: 设计高度(iPhone6) /// - Returns: 真实尺寸(0.5对齐) @objc static func relativeHeight(_ designHeight: CGFloat) -> CGFloat { return self.normalizerSize(heightScaleFactor * designHeight) } }
true
c7423de650f5be815308462bb944229cf02e6363
Swift
sammanthp007/DySi-Open
/DySiOpenTests/ErrorHandlerTests.swift
UTF-8
2,733
2.546875
3
[]
no_license
// // ErrorHandlerTests.swift // DySiOpenTests // // Created by Samman Thapa on 5/8/18. // Copyright © 2018 Samman Labs. All rights reserved. // import XCTest @testable import DySi_Open class MockUIViewController: UIViewController { var testDisplayedMessageToUserUsingAlertViewCount: Int = 0 var testTitleOfAlertView: String? var testMessageOfAlertView: String? override func displayMessageToUserUsingAlert(title: String, message: String, style: UIAlertControllerStyle, completion: (() -> Void)?, okButtonText: String, actionStyle: UIAlertActionStyle, afterHittingAction: ((UIAlertAction) -> Void)?) { testTitleOfAlertView = title testMessageOfAlertView = message testDisplayedMessageToUserUsingAlertViewCount += 1 } } class ErrorHandlerTests: XCTestCase { var sut: _ErrorHandler! var mockViewController: MockUIViewController! override func setUp() { super.setUp() // GIVEN mockViewController = MockUIViewController() sut = _ErrorHandler() } override func tearDown() { sut = nil mockViewController = nil // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func test_displayErrorOnDeviceScreen_calls_alertViewController_once() { // WHEN sut.displayErrorOnDeviceScreen(viewController: mockViewController, error: nil) // THEN XCTAssertEqual(mockViewController.testDisplayedMessageToUserUsingAlertViewCount, 1) } func test_displayErrorOnDeviceScreen_calls_alertViewControllerWithDefaultMessages_with_FallBackTitleAndMessage_on_EmptyError() { // WHEN sut.displayErrorOnDeviceScreen(viewController: mockViewController, error: nil) // THEN XCTAssertEqual(mockViewController.testTitleOfAlertView!, Constants.CustomErrors.Fallback.title) XCTAssertEqual(mockViewController.testMessageOfAlertView!, Constants.CustomErrors.Fallback.message) } func test_displayErrorOnDeviceScreen_calls_alertViewControllerWithDefaultMessages_with_KnownUserFriendlyErrorTitleAndMessage_on_KnownCustomAppError() { // GIVEN let newError = NSError(domain: "DySiDataManagerError", code: 100, userInfo: ["message": " Could not unwrap the url for getting all public posts"]) // WHEN sut.displayErrorOnDeviceScreen(viewController: mockViewController, error: newError) // THEN XCTAssertEqual(mockViewController.testTitleOfAlertView!, "Uh oh!") XCTAssertEqual(mockViewController.testMessageOfAlertView!, "Unable to open the page. Please retry") } }
true
e707ccfb502cad5707cae1dcf8d2c398af1459c5
Swift
balenaik/thankYouList
/ThankYouList/Extensions/String+Validation.swift
UTF-8
494
2.84375
3
[]
no_license
// // String+Validation.swift // ThankYouList // // Created by Aika Yamada on 2023/01/04. // Copyright © 2023 Aika Yamada. All rights reserved. // import Foundation extension String { var isValidMail: Bool { return matches(regEx: "^[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}") } } private extension String { func matches(regEx: String) -> Bool { let predicate = NSPredicate(format: "SELF MATCHES%@", regEx) return predicate.evaluate(with: self) } }
true
a99cd42b0433ce13ccb194627d8c5f875373edf8
Swift
JeetSindal2/FamaCashAssignment
/FamaCashAssignment/FamaCashAssignment/RequestManager/ApiManager.swift
UTF-8
4,744
2.5625
3
[]
no_license
// // ApiManager.swift // FamaCashAssignment // // Created by Mac on 25/07/20. // Copyright © 2020 Jeet. All rights reserved. // import UIKit typealias ApiCompletionHandler = (Bool, Any?) -> Void class ApiManager: NSObject { static let sharedInstance = ApiManager() let baseUrl = "https://api.themoviedb.org/3/" func getGenreList(parameters: [String: Any], completion: @escaping ApiCompletionHandler) { let fullPath = baseUrl + genreListApiEndpoint makeHttpGetApiCall(path: fullPath, parameters: parameters) { (success, response) in if success { let genreList = ResponseManager.parseGenreResponse(response: response) completion(success, genreList) } else { completion(success, response) } } } func getMovieList(movieId: Int, parameters: [String: Any], completion: @escaping ApiCompletionHandler) { let fullPath = baseUrl + String(format: movieListApiEndPoint, String(movieId)) makeHttpGetApiCall(path: fullPath, parameters: parameters) { (success, response) in if success { let genreList = ResponseManager.parseMovieListResponse(response: response) completion(success, genreList) } else { completion(success, response) } } } func getMovieDetail(movieId: Int, parameters: [String: Any], completion: @escaping ApiCompletionHandler) { let fullPath = baseUrl + String(format: movieDetailApiEndPoint, String(movieId)) makeHttpGetApiCall(path: fullPath, parameters: parameters) { (success, response) in if success { let genreList = ResponseManager.parseMovieDetail(response: response) completion(success, genreList) } else { completion(success, response) } } } func getMovieVideoList(movieId: Int, parameters: [String: Any], completion: @escaping ApiCompletionHandler) { let fullPath = baseUrl + String(format: movieVideoListAPIEndPoint, String(movieId)) makeHttpGetApiCall(path: fullPath, parameters: parameters) { (success, response) in if success { let genreList = ResponseManager.parseMovieVideoList(response: response) completion(success, genreList) } else { completion(success, response) } } } func getMovieReviewList(movieId: Int, parameters: [String: Any], completion: @escaping ApiCompletionHandler) { let fullPath = baseUrl + String(format: movieReviewListAPIEndPoint, String(movieId)) makeHttpGetApiCall(path: fullPath, parameters: parameters) { (success, response) in if success { let genreList = ResponseManager.parseMovieReviewListResponse(response: response) completion(success, genreList) } else { completion(success, response) } } } private func makeHttpGetApiCall(path: String, parameters: [String: Any], completionHandler: @escaping ApiCompletionHandler) { var paramWithKey = parameters paramWithKey[kApiKey] = ApiKey let pathWithParam = path.getUrlWithParam(parameters: paramWithKey) guard let url = URL(string: pathWithParam) else { return } let request = URLRequest(url: url) let session = URLSession(configuration: .default) let dataTask = session.dataTask(with: request) { (data, response, error) in if error == nil { if let jsonData = data { let anyObject = try? JSONSerialization.jsonObject(with: jsonData, options: .allowFragments) print("Url: \(pathWithParam) response: \(anyObject ?? "")") if let httpRespnse = response as? HTTPURLResponse { if httpRespnse.statusCode == 401 || httpRespnse.statusCode == 404 { let errorMdl = ResponseManager.parseErrorResponse(response: anyObject) completionHandler(false, errorMdl) } else if httpRespnse.statusCode == 200 { completionHandler(true, anyObject) } else { completionHandler(false, anyObject) } } } else { completionHandler(false, nil) } } else { completionHandler(false, nil) } } dataTask.resume() } }
true
93b3dfd1b97aee924ab8314e5992abfc8d041edf
Swift
onl1ner/weather-ios
/Source/Weather/Common/Layers/Location/Location.swift
UTF-8
3,727
3.171875
3
[]
no_license
// // Location.swift // Weather // // Created by Tamerlan Satualdypov on 23.07.2021. // import CoreLocation typealias LocationResult = Result<(location: CLLocation, city: String), LocationError> typealias LocationCallback = (LocationResult) -> () protocol LocationProtocol { func set(lat: Double, lon: Double) -> () func clear() -> () func location(completion: LocationCallback?) -> () } final class Location: NSObject, LocationProtocol { public static let shared: LocationProtocol = Location() private var manager: CLLocationManager private var choosenLocation: CLLocation? private var isAuthorized: Bool { return CLLocationManager.authorizationStatus() == .authorizedAlways || CLLocationManager.authorizationStatus() == .authorizedWhenInUse } private var locationCallback: LocationCallback? private func flush(reason: LocationError) -> () { self.locationCallback?(.failure(reason)) self.locationCallback = nil } private func authorize() -> () { if CLLocationManager.authorizationStatus() == .notDetermined { return self.manager.requestWhenInUseAuthorization() } self.flush(reason: .unauthorized) } private func city(for location: CLLocation, completion: @escaping (String?) -> ()) { CLGeocoder().reverseGeocodeLocation(location) { placemarks, error in guard error == nil, let placemark = placemarks?.first, let city = placemark.locality else { return completion(nil) } completion(city) } } private func process(location: CLLocation, completion: LocationCallback?) -> () { self.city(for: location) { city in guard let city = city else { completion?(.failure(.geocode)) return } completion?(.success((location, city))) } } public func set(lat: Double, lon: Double) -> () { self.choosenLocation = .init(latitude: lat, longitude: lon) } public func clear() -> () { self.choosenLocation = nil } public func location(completion: LocationCallback?) -> () { if let location = self.choosenLocation { return self.process(location: location, completion: completion) } self.locationCallback = completion guard self.isAuthorized else { return self.authorize() } self.manager.startUpdatingLocation() } override public init() { self.manager = .init() super.init() self.manager.delegate = self } deinit { self.manager.stopUpdatingLocation() } } extension Location: CLLocationManagerDelegate { public func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) -> () { if status == .authorizedAlways || status == .authorizedWhenInUse { return self.location(completion: self.locationCallback) } self.flush(reason: .unauthorized) } public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) -> () { guard let location = locations.last else { return self.flush(reason: .internal) } self.process(location: location, completion: self.locationCallback) self.locationCallback = nil } public func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) -> () { self.flush(reason: .notDetermined) } }
true
8d92643ff10c4b6055831bef09ca441d221967ac
Swift
kvyatkovskys/KVKCalendar
/Sources/KVKCalendar/CalendarModel.swift
UTF-8
23,101
2.859375
3
[ "MIT" ]
permissive
// // CalendarModel.swift // KVKCalendar // // Created by Sergei Kviatkovskii on 25.02.2020. // #if os(iOS) import UIKit import EventKit @available(swift, deprecated: 0.6.5, obsoleted: 0.6.6, renamed: "CellParameter") public struct DateParameter { public var date: Date? public var type: DayType? } public struct CellParameter { public var date: Date? public var type: DayType? = .empty public var events: [Event] = [] } public enum TimeHourSystem: Int { @available(swift, deprecated: 0.3.6, obsoleted: 0.3.7, renamed: "twelve") case twelveHour = 0 @available(swift, deprecated: 0.3.6, obsoleted: 0.3.7, renamed: "twentyFour") case twentyFourHour = 1 case twelve = 12 case twentyFour = 24 var hours: [String] { switch self { case .twelveHour, .twelve: let array = ["12"] + Array(1...11).map { String($0) } let am = array.map { $0 + " AM" } + ["Noon"] var pm = array.map { $0 + " PM" } pm.removeFirst() if let item = am.first { pm.append(item) } return am + pm case .twentyFourHour, .twentyFour: let array = ["00:00"] + Array(1...24).map { (i) -> String in let i = i % 24 var string = i < 10 ? "0" + "\(i)" : "\(i)" string.append(":00") return string } return array } } @available(swift, deprecated: 0.5.8, obsoleted: 0.5.9, renamed: "current") public static var currentSystemOnDevice: TimeHourSystem? { current } public static var current: TimeHourSystem? { let locale = NSLocale.current guard let formatter = DateFormatter.dateFormat(fromTemplate: "j", options: 0, locale: locale) else { return nil } if formatter.contains("a") { return .twelve } else { return .twentyFour } } public var format: String { switch self { case .twelveHour, .twelve: return "h:mm a" case .twentyFourHour, .twentyFour: return "HH:mm" } } public var shortFormat: String { switch self { case .twelveHour, .twelve: return "h a" case .twentyFourHour, .twentyFour: return "HH:mm" } } } public enum CalendarType: String, CaseIterable, ItemsMenuProxy { case day, week, month, year, list public var title: String { rawValue.capitalized } } extension CalendarType: Identifiable { public var id: CalendarType { self } } // MARK: Event model @available(swift, deprecated: 0.4.1, obsoleted: 0.4.2, renamed: "Event.Color") public struct EventColor { let value: UIColor let alpha: CGFloat public init(_ color: UIColor, alpha: CGFloat = 0.3) { self.value = color self.alpha = alpha } } public struct TextEvent { public let timeline: String public let month: String? public let list: String? public init(timeline: String = "", month: String? = nil, list: String? = nil) { self.timeline = timeline self.month = month self.list = list } } public struct Event { static let idForNewEvent = "-999" /// unique identifier of Event public var ID: String public var title: TextEvent = TextEvent() public var start: Date = Date() public var end: Date = Date() public var color: Event.Color? = Event.Color(.systemBlue) { didSet { guard let tempColor = color else { return } let value = prepareColor(tempColor) backgroundColor = value.background textColor = value.text } } public var backgroundColor: UIColor = .systemBlue.withAlphaComponent(0.3) public var textColor: UIColor = .white public var isAllDay: Bool = false public var isContainsFile: Bool = false public var data: Any? = nil public var recurringType: Event.RecurringType = .none ///custom style ///(in-progress) works only with a default (widht & height) public var style: EventStyle? = nil public var systemEvent: EKEvent? = nil public init(ID: String) { self.ID = ID if let tempColor = color { let value = prepareColor(tempColor) backgroundColor = value.background textColor = value.text } } public init(event: EKEvent, monthTitle: String? = nil, listTitle: String? = nil) { ID = event.eventIdentifier title = TextEvent(timeline: event.title, month: monthTitle ?? event.title, list: listTitle ?? event.title) start = event.startDate end = event.endDate color = Event.Color(UIColor(cgColor: event.calendar.cgColor)) isAllDay = event.isAllDay systemEvent = event if let tempColor = color { let value = prepareColor(tempColor) backgroundColor = value.background textColor = value.text } } func prepareColor(_ color: Event.Color, brightnessOffset: CGFloat = 0.4) -> (background: UIColor, text: UIColor) { let bgColor = color.value.withAlphaComponent(color.alpha) var hue: CGFloat = 0, saturation: CGFloat = 0, brightness: CGFloat = 0, alpha: CGFloat = 0 color.value.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) let txtColor = UIColor(hue: hue, saturation: saturation, brightness: UIScreen.isDarkMode ? brightness : brightness * brightnessOffset, alpha: alpha) return (bgColor, txtColor) } } extension Event { enum EventType: String { case allDay, usual } } extension Event { var hash: Int { ID.hashValue } } public extension Event { var isNew: Bool { ID == Event.idForNewEvent } enum RecurringType: Int { case everyDay, everyWeek, everyMonth, everyYear, none var shift: Int { switch self { case .everyDay, .everyMonth, .everyYear: return 1 case .everyWeek: return 7 case .none: return 0 } } var component: Calendar.Component { switch self { case .everyDay, .everyWeek: return .day case .everyMonth: return .month case .everyYear: return .year case .none: return .nanosecond } } } struct Color { public let value: UIColor public let alpha: CGFloat public init(_ color: UIColor, alpha: CGFloat = 0.3) { self.value = color self.alpha = alpha } } } @available(swift, deprecated: 0.4.1, obsoleted: 0.4.2, renamed: "Event.RecurringType") public enum RecurringType: Int { case everyDay, everyWeek, everyMonth, everyYear, none } extension Event: EventProtocol { public func compare(_ event: Event) -> Bool { hash == event.hash } } extension Event { func updateDate(newDate: Date, calendar: Calendar = Calendar.current) -> Event? { var startComponents = DateComponents() startComponents.year = newDate.kvkYear startComponents.month = newDate.kvkMonth startComponents.hour = start.kvkHour startComponents.minute = start.kvkMinute var endComponents = DateComponents() endComponents.year = newDate.kvkYear endComponents.month = newDate.kvkMonth endComponents.hour = end.kvkHour endComponents.minute = end.kvkMinute let newDay = newDate.kvkDay switch recurringType { case .everyDay: startComponents.day = newDay case .everyWeek where newDate.kvkWeekday == start.kvkWeekday: startComponents.day = newDay startComponents.weekday = newDate.kvkWeekday endComponents.weekday = newDate.kvkWeekday case .everyMonth where (newDate.kvkYear != start.kvkYear || newDate.kvkMonth != start.kvkMonth) && newDate.kvkDay == start.kvkDay: startComponents.day = newDay case .everyYear where newDate.kvkYear != start.kvkYear && newDate.kvkMonth == start.kvkMonth && newDate.kvkDay == start.kvkDay: startComponents.day = newDay default: return nil } let offsetDay = end.kvkDay - start.kvkDay if start.kvkDay == end.kvkDay { endComponents.day = newDay } else { endComponents.day = newDay + offsetDay } guard let newStart = calendar.date(from: startComponents), let newEnd = calendar.date(from: endComponents) else { return nil } var newEvent = self newEvent.start = newStart newEvent.end = newEnd return newEvent } } // MARK: - Event protocol public protocol EventProtocol { func compare(_ event: Event) -> Bool } // MARK: - Settings protocol protocol CalendarSettingProtocol: AnyObject { var style: Style { get set } func reloadFrame(_ frame: CGRect) func updateStyle(_ style: Style, force: Bool) func reloadData(_ events: [Event]) func setDate(_ date: Date, animated: Bool) } extension CalendarSettingProtocol { func reloadData(_ events: [Event]) {} func setDate(_ date: Date, animated: Bool) {} func setUI(reload: Bool = false) {} var actualSelectedTimeZoneCount: CGFloat { guard style.selectedTimeZones.count > 1 else { return 0 } return CGFloat(style.selectedTimeZones.count) } var leftOffsetWithAdditionalTime: CGFloat { guard actualSelectedTimeZoneCount > 0 else { return style.timeline.allLeftOffset } return (actualSelectedTimeZoneCount * style.timeline.widthTime) + style.timeline.offsetTimeX + style.timeline.offsetLineLeft } func changeToTimeZone(_ hour: Int, from: TimeZone, to: TimeZone) -> Date { let today = Date() let components = DateComponents(year: today.kvkYear, month: today.kvkMonth, day: today.kvkDay, hour: hour, minute: 0) let date = Calendar.current.date(from: components) ?? today let sourceOffset = from.secondsFromGMT(for: date) let destinationOffset = to.secondsFromGMT(for: date) let timeInterval = TimeInterval(destinationOffset - sourceOffset) return Date(timeInterval: timeInterval, since: date) } func handleTimelineLabel(zones: [TimeZone], label: TimelineLabel) -> (current: TimelineLabel, others: [UILabel])? { var otherLabels = [UILabel]() let current = label zones.enumerated().forEach { let x = (CGFloat($0.offset) * current.frame.width) + style.timeline.offsetTimeX let otherLabel = UILabel(frame: CGRect(x: x, y: current.frame.origin.y, width: current.frame.width, height: current.frame.height)) let labelDate = changeToTimeZone(label.hashTime, from: style.timezone, to: $0.element) otherLabel.text = timeFormatter(date: labelDate, format: style.timeSystem.shortFormat) otherLabel.textAlignment = style.timeline.timeAlignment otherLabel.font = style.timeline.timeFont otherLabel.adjustsFontSizeToFitWidth = true if $0.element.identifier == style.timezone.identifier { current.frame = otherLabel.frame } else { otherLabels.append(otherLabel) } } return (current, otherLabels) } func timeFormatter(date: Date, format: String) -> String { let formatter = DateFormatter() formatter.dateFormat = format return formatter.string(from: date) } } // MARK: - Data source protocol public protocol CalendarDataSource: AnyObject { /// get events to display on view /// also this method returns a system events from iOS calendars if you set the property `systemCalendar` in style func eventsForCalendar(systemEvents: [EKEvent]) -> [Event] func willDisplayDate(_ date: Date?, events: [Event]) /// Use this method to add a custom event view func willDisplayEventView(_ event: Event, frame: CGRect, date: Date?) -> EventViewGeneral? /// Use this method to add a custom header subview (works for Day, Week, Month) func willDisplayHeaderSubview(date: Date?, frame: CGRect, type: CalendarType) -> UIView? /// Use this method to add a custom header view (works for Day, Week) //func willDisplayHeaderView(date: Date?, frame: CGRect, type: CalendarType) -> UIView? /// Use the method to replace the collectionView (works for Month, Year) func willDisplayCollectionView(frame: CGRect, type: CalendarType) -> UICollectionView? func willDisplayEventViewer(date: Date, frame: CGRect) -> UIView? /// The method is **DEPRECATED** /// Use a new **dequeueCell** @available(*, deprecated, renamed: "dequeueCell") func dequeueDateCell(date: Date?, type: CalendarType, collectionView: UICollectionView, indexPath: IndexPath) -> UICollectionViewCell? /// The method is **DEPRECATED** /// Use a new **dequeueHeader** @available(*, deprecated, renamed: "dequeueHeader") func dequeueHeaderView(date: Date?, type: CalendarType, collectionView: UICollectionView, indexPath: IndexPath) -> UICollectionReusableView? /// The method is **DEPRECATED** /// Use a new **dequeueCell** @available(*, deprecated, renamed: "dequeueCell") func dequeueListCell(date: Date?, tableView: UITableView, indexPath: IndexPath) -> UITableViewCell? /// Use this method to add a custom day cell func dequeueCell<T: UIScrollView>(parameter: CellParameter, type: CalendarType, view: T, indexPath: IndexPath) -> KVKCalendarCellProtocol? /// Use this method to add a header view func dequeueHeader<T: UIScrollView>(date: Date?, type: CalendarType, view: T, indexPath: IndexPath) -> KVKCalendarHeaderProtocol? @available(iOS 14.0, *) func willDisplayEventOptionMenu(_ event: Event, type: CalendarType) -> (menu: UIMenu, customButton: UIButton?)? /// Use this method to create a custom content view func dequeueMonthViewEvents(_ events: [Event], date: Date, frame: CGRect) -> UIView? /// Use this method to create a custom all day event func dequeueAllDayViewEvent(_ event: Event, date: Date, frame: CGRect) -> UIView? func dequeueTimeLabel(_ label: TimelineLabel) -> (current: TimelineLabel, others: [UILabel])? func dequeueCornerHeader(date: Date, frame: CGRect, type: CalendarType) -> UIView? func dequeueAllDayCornerHeader(date: Date, frame: CGRect) -> UIView? func willDisplaySectionsInListView(_ sections: [ListViewData.SectionListView]) } public extension CalendarDataSource { func willDisplayHeaderView(date: Date?, frame: CGRect, type: CalendarType) -> UIView? { nil } func willDisplayEventViewer(date: Date, frame: CGRect) -> UIView? { nil } func willDisplayDate(_ date: Date?, events: [Event]) {} func willDisplayEventView(_ event: Event, frame: CGRect, date: Date?) -> EventViewGeneral? { nil } func willDisplayHeaderSubview(date: Date?, frame: CGRect, type: CalendarType) -> UIView? { nil } func willDisplayCollectionView(frame: CGRect, type: CalendarType) -> UICollectionView? { nil } func dequeueDateCell(date: Date?, type: CalendarType, collectionView: UICollectionView, indexPath: IndexPath) -> UICollectionViewCell? { nil } func dequeueHeaderView(date: Date?, type: CalendarType, collectionView: UICollectionView, indexPath: IndexPath) -> UICollectionReusableView? { nil } func dequeueListCell(date: Date?, tableView: UITableView, indexPath: IndexPath) -> UITableViewCell? { nil } func dequeueCell<T: UIScrollView>(parameter: CellParameter, type: CalendarType, view: T, indexPath: IndexPath) -> KVKCalendarCellProtocol? { nil } func dequeueHeader<T: UIScrollView>(date: Date?, type: CalendarType, view: T, indexPath: IndexPath) -> KVKCalendarHeaderProtocol? { nil } @available(iOS 14.0, *) func willDisplayEventOptionMenu(_ event: Event, type: CalendarType) -> (menu: UIMenu, customButton: UIButton?)? { nil } func dequeueMonthViewEvents(_ events: [Event], date: Date, frame: CGRect) -> UIView? { nil } func dequeueAllDayViewEvent(_ event: Event, date: Date, frame: CGRect) -> UIView? { nil } func dequeueTimeLabel(_ label: TimelineLabel) -> (current: TimelineLabel, others: [UILabel])? { nil } func dequeueCornerHeader(date: Date, frame: CGRect, type: CalendarType) -> UIView? { nil } func dequeueAllDayCornerHeader(date: Date, frame: CGRect) -> UIView? { nil } func willDisplaySectionsInListView(_ sections: [ListViewData.SectionListView]) {} } // MARK: - Delegate protocol public protocol CalendarDelegate: AnyObject { func sizeForHeader(_ date: Date?, type: CalendarType) -> CGSize? /// size cell for (month, year, list) view func sizeForCell(_ date: Date?, type: CalendarType) -> CGSize? /** The method is **DEPRECATED** Use a new **didSelectDates** */ @available(*, deprecated, renamed: "didSelectDates") func didSelectDate(_ date: Date?, type: CalendarType, frame: CGRect?) /// get selected dates func didSelectDates(_ dates: [Date], type: CalendarType, frame: CGRect?) /// get a selected event func didSelectEvent(_ event: Event, type: CalendarType, frame: CGRect?) /// tap on more fro month view func didSelectMore(_ date: Date, frame: CGRect?) /** The method is **DEPRECATED** Use a new **didChangeViewerFrame** */ @available(*, deprecated, renamed: "didChangeViewerFrame") func eventViewerFrame(_ frame: CGRect) /// event's viewer for iPad func didChangeViewerFrame(_ frame: CGRect) /// drag & drop events and resize func didChangeEvent(_ event: Event, start: Date?, end: Date?) /// add new event func didAddNewEvent(_ event: Event, _ date: Date?) /// get current displaying events func didDisplayEvents(_ events: [Event], dates: [Date?]) /// get next date when the calendar scrolls (works for month view) func willSelectDate(_ date: Date, type: CalendarType) /** The method is **DEPRECATED** Use a new **didDeselectEvent** */ @available(*, deprecated, renamed: "didDeselectEvent") func deselectEvent(_ event: Event, animated: Bool) /// deselect event on timeline func didDeselectEvent(_ event: Event, animated: Bool) func didUpdateStyle(_ style: Style, type: CalendarType) /// get current displaying header date func didDisplayHeaderTitle(_ date: Date, style: Style, type: CalendarType) } public extension CalendarDelegate { func sizeForHeader(_ date: Date?, type: CalendarType) -> CGSize? { nil } func sizeForCell(_ date: Date?, type: CalendarType) -> CGSize? { nil } func didSelectDate(_ date: Date?, type: CalendarType, frame: CGRect?) {} func didSelectDates(_ dates: [Date], type: CalendarType, frame: CGRect?) {} func didSelectEvent(_ event: Event, type: CalendarType, frame: CGRect?) {} func didSelectMore(_ date: Date, frame: CGRect?) {} func eventViewerFrame(_ frame: CGRect) {} func didChangeEvent(_ event: Event, start: Date?, end: Date?) {} func didAddNewEvent(_ event: Event, _ date: Date?) {} func didDisplayEvents(_ events: [Event], dates: [Date?]) {} func willSelectDate(_ date: Date, type: CalendarType) {} func deselectEvent(_ event: Event, animated: Bool) {} func didDeselectEvent(_ event: Event, animated: Bool) {} func didChangeViewerFrame(_ frame: CGRect) {} func didUpdateStyle(_ style: Style, type: CalendarType) {} func didDisplayHeaderTitle(_ date: Date, style: Style, type: CalendarType) {} } // MARK: - Private Display dataSource protocol DisplayDataSource: CalendarDataSource {} extension DisplayDataSource { public func eventsForCalendar(systemEvents: [EKEvent]) -> [Event] { [] } } // MARK: - Private Display delegate protocol DisplayDelegate: CalendarDelegate { func didDisplayEvents(_ events: [Event], dates: [Date?], type: CalendarType) } extension DisplayDelegate { public func willSelectDate(_ date: Date, type: CalendarType) {} func deselectEvent(_ event: Event, animated: Bool) {} } // MARK: - EKEvent public extension EKEvent { @available(swift, deprecated: 0.5.8, obsoleted: 0.5.9, message: "Please use a constructor Event(event: _)") func transform(text: String? = nil, textForMonth: String? = nil, textForList: String? = nil) -> Event { var event = Event(ID: eventIdentifier) event.title = TextEvent(timeline: text ?? title, month: textForMonth ?? title, list: textForList ?? title) event.start = startDate event.end = endDate event.color = Event.Color(UIColor(cgColor: calendar.cgColor)) event.isAllDay = isAllDay return event } } // MARK: - Protocols to customize calendar public protocol KVKCalendarCellProtocol: AnyObject {} extension UICollectionViewCell: KVKCalendarCellProtocol {} extension UITableViewCell: KVKCalendarCellProtocol {} public protocol KVKCalendarHeaderProtocol: AnyObject {} extension UIView: KVKCalendarHeaderProtocol {} // MARK: - Scrollable Week settings protocol ScrollableWeekProtocol: AnyObject { var daysBySection: [[Day]] { get set } } extension ScrollableWeekProtocol { func prepareDays(_ days: [Day], maxDayInWeek: Int) -> [[Day]] { var daysBySection: [[Day]] = [] var idx = 0 var stop = false while !stop { var endIdx = idx + maxDayInWeek if endIdx > days.count { endIdx = days.count } let items = Array(days[idx..<endIdx]) daysBySection.append(items) idx += maxDayInWeek if idx > days.count - 1 { stop = true } } return daysBySection } } #endif
true
a0b9eec7932ae1af8014dd62e196f95c8d3982a9
Swift
aruffolo/MovingArcsView
/Example/MovingArcsMenu/ViewController.swift
UTF-8
2,939
2.5625
3
[ "MIT" ]
permissive
// // ViewController.swift // MovingArcsMenu // // Created by aruffolo on 04/20/2018. // Copyright (c) 2018 aruffolo. All rights reserved. // import UIKit import MovingArcsMenu class ViewController: UIViewController { @IBOutlet weak var arcsView: MovingArcsView! private let deepMarineBlue = UIColor(red: 1 / 255, green: 0 / 255, blue: 49 / 255, alpha: 1.0) private let waterGreen = UIColor(red: 45 / 255, green: 182 / 255, blue: 166 / 255, alpha: 1.0) override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) initArcsView() setArcsViewCallbacks() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } private func initArcsView() { let viewsOnExternalArc: ArcsButtonsNumber = .five let viewsOnMiddleArc: ArcsButtonsNumber = .three let tagsForButtonsInExternalArc: [Int] = [24, 28, 27, 25, 26] let tagsForButtonsInMiddleArc: [Int] = [23, 22, 21] do { let tuple = (innerArcColor: deepMarineBlue, middleArcColor: deepMarineBlue, externalArcColor: deepMarineBlue, innerArcShadowColor: waterGreen, middleArcShadowColor: waterGreen, externalArcShadowColor: UIColor.black) try arcsView.initParameters(viewsOnExternalArc: viewsOnExternalArc, viewsOnMiddleArc: viewsOnMiddleArc, tagsForButtonsInExternalArc: tagsForButtonsInExternalArc, tagsForButtonsInMiddleArc: tagsForButtonsInMiddleArc, arcColors: tuple, buttonScale: 0.33, imagesForExternalArc: ["CloseIcon", "CloseIcon", "CloseIcon", "CloseIcon", "CloseIcon"], imagesForMiddleArc: ["CloseIcon", "CloseIcon", "CloseIcon"], imagesForInnerArc: ["CloseIcon"]) } catch ArcsViewsError.viewsNUmberAndTagsNumberMismatch(let errorMessage) { print(errorMessage) } catch { print(error) } } private func setArcsViewCallbacks() { arcsView.animationsFinishedCallback = self.arcsAnimationsFinishedCallback arcsView.viewsOnArcHasBeenTapped = self.viewsOnArcTapped } private lazy var arcsAnimationsFinishedCallback: () -> Void = { [unowned self] in print("Arcs view animation is finished") self.arcsView.resetVariables() } private lazy var viewsOnArcTapped: ((_ sneder: UITapGestureRecognizer) -> Void)? = { [unowned self] sender in print("Button in external arc has been tapped, tag: \(sender.view!.tag)") self.arcsView.revertAnimations() } @IBAction func showHideArcsAction(_ sender: UIButton) { arcsView.start() } }
true
1bd81818219e8d40b6419dbba1bc891e6d05e222
Swift
mohsinalimat/mailswipe
/MailSwipe/NotificationManager.swift
UTF-8
2,919
2.65625
3
[]
no_license
// // NotificationManager.swift // MailSwipe // // Created by Aivant Goyal on 9/1/16. // Copyright © 2016 aivantgoyal. All rights reserved. // import UIKit import UserNotifications class NotificationManager { class func scheduleEmailNotifications(forEmail email: Email, withName name: String, withDate date: Date){ var newIdentifier = "\(email.id)-\(String.randomStringWithLength(length: 5))" if let existingIdentifier = UserDefaults.standard.object(forKey: email.id) as? String { print("Existing Identifier: \(existingIdentifier)") for notification in UIApplication.shared.scheduledLocalNotifications ?? [] { guard let id = notification.userInfo?["id"] as? String else { continue } if id == existingIdentifier { print("Cancelling Notification with Identifier: \(id)") UIApplication.shared.cancelLocalNotification(notification) } } while (existingIdentifier == newIdentifier) { newIdentifier = "\(email.id)-\(String.randomStringWithLength(length: 5))" } } UserDefaults.standard.set(newIdentifier, forKey: email.id) let calendar = Calendar.current let curYear = calendar.component(.year, from: Date()) let setDay = calendar.component(.day, from: date) var timeComponents = calendar.dateComponents([.hour, .minute, .second, .day, .month], from: date) timeComponents.year = curYear timeComponents.day = setDay - 1 let adjustedDate = calendar.date(from: timeComponents) let repeatInterval = email.info["repeatInterval"] as? String ?? "Weekly" print("Adjusted Date by setting year \(adjustedDate)") // create a corresponding local notification let notification = UILocalNotification() if #available(iOS 8.2, *) { notification.alertTitle = "\(name) Tomorrow" } notification.alertBody = "Swipe to send your \(name) email!" notification.alertAction = "Send" notification.fireDate = adjustedDate // todo item due date (when notification will be fired) print("\(name) will be fired \(adjustedDate)") switch repeatInterval { case "Monthly": notification.repeatInterval = .month case "Once" : break //No Repeat Interval default: notification.repeatInterval = .weekOfYear } notification.soundName = UILocalNotificationDefaultSoundName notification.applicationIconBadgeNumber = UIApplication.shared.applicationIconBadgeNumber + 1 notification.userInfo = ["id": newIdentifier, "email" : email.info] // assign a unique identifier to the notification so that we can retrieve it later UIApplication.shared.scheduleLocalNotification(notification) } }
true
8067024b6a633f9388139dffdf58132cb38ef1d7
Swift
iamtanveer/Capsule
/Capsule/ViewController.swift
UTF-8
2,032
2.890625
3
[]
no_license
// // ViewController.swift // Capsule // // Created by Tanveer Singh on 05/06/17. // Copyright © 2017 Tanveer Singh. All rights reserved. // import UIKit class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate { @IBOutlet var statePicker: UIPickerView! @IBOutlet var statePickerBtn: UIButton! @IBOutlet var countryLabel: UILabel! @IBOutlet var countryInput: UITextField! @IBOutlet var buynowBtn: UIButton! let states = ["Delhi", "West Bengal", "Assam", "Punjab", "Haryana", "Jharkhand"] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. statePicker.dataSource = self //**** Must add when using UIpickerview statePicker.delegate = self //**** Must add when using UIpickerview } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func stateBtnPressed(_ sender: Any) { statePicker.isHidden = false countryInput.isHidden = true countryLabel.isHidden = true } @IBAction func buybtnPressed(_ sender: Any) { } func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 //number of columns = 1 column ie "state" } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return states.count //how many states do you wanna put } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return states[row] } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { statePickerBtn.setTitle(states[row], for: UIControlState.normal) //for changing of button text statePicker.isHidden = true countryLabel.isHidden = false countryInput.isHidden = false } }
true
b5dadac927fa1d0a6e2618889c18d4c9a4b38390
Swift
hongruqi/AnimationSwift
/AnimationSwift/AnimationSwift/DCPathButton/DCPathItemButton.swift
UTF-8
2,689
2.84375
3
[]
no_license
// // DCPathItemButton.swift // AnimationSwift // // Created by qihongru on 16/5/4. // Copyright © 2016年 qihongru. All rights reserved. // import UIKit protocol DCPathItemButtonDelegate: NSObjectProtocol { func itemButtonTapped(itemButton: DCPathItemButton) } class DCPathItemButton: UIImageView { weak var delegate: DCPathItemButtonDelegate? var index: Int = 0 var backgroundImageView: UIImageView? override init(image: UIImage?, highlightedImage: UIImage?) { super.init(image: image, highlightedImage: highlightedImage) } override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } init(image: UIImage?, highlightedImage: UIImage?, backgroudImage: UIImage?, backgroundHigtlightedImage: UIImage?) { super.init(frame: CGRectZero) var itemFrame: CGRect = CGRectMake(0, 0, (backgroudImage?.size.width)!, (backgroudImage?.size.height)!) if backgroudImage == nil || backgroundHigtlightedImage == nil { itemFrame = CGRectMake(0, 0, (image?.size.width)!, (image?.size.height)!) } self.index = 0 self.frame = itemFrame self.image = backgroudImage self.highlightedImage = backgroundHigtlightedImage self.userInteractionEnabled = true backgroundImageView = UIImageView.init(image: image, highlightedImage: highlightedImage) backgroundImageView!.center = CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2) self.addSubview(backgroundImageView!) } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { self.highlighted = true self.backgroundImageView?.highlighted = true } override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { let currentLocation: CGPoint = (touches.first?.locationInView(self))! if !CGRectContainsPoint(self.scaleRect(self.bounds), currentLocation) { self.highlighted = false self.backgroundImageView?.highlighted = false return } self.highlighted = true self.backgroundImageView?.highlighted = true } override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { delegate?.itemButtonTapped(self) self.highlighted = false self.backgroundImageView?.highlighted = false } func scaleRect(originRect:CGRect) -> CGRect{ return CGRectMake(-originRect.size.width * 2, -originRect.size.height * 2, originRect.size.width * 5,originRect.size.height * 5); } }
true
1abfe6775add46b8cc248c3252763c67c7776db0
Swift
mableliza/iOS-Proficiency-Exercise
/FactsApp/FactsApp/Views/Controllers/FactsViewController.swift
UTF-8
3,519
2.71875
3
[]
no_license
// // FactsViewController.swift // FactsApp // // Created by Mable on 30/03/20. // Copyright © 2020 Mable. All rights reserved. // import UIKit class FactsViewController: UIViewController { let tableView = UITableView() var viewModel: FactsViewModel! lazy var refreshControl: UIRefreshControl = { let refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: #selector(self.handleRefresh(_:)),for: .valueChanged) refreshControl.tintColor = AppColors.refreshTintColor return refreshControl }() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white self.view.backgroundColor = .white setViewModel() setupTableview() setData() } /// Initialise viewModel and add delegate func setViewModel() { self.viewModel = FactsViewModel() viewModel.delegate = self } /// Setup tableview properties and constraints func setupTableview() { self.view.addSubview(tableView) let layoutMargins = view.layoutMarginsGuide tableView.translatesAutoresizingMaskIntoConstraints = false tableView.topAnchor.constraint(equalTo: layoutMargins.topAnchor).isActive = true tableView.bottomAnchor.constraint(equalTo: layoutMargins.bottomAnchor).isActive = true tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true tableView.dataSource = self tableView.tableFooterView = UIView() tableView.rowHeight = UITableView.automaticDimension tableView.estimatedRowHeight = AppConstants.rowHeight tableView.rowHeight = UITableView.automaticDimension tableView.showsVerticalScrollIndicator = false tableView.refreshControl = refreshControl tableView.register(FactsTableViewCell.self, forCellReuseIdentifier: cellIdentifier) tableView.reloadData() } /// Calls viewModel to initiate network call func setData() { viewModel.setData() } /// Handles title for the page func setTitle() { self.title = viewModel.getTitle() } /// Tableview refresh method @objc private func handleRefresh(_ refresh: UIRefreshControl) { setData() } /// Get an alertviewcontroller to show eoor message when network request returns an error func showErrorAlert(message: String) { let alertVC = UIAlertController(title: nil, message: message, preferredStyle: .alert) alertVC.addAction(UIAlertAction(title: ok, style: .default)) self.present(alertVC, animated: true) } } //MARK:- Tableview datasource methods extension FactsViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModel.getNumberOfRows() } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! FactsTableViewCell cell.setData(fact: viewModel.country!.facts[indexPath.row]) return cell } } //MARK:- ViewModel delegate methods extension FactsViewController: FactsDelegate { /// Handles API success func getFactsSuccessful() { self.refreshControl.endRefreshing() setTitle() tableView.reloadData() } ///Handles API call failure func getFactsFailure(message: String) { self.refreshControl.endRefreshing() self.showErrorAlert(message: message) tableView.reloadData() } }
true
957a1bd4dc27a2ece08202e1a69434a76d5f1ca8
Swift
sayler8182/WineBook
/WineBook/Source/Scenes/Authorization/Login/LoginWorker.swift
UTF-8
2,049
2.671875
3
[]
no_license
// // LoginWorker.swift // WineBook // // Created by Konrad on 6/19/20. // Copyright © 2020 Limbo. All rights reserved. // import FormsNetworking import Foundation // MARK: LoginWorker class LoginWorker { func signInWithApple(token: String, onSuccess: @escaping (LoginResponse) -> Void, onError: @escaping (NetworkError) -> Void) { let content = NetworkMethods.auth.signInWithApple.Content( token: token) NetworkMethods.auth.signInWithApple(content) .call(onSuccess: { (data: LoginResponse) in self.signInSuccess(data) onSuccess(data) }, onError: { (error) in onError(error) }, onCompletion: nil) } func signInWithFacebook(token: String, onSuccess: @escaping (LoginResponse) -> Void, onError: @escaping (NetworkError) -> Void) { let content = NetworkMethods.auth.signInWithFacebook.Content( token: token) NetworkMethods.auth.signInWithFacebook(content) .call(onSuccess: { (data: LoginResponse) in self.signInSuccess(data) onSuccess(data) }, onError: { (error) in onError(error) }, onCompletion: nil) } func signInWithGoogle(token: String, onSuccess: @escaping (LoginResponse) -> Void, onError: @escaping (NetworkError) -> Void) { let content = NetworkMethods.auth.signInWithGoogle.Content( token: token) NetworkMethods.auth.signInWithGoogle(content) .call(onSuccess: { (data: LoginResponse) in self.signInSuccess(data) onSuccess(data) }, onError: { (error) in onError(error) }, onCompletion: nil) } fileprivate func signInSuccess(_ data: LoginResponse) { Storage.token.value = data.token } }
true
888a35320f78a9f6e4146039eab389e724988995
Swift
hkfdlr/MeterReadingsiOS
/MeterReadings/MeterReadings/ViewModels/AccountDetailViewModel.swift
UTF-8
2,872
2.78125
3
[]
no_license
// // AccountDetailViewModel.swift // MeterReadings // // Created by Student on 04.07.21. // import Foundation import MeterReadingsCore import MeterReadingsInfrastructure final class AccountDetailViewModel: ObservableObject { public init(account: Account) { self.account = account } @Published var account: Account @Published var meterList: [Meter] = [] let meterSaver = ConcreteSaveMeterCommand(meterSaver: SaveMeterAdapter()) let meterGetter = ConcreteGetMeterCommand(meterGetter: GetMeterAdapter()) let meterDeleter = ConcreteDeleteMeterCommand(meterDeleter: DeleteMeterAdapter()) let readingGetter = ConcreteGetReadingCommand(readingGetter: GetReadingAdapter()) func deleteMeter(at index: IndexSet) { guard let index = index.first else {return} let meterToDelete = meterList[index] do { try meterDeleter.deleteMeter(meter: meterToDelete) { switch $0 { case let .success(value): debugPrint(value) case let .failure(error): debugPrint(error) } } } catch { debugPrint(error.localizedDescription) } meterList.remove(at: index) } func saveMeter(meter: inout Meter) throws { try meterSaver.saveMeter(meter: &meter) { switch $0 { case let .success(value): debugPrint(value) case let .failure(error): debugPrint(error.localizedDescription) } } debugPrint(account) try getAllMeters(accountNumber: account.accountNumber) } func getAllMeters(accountNumber: Int) throws { meterList = [] try meterGetter.getMeters(accountNumber: accountNumber) { switch $0 { case let .success(meters): do { for elem in meters { if (!self.meterList.contains(elem)) { let lastIndex = self.meterList.endIndex self.meterList.insert(elem, at: lastIndex) } } } case let .failure(error): debugPrint(error.localizedDescription) } } try getReadingsForMeters() } func getReadingsForMeters() throws { for elem in meterList { try readingGetter.getReadings(meterNumber: elem.meterNumber) { switch $0 { case let .success(readings): do { let i = self.meterList.firstIndex(of: elem) if (i != nil) { self.meterList[i!].meterReadingEntries = readings } } case let .failure(error): debugPrint(error.localizedDescription) } } } debugPrint(meterList) } }
true
f1152575250ad6058ec003539be7ff75dd9ea618
Swift
akuzminskyi/moviedb_test
/MovieDB/Scenes/Search/Extensions/SearchViewModel+SearchViewModeling.swift
UTF-8
1,246
2.578125
3
[]
no_license
// // SearchViewModel+SearchViewModeling.swift // MovieDB // // Created by Andrii Kuzminskyi on 18/02/2018. // Copyright © 2018 A.Kuzminskyi. All rights reserved. // import Foundation extension SearchViewModel: SearchViewModeling { func loadItems(at indexPaths: [IndexPath]) { let emptyIndexPaths = indexPaths.filter { (indexPath) -> Bool in guard case ItemModelState.empty = itemAt(indexPath: indexPath) else { return false } return true } guard !emptyIndexPaths.isEmpty else { return } let pagesToLoad = emptyIndexPaths.reduce(Set<Int>()) { (set, indexPath) -> Set<Int> in let page = indexPath.row / paginator.batchSize + 1 var muttableSet = set muttableSet.insert(page) return muttableSet } print("Load pages: \(pagesToLoad)") pagesToLoad.forEach { (page) in do { try paginator.load(page: page) } catch let error { print("cought an error \(error)") } } } func clearResult() { paginator.baseURL = nil items.removeAll() itemsDidChange?() } }
true
f7066616d8b81853533a8c64523846f050d41476
Swift
siddharthpant92/Sid_AdvancedMobApp_Spring17
/lab_3/collectionView/CollectionViewController.swift
UTF-8
8,655
2.859375
3
[]
no_license
// // CollectionViewController.swift // collectionView // // Created by Siddharth on 2/21/17. // Copyright © 2017 Siddharth. All rights reserved. // import UIKit private let reuseIdentifier = "Cell" class CollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout { var actionImages: [String] = ["action1","action2","action3", "action4"] var comedyImage: [String] = ["comedy1", "comedy2"] var dramaImages: [String] = ["drama1", "drama2"] var crimeImages: [String] = ["crime1","crime2","crime3", "crime4"] let sectionInsets = UIEdgeInsetsMake(25.0, 10.0, 25.0, 10.0) var selectedImageName = String() override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Register cell classes. Commented out since it is done in storyboard also. //self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier) // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // 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. } */ // MARK: UICollectionViewDataSource override func numberOfSections(in collectionView: UICollectionView) -> Int { // #warning Incomplete implementation, return the number of sections return 4 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if(section == 0) { return actionImages.count } if(section == 1) { return comedyImage.count } if(section == 2) { return crimeImages.count } if(section == 3) { return dramaImages.count } else { return 0 } } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! CollectionViewCell if(indexPath.section == 0) { cell.imageView.image = UIImage(named: actionImages[indexPath.row]) } if(indexPath.section == 1) { cell.imageView.image = UIImage(named: comedyImage[indexPath.row]) } if(indexPath.section == 2) { cell.imageView.image = UIImage(named: crimeImages[indexPath.row]) } if(indexPath.section == 3) { cell.imageView.image = UIImage(named: dramaImages[indexPath.row]) } return cell } override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { var header: CollectionSupplementaryView? var footer: CollectionSupplementaryView? if kind == UICollectionElementKindSectionHeader { header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "Header", for: indexPath) as? CollectionSupplementaryView if(indexPath.section == 0) { header?.headerLabel.text = "Action" } if(indexPath.section == 1) { header?.headerLabel.text = "Comedy" } if(indexPath.section == 2) { header?.headerLabel.text = "Crime" } if(indexPath.section == 3) { header?.headerLabel.text = "Drama" } return header! } else if kind == UICollectionElementKindSectionFooter { footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "Footer", for: indexPath) as? CollectionSupplementaryView if(indexPath.section == 0) { footer?.footerLabel.text = "Feel the adrenaline" } if(indexPath.section == 1) { footer?.footerLabel.text = "Have fun and laughter" } if(indexPath.section == 2) { footer?.footerLabel.text = "Watch out for the law" } if(indexPath.section == 3) { footer?.footerLabel.text = "Enjoy" } return footer! } else { assert(false, "Unexpected element kind") } } //UICollectionViewDelegateFlowLayout method func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { var image = UIImage() if(indexPath.section == 0) { image = UIImage(named: actionImages[indexPath.row])! } if(indexPath.section == 1) { image = UIImage(named: comedyImage[indexPath.row])! } if(indexPath.section == 2) { image = UIImage(named: crimeImages[indexPath.row])! } if(indexPath.section == 3) { image = UIImage(named: dramaImages[indexPath.row])! } let newSize:CGSize = CGSize(width: (image.size.width)/2, height: (image.size.height)/2) let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height) UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0) image.draw(in: rect) let image2 = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() //end resizing return (image2?.size)! } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return sectionInsets } override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if(indexPath.section == 0) { selectedImageName = actionImages[indexPath.row] } if(indexPath.section == 1) { selectedImageName = comedyImage[indexPath.row] } if(indexPath.section == 2) { selectedImageName = crimeImages[indexPath.row] } if(indexPath.section == 3) { selectedImageName = dramaImages[indexPath.row] } self.performSegue(withIdentifier: "showDetail", sender: self) } // MARK: UICollectionViewDelegate /* // Uncomment this method to specify if the specified item should be highlighted during tracking override func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool { return true } */ /* // Uncomment this method to specify if the specified item should be selected override func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool { return true } */ /* // Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item override func collectionView(_ collectionView: UICollectionView, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool { return false } override func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool { return false } override func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) { } */ override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let destinationVC = segue.destination as! DetailViewController destinationVC.imageName = selectedImageName } }
true
2914ae6d27a4ef4b338238b88fdbcad45e12de65
Swift
BigBot22/Cookbook
/Cookbook/Cookbook/Reusable Components/PlayerControls.swift
UTF-8
5,825
2.984375
3
[ "MIT" ]
permissive
import AudioKit import AudioKitUI import AVFoundation import SwiftUI protocol ProcessesPlayerInput { var player: AudioPlayer { get } } struct PlayerControls: View { @Environment(\.colorScheme) var colorScheme var conductor: ProcessesPlayerInput let sources: [[String]] = [ ["Bass Synth", "Bass Synth.mp3"], ["Drums", "beat.aiff"], ["Female Voice", "alphabet.mp3"], ["Guitar", "Guitar.mp3"], ["Male Voice", "Counting.mp3"], ["Piano", "Piano.mp3"], ["Strings", "Strings.mp3"], ["Synth", "Synth.mp3"], ] @State var isPlaying = false @State var sourceName = "Drums" @State var isShowingSources = false var body: some View { HStack(spacing: 10) { ZStack { LinearGradient(gradient: Gradient(colors: [.blue, .accentColor]), startPoint: .top, endPoint: .bottom) .cornerRadius(25.0) .shadow(color: ColorManager.accentColor.opacity(0.4), radius: 5, x: 0.0, y: 3) HStack { Image(systemName: "music.note.list") .foregroundColor(.white) .font(.system(size: 14, weight: .semibold, design: .rounded)) Text("Source Audio: \(sourceName)").foregroundColor(.white) .font(.system(size: 14, weight: .semibold, design: .rounded)) } .padding() }.onTapGesture { isShowingSources.toggle() } Button(action: { self.isPlaying ? self.conductor.player.stop() : self.conductor.player.play() self.isPlaying.toggle() }, label: { Image(systemName: isPlaying ? "stop.fill" : "play.fill") }) .padding() .background(isPlaying ? Color.red : Color.green) .foregroundColor(.white) .font(.system(size: 14, weight: .semibold, design: .rounded)) .cornerRadius(25.0) .shadow(color: ColorManager.accentColor.opacity(0.4), radius: 5, x: 0.0, y: 3) } .frame(minWidth: 300, idealWidth: 350, maxWidth: 360, minHeight: 50, idealHeight: 50, maxHeight: 50, alignment: .center) .padding() .sheet(isPresented: $isShowingSources, onDismiss: { print("finished!") }, content: { SourceAudioSheet(playerControls: self) }) } func load(filename: String) { conductor.player.stop() Log(filename) guard let url = Bundle.main.resourceURL?.appendingPathComponent("Samples/\(filename)"), let buffer = try? AVAudioPCMBuffer(url: url) else { Log("failed to load sample", filename) return } conductor.player.isLooping = true conductor.player.buffer = buffer if isPlaying { conductor.player.play() } } func load(url: URL) { conductor.player.stop() Log(url) guard let buffer = try? AVAudioPCMBuffer(url: url) else { Log("failed to load sample", url.deletingPathExtension().lastPathComponent) return } conductor.player.isLooping = true conductor.player.buffer = buffer if isPlaying { conductor.player.play() } } } struct SourceAudioSheet: View { @Environment(\.presentationMode) var presentationMode var playerControls: PlayerControls @State var browseFiles = false @State var fileURL = URL(fileURLWithPath: "") var body: some View { NavigationView { ScrollView { VStack(spacing: 20) { ForEach(playerControls.sources, id: \.self) { source in Button(action: { playerControls.load(filename: source[1]) playerControls.sourceName = source[0] }) { HStack { Text(source[0]) Spacer() if playerControls.sourceName == source[0] { Image(systemName: playerControls.isPlaying ? "speaker.3.fill" : "speaker.fill") } }.padding() } } } Button(action: {browseFiles.toggle()}, label: { Text("Select Custom File") }) .fileImporter(isPresented: $browseFiles, allowedContentTypes: [.audio]) { res in do { fileURL = try res.get() if fileURL.startAccessingSecurityScopedResource() { playerControls.load(url: fileURL) playerControls.sourceName = fileURL.deletingPathExtension().lastPathComponent } else { Log("Couldn't load file URL", type: .error) } } catch { Log(error.localizedDescription, type: .error) } } } .onDisappear { fileURL.stopAccessingSecurityScopedResource() } .padding(.vertical, 15) .navigationTitle("Source Audio") .navigationBarTitleDisplayMode(.inline) .toolbar { ToolbarItem(placement: .navigationBarTrailing) { Button("Close") { presentationMode.wrappedValue.dismiss() } } } } } }
true
4fb5218ea808b3d7ea807900515bbdba4ca71991
Swift
alastar13rus/TMDB
/TMDB/TMDB/Scene/MediaDetail/ViewModel/CellViewModel/CastCellViewModel.swift
UTF-8
1,250
2.6875
3
[]
no_license
// // CastListViewModel.swift // TMDB // // Created by Докин Андрей (IOS) on 11.04.2021. // import Foundation import RxSwift import RxRelay import RxDataSources import Domain class CastCellViewModel { // MARK: - Properties let gender: Int let id: String let name: String let popularity: Float let profilePath: String? let character: String let creditID: String var order: Int var profileURL: URL? { ImageURL.profile(.w185, profilePath).fullURL } // MARK: - Init init(_ model: CastModel) { self.gender = model.gender self.id = "\(model.id)" self.name = model.name self.popularity = model.popularity self.profilePath = model.profilePath self.character = model.character self.creditID = model.creditID self.order = model.order } } extension CastCellViewModel: IdentifiableType, Equatable, Comparable { var identity: String { self.creditID } static func ==(lhs: CastCellViewModel, rhs: CastCellViewModel) -> Bool { return lhs.creditID == rhs.creditID } static func < (lhs: CastCellViewModel, rhs: CastCellViewModel) -> Bool { return lhs.name < rhs.name } }
true
74d85a25c27e75248a7f6e773e64c0fb9a7479e4
Swift
ForgeRock/forgerock-ios-sdk
/FRAuth/FRAuth/Session/FRSession.swift
UTF-8
6,067
2.609375
3
[ "MIT" ]
permissive
// // FRSession.swift // FRAuth // // Copyright (c) 2020-2021 ForgeRock. All rights reserved. // // This software may be modified and distributed under the terms // of the MIT license. See the LICENSE file for details. // import Foundation /// FRSession represents a session authenticated by AM's Authentication Tree @objc public class FRSession: NSObject { // MARK: - Properties /** Singleton instance represents currently authenticated session. ## Note ## If SDK has not been started using *FRAuth.start()*, *FRSession.currentSession* returns nil even if session has previously authenticated, and valid. When Session Token does not exist in Keychain Service, *FRSession.currentSession* also returns nil even if SDK has properly started. */ @objc public static var currentSession: FRSession? { get { if let staticSession = _staticSession { return staticSession } else if let frAuth = FRAuth.shared, let _ = frAuth.keychainManager.getSSOToken() { FRLog.v("FRSession retrieved from SessionManager") _staticSession = FRSession() return _staticSession } FRLog.w("Invalid SDK State; SDK is not initialized or Session Token does not exist") return nil } } /// Static property of current FRSession object static var _staticSession: FRSession? = nil /// Session Token object @objc public var sessionToken: Token? { get { if let frAuth = FRAuth.shared, let sessionToken = frAuth.keychainManager.getSSOToken() { return sessionToken } return nil } } // MARK: - Authenticate /// Invokes /authenticate endpoint in AM to go through Authentication Tree flow with given PolicyAdvice information /// - Parameter policyAdvice: PolicyAdvice object which contains the information for authorization /// - Parameter completion: NodeCompletion callback which returns the result of Session Token as Token object @objc public static func authenticate(policyAdvice: PolicyAdvice, completion:@escaping NodeCompletion<Token>) { if let frAuth = FRAuth.shared { FRLog.v("Initiating FRSession authenticate process") frAuth.next(authIndexValue: policyAdvice.authIndexValue, authIndexType: policyAdvice.authIndexType) { (token: Token?, node, error) in completion(token, node, error) } } else { FRLog.w("Invalid SDK State") completion(nil, nil, ConfigError.invalidSDKState) } } /// Invokes /authenticate endpoint in AM to go through Authentication Tree flow with specified authIndexValue and authIndexType; authIndexType is an optional parameter defaulted to 'service' if not defined /// - Parameter authIndexValue: authIndexValue; Authentication Tree name value in String /// - Parameter authIndexType: authIndexType; Authentication Tree type value in String /// - Parameter completion: NodeCompletion callback which returns the result of Session Token as Token object @objc public static func authenticate(authIndexValue: String, authIndexType: String = "service", completion:@escaping NodeCompletion<Token>) { if let frAuth = FRAuth.shared { FRLog.v("Initiating FRSession authenticate process") frAuth.next(authIndexValue: authIndexValue, authIndexType: authIndexType) { (token: Token?, node, error) in completion(token, node, error) } } else { FRLog.w("Invalid SDK State") completion(nil, nil, ConfigError.invalidSDKState) } } /// Invokes /authenticate endpoint in AM to go through Authentication Tree flow with `resumeURI` and `suspendedId` to resume Authentication Tree flow. /// - Parameters: /// - resumeURI: Resume URI received in Email from Suspend Email Node; URI **must** contain `suspendedId` in URL query parameter /// - completion: NodeCompletion callback which returns the result of Session Token as Token object @objc public static func authenticate(resumeURI: URL, completion:@escaping NodeCompletion<Token>) { if let frAuth = FRAuth.shared { FRLog.v("Initiating FRSession authenticate process with resumeURI") if let suspendedId = resumeURI.valueOf("suspendedId") { frAuth.next(suspendedId: suspendedId) { (token: Token?, node, error) in completion(token, node, error) } } else { FRLog.w("Invalid resumeURI for missing suspendedId") completion(nil, nil, AuthError.invalidResumeURI("suspendedId")) } } else { FRLog.w("Invalid SDK State") completion(nil, nil, ConfigError.invalidSDKState) } } // MARK: - Logout /// Invalidates Session Token using AM's REST API @objc public func logout() { if let frAuth = FRAuth.shared { FRLog.i("Clearing Session Token") // Revoke Session Token frAuth.sessionManager.revokeSSOToken() // Clear currentSession FRSession._staticSession = nil } else { FRLog.w("Invalid SDK State") } } // MARK: - Objective-C Compatibility @objc(authenticateWithAuthIndexValue:authIndexType:completion:) @available(swift, obsoleted: 1.0) public func authenticate(authIndexValue: String, authIndexType: String, completion:@escaping NodeCompletion<Token>) { FRSession.authenticate(authIndexValue: authIndexValue, authIndexType: authIndexType) { (token: Token?, node, error) in completion(token, node, error) } } }
true
b5aecdb48d97a1a9517e97f1cd382eb870222533
Swift
NirupamaAbraham/VIPERDesignSample
/VIPERDesignSample/Modules/Activity/Interactor/ActivityInteractor.swift
UTF-8
1,848
2.671875
3
[]
no_license
// // ActivityInteractor.swift // VIPERDesignSample // // Created by Nirupama M Abraham on 09/02/18. // Copyright © 2018 Nirupama M Abraham. All rights reserved. // import Foundation class ActivityInteractor : ActivityPresentorToInterectorProtocol { weak var presenter: ActivityInterectorToPresenterProtocol? func getActivities() { Request.getClaimFiles().execute().validate().responseJSON { (urlRequest, urlResponse, json, error) -> Void in guard error == nil else { self.presenter?.claimsFetchFailed(withError: error!) return } let claimFileArray = json["response"] let claimData : [Claim] = claimFileArray.map({ return Claim(claimantName: $0["claimantName"].stringValue, description: $0["claimDescription"].stringValue, claimFileNumber: $0["claimFileNumber"].stringValue, peril: $0["peril"].stringValue) }) self.presenter?.claimsFetched(claimData:claimData) } Request.getAppointments().execute().validate().responseJSON { (urlRequest, urlResponse, json, error) -> Void in guard error == nil else { self.presenter?.appointmentsFetchedFailed(withError: error!) return } let appointmentArray = json["response"] let appointmentData : [Appointment] = appointmentArray.map({ return Appointment(claimantName: $0["claimantName"].stringValue, description: $0["description"].stringValue, appointmentType: $0["appointmentType"].stringValue, date: $0["date"].stringValue) }) self.presenter?.appointmentsFetched(appointmentData: appointmentData) } } }
true
53d723bdc3728bebf12e1822a60e54eba86305e5
Swift
FFIB/leetcode
/leetcode/Math/SumofSquareNumbers.swift
UTF-8
869
3.546875
4
[]
no_license
// // SumofSquareNumbers.swift // leetcode // // Created by FFIB on 2017/7/3. // Copyright © 2017年 FFIB. All rights reserved. // import Foundation //633. Sum of Square Numbers /* Given a non-negative integer c, your task is to decide whether there're two integers a and b such that a2 + b2 = c. Example 1: Input: 5 Output: True Explanation: 1 * 1 + 2 * 2 = 5 Example 2: Input: 3 Output: False */ extension Solution { func judgeSquareSum(_ c: Int) -> Bool { let value = sqrt(Double(c)) if Double(Int(value)) == value { return true }else { for num in 0..<Int(ceil(value)) { let square = sqrt(Double(c - num * num)) if Double(Int(square)) == square { return true } } return false } } }
true
8ccd1ce141d573497fd4a5ac582ca3e1e15384bb
Swift
jinzhanjun/WeiBo
/WeiBo/SceneDelegate.swift
UTF-8
3,277
2.53125
3
[]
no_license
// // SceneDelegate.swift // WeiBo // // Created by jinzhanjun on 2020/4/3. // Copyright © 2020 jinzhanjun. All rights reserved. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). guard let windowScene = (scene as? UIWindowScene) else { return } window = UIWindow() window?.windowScene = windowScene window?.frame = UIScreen.main.bounds window?.backgroundColor = .white window?.rootViewController = WBMainViewController() // 注册通知 NotificationCenter.default.addObserver(self, selector: #selector(resetRootViewController), name: .WBUserHasLogin, object: nil) // 从网络获取APP数据 getAppInfo() // 设置APP的用户授权 setupAppSettings() window?.makeKeyAndVisible() } } /// 用户授权 extension SceneDelegate { private func setupAppSettings() { // 获取用户授权,发送通知、消息、声音等 // available 判断用户系统是否是10.0及以上。 if #available(iOS 10.0, *) { UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound, .carPlay]) { (isAuthorized, error) in print(isAuthorized) } }else { let notification = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil) UIApplication.shared.registerUserNotificationSettings(notification) } } } /// 模拟从网络获取App配置信息 extension SceneDelegate { private func getAppInfo() { DispatchQueue.global().async { // 获取路径 let url = URL(fileURLWithPath: "Users/jinzhanjun/Desktop/mian.json") // 获取二进制数据 let data = try? Data(contentsOf: url) // 获取沙盒路径 var sandBoxUrl = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) sandBoxUrl?.appendPathComponent("main.json") // 将数据写入url try? data?.write(to: sandBoxUrl!) } } } /// 登录后跳转界面 extension SceneDelegate { @objc func resetRootViewController() { if let sceneDelegate = UIApplication.shared.connectedScenes.first?.delegate as? SceneDelegate { if sceneDelegate.window?.rootViewController != nil { sceneDelegate.window?.rootViewController = nil } sceneDelegate.window?.rootViewController = WBMainViewController() } } }
true
154369798b8cde6ce1fefc6fbf796f828a959987
Swift
ayush-webonise/alamofire-sample-app
/alamofireObjectMapperSample/ModelAPIUtility.swift
UTF-8
1,728
2.828125
3
[]
no_license
// ModelAPIUtility.swift // alamofireObjectMapperSample import Foundation import ObjectMapper let ModelAPIUtilityInstance = ModelAPIUtility() class ModelAPIUtility { func callWeatherWebService(city: String, completionHandler: ((_ weatherModel: WeatherModel?) -> ())?) { let parameters = [ "q": city, "appid": "82d42d1bbaa0bbec840a96ca44a1660d" ] AlamofireUtilityInstance.getCallWithAlamofireUtility(url: "http://api.openweathermap.org/data/2.5/weather?", requestParams: parameters, success: { (response) in if let response = response as? [String: Any], let weatherModel = Mapper<WeatherModel>().map(JSON: response) { print("weatherModel: \(weatherModel)") completionHandler!(weatherModel) } else { completionHandler!(nil) } }, failure: { (error) in print(error ?? "error as default") }) } }
true
30884db9bfa0096a7941f32adcb1dba07f1f7295
Swift
kafejo/TestProject
/MTTTestProject/LocationServices.swift
UTF-8
3,505
2.84375
3
[]
no_license
// // WeatherServices.swift // mtt-test-project // // Created by Aleš Kocur on 05/01/16. // Copyright © 2016 Aleš Kocur. All rights reserved. // import PromiseKit import Foundation import AERecord import CoreData enum LocationServicesError: ErrorType { case NotFound case DataError } class LocationServices { static let updateInterval: NSTimeInterval = 15 * 60 // 15 minutes /// Update location if lastUpdate timestamp exceed the update interval class func updateLocation(location: Location) -> Promise<Void> { return Promise { fulfill, reject in if let timestamp = location.lastUpdate where NSDate().compare(timestamp) == NSComparisonResult.OrderedAscending { fulfill() return } search(locationQuery: location.name!).then { loc -> Void in loc.lastUpdate = NSDate(timeIntervalSinceNow: updateInterval) AERecord.saveContext(loc.managedObjectContext!) fulfill() }.error(reject) } } /** Search for location. May throw WeatherServicesError or APIClientError @param cityQuery Name of location (city) @return Promise<Location> */ class func search(locationQuery locationQuery: String, numberOfDays: Int = 5, context: NSManagedObjectContext = AERecord.backgroundContext) -> Promise<Location> { return Promise { fulfill, reject in let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT dispatch_async(dispatch_get_global_queue(priority, 0)) { let params: [String: AnyObject] = [ "query": locationQuery, "num_of_days": numberOfDays ] APIClient.requestJSON(.GET, URLString: "/weather.ashx", parameters: params).then { json -> Void in if json["data"]["error"].object != nil { dispatch_async(dispatch_get_main_queue()) { reject(LocationServicesError.DataError) } return } guard let location: Location = Decoder.decode(json["data"]["request"].jsonArrayValue.first!, context: context) else { dispatch_async(dispatch_get_main_queue()) { reject(LocationServicesError.DataError) } return } if let forecast: [Weather] = Decoder.decode(json["data"]["weather"].jsonArrayValue, context: context) { location.forecast = NSOrderedSet(array: forecast) } if let json = json["data"]["current_condition"].jsonArrayValue.first, let currentCondition: Weather = Decoder.decode(json, context: context) { location.currentCondition = currentCondition } dispatch_async(dispatch_get_main_queue()) { fulfill(location) } }.error { err in dispatch_async(dispatch_get_main_queue()) { reject(err) } } } } } }
true
13fb0e782bc9e3f77d101c5d707a75a4ac6da55d
Swift
fndmaioli/MovieDB_Viper
/MovieDB_NanoChallenge/MovieDB_NanoChallenge/MovieDetailModule/Router/MovieDetailRouter.swift
UTF-8
1,061
2.671875
3
[]
no_license
// // MovieDetailRouter.swift // MovieDB_NanoChallenge // // Created Fernando Locatelli Maioli on 16/08/19. // Copyright © 2019 Fernando Locatelli Maioli. All rights reserved. // import UIKit /// MovieDetail Module Router (aka: Wireframe) class MovieDetailRouter: MovieDetailRouterProtocol { class func createModule(view: UIViewController, movie: Movie) { let movieView = mainstoryboard.instantiateViewController(withIdentifier: "MovieDetailView") as? MovieDetailView; let presenter = MovieDetailPresenter(movie: MovieDetailEntity(movie: movie, genres: nil)) let interactor = MovieDetailInteractor() let router = MovieDetailRouter() movieView!.presenter = presenter interactor.presenter = presenter presenter.view = movieView presenter.interactor = interactor presenter.router = router view.navigationController?.pushViewController(movieView!, animated: true) } static var mainstoryboard: UIStoryboard{ return UIStoryboard(name:"Main",bundle: Bundle.main) } }
true
916808d1720906787f2b04fb3b85cc4182c5df63
Swift
satorun/SearchGithubMVC
/SearchGithubMVC/UIComponent/UITableView+Extensions.swift
UTF-8
531
2.609375
3
[ "MIT" ]
permissive
// // UITableView+Extensions.swift // SearchGithubMVC // // Created by satorun on 2018/09/23. // Copyright © 2018年 satorun. All rights reserved. // import UIKit protocol Identifiable { static var identifier: String { get } } extension Identifiable { static var identifier: String { return String(describing: type(of: self)) } } extension Identifiable where Self: UITableViewCell { static func register(to tableView: UITableView) { tableView.register(self, forCellReuseIdentifier: identifier) } }
true
5e430b0cc6d642a7a861b0080196232af22c501e
Swift
mohsinalimat/Swiftlier
/Sources/Alert.swift
UTF-8
8,338
2.515625
3
[ "MIT" ]
permissive
// // Alert.swift // Swiftlier // // Created by Andrew J Wagner on 9/10/15. // Copyright © 2015 Drewag LLC. All rights reserved. // #if os(iOS) import UIKit import ObjectiveC var MakeAlertAction: (String?, UIAlertActionStyle, ((UIAlertAction) -> Swift.Void)?) -> UIAlertAction = UIAlertAction.init public class ErrorOccured: EventType { public typealias CallbackParam = ReportableError } class Alert: NSObject { private let onButtonClicked: (_ buttonTitle: String?, _ textFieldText: String?) -> () private init(onButtonClicked: @escaping (_ buttonTitle: String?, _ textFieldText: String?) -> ()) { self.onButtonClicked = onButtonClicked super.init() } } protocol AnyAlertAction { var name: String {get} var isDestructive: Bool {get} } public final class AlertAction: AnyAlertAction { let name: String let isDestructive: Bool let handler: (() -> ())? init(name: String, isDestructive: Bool = false, handler: (() -> ())?) { self.name = name self.isDestructive = isDestructive self.handler = handler } public static func action(_ name: String, isDestructive: Bool = false, handler: (() -> ())? = nil) -> AlertAction { return AlertAction(name: name, isDestructive: isDestructive, handler: handler) } } public final class TextAction: AnyAlertAction { let name: String let isDestructive: Bool let handler: ((_ text: String) -> ())? init(name: String, isDestructive: Bool = false, handler: ((_ text: String) -> ())?) { self.name = name self.isDestructive = isDestructive self.handler = handler } public static func action(_ name: String, isDestructive: Bool = false, handler: ((_ text: String) -> ())? = nil) -> TextAction { return TextAction(name: name, isDestructive: isDestructive, handler: handler) } } extension ErrorGenerating where Self: UIViewController { public func showAlert( withError error: Error, _ doing: String, other: [AlertAction] = [] ) { self.showAlert(withError: self.error(doing, from: error), other: other) } } extension UIViewController { public func showAlert( withError error: ReportableError, other: [AlertAction] = [] ) { let finalError: ReportableError switch (error.reason as? NetworkResponseErrorReason)?.kind ?? .unknown { case .unauthorized, .forbidden, .noInternet, .gone: finalError = error.byUser case .unknown, .invalid, .notFound, .untrusted: finalError = error } EventCenter.defaultCenter().triggerEvent(ErrorOccured.self, params: finalError) self.showAlert( withTitle: finalError.alertDescription.title, message: finalError.alertDescription.message, other: other ) } public func showActionSheet( withTitle title: String, message: String? = nil, cancel: AlertAction? = nil, preferred: AlertAction? = nil, other: [AlertAction] = [] ) { var other = other if cancel == nil && other.isEmpty { other.append(.action("OK")) } let alert = Alert.buildAlert( withTitle: title, message: message, style: .actionSheet, cancel: cancel, preferred: preferred, other: other, onTapped: { tappedAction in if let action = cancel, action.name == tappedAction.title { action.handler?() return } if let preferred = preferred, preferred.name == tappedAction.title { preferred.handler?() return } for action in other { if action.name == tappedAction.title { action.handler?() return } } } ) self.present(alert, animated: true, completion: nil) } public func showAlert( withTitle title: String, message: String, cancel: AlertAction? = nil, preferred: AlertAction? = nil, other: [AlertAction] = [] ) { var other = other if cancel == nil && other.isEmpty && preferred == nil { other.append(.action("OK")) } let alert = Alert.buildAlert( withTitle: title, message: message, style: .alert, cancel: cancel, preferred: preferred, other: other, onTapped: { tappedAction in if let action = cancel, action.name == tappedAction.title { action.handler?() return } if let preferred = preferred, preferred.name == tappedAction.title { preferred.handler?() return } for action in other { if action.name == tappedAction.title { action.handler?() return } } } ) self.present(alert, animated: true, completion: nil) } public func showTextInput( withTitle title: String, message: String, textFieldPlaceholder: String = "", textFieldDefault: String? = nil, keyboardType: UIKeyboardType = .default, cancel: TextAction? = nil, preferred: TextAction? = nil, other: [TextAction] = [] ) { var other = other if cancel == nil && other.isEmpty { other.append(.action("OK")) } var promptTextField: UITextField? let alert = Alert.buildAlert( withTitle: title, message: message, style: .alert, cancel: cancel, preferred: preferred, other: other, onTapped: { tappedAction in if let action = cancel, action.name == tappedAction.title { action.handler?(promptTextField?.text ?? "") return } if let preferred = preferred, preferred.name == tappedAction.title { preferred.handler?(promptTextField?.text ?? "") return } for action in other { if action.name == tappedAction.title { action.handler?(promptTextField?.text ?? "") return } } } ) alert.addTextField { textField in textField.placeholder = textFieldPlaceholder textField.text = textFieldDefault textField.keyboardType = keyboardType promptTextField = textField } self.present(alert, animated: true, completion: nil) } } private extension Alert { struct Keys { static var Delegate = "Delegate" } class func buildAlert( withTitle title: String, message: String?, style: UIAlertControllerStyle, cancel: AnyAlertAction? = nil, preferred: AnyAlertAction? = nil, other: [AnyAlertAction] = [], onTapped: @escaping (UIAlertAction) -> () ) -> UIAlertController { let alert = UIAlertController(title: title, message: message, preferredStyle: style) if let cancel = cancel { alert.addAction(MakeAlertAction( cancel.name, .cancel, onTapped )) } if let preferred = preferred { let action = MakeAlertAction( preferred.name, preferred.isDestructive ? .destructive : .default, onTapped ) alert.addAction(action) alert.preferredAction = action } for action in other { alert.addAction(MakeAlertAction( action.name, action.isDestructive ? .destructive : .default, onTapped )) } return alert } } #endif
true
512dadb3871cbf9dbaaa19f1578f9797cc281c19
Swift
KrisdaSiangchaew/MyCourses
/MyCourses/Views/CoursesView.swift
UTF-8
4,627
3.03125
3
[]
no_license
// // CoursesView.swift // MyCourses // // Created by Kris Siangchaew on 2/12/2563 BE. // import SwiftUI struct CoursesView: View { @EnvironmentObject var dataController: DataController @Environment(\.managedObjectContext) var moc let showArchived: Bool let courses: FetchRequest<Course> static let tagArchived: String? = "Archived" static let tagOpen: String? = "Open" @State private var showSortingOrder = false @State private var sortOrder: Topic.SortOrder = .optimized init(showArchive: Bool) { self.showArchived = showArchive courses = FetchRequest<Course>( entity: Course.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Course.creationDate, ascending: true)], predicate: NSPredicate(format: "archived = %d", showArchived) ) } var body: some View { NavigationView { Group { if courses.wrappedValue.count == 0 { Text("There is nothing to show now.") } else { List { ForEach(courses.wrappedValue) { course in Section(header: CourseHeaderView(course: course)) { ForEach(course.courseTopics(using: sortOrder)) { item in TopicRowView(course: course, topic: item) } .onDelete { offsets in let allItems = course.courseTopics(using: sortOrder) for offset in offsets { let topic = allItems[offset] dataController.delete(topic) } dataController.save() } if showArchived == false { Button { let topic = Topic(context: moc) topic.course = course topic.creationDate = Date() dataController.save() } label: { Label("Add new item", systemImage: "plus") } } } } } .listStyle(InsetGroupedListStyle()) } } .navigationTitle(Text(showArchived ? "Archived Courses" : "Open Courses")) .toolbar { ToolbarItem(placement: .navigationBarTrailing) { if showArchived == false { Button { withAnimation { let course = Course(context: moc) course.creationDate = Date() course.archived = false dataController.save() } } label: { Label("Add course", systemImage: "plus") } } } ToolbarItem(placement: .navigationBarLeading) { Button { showSortingOrder.toggle() } label: { Label("Sort", systemImage: "arrow.up.arrow.down") } } } .actionSheet(isPresented: $showSortingOrder) { ActionSheet( title: Text("Sort topics"), message: nil, buttons: [ .default(Text("Optimized")) { sortOrder = .optimized }, .default(Text("Title")) { sortOrder = .title }, .default(Text("Date")) { sortOrder = .creationDate } ] ) } SelectSomethingView() } } } struct CoursesView_Previews: PreviewProvider { static let dataController = DataController.preview static var previews: some View { CoursesView(showArchive: false) .environment(\.managedObjectContext, dataController.container.viewContext) .environmentObject(dataController) } }
true
a340bbf4c1a287ec140e3b66b15705834dcabbf6
Swift
magdy-kamal-ok/MarvelHeroes
/Marvel/Extensions/SwiftTypeExtensions.swift
UTF-8
734
3
3
[]
no_license
// // SwiftTypeExtensions.swift // Marvel // // Created by mac on 7/3/19. // Copyright © 2019 OwnProjects. All rights reserved. // import Foundation // MARK: - extension to provide default value to optional string extension Optional where Wrapped == String { func defaultValueIfNotExists()->String{ return self != nil ? self! : "" } } // MARK: - extention to convert struct to json dictionary to send to api extension Encodable { subscript(key: String) -> Any? { return dictionary[key] } var data: Data { return try! JSONEncoder().encode(self) } var dictionary: [String: Any] { return (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] ?? [:] } }
true
7951791d4cdab29007da6b1a5910e713e27f1da8
Swift
blladnar/VCSpecs
/VCSpecs/VCTestHolder.swift
UTF-8
1,582
2.546875
3
[]
no_license
import Foundation final internal class VCTestHolder: NSObject { static let shared = VCTestHolder() private var appearTestsForClass = [String: [VCTest]]() private var disappearTestsForClass = [String: [VCTest]]() private var appear: Bool? = nil var currentViewController: UIViewController? var currentClass = "" var appearanceTests: [VCTest]? { return appearTestsForClass[currentClass] } var disappearanceTests: [VCTest]? { return disappearTestsForClass[currentClass] } func addAppear() { appear = true } func addDisappear() { appear = false } func add(test: VCTest) { if let appearing = appear { if appearing { if var tests = appearTestsForClass[currentClass] { tests.append(test) appearTestsForClass[currentClass] = tests } else { var tests = [VCTest]() tests.append(test) appearTestsForClass[self.currentClass] = tests } } else { if var tests = disappearTestsForClass[currentClass] { tests.append(test) disappearTestsForClass[currentClass] = tests } else { var tests = [VCTest]() tests.append(test) disappearTestsForClass[self.currentClass] = tests } } } } }
true
262e8b3904f4eb0e299809f45471dd5369b1f13f
Swift
mattpolzin/Poly
/Sources/Poly/Poly.swift
UTF-8
27,894
3.6875
4
[ "MIT" ]
permissive
// // Poly.swift // Poly // // Created by Mathew Polzin on 11/22/18. // /// Poly is a protocol to which types that /// are polymorphic belong to. /// /// Specifically, `Poly1`, `Poly2`, `Poly3`, etc. /// types conform to the `Poly` protocol. /// These types allow typesafe grouping /// of a number of disparate types under /// one roof. /// /// # Access /// You can access the value of a `Poly` type /// in one of four different ways. /// 1. You can switch over its cases /// /// switch poly2Value { /// case .a(let value): /// // value is of type `A` /// case .b(let value): /// // value is of type `B` /// } /// /// 2. You can ask for a value by accessor /// /// let value1 = poly2Value.a // value1 is of type `A?` /// let value2 = poly2Value.b // value2 is of type `B?` /// /// 3. You can ask for a value by type /// /// let value1 = poly2Value[A.self] // value1 is of type `A?` /// let value2 = poly2Value[B.self] // value2 is of type `B?` /// /// 4. You can ask for a type-erased value /// /// let value = poly2Value.value // value is of type `Any` /// public protocol Poly { /// Get a type-erased value. var value: Any { get } /// Get a list of all types this `Poly` supports. static var allTypes: [Any.Type] { get } } // MARK: - 0 types public protocol _Poly0: Poly { } public struct Poly0: _Poly0 { public init() {} public var value: Any { return () } } extension Poly0: Equatable, Hashable {} // MARK: - 1 type public protocol _Poly1: _Poly0 { associatedtype A /// Get the value if it is of type `A` var a: A? { get } init(_ a: A) } public extension _Poly1 { subscript(_ lookup: A.Type) -> A? { return a } } /// See `Poly` for documentation public enum Poly1<A>: _Poly1 { case a(A) public var a: A? { switch self { case .a(let ret): return ret } } public init(_ a: A) { self = .a(a) } public var value: Any { switch self { case .a(let ret): return ret } } } extension Poly1: Equatable where A: Equatable {} extension Poly1: Hashable where A: Hashable {} // MARK: - 2 types public protocol _Poly2: _Poly1 { associatedtype B /// Get the value if it is of type `B` var b: B? { get } init(_ b: B) } public extension _Poly2 { subscript(_ lookup: B.Type) -> B? { return b } } /// See `Poly` for documentation public typealias Either = Poly2 /// See `Poly` for documentation public enum Poly2<A, B>: _Poly2 { case a(A) case b(B) public var a: A? { guard case let .a(ret) = self else { return nil } return ret } public init(_ a: A) { self = .a(a) } public var b: B? { guard case let .b(ret) = self else { return nil } return ret } public init(_ b: B) { self = .b(b) } public var value: Any { switch self { case .a(let ret): return ret case .b(let ret): return ret } } } extension Poly2: Equatable where A: Equatable, B: Equatable {} extension Poly2: Hashable where A: Hashable, B: Hashable {} // MARK: - 3 types public protocol _Poly3: _Poly2 { associatedtype C /// Get the value if it is of type `C` var c: C? { get } init(_ c: C) } public extension _Poly3 { subscript(_ lookup: C.Type) -> C? { return c } } /// See `Poly` for documentation public enum Poly3<A, B, C>: _Poly3 { case a(A) case b(B) case c(C) public var a: A? { guard case let .a(ret) = self else { return nil } return ret } public init(_ a: A) { self = .a(a) } public var b: B? { guard case let .b(ret) = self else { return nil } return ret } public init(_ b: B) { self = .b(b) } public var c: C? { guard case let .c(ret) = self else { return nil } return ret } public init(_ c: C) { self = .c(c) } public var value: Any { switch self { case .a(let ret): return ret case .b(let ret): return ret case .c(let ret): return ret } } } extension Poly3: Equatable where A: Equatable, B: Equatable, C: Equatable {} extension Poly3: Hashable where A: Hashable, B: Hashable, C: Hashable {} // MARK: - 4 types public protocol _Poly4: _Poly3 { associatedtype D /// Get the value if it is of type `D` var d: D? { get } init(_ d: D) } public extension _Poly4 { subscript(_ lookup: D.Type) -> D? { return d } } /// See `Poly` for documentation public enum Poly4<A, B, C, D>: _Poly4 { case a(A) case b(B) case c(C) case d(D) public var a: A? { guard case let .a(ret) = self else { return nil } return ret } public init(_ a: A) { self = .a(a) } public var b: B? { guard case let .b(ret) = self else { return nil } return ret } public init(_ b: B) { self = .b(b) } public var c: C? { guard case let .c(ret) = self else { return nil } return ret } public init(_ c: C) { self = .c(c) } public var d: D? { guard case let .d(ret) = self else { return nil } return ret } public init(_ d: D) { self = .d(d) } public var value: Any { switch self { case .a(let ret): return ret case .b(let ret): return ret case .c(let ret): return ret case .d(let ret): return ret } } } extension Poly4: Equatable where A: Equatable, B: Equatable, C: Equatable, D: Equatable {} extension Poly4: Hashable where A: Hashable, B: Hashable, C: Hashable, D: Hashable {} // MARK: - 5 types public protocol _Poly5: _Poly4 { associatedtype E /// Get the value if it is of type `E` var e: E? { get } init(_ e: E) } public extension _Poly5 { subscript(_ lookup: E.Type) -> E? { return e } } /// See `Poly` for documentation public enum Poly5<A, B, C, D, E>: _Poly5 { case a(A) case b(B) case c(C) case d(D) case e(E) public var a: A? { guard case let .a(ret) = self else { return nil } return ret } public init(_ a: A) { self = .a(a) } public var b: B? { guard case let .b(ret) = self else { return nil } return ret } public init(_ b: B) { self = .b(b) } public var c: C? { guard case let .c(ret) = self else { return nil } return ret } public init(_ c: C) { self = .c(c) } public var d: D? { guard case let .d(ret) = self else { return nil } return ret } public init(_ d: D) { self = .d(d) } public var e: E? { guard case let .e(ret) = self else { return nil } return ret } public init(_ e: E) { self = .e(e) } public var value: Any { switch self { case .a(let ret): return ret case .b(let ret): return ret case .c(let ret): return ret case .d(let ret): return ret case .e(let ret): return ret } } } extension Poly5: Equatable where A: Equatable, B: Equatable, C: Equatable, D: Equatable, E: Equatable {} extension Poly5: Hashable where A: Hashable, B: Hashable, C: Hashable, D: Hashable, E: Hashable {} // MARK: - 6 types public protocol _Poly6: _Poly5 { associatedtype F /// Get the value if it is of type `F` var f: F? { get } init(_ f: F) } public extension _Poly6 { subscript(_ lookup: F.Type) -> F? { return f } } /// See `Poly` for documentation public enum Poly6<A, B, C, D, E, F>: _Poly6 { case a(A) case b(B) case c(C) case d(D) case e(E) case f(F) public var a: A? { guard case let .a(ret) = self else { return nil } return ret } public init(_ a: A) { self = .a(a) } public var b: B? { guard case let .b(ret) = self else { return nil } return ret } public init(_ b: B) { self = .b(b) } public var c: C? { guard case let .c(ret) = self else { return nil } return ret } public init(_ c: C) { self = .c(c) } public var d: D? { guard case let .d(ret) = self else { return nil } return ret } public init(_ d: D) { self = .d(d) } public var e: E? { guard case let .e(ret) = self else { return nil } return ret } public init(_ e: E) { self = .e(e) } public var f: F? { guard case let .f(ret) = self else { return nil } return ret } public init(_ f: F) { self = .f(f) } public var value: Any { switch self { case .a(let ret): return ret case .b(let ret): return ret case .c(let ret): return ret case .d(let ret): return ret case .e(let ret): return ret case .f(let ret): return ret } } } extension Poly6: Equatable where A: Equatable, B: Equatable, C: Equatable, D: Equatable, E: Equatable, F: Equatable {} extension Poly6: Hashable where A: Hashable, B: Hashable, C: Hashable, D: Hashable, E: Hashable, F: Hashable {} // MARK: - 7 types public protocol _Poly7: _Poly6 { associatedtype G /// Get the value if it is of type `G` var g: G? { get } init(_ g: G) } public extension _Poly7 { subscript(_ lookup: G.Type) -> G? { return g } } /// See `Poly` for documentation public enum Poly7<A, B, C, D, E, F, G>: _Poly7 { case a(A) case b(B) case c(C) case d(D) case e(E) case f(F) case g(G) public var a: A? { guard case let .a(ret) = self else { return nil } return ret } public init(_ a: A) { self = .a(a) } public var b: B? { guard case let .b(ret) = self else { return nil } return ret } public init(_ b: B) { self = .b(b) } public var c: C? { guard case let .c(ret) = self else { return nil } return ret } public init(_ c: C) { self = .c(c) } public var d: D? { guard case let .d(ret) = self else { return nil } return ret } public init(_ d: D) { self = .d(d) } public var e: E? { guard case let .e(ret) = self else { return nil } return ret } public init(_ e: E) { self = .e(e) } public var f: F? { guard case let .f(ret) = self else { return nil } return ret } public init(_ f: F) { self = .f(f) } public var g: G? { guard case let .g(ret) = self else { return nil } return ret } public init(_ g: G) { self = .g(g) } public var value: Any { switch self { case .a(let ret): return ret case .b(let ret): return ret case .c(let ret): return ret case .d(let ret): return ret case .e(let ret): return ret case .f(let ret): return ret case .g(let ret): return ret } } } extension Poly7: Equatable where A: Equatable, B: Equatable, C: Equatable, D: Equatable, E: Equatable, F: Equatable, G: Equatable {} extension Poly7: Hashable where A: Hashable, B: Hashable, C: Hashable, D: Hashable, E: Hashable, F: Hashable, G: Hashable {} // MARK: - 8 types public protocol _Poly8: _Poly7 { associatedtype H /// Get the value if it is of type `H` var h: H? { get } init(_ h: H) } public extension _Poly8 { subscript(_ lookup: H.Type) -> H? { return h } } /// See `Poly` for documentation public enum Poly8<A, B, C, D, E, F, G, H>: _Poly8 { case a(A) case b(B) case c(C) case d(D) case e(E) case f(F) case g(G) case h(H) public var a: A? { guard case let .a(ret) = self else { return nil } return ret } public init(_ a: A) { self = .a(a) } public var b: B? { guard case let .b(ret) = self else { return nil } return ret } public init(_ b: B) { self = .b(b) } public var c: C? { guard case let .c(ret) = self else { return nil } return ret } public init(_ c: C) { self = .c(c) } public var d: D? { guard case let .d(ret) = self else { return nil } return ret } public init(_ d: D) { self = .d(d) } public var e: E? { guard case let .e(ret) = self else { return nil } return ret } public init(_ e: E) { self = .e(e) } public var f: F? { guard case let .f(ret) = self else { return nil } return ret } public init(_ f: F) { self = .f(f) } public var g: G? { guard case let .g(ret) = self else { return nil } return ret } public init(_ g: G) { self = .g(g) } public var h: H? { guard case let .h(ret) = self else { return nil } return ret } public init(_ h: H) { self = .h(h) } public var value: Any { switch self { case .a(let ret): return ret case .b(let ret): return ret case .c(let ret): return ret case .d(let ret): return ret case .e(let ret): return ret case .f(let ret): return ret case .g(let ret): return ret case .h(let ret): return ret } } } extension Poly8: Equatable where A: Equatable, B: Equatable, C: Equatable, D: Equatable, E: Equatable, F: Equatable, G: Equatable, H: Equatable {} extension Poly8: Hashable where A: Hashable, B: Hashable, C: Hashable, D: Hashable, E: Hashable, F: Hashable, G: Hashable, H: Hashable {} // MARK: - 9 types public protocol _Poly9: _Poly8 { associatedtype I /// Get the value if it is of type `I` var i: I? { get } init(_ i: I) } public extension _Poly9 { subscript(_ lookup: I.Type) -> I? { return i } } /// See `Poly` for documentation public enum Poly9<A, B, C, D, E, F, G, H, I>: _Poly9 { case a(A) case b(B) case c(C) case d(D) case e(E) case f(F) case g(G) case h(H) case i(I) public var a: A? { guard case let .a(ret) = self else { return nil } return ret } public init(_ a: A) { self = .a(a) } public var b: B? { guard case let .b(ret) = self else { return nil } return ret } public init(_ b: B) { self = .b(b) } public var c: C? { guard case let .c(ret) = self else { return nil } return ret } public init(_ c: C) { self = .c(c) } public var d: D? { guard case let .d(ret) = self else { return nil } return ret } public init(_ d: D) { self = .d(d) } public var e: E? { guard case let .e(ret) = self else { return nil } return ret } public init(_ e: E) { self = .e(e) } public var f: F? { guard case let .f(ret) = self else { return nil } return ret } public init(_ f: F) { self = .f(f) } public var g: G? { guard case let .g(ret) = self else { return nil } return ret } public init(_ g: G) { self = .g(g) } public var h: H? { guard case let .h(ret) = self else { return nil } return ret } public init(_ h: H) { self = .h(h) } public var i: I? { guard case let .i(ret) = self else { return nil } return ret } public init(_ i: I) { self = .i(i) } public var value: Any { switch self { case .a(let ret): return ret case .b(let ret): return ret case .c(let ret): return ret case .d(let ret): return ret case .e(let ret): return ret case .f(let ret): return ret case .g(let ret): return ret case .h(let ret): return ret case .i(let ret): return ret } } } extension Poly9: Equatable where A: Equatable, B: Equatable, C: Equatable, D: Equatable, E: Equatable, F: Equatable, G: Equatable, H: Equatable, I: Equatable {} extension Poly9: Hashable where A: Hashable, B: Hashable, C: Hashable, D: Hashable, E: Hashable, F: Hashable, G: Hashable, H: Hashable, I: Hashable {} // MARK: - 10 types public protocol _Poly10: _Poly9 { associatedtype J /// Get the value if it is of type `J` var j: J? { get } init(_ j: J) } public extension _Poly10 { subscript(_ lookup: J.Type) -> J? { return j } } /// See `Poly` for documentation public enum Poly10<A, B, C, D, E, F, G, H, I, J>: _Poly10 { case a(A) case b(B) case c(C) case d(D) case e(E) case f(F) case g(G) case h(H) case i(I) case j(J) public var a: A? { guard case let .a(ret) = self else { return nil } return ret } public init(_ a: A) { self = .a(a) } public var b: B? { guard case let .b(ret) = self else { return nil } return ret } public init(_ b: B) { self = .b(b) } public var c: C? { guard case let .c(ret) = self else { return nil } return ret } public init(_ c: C) { self = .c(c) } public var d: D? { guard case let .d(ret) = self else { return nil } return ret } public init(_ d: D) { self = .d(d) } public var e: E? { guard case let .e(ret) = self else { return nil } return ret } public init(_ e: E) { self = .e(e) } public var f: F? { guard case let .f(ret) = self else { return nil } return ret } public init(_ f: F) { self = .f(f) } public var g: G? { guard case let .g(ret) = self else { return nil } return ret } public init(_ g: G) { self = .g(g) } public var h: H? { guard case let .h(ret) = self else { return nil } return ret } public init(_ h: H) { self = .h(h) } public var i: I? { guard case let .i(ret) = self else { return nil } return ret } public init(_ i: I) { self = .i(i) } public var j: J? { guard case let .j(ret) = self else { return nil } return ret } public init(_ j: J) { self = .j(j) } public var value: Any { switch self { case .a(let ret): return ret case .b(let ret): return ret case .c(let ret): return ret case .d(let ret): return ret case .e(let ret): return ret case .f(let ret): return ret case .g(let ret): return ret case .h(let ret): return ret case .i(let ret): return ret case .j(let ret): return ret } } } extension Poly10: Equatable where A: Equatable, B: Equatable, C: Equatable, D: Equatable, E: Equatable, F: Equatable, G: Equatable, H: Equatable, I: Equatable, J: Equatable {} extension Poly10: Hashable where A: Hashable, B: Hashable, C: Hashable, D: Hashable, E: Hashable, F: Hashable, G: Hashable, H: Hashable, I: Hashable, J: Hashable {} // MARK: - 11 types public protocol _Poly11: _Poly10 { associatedtype K /// Get the value if it is of type `K` var k: K? { get } init(_ k: K) } public extension _Poly11 { subscript(_ lookup: K.Type) -> K? { return k } } /// See `Poly` for documentation public enum Poly11<A, B, C, D, E, F, G, H, I, J, K>: _Poly11 { case a(A) case b(B) case c(C) case d(D) case e(E) case f(F) case g(G) case h(H) case i(I) case j(J) case k(K) public var a: A? { guard case let .a(ret) = self else { return nil } return ret } public init(_ a: A) { self = .a(a) } public var b: B? { guard case let .b(ret) = self else { return nil } return ret } public init(_ b: B) { self = .b(b) } public var c: C? { guard case let .c(ret) = self else { return nil } return ret } public init(_ c: C) { self = .c(c) } public var d: D? { guard case let .d(ret) = self else { return nil } return ret } public init(_ d: D) { self = .d(d) } public var e: E? { guard case let .e(ret) = self else { return nil } return ret } public init(_ e: E) { self = .e(e) } public var f: F? { guard case let .f(ret) = self else { return nil } return ret } public init(_ f: F) { self = .f(f) } public var g: G? { guard case let .g(ret) = self else { return nil } return ret } public init(_ g: G) { self = .g(g) } public var h: H? { guard case let .h(ret) = self else { return nil } return ret } public init(_ h: H) { self = .h(h) } public var i: I? { guard case let .i(ret) = self else { return nil } return ret } public init(_ i: I) { self = .i(i) } public var j: J? { guard case let .j(ret) = self else { return nil } return ret } public init(_ j: J) { self = .j(j) } public var k: K? { guard case let .k(ret) = self else { return nil } return ret } public init(_ k: K) { self = .k(k) } public var value: Any { switch self { case .a(let ret): return ret case .b(let ret): return ret case .c(let ret): return ret case .d(let ret): return ret case .e(let ret): return ret case .f(let ret): return ret case .g(let ret): return ret case .h(let ret): return ret case .i(let ret): return ret case .j(let ret): return ret case .k(let ret): return ret } } } extension Poly11: Equatable where A: Equatable, B: Equatable, C: Equatable, D: Equatable, E: Equatable, F: Equatable, G: Equatable, H: Equatable, I: Equatable, J: Equatable, K: Equatable {} extension Poly11: Hashable where A: Hashable, B: Hashable, C: Hashable, D: Hashable, E: Hashable, F: Hashable, G: Hashable, H: Hashable, I: Hashable, J: Hashable, K: Hashable {} // MARK: - 12 types public protocol _Poly12: _Poly11 { associatedtype L /// Get the value if it is of type `L` var l: L? { get } init(_ l: L) } public extension _Poly12 { subscript(_ lookup: L.Type) -> L? { return l } } /// See `Poly` for documentation public enum Poly12<A, B, C, D, E, F, G, H, I, J, K, L>: _Poly12 { case a(A) case b(B) case c(C) case d(D) case e(E) case f(F) case g(G) case h(H) case i(I) case j(J) case k(K) case l(L) public var a: A? { guard case let .a(ret) = self else { return nil } return ret } public init(_ a: A) { self = .a(a) } public var b: B? { guard case let .b(ret) = self else { return nil } return ret } public init(_ b: B) { self = .b(b) } public var c: C? { guard case let .c(ret) = self else { return nil } return ret } public init(_ c: C) { self = .c(c) } public var d: D? { guard case let .d(ret) = self else { return nil } return ret } public init(_ d: D) { self = .d(d) } public var e: E? { guard case let .e(ret) = self else { return nil } return ret } public init(_ e: E) { self = .e(e) } public var f: F? { guard case let .f(ret) = self else { return nil } return ret } public init(_ f: F) { self = .f(f) } public var g: G? { guard case let .g(ret) = self else { return nil } return ret } public init(_ g: G) { self = .g(g) } public var h: H? { guard case let .h(ret) = self else { return nil } return ret } public init(_ h: H) { self = .h(h) } public var i: I? { guard case let .i(ret) = self else { return nil } return ret } public init(_ i: I) { self = .i(i) } public var j: J? { guard case let .j(ret) = self else { return nil } return ret } public init(_ j: J) { self = .j(j) } public var k: K? { guard case let .k(ret) = self else { return nil } return ret } public init(_ k: K) { self = .k(k) } public var l: L? { guard case let .l(ret) = self else { return nil } return ret } public init(_ l: L) { self = .l(l) } public var value: Any { switch self { case .a(let ret): return ret case .b(let ret): return ret case .c(let ret): return ret case .d(let ret): return ret case .e(let ret): return ret case .f(let ret): return ret case .g(let ret): return ret case .h(let ret): return ret case .i(let ret): return ret case .j(let ret): return ret case .k(let ret): return ret case .l(let ret): return ret } } } extension Poly12: Equatable where A: Equatable, B: Equatable, C: Equatable, D: Equatable, E: Equatable, F: Equatable, G: Equatable, H: Equatable, I: Equatable, J: Equatable, K: Equatable, L: Equatable {} extension Poly12: Hashable where A: Hashable, B: Hashable, C: Hashable, D: Hashable, E: Hashable, F: Hashable, G: Hashable, H: Hashable, I: Hashable, J: Hashable, K: Hashable, L: Hashable {} // MARK: - 13 types public protocol _Poly13: _Poly12 { associatedtype M /// Get the value if it is of type `L` var m: M? { get } init(_ m: M) } public extension _Poly13 { subscript(_ lookup: M.Type) -> M? { return m } } /// See `Poly` for documentation public enum Poly13<A, B, C, D, E, F, G, H, I, J, K, L, M>: _Poly13 { case a(A) case b(B) case c(C) case d(D) case e(E) case f(F) case g(G) case h(H) case i(I) case j(J) case k(K) case l(L) case m(M) public var a: A? { guard case let .a(ret) = self else { return nil } return ret } public init(_ a: A) { self = .a(a) } public var b: B? { guard case let .b(ret) = self else { return nil } return ret } public init(_ b: B) { self = .b(b) } public var c: C? { guard case let .c(ret) = self else { return nil } return ret } public init(_ c: C) { self = .c(c) } public var d: D? { guard case let .d(ret) = self else { return nil } return ret } public init(_ d: D) { self = .d(d) } public var e: E? { guard case let .e(ret) = self else { return nil } return ret } public init(_ e: E) { self = .e(e) } public var f: F? { guard case let .f(ret) = self else { return nil } return ret } public init(_ f: F) { self = .f(f) } public var g: G? { guard case let .g(ret) = self else { return nil } return ret } public init(_ g: G) { self = .g(g) } public var h: H? { guard case let .h(ret) = self else { return nil } return ret } public init(_ h: H) { self = .h(h) } public var i: I? { guard case let .i(ret) = self else { return nil } return ret } public init(_ i: I) { self = .i(i) } public var j: J? { guard case let .j(ret) = self else { return nil } return ret } public init(_ j: J) { self = .j(j) } public var k: K? { guard case let .k(ret) = self else { return nil } return ret } public init(_ k: K) { self = .k(k) } public var l: L? { guard case let .l(ret) = self else { return nil } return ret } public init(_ l: L) { self = .l(l) } public var m: M? { guard case let .m(ret) = self else { return nil } return ret } public init(_ m: M) { self = .m(m) } public var value: Any { switch self { case .a(let ret): return ret case .b(let ret): return ret case .c(let ret): return ret case .d(let ret): return ret case .e(let ret): return ret case .f(let ret): return ret case .g(let ret): return ret case .h(let ret): return ret case .i(let ret): return ret case .j(let ret): return ret case .k(let ret): return ret case .l(let ret): return ret case .m(let ret): return ret } } } extension Poly13: Equatable where A: Equatable, B: Equatable, C: Equatable, D: Equatable, E: Equatable, F: Equatable, G: Equatable, H: Equatable, I: Equatable, J: Equatable, K: Equatable, L: Equatable, M: Equatable {} extension Poly13: Hashable where A: Hashable, B: Hashable, C: Hashable, D: Hashable, E: Hashable, F: Hashable, G: Hashable, H: Hashable, I: Hashable, J: Hashable, K: Hashable, L: Hashable, M: Hashable {}
true
9382bf74b4484ff91e5e2e6d6a85110746277ce4
Swift
charliemchapman/parallax-uikit-demo
/ParallaxDemo/MainViewController.swift
UTF-8
2,694
2.5625
3
[ "MIT" ]
permissive
import UIKit class MainViewController: UIViewController { let parallaxDots = ParallaxDotsView() let darkCard = DarkCardView() let darkCard2 = DarkCardView2() override func viewDidLoad() { configureViews() } override var preferredStatusBarStyle: UIStatusBarStyle { get { .lightContent } } private func configureViews() { configureGradient() //configureParallaxDots() // configureDarkCard() configureDarkCard2() constrainViews() } private func constrainViews() { // constrainParallaxDots() // constrainDarkCard() constrainDarkCard2() } // MARK: Configure Views private func configureGradient() { let gradient = CAGradientLayer() gradient.frame = view.bounds gradient.colors = [ UIColor(red: 84/256, green: 20/256, blue: 163/256, alpha: 1).cgColor, UIColor(red: 23/256, green: 3/256, blue: 49/256, alpha: 1).cgColor ] view.layer.insertSublayer(gradient, at: 0) } private func configureParallaxDots() { parallaxDots.layer.cornerRadius = 40 parallaxDots.clipsToBounds = true view.addSubview(parallaxDots) } private func configureDarkCard() { view.addSubview(darkCard) } private func configureDarkCard2() { view.addSubview(darkCard2) } // MARK: Constrain Views private func constrainParallaxDots() { parallaxDots.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ parallaxDots.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 100), parallaxDots.centerXAnchor.constraint(equalTo: view.centerXAnchor), parallaxDots.heightAnchor.constraint(equalToConstant: 200), parallaxDots.widthAnchor.constraint(equalToConstant: 200) ]) } private func constrainDarkCard() { darkCard.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ darkCard.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 50), darkCard.centerXAnchor.constraint(equalTo: view.centerXAnchor) ]) } private func constrainDarkCard2() { darkCard2.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ darkCard2.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 50), darkCard2.centerXAnchor.constraint(equalTo: view.centerXAnchor) ]) } }
true
981c607410a2621406a01e62219ae3cb8d62e213
Swift
Torsph/DynamicLayout
/Carthage/Checkouts/Spots/Sources/Shared/Library/Componentable.swift
UTF-8
171
2.578125
3
[ "MIT" ]
permissive
#if os(iOS) import UIKit #else import Foundation #endif public protocol Componentable { var defaultHeight: CGFloat { get } func configure(component: Component) }
true
8a4832ef513be9604b62b3557c56f99ffbba2f73
Swift
robbiealixsantos/memory-panda
/memorypanda/GameScene.swift
UTF-8
3,089
2.734375
3
[]
no_license
// // GameScene.swift // memorypanda // // Created by Robbie Santos on 11/28/16. // Copyright (c) 2016 Robbie Santos. All rights reserved. // import SpriteKit class GameScene: SKScene { var buttonPlay : SKSpriteNode! var buttonLeaderboard : SKSpriteNode! var buttonRate : SKSpriteNode! var title : SKSpriteNode! override func didMoveToView(view: SKView) { setupScenery() CreateMenu() } override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { } override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) { let touch = touches.first as! UITouch // let touchLocation = touch.locationInNode(self) var positionInScene : CGPoint = touch.locationInNode(self) var touchedNode : SKSpriteNode = self.nodeAtPoint(positionInScene) as! SKSpriteNode self.ProcessItemTouch(touchedNode) } override func update(currentTime: CFTimeInterval) { /* Called before each frame is rendered */ } func setupScenery(){ let background = SKSpriteNode(imageNamed: BackgroundImage) background.anchorPoint = CGPointMake(0, 1) background.position = CGPointMake(0, size.height) background.zPosition = 0 background.size = CGSize(width: self.view!.bounds.size.width, height: self.view!.bounds.size.height) addChild(background) } func CreateMenu(){ var offsetY : CGFloat = 3.0 var offsetX : CGFloat = 5.0 buttonRate = SKSpriteNode(imageNamed: buttonRateImage) buttonRate.position = CGPointMake(size.width/2, size.height/2 + buttonRate.size.height + offsetY) buttonRate.zPosition = 10 buttonRate.name = "rate" addChild(buttonRate) buttonPlay = SKSpriteNode(imageNamed: buttonPlayImage) buttonPlay.position = CGPointMake(size.width / 2 - offsetX - buttonPlay.size.width / 2 , size.height/2) buttonPlay.zPosition = 10 buttonPlay.name = "play" addChild(buttonPlay) buttonLeaderboard = SKSpriteNode(imageNamed: buttonLeaderboardImage) buttonLeaderboard.position = CGPointMake(size.width / 2 + offsetX + buttonLeaderboard.size.width / 2, size.height / 2) buttonLeaderboard.zPosition = 10 buttonLeaderboard.name = "leaderboard" addChild(buttonLeaderboard) title = SKSpriteNode(imageNamed: titleImage) title.position = CGPointMake(size.width / 2, buttonRate.position.y + buttonRate.size.height / 2 + title.size.height / 2 + offsetY) title.zPosition = 10 title.name = "title" addChild(title) title.setScale(1) } func ProcessItemTouch(nod : SKSpriteNode){ if(nod.name == "play") { println("play button pressed") } else if (nod.name == "leaderboard") { println("leaderboard button pressed") } else if (nod.name == "rate") { println("rate button pressed") } } }
true
33bc395061e96a3b37724b2c7f28434420506517
Swift
Justinwveach/whirly-dirly-words
/WhirlyDirlyWordsTests/WhirlyDirlyWordsTests.swift
UTF-8
2,985
3.09375
3
[]
no_license
// // WhirlyDirlyWordsTests.swift // WhirlyDirlyWordsTests // // Created by Justin Veach on 12/6/17. // Copyright © 2017 justinveach. All rights reserved. // import XCTest @testable import WhirlyDirlyWords class WhirlyDirlyWordsTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testColumnRowCalculation() { let size = 8 let index = 11 let column = index < size ? index : index % size let row = index / size assert(column == 3) assert(row == 1) } func testColumnRowCalculationTwo() { let size = 8 let index = 3 let column = index < size ? index : index % size let row = index / size assert(column == 3) assert(row == 0) } func testCharAtIndex() { let string = "Hello" let index = string.index(of: "e") assert(index == 1) let lIndex = string.index(of: "l") assert(lIndex == 2) } func testTileValue() { let tileOne = Tile(letter: "z", column: 0, row: 0) assert(tileOne.pointValue == 10) let tileTwo = Tile(letter: "w", column: 0, row: 0) assert(tileTwo.pointValue == 4) let tileThree = Tile(invalid: true) assert(tileThree.pointValue == 0) } func testFindingRandomLetter() { let puzzleSize = 3 let puzzle = CrosswordPuzzle(size: puzzleSize) for column in 0..<puzzleSize { for row in 0..<puzzleSize { let tile = Tile(letter: " ", column: column, row: row) if column == 1 && row == 2 { tile.character = "t" } else if column == 2 && row == 0 { tile.character = "e" } puzzle.add(tile) } } let randomTiles = puzzle.findRandomTiles(amount: 2) assert(randomTiles.count == 2) let tile1 = randomTiles[0] let tile2 = randomTiles[1] assert((tile1.column == 1 && tile1.row == 2) || (tile2.column == 1 && tile2.row == 2)) assert((tile2.column == 2 && tile2.row == 0) || (tile1.column == 2 && tile1.row == 0)) } func testStringHash() { var dog = "dog".hash var god = "god".hash assert(dog != god) dog = String("dog".sorted()).hash god = String("god".sorted()).hash assert(dog == god) } func testWordCombos() { let results = Words.sharedInstance.getCombinations(word: "pension") assert(results.count > 0) } }
true
9e579df87a67dd53c0ede1ddd15fc6af847b17f3
Swift
Lucas-ZX-W/CardinalKit
/CardinalKit-Example/CardinalKit/Components/Onboarding/Steps/CKInstructionSteps.swift
UTF-8
1,308
2.6875
3
[ "MIT" ]
permissive
// // CKInstructionSteps.swift // CardinalKit_Example // // Created by Vishnu Ravi on 1/1/23. // Copyright © 2023 CardinalKit. All rights reserved. // import ResearchKit struct CKInstructionSteps { /// Creates individual instruction steps that summarize the sections in the study consent, /// with titles and text pulled from CKConfiguration.plist. /// /// This may be replaced with your own custom instruction steps for your onboarding workflow. static var steps: [ORKInstructionStep] = { let config = CKConfig.shared let instructionSteps = config["Consent Form"] as? [String: [String: String]] let stepKeys = [ "Overview", "DataGathering", "Privacy", "DataUse", "TimeCommitment", "StudySurvey", "StudyTasks" ] var steps = [ORKInstructionStep]() for key in stepKeys { guard let title = instructionSteps?[key]?["Title"], let summary = instructionSteps?[key]?["Summary"] else { continue } let step = ORKInstructionStep(identifier: "\(key)Step") step.title = title step.text = summary steps.append(step) } return steps }() }
true
d9b8f120c738b497778d632f5aa5ec6c9a9779ce
Swift
skykywind/JFJExtension
/Example/JFJExtension/ViewController.swift
UTF-8
1,105
2.609375
3
[ "MIT" ]
permissive
// // ViewController.swift // JFJExtension // // Created by skykywind on 03/05/2019. // Copyright (c) 2019 skykywind. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() _ = UIView(frame: CGRect(x: 100, y: 100, width: 100, height: 100)) .addTo(view) .config { $0.addRounded(radius: 10, corners: [.topLeft, .topRight]) $0.backgroundColor = UIColor.red }.layout({ (make) in make.left.top.equalToSuperview().offset(100) make.width.height.equalTo(200) }) _ = UILabel() .addTo(view) .config({ (label) in label.font = UIFont.systemFont(ofSize: 16) label.text = "Hello world" }) .layout({ (make) in make.left.equalToSuperview().offset(100) make.top.equalToSuperview().offset(300) make.size.equalTo(CGSize(width: 100, height: 100)) }) } }
true
395d1b9641a72bc0afef7a4c5fa2325f27a4192d
Swift
Pelikandr/OnlineStore
/OnlineStore/CatalogViewController/CatalogAdapter.swift
UTF-8
2,142
2.671875
3
[]
no_license
// // CatalogAdapter.swift // OnlineStore // // Created by Denis Zayakin on 12/6/19. // Copyright © 2019 Denis Zayakin. All rights reserved. // import UIKit class CatalogAdapter: NSObject, UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating, UISearchControllerDelegate { var onCategorySelected: ((String) -> Void)? var onCategoryUpdate: ((Int) -> Void)? var searchController = UISearchController() func numberOfSections(in tableView: UITableView) -> Int { return DataSource.shared.category.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 4 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "catalogCell", for: indexPath as IndexPath) as! CatalogTableViewCell configureCell(cell: cell, forRowAtIndexPath: indexPath) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { onCategorySelected!(DataSource.shared.category[indexPath.section][indexPath.row]) } func configureCell(cell: UITableViewCell, forRowAtIndexPath: IndexPath) { if forRowAtIndexPath.row != 0 { cell.textLabel?.textColor = UIColor.lightGray cell.textLabel?.text = DataSource.shared.category[forRowAtIndexPath.section][forRowAtIndexPath.row] } else { cell.textLabel?.textColor = UIColor.darkText cell.textLabel?.text = DataSource.shared.category[forRowAtIndexPath.section][forRowAtIndexPath.row] } } func updateSearchResults(for searchController: UISearchController) { DataSource.shared.arrFilter.removeAll(keepingCapacity: false) let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text!) let array = (DataSource.shared.category as NSArray).filtered(using: searchPredicate) DataSource.shared.arrFilter = array as! [String] onCategoryUpdate!(1) } }
true
7fc9061f07a4ea4ff0b91899d2c5813550e92843
Swift
jeffeom/Hippojobtamus
/HireDev/HireDev/ViewController+getLatLong.swift
UTF-8
1,975
2.703125
3
[ "Apache-2.0" ]
permissive
// // ViewController+getLatLong.swift // HireDev // // Created by Jeff Eom on 2016-10-07. // Copyright © 2016 Jeff Eom. All rights reserved. // import UIKit extension UIViewController{ func fetchLatLong(_ address: String, completion: @escaping (_ fetchedData: [String: Float]?) -> ()){ var latLong: [String: Float] = [:] var keys: NSDictionary? if let path = Bundle.main.path(forResource: "Keys", ofType: "plist") { keys = NSDictionary(contentsOfFile: path) } if let dict = keys { let api = dict["googleGeocode"] as? String let url = "https://maps.googleapis.com/maps/api/geocode/json?address=\(address)&key=\(api!)" let urlStr: String = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)! if let aURL = (URL(string: urlStr)){ let requestURL = aURL let urlRequest: NSMutableURLRequest = NSMutableURLRequest(url: requestURL as URL) let session = URLSession.shared let task = session.dataTask(with: urlRequest as URLRequest) { (data, response, error) -> Void in let httpResponse = response as! HTTPURLResponse let statusCode = httpResponse.statusCode if (statusCode == 200) { do{ let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as? [String: Any] if let rows = json?["results"] as? [[String: Any]] { for aRow in rows { if let geometry = aRow["geometry"] as? [String: Any]{ if let location = geometry["location"] as? [String : Float]{ latLong = location } } } completion(latLong) } }catch { print("Error with Json: \(error)") } } } task.resume() } } } }
true
fa1c82e3a502b678babe8aa43d478dc010c7b488
Swift
slackburn/Sound-It-
/Sound It!/WeatherNoisesViewController.swift
UTF-8
1,155
2.953125
3
[]
no_license
// // WeatherNoisesViewController.swift // Sound It! // // Created by Sam Blackburn on 06/12/2018. // Copyright © 2018 Sam Blackburn. All rights reserved. // import UIKit class WeatherNoisesViewController: UITableViewController { @IBOutlet weak var tableViewOutlet: UITableView! @IBAction func barBackButtonPressed(_ sender: UIBarButtonItem) { dismiss(animated: true, completion: nil) } var noises = SomeData.generateWeatherNoiseData() // retrieves data from class generateNoiseData from file SomeData } extension WeatherNoisesViewController { override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return noises.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // creates function let cell = tableView.dequeueReusableCell(withIdentifier: "NoiseCell", for: indexPath) as! AnimalNoisesCell // identifies cell let noise = noises[indexPath.row] cell.noise = noise // places name as title return cell // returns value to be produced in table } }
true
fe8aba50f139c1fe52095f0833d1c9d6fc6d2b05
Swift
jstorm31/grades-ios
/Grades/Model/Entity/Course.swift
UTF-8
3,102
3.140625
3
[ "Apache-2.0" ]
permissive
// // Subject.swift // Grades // // Created by Jiří Zdvomka on 04/03/2019. // Copyright © 2019 jiri.zdovmka. All rights reserved. // import Foundation import RxDataSources class Course: Decodable { var code: String var name: String? init(code: String, name: String? = nil) { self.code = code self.name = name } init(fromCourse course: Course) { code = course.code name = course.name } enum CodingKeys: String, CodingKey { case code = "courseCode" case name = "courseName" } } /// Raw course representation for decoding from JSON struct StudentCourseRaw: Decodable { var code: String var items: [OverviewItem] enum CodingKeys: String, CodingKey { case code = "courseCode" case items = "overviewItems" } } class StudentCourse: Course { var finalValue: DynamicValue? init(code: String, name: String? = nil, finalValue: DynamicValue? = nil) { super.init(code: code) self.code = code self.name = name self.finalValue = finalValue } override init(fromCourse course: Course) { super.init(fromCourse: course) } init(fromCourse course: StudentCourse) { super.init(code: course.code, name: course.name) finalValue = course.finalValue } init(fromRawCourse rawCourse: StudentCourseRaw) { super.init(code: rawCourse.code) if let overviewItem = rawCourse.items.first(where: { $0.type == "POINTS_TOTAL" }), let value = overviewItem.value { finalValue = value } else if let overviewItem = rawCourse.items.first(where: { $0.type == "FINAL_SCORE" }), let value = overviewItem.value { finalValue = value } } required init(from _: Decoder) throws { fatalError("init(from:) has not been implemented") } } class TeacherCourse: Course { init(code: String) { super.init(code: code) } override init(fromCourse course: Course) { super.init(fromCourse: course) } required init(from _: Decoder) throws { fatalError("init(from:) has not been implemented") } } struct CoursesByRolesRaw: Decodable { var studentCourses: [String] var teacherCourses: [String] } struct CoursesByRoles { var student: [StudentCourse] var teacher: [TeacherCourse] func course(for indexPath: IndexPath) -> Course? { if indexPath.section == 0, indexPath.item < student.count { return student[indexPath.item] } else if indexPath.section == 1, indexPath.item < teacher.count { return teacher[indexPath.item] } return nil } func indexPath(for courseCode: String) -> IndexPath? { if let index = student.firstIndex(where: { $0.code == courseCode }) { return IndexPath(item: index, section: 0) } else if let index = teacher.firstIndex(where: { $0.code == courseCode }) { return IndexPath(item: index, section: 1) } return nil } }
true
a30a9354a21de46207f2419d552e5b22ab064de7
Swift
dnpp73/VanillaTextView
/ExampleApp/ViewController/FontListTableViewController.swift
UTF-8
9,548
2.578125
3
[ "MIT" ]
permissive
import UIKit import VanillaTextView final class FontListTableViewController: UITableViewController { private let sampleText: String = "Sample Plain Text. Apple gjpqy\nサンプルの平文のテキストです。\nSample で English と日本語を混ぜた行です。\n中華 Check 「底辺直卿蝕薩化」 gjpqy" private var fontLists: [String: [String]] = [:] private var isJapaneseFontOnly = true private var fontSize: CGFloat = 18.0 private var japaneseFontFallback: Bool = true private var fittingWidth: CGFloat = 300.0 private var lineSpacing: CGFloat = 0.0 private var minimumLineHeight: CGFloat = 0.0 private var maximumLineHeight: CGFloat = 0.0 private func reloadDataSource() { for fontFamilyName in UIFont.familyNames { fontLists[fontFamilyName] = UIFont.fontNames(forFamilyName: fontFamilyName).filter { if isJapaneseFontOnly { return UIFont(name: $0, size: 12.0)?.hasJapaneseGlyph ?? false } else { return true } } } } override func viewDidLoad() { super.viewDidLoad() // swiftlint:disable trailing_closure let fontFamilyNames = UIFont.familyNames let fontFamilyNamesCount = fontFamilyNames.count let fontNamesCount = UIFont.familyNames.compactMap({ UIFont.fontNames(forFamilyName: $0).count }).reduce(0, { $0 + $1 }) let japaneseFontNamesCount = UIFont.familyNames.compactMap({ familyName in UIFont.fontNames(forFamilyName: familyName).compactMap({ fontName in UIFont(name: fontName, size: 10.0) }).filter({ $0.hasJapaneseGlyph }).count }).reduce(0, { $0 + $1 }) // swiftlint:enable trailing_closure // family: 75, total: 248, jp: ? (on iOS 10.3.3) // family: 82, total: 263, jp: 30 (on iOS 11.4.1) // family: 83, total: 264, jp: 30 (on iOS 12.0) title = String(format: "family: %d, total: %d, jp: %d", fontFamilyNamesCount, fontNamesCount, japaneseFontNamesCount) reloadDataSource() tableView.reloadData() } @IBAction private func settingBarButtonDidPress(_ sender: UIBarButtonItem) { let actionSheet = UIAlertController(title: "Title", message: "Message", preferredStyle: .actionSheet) actionSheet.addAction(UIAlertAction(title: "Reset Default", style: .destructive) { (action: UIAlertAction) -> Void in self.isJapaneseFontOnly = true self.reloadDataSource() self.fontSize = 18.0 self.japaneseFontFallback = true self.fittingWidth = 300.0 self.lineSpacing = 0.0 self.minimumLineHeight = 0.0 self.maximumLineHeight = 0.0 self.tableView.reloadData() }) actionSheet.addAction(UIAlertAction(title: "Toggle Japanese Font Only (current: \(isJapaneseFontOnly))", style: .default) { (action: UIAlertAction) -> Void in self.isJapaneseFontOnly.toggle() self.reloadDataSource() self.tableView.reloadData() }) actionSheet.addAction(UIAlertAction(title: "Toggle Japanese font fallback (current: \(japaneseFontFallback))", style: .default) { (action: UIAlertAction) -> Void in self.japaneseFontFallback.toggle() self.tableView.reloadData() }) [9.0, 12.0, 18.0, 36.0].forEach { (f: CGFloat) -> Void in actionSheet.addAction(UIAlertAction(title: "fontSize to \(f) (current: \(fontSize))", style: .default) { (action: UIAlertAction) -> Void in self.fontSize = f self.tableView.reloadData() }) } [100.0, 300.0, 600.0].forEach { (w: CGFloat) -> Void in actionSheet.addAction(UIAlertAction(title: "fittingWidth to \(w) (current: \(fittingWidth))", style: .default) { (action: UIAlertAction) -> Void in self.fittingWidth = w self.tableView.reloadData() }) } [0.0, -0.5 * fontSize, fontSize, 2.0 * fontSize].forEach { (v: CGFloat) -> Void in actionSheet.addAction(UIAlertAction(title: "lineSpacing to \(v) (current: \(lineSpacing))", style: .default) { (action: UIAlertAction) -> Void in self.lineSpacing = v self.tableView.reloadData() }) actionSheet.addAction(UIAlertAction(title: "minimumLineHeight to \(v) (current: \(minimumLineHeight))", style: .default) { (action: UIAlertAction) -> Void in self.minimumLineHeight = v self.tableView.reloadData() }) actionSheet.addAction(UIAlertAction(title: "maximumLineHeight to \(v) (current: \(maximumLineHeight))", style: .default) { (action: UIAlertAction) -> Void in self.maximumLineHeight = v self.tableView.reloadData() }) } actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) present(actionSheet, animated: true, completion: nil) } @IBAction private func valueChangedRefreshControl(_ sender: UIRefreshControl) { DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { sender.endRefreshing() } tableView.reloadData() } override func numberOfSections(in tableView: UITableView) -> Int { return UIFont.familyNames.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let key = UIFont.familyNames[section] return fontLists[key]?.count ?? 0 } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { let familyName = UIFont.familyNames[section] let count = UIFont.fontNames(forFamilyName: familyName).count return "familyName: \"\(familyName)\", count: \(count)" } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let familyName = UIFont.familyNames[indexPath.section] let fontName = UIFont.fontNames(forFamilyName: familyName)[indexPath.row] let font = UIFont(name: fontName, size: fontSize) ?? UIFont.systemFont(ofSize: fontSize) let cell = tableView.dequeueReusableCell(withIdentifier: "FontPreviewCell", for: indexPath) cell.textLabel?.font = font cell.textLabel?.numberOfLines = 0 let shouldUseAttributedString: Bool = japaneseFontFallback || lineSpacing > 0.0 || minimumLineHeight > 0.0 || maximumLineHeight > 0.0 if shouldUseAttributedString { var attributes: [NSAttributedString.Key: Any] = [.font: font] if japaneseFontFallback { attributes[kCTLanguageAttributeName as NSAttributedString.Key] = "ja" } if lineSpacing > 0.0 || minimumLineHeight > 0.0 || maximumLineHeight > 0.0 { let p = NSMutableParagraphStyle() if lineSpacing > 0.0 { p.lineSpacing = lineSpacing } if minimumLineHeight > 0.0 { p.minimumLineHeight = minimumLineHeight } if maximumLineHeight > 0.0 { p.maximumLineHeight = maximumLineHeight } attributes[.paragraphStyle] = p } cell.textLabel?.text = nil cell.textLabel?.attributedText = NSAttributedString(string: sampleText, attributes: attributes) } else { cell.textLabel?.attributedText = nil cell.textLabel?.text = sampleText } let size: CGSize = cell.textLabel?.bounds.size ?? .zero let fitSize: CGSize = cell.textLabel?.sizeThatFits(CGSize(width: fittingWidth, height: 0.0)) ?? .zero let detailText = String( format: "Japanese Glyph Supported: \(font.hasJapaneseGlyph)\nfontName: \(fontName)\nsize: (w:%.2f, h:%.2f)\nsizeThatFits: (w:%.2f, h:%.2f)\nascender: %.1f, descender: %.1f, leading: %.1f\ncapHeight: %.1f, xHeight: %.1f, lineHeight: %.1f, point: %.1f", size.width, size.height, fitSize.width, fitSize.height, font.ascender, font.descender, font.leading, font.capHeight, font.xHeight, font.lineHeight, font.pointSize ) cell.detailTextLabel?.text = detailText cell.detailTextLabel?.numberOfLines = 0 return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let familyName = UIFont.familyNames[indexPath.section] let fontName = UIFont.fontNames(forFamilyName: familyName)[indexPath.row] let alert = UIAlertController(title: "Copy FontName?", message: "fontName: \(fontName)", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { (action: UIAlertAction) -> Void in tableView.deselectRow(at: indexPath, animated: true) }) alert.addAction(UIAlertAction(title: "Copy", style: .default) { (action: UIAlertAction) -> Void in UIPasteboard.general.string = fontName tableView.deselectRow(at: indexPath, animated: true) }) present(alert, animated: true, completion: nil) } override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { cell.textLabel?.backgroundColor = UIColor(red: 255.0 / 255, green: 126.0 / 255, blue: 121.0 / 255.0, alpha: 0.5) } }
true
6a14f33281904f1b71195c056c60821182bbead3
Swift
bernardinus/DotaHeroStats
/DotaHeroStats/DotaHeroStats/Networking.swift
UTF-8
2,076
2.734375
3
[]
no_license
// // Networking.swift // DotaHeroStats // // Created by Bernardinus on 29/04/21. // import Foundation class Networking { static let shared = Networking() static let baseUrl = "https://api.opendota.com" let apiUrl = "https://api.opendota.com/api/herostats" var roleArray:[String] = [] init() { } func loadHeroes(completion:@escaping (Bool, String, [Hero]) -> Void) { if(false) { } else { loadHeroFromAPI(completion: completion) } } func loadHeroFromAPI(completion: @escaping (Bool, String, [Hero]) -> Void) { request(reqURL: URL(string: apiUrl)!,completion: { (isSuccess, errorString, data) in if(isSuccess) { do { let decoded = try JSONDecoder().decode([Hero].self, from: data) completion(isSuccess, "", decoded) } catch let error as NSError { print("Failed to decode JSON " + error.debugDescription) completion(isSuccess,error.debugDescription, []) } } else { completion(isSuccess, errorString, []) } }) } func request(reqURL:URL, completion: @escaping (Bool, String, Data) -> Void) { let session = URLSession.init(configuration: .default) let dataTask = session.dataTask(with: URLRequest(url: reqURL)) { data, response, error -> Void in let httpResponse = response as! HTTPURLResponse if (httpResponse.statusCode == 200) { print("status code " + String(httpResponse.statusCode)) completion(true, "", data!) } else { completion(false, error.debugDescription, data!) } } dataTask.resume() } }
true
7e5235e337066e5ed507837f82465aba2480c4ee
Swift
axrs/cp3307-sp15-prac8
/SwiftCalc/ViewController.swift
UTF-8
3,882
3.25
3
[]
no_license
// // ViewController.swift // SwiftCalc // // Created by Alexander Scott on 14/04/2015. // Copyright (c) 2015 Alexander Scott. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var calculatorLabel: UILabel! @IBOutlet weak var operandLabel: UILabel! @IBOutlet weak var operationMethodLabel: UILabel! //variable for the calculator private var calc : Calculator = Calculator() //variable to track the number presses before equals private var operandSequence : String = "" override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. updateDisplay() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } private func updateDisplay(){ calculatorLabel.text = String(format:"%.8f", calc.value()) updateOperandDisplay() println("Updating Display") switch calc.operationType(){ case .Addition: operationMethodLabel.text = "➕" break case .Subtraction: operationMethodLabel.text = "➖" break case .Multiplication: operationMethodLabel.text = "✖️" break case .Division: operationMethodLabel.text = "➗" break } } private func updateOperandDisplay(){ //allows us to remove any forwarded padded zeros let trimmedValue = (operandSequence as NSString).doubleValue operandLabel.text = String(format: "%.8f", trimmedValue) } @IBAction func clearAction(sender: AnyObject) { self.calc.reset() operandSequence = "" updateDisplay() } @IBAction func symbolPressed(sender: UIButton) { let symbol = sender.titleLabel?.text ?? "" switch symbol{ case "➕": calc.setOperationType(Calculator.OperationType.Addition) break case "➖": calc.setOperationType(Calculator.OperationType.Subtraction) break case "✖️": calc.setOperationType(Calculator.OperationType.Multiplication) break case "➗": calc.setOperationType(Calculator.OperationType.Division) break default: break } if calc.value() == 0.0 && !operandSequence.isEmpty{ calc.setValue((operandSequence as NSString).doubleValue) operandSequence = "" } updateDisplay() } @IBAction func valuePressed(sender: UIButton) { //Get the button label let valueToAppend = sender.titleLabel?.text ?? "" var canAppend = false //if the value is a decimal, check for an already pressed one if (valueToAppend == "."){ var charSet = NSCharacterSet(charactersInString: "."); var range = (operandSequence as NSString).rangeOfCharacterFromSet(charSet); if range.location == NSNotFound{ canAppend = true } }else{ canAppend = true } println("\t Value pressed: \(valueToAppend). Appending: \(canAppend)") //append if possible to the end of the character sequence if canAppend{ operandSequence += valueToAppend updateOperandDisplay() } } @IBAction func apply(sender: AnyObject) { if !operandSequence.isEmpty{ self.calc.applyOperand((operandSequence as NSString).doubleValue) operandSequence = "" updateDisplay() } } }
true
78dcfdfb49cf2105319eda033fa1bd8f1a19d084
Swift
aytugsevgi/Exercism-Solutions
/difference-of-squares/Sources/DifferenceOfSquares/DifferenceOfSquares.swift
UTF-8
508
2.921875
3
[]
no_license
//Solution goes in Sources import Foundation class Squares { let number: Int var differenceOfSquares: Int { squareOfSum - sumOfSquares } var sumOfSquares: Int { var sum = 0 for i in 1...number { sum += i*i } return sum } var squareOfSum: Int { var sum = 0 for i in 1...number { sum += i } return sum*sum } init(_ number: Int) { self.number = number } }
true
68096eab126f6b57ab6caf6fef1c06fc1275019a
Swift
ozeraltun/RPI_IOS_BLE
/BleDeviceTrial/ViewController.swift
UTF-8
4,459
2.671875
3
[]
no_license
// // ViewController.swift // BleDeviceTrial // // Created by murat ersen unal on 18.12.2020. // import UIKit import CoreBluetooth class ViewController: UIViewController, CBCentralManagerDelegate, CBPeripheralDelegate { @IBOutlet weak var txtIn1: UITextField! @IBOutlet weak var txtIn2: UITextField! @IBOutlet weak var mylabel: UILabel! var centralManager: CBCentralManager! var myPeripheral: CBPeripheral! func centralManagerDidUpdateState(_ central: CBCentralManager) { if central.state == CBManagerState.poweredOn { print("BLE powered on") // Turned on central.scanForPeripherals(withServices: nil, options: nil) } else { print("Something wrong with BLE") // Not on, but can have different issues } } func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) { if let pname = peripheral.name { print(pname) /* İf ble peripheral has a name, then I can connect to the device if pname == "Nordic_HRM" { self.centralManager.stopScan() self.myPeripheral = peripheral self.myPeripheral.delegate = self self.centralManager.connect(peripheral, options: nil) } */ if pname == "OzerDeviceRPIBLE"{ print("Trying to connect OzerDevice") self.centralManager.stopScan() self.myPeripheral = peripheral self.myPeripheral.delegate = self self.centralManager.connect(peripheral, options: nil) } if pname == "raspberrypi"{ print("Trying to connect raspberry") self.centralManager.stopScan() self.myPeripheral = peripheral self.myPeripheral.delegate = self self.centralManager.connect(peripheral, options: nil) print("Connected OzerDevice") //myPeripheral.readValue(for: <#T##CBCharacteristic#>) } } } func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) { print("Central connected peripheral") self.myPeripheral.discoverServices(nil) } func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) { for newChar: CBCharacteristic in service.characteristics!{ peripheral.readValue(for: newChar) } }/* func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) { print("Reading Characteristics") if error != nil { print("ERROR DISCOVERING CHARACTERISTICS: \(error?.localizedDescription)") return } if let characteristics = service.characteristics { for characteristic in characteristics { print("--------------------------------------------") print("Characteristic UUID: \(characteristic.uuid)") print("Characteristic isNotifying: \(characteristic.isNotifying)") print("Characteristic properties: \(characteristic.properties)") print("Characteristic descriptors: \(characteristic.descriptors)") print("Characteristic value: \(characteristic.value)") } } } */ override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. centralManager = CBCentralManager(delegate: self, queue: nil) //Immediately calls centralManagerDidUpdateState } @IBAction func btn(_ sender: Any) { var firsttext = txtIn1.text ?? "0" var secondtext = txtIn2.text ?? "0" print("firstvalue is \(firsttext)") print("secondvalue is \(secondtext)") var toint1 = Int(firsttext) ?? 0 var toint2 = Int(secondtext) ?? 0 var avg = (toint1+toint2)/2 print("average value = \( avg )") if avg < 50{ mylabel.text = "KALDI" }else{ mylabel.text = "GECTI" } } }
true
278d93d037f1c7f89f0b480964b071fa0c3cb305
Swift
13bhavya/Todo_List
/Todo_List_B/InfoViewController.swift
UTF-8
1,343
2.578125
3
[]
no_license
// // InfoViewController.swift // Todo_List_B // // Created by Student on 2019-12-04. // Copyright © 2019 student. All rights reserved. // import UIKit import Firebase class InfoViewController: UIViewController { var ref: DatabaseReference! //var Title = [String]() //var descrip = [String]() //var ref: DatabaseReference! //var databaseHandle:DatabaseHandle! var taskId = "" var tasktitle = "" var taskdescrip = "" public var firstViewController:FirstViewController! @IBOutlet weak var titleLabel: UITextField! @IBOutlet weak var descField: UITextView! @IBAction func backBtn(_ sender: UIButton) { navigationController?.popViewController(animated: true) } @IBAction func updateBtn(_ sender: UIButton) { guard let key = ref.child("Tasks").child(taskId).key else { return } let task = ["task_description" : descField.text, "task_title" : titleLabel.text ] ref.child(key).updateChildValues(task) firstViewController.viewData() } override func viewDidLoad() { super.viewDidLoad() ref = Database.database().reference().child("Tasks") titleLabel.text = tasktitle descField.text = taskdescrip } }
true
a65c352374714d0d1f5344824bfae51d299b947c
Swift
skyrrt/passwordManager
/PasswordManager/Networking/GroupRequestsApiService.swift
UTF-8
2,328
2.703125
3
[]
no_license
// // GroupRequestsApiService.swift // PasswordManager // // Created by Bartek Rzyszkiewicz on 01/12/2020. // Copyright © 2020 Bartek Rzyszkiewicz. All rights reserved. // import Foundation import Firebase class GroupRequestsApiService { let urlSession = URLSession.shared let urlString = "http://192.168.1.7:8080/requests" let encoder = JSONEncoder() let decoder = JSONDecoder() func sendRequest(requestDto: GroupRequestDto) { let url = URL(string: urlString)! var request = URLRequest(url: url) request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") let json = try? encoder.encode(requestDto) let task = urlSession.uploadTask(with: request, from: json) { data, response, error in guard let responseData = data, error == nil else { print("REST ERRROR GROUP REQUEST") return } if let jsonResponse = try? self.decoder.decode(GroupRequestDto.self, from: responseData) { print(jsonResponse) } } task.resume() } func fetchRequests(completion: @escaping ([GroupRequestDetails]) -> Void) { let url = URL(string: urlString + "?userUid=\(Auth.auth().currentUser!.uid)")! let task = urlSession.dataTask(with: url) { data, response, error in guard let resData = data, error == nil else { print("REST ERROR GROUPS FETCH") return } if let jsonResponse = try? self.decoder.decode([GroupRequestDetails].self, from: resData) { completion(jsonResponse) } } task.resume() } func answerRequest(requestId: String, answer: Bool, completion: @escaping () -> Void) { let url = URL(string: urlString + "?requestId=\(requestId)&accepted=\(answer)")! var request = URLRequest(url: url) request.httpMethod = "PATCH" let task = urlSession.dataTask(with: request) { data, response, error in guard data != nil, error == nil else { print("answer request error") return } completion() } task.resume() } }
true
36a5ae7152027c11d59c839d34b52cfb4f30e98a
Swift
peter0bassem/App-Store
/App Store/Views/Today/TodayCollectionViewCell.swift
UTF-8
2,432
2.765625
3
[]
no_license
// // TodayCollectionViewCell.swift // App Store // // Created by Peter Bassem on 7/26/20. // Copyright © 2020 Peter Bassem. All rights reserved. // import UIKit class TodayCollectionViewCell: BaseTodayCollectionViewCell { static let identifier = "TodayCollectionViewCell" private lazy var categoryLabel: UILabel = UILabel(text: "LIFE HACK", font: .systemFont(ofSize: 20, weight: .bold)) private lazy var titleLabel: UILabel = UILabel(text: "Utilizing your Time", font: .systemFont(ofSize: 28, weight: .bold)) private lazy var imageView: UIImageView = UIImageView(image: #imageLiteral(resourceName: "garden")) private lazy var descriptionLabel: UILabel = UILabel(text: "All the tools and apps you need to intelligently organize your life the right way.", font: .systemFont(ofSize: 16), numberOfLines: 3) override var item: TodayItem! { didSet { categoryLabel.text = item.category titleLabel.text = item.title imageView.image = item.image descriptionLabel.text = item.description backgroundColor = item.backgroundColor backgroundView?.backgroundColor = item.backgroundColor } } var topConstraint: NSLayoutConstraint! override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .white layer.cornerRadius = 16 imageView.contentMode = .scaleAspectFill imageView.clipsToBounds = true let imageContainerView = UIView() imageContainerView.addSubview(imageView) imageView.centerInSuperview(size: .init(width: 240, height: 240)) let stackView = VerticalStackView(arrangedSubviews: [ categoryLabel, titleLabel, imageContainerView, descriptionLabel ], spacing: 8) addSubview(stackView) stackView.anchor(top: nil, leading: leadingAnchor, bottom: bottomAnchor, trailing: trailingAnchor, padding: .init(top: 0, left: 24, bottom: 24, right: 24)) self.topConstraint = stackView.topAnchor.constraint(equalTo: topAnchor, constant: 24) self.topConstraint?.isActive = true // stackView.fillSuperview(padding: .init(top: 24, left: 24, bottom: 24, right: 24)) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
true
9c4f50d15adc868b64963278206716b6b8eb8fee
Swift
hongCJ/analyzer
/MVTimeAnalyzer/Classes/Proxy.swift
UTF-8
2,973
2.96875
3
[ "MIT" ]
permissive
// // Proxy.swift // MVTimeAnalyzer // // Created by mac on 2021/1/19. // import UIKit protocol ProxyDelegate: NSObjectProtocol { func proxyViewClickAtIndex(indexPath: IndexPath, _ view: UIView) func proxyViewShowFor(view: UIView) func proxyViewClickAtLocation(location: CGPoint, _ view: UIView) } extension UIView { var viewProxy: ViewProxy { if let collection = self as? UICollectionView { return CollectionDelegateProxy(view: collection) } if let table = self as? UITableView { return TableDelegateProxy(view: table) } if let scrollView = self as? UIScrollView { return ScrollViewProxy(view: scrollView) } fatalError() } } class ViewProxy: NSObject { weak var proxyDelegate: ProxyDelegate? init(view: UIView) { super.init() if let scrollView = view as? UIScrollView { bindGesture(view: scrollView) bindOffSet(view: scrollView) } else { fatalError() } } var contentOffSet: NSKeyValueObservation? func bindGesture(view: UIView) { let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTapGesture(gesture:))) tapGesture.cancelsTouchesInView = false view.addGestureRecognizer(tapGesture) } func bindOffSet(view: UIScrollView) { contentOffSet = view.observe(\UIScrollView.contentOffset, options: .new, changeHandler: { (scrollView, value) in if scrollView.isDragging { return } self.proxyDelegate?.proxyViewShowFor(view: scrollView) }) } @objc func handleTapGesture(gesture: UITapGestureRecognizer) {} } class ScrollViewProxy: ViewProxy { override func handleTapGesture(gesture: UITapGestureRecognizer) { guard let scrollView = gesture.view as? UIScrollView else { return } self.proxyDelegate?.proxyViewClickAtLocation(location: gesture.location(in: scrollView), scrollView) } } class CollectionDelegateProxy: ViewProxy { override func handleTapGesture(gesture: UITapGestureRecognizer) { guard let collectionView = gesture.view as? UICollectionView else { return } guard let indexPath = collectionView.indexPathForItem(at: gesture.location(in: collectionView)) else { return } self.proxyDelegate?.proxyViewClickAtIndex(indexPath: indexPath, collectionView) } } class TableDelegateProxy: ViewProxy { override func handleTapGesture(gesture: UITapGestureRecognizer) { guard let tableView = gesture.view as? UITableView else { return } guard let indexPath = tableView.indexPathForRow(at: gesture.location(in: tableView)) else { return } self.proxyDelegate?.proxyViewClickAtIndex(indexPath: indexPath, tableView) } }
true
73b0ba9a76970744bb392ff48b894537e028c6c0
Swift
mohsinalimat/Hadith
/Hadith/SearchFooterView.swift
UTF-8
859
2.609375
3
[ "MIT" ]
permissive
// // SearchFooterView.swift // Hadith // // Created by Majid Khan on 19/06/2016. // Copyright © 2016 Muflihun.com. All rights reserved. // import Foundation import UIKit @objc protocol SearchFooterDelegate : NSObjectProtocol { func nextPage() func prevPage() func firstPage() } class SearchFooterView : UIView { weak var delegate : SearchFooterDelegate? @IBOutlet weak var firstPageButton : UIBarButtonItem! @IBOutlet weak var nextPageButton : UIBarButtonItem! @IBOutlet weak var prevPageButton : UIBarButtonItem! @IBAction func changePage(sender:UIBarButtonItem!) { if sender == nextPageButton { delegate?.nextPage() } else if sender == prevPageButton { delegate?.prevPage() } else if sender == firstPageButton { delegate?.firstPage() } } }
true
27e4b6eaa91cc13ce4f149a93404d727d9c4f89c
Swift
hirothings/FireTodo
/FireTodo/Views/SignUp/SignUpView.swift
UTF-8
1,912
2.890625
3
[ "MIT" ]
permissive
// // Copyright © Suguru Kishimoto. All rights reserved. // import SwiftUI struct SignUpView: View { @EnvironmentObject private var store: AppStore @State private var name: String = "" private var canRegister: Bool { name.count >= 3 && name.count <= 16 } var body: some View { GeometryReader { geometry in ZStack { VStack(alignment: .center) { Text("Fire Todo") .font(.title) .padding(.top, geometry.size.height / 4) .padding(.bottom, 44.0) VStack { TextField("Enter your name...", text: self.$name.animation()) Color.primary.frame(height: 1.0) } .padding() Button(action: { self.store.dispatch(SignUpAction.signUp(with: self.name)) }) { Text("Sign Up") .foregroundColor(.primary) .fontWeight(.bold) .padding(.init(top: 8.0, leading: 32.0, bottom: 8.0, trailing: 32.0)) .overlay( Capsule(style: .continuous) .stroke(self.canRegister ? Color.primary : Color.gray, lineWidth: 2.0) ) } .opacity(self.canRegister ? 1.0 : 0.5) .disabled(!self.canRegister) Spacer() } LoadingView(isLoading: self.store.state.signUpState.requesting) } } } } #if DEBUG struct SignUpView_Previews: PreviewProvider { static var previews: some View { SignUpView().environmentObject(AppMain().store) } } #endif
true
2c4ac59ead73ae2b131df7933c69b8690cc93ed1
Swift
xiangyu-sun/Gnilwob
/Bowlingure/Classes/Scorer.swift
UTF-8
1,239
3.046875
3
[ "MIT" ]
permissive
// // Scorer.swift // Bowlingure // // Created by 孙翔宇 on 4/17/19. // Copyright © 2019 孙翔宇. All rights reserved. // import Foundation public struct Scorer { private(set) var game: Game public var frameNumber: String { return String(describing: game.nextBallFrameNumber) } public var gameIsOver: Bool { return game.isGameover } public var scoreSoFar: String { return String(describing: game.frames.mapToScores.sum()) } public init() { self.game = Game() } @discardableResult public mutating func rolledWith(pinsKnockedDown: UInt) -> [UInt] { if gameIsOver { game = Game() } game.rolledWith(pinsKnockedDown: pinsKnockedDown) return cuculativeScores(frames: game.completelyScoredFames) } @discardableResult public mutating func rolledWith(pinsKnockedDownSequence: [UInt]) -> [UInt] { return pinsKnockedDownSequence.compactMap { self.rolledWith(pinsKnockedDown: $0) }.last ?? [] } private func cuculativeScores(frames: [Frame]) -> [UInt] { return frames.enumerated().map { frames[...$0.0].mapToScores.sum()} } }
true
439849774fde1595e3da3528a3cba6959fc80bcb
Swift
DimensionDev/Mailway-iOS
/CoreDataStack/Entity/Keypair.swift
UTF-8
1,781
2.78125
3
[]
no_license
// // Keypair.swift // Mailway // // Created by Cirno MainasuK on 2020-6-10. // Copyright © 2020 Dimension. All rights reserved. // import Foundation import CoreData final public class Keypair: NSManagedObject { @NSManaged public private(set) var id: UUID @NSManaged public private(set) var privateKey: String? @NSManaged public private(set) var publicKey: String @NSManaged public private(set) var keyID: String @NSManaged public private(set) var createdAt: Date @NSManaged public private(set) var updatedAt: Date // many-to-one relationship @NSManaged public private(set) var contact: Contact } extension Keypair { public override func awakeFromInsert() { super.awakeFromInsert() id = UUID() let now = Date() createdAt = now updatedAt = now } @discardableResult public static func insert(into context: NSManagedObjectContext, property: Property) -> Keypair { let keypair: Keypair = context.insertObject() keypair.privateKey = property.privateKey keypair.publicKey = property.publicKey keypair.keyID = property.keyID return keypair } } extension Keypair { public struct Property { public let privateKey: String? public let publicKey: String public let keyID: String public init(privateKey: String?, publicKey: String, keyID: String) { self.privateKey = privateKey self.publicKey = publicKey self.keyID = keyID } } } extension Keypair: Managed { public static var defaultSortDescriptors: [NSSortDescriptor] { return [NSSortDescriptor(keyPath: \Keypair.createdAt, ascending: true)] } }
true
79fcf46e86b92a2b71b722adb0f5b423906f1c3c
Swift
jihyundev/AutoLayout-Programmatically
/AutolayoutPractice/AutolayoutPractice/ViewController.swift
UTF-8
4,938
2.8125
3
[]
no_license
// // ViewController.swift // AutolayoutPractice // // Created by 정지현 on 2021/05/01. // import UIKit class ViewController: UIViewController { // make view with closure var myView: UIView = { let view = UIView() view.backgroundColor = #colorLiteral(red: 0.721568644, green: 0.8862745166, blue: 0.5921568871, alpha: 1) view.layer.cornerRadius = 30 view.clipsToBounds = true view.translatesAutoresizingMaskIntoConstraints = false return view }() var myImageView: UIImageView = { let imageView = UIImageView() imageView.image = UIImage(named: "app_icon") imageView.translatesAutoresizingMaskIntoConstraints = false return imageView }() var myLabel: UILabel = { let label = UILabel() label.text = "Go Get Rocket" label.font = UIFont.systemFont(ofSize: 15) label.textAlignment = .center label.textColor = .systemBlue label.translatesAutoresizingMaskIntoConstraints = false return label }() var myButton: UIButton = { let button = UIButton() button.setTitle("Go Get Rocket", for: .normal) button.setTitleColor(.white, for: .normal) button.backgroundColor = .darkGray button.layer.cornerRadius = 5 button.translatesAutoresizingMaskIntoConstraints = false button.addTarget(self, action: #selector(gotoRocketVC), for: .touchUpInside) return button }() @objc func gotoRocketVC() { let vc = RocketViewController() vc.modalPresentationStyle = .fullScreen self.present(vc, animated: true, completion: nil) } var myButton2: UIButton = { let button = UIButton() button.setTitle("Go To Animation", for: .normal) button.setTitleColor(.white, for: .normal) button.backgroundColor = #colorLiteral(red: 0.9607843161, green: 0.7058823705, blue: 0.200000003, alpha: 1) button.layer.cornerRadius = 5 button.translatesAutoresizingMaskIntoConstraints = false button.addTarget(self, action: #selector(goToAnimationVC), for: .touchUpInside) return button }() @objc func goToAnimationVC() { let vc = AnimationViewController() vc.modalPresentationStyle = .fullScreen self.present(vc, animated: true, completion: nil) } override func viewDidLoad() { super.viewDidLoad() self.view.addSubview(myView) // position of x, y, width, height myView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 50).isActive = true myView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -50).isActive = true //myView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true myView.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 100).isActive = true //myView.widthAnchor.constraint(equalToConstant: 200).isActive = true myView.heightAnchor.constraint(equalToConstant: 200).isActive = true self.view.addSubview(myImageView) myImageView.widthAnchor.constraint(equalToConstant: 100).isActive = true myImageView.heightAnchor.constraint(equalToConstant: 100).isActive = true myImageView.leadingAnchor.constraint(equalTo: myView.leadingAnchor, constant: 10).isActive = true myImageView.topAnchor.constraint(equalTo: myView.bottomAnchor, constant: 20).isActive = true self.view.addSubview(myLabel) NSLayoutConstraint.activate([ myLabel.leadingAnchor.constraint(equalTo: myImageView.trailingAnchor, constant: 20), myLabel.topAnchor.constraint(equalTo: myView.bottomAnchor, constant: 20) ]) self.view.addSubview(myButton) NSLayoutConstraint.activate([ myButton.leadingAnchor.constraint(equalTo: myImageView.trailingAnchor, constant: 20), myButton.topAnchor.constraint(equalTo: myLabel.bottomAnchor, constant: 10) ]) self.view.addSubview(myButton2) NSLayoutConstraint.activate([ myButton2.leadingAnchor.constraint(equalTo: myImageView.trailingAnchor, constant: 20), myButton2.topAnchor.constraint(equalTo: myButton.bottomAnchor, constant: 20) ]) } } #if DEBUG import SwiftUI struct ViewControllerRepresentable: UIViewControllerRepresentable { // update func updateUIViewController(_ uiViewController: UIViewController, context: Context) { } // make ui @available(iOS 13.0, *) func makeUIViewController(context: Context) -> UIViewController { ViewController() } } struct ViewController_Previews: PreviewProvider { static var previews: some View { ViewControllerRepresentable() .previewDisplayName("아이폰") } } #endif
true
2ce0e6a114d33942fa306e43409b6cca8ad8cd70
Swift
lilencet0/MOB-DC-01
/Homework/Week 2/Lesson02/SecondViewController.swift
UTF-8
673
2.953125
3
[]
no_license
// // SecondViewController.swift // Lesson02 // // Created by Rudd Taylor on 9/28/14. // Copyright (c) 2014 General Assembly. All rights reserved. // import UIKit class SecondViewController: UIViewController { @IBOutlet weak var textField: UITextField! @IBOutlet weak var sumLabel: UILabel! @IBAction func addButton(sender: AnyObject) { var sum = 0 let number = textField.text.toInt() sum += number! sumLabel.text = "\(sum)" } //TODO five: Display the cumulative sum of all numbers added every time the ‘add’ button is pressed. Hook up the label, text box and button to make this work. }
true
25e8ef6d9baa007b520e6b30974acc9b9fb96d05
Swift
cdescours-7C/lux
/Sources/Lux/Injection/AttributedInjector.swift
UTF-8
609
3.125
3
[ "MIT" ]
permissive
import Foundation /// Injector that can be used to output attributed strings public protocol AttributedInjector { /// Set of language identifier strings used in css and html files code blocks /// - Note: Add strings to this set to match new identifiers not already present in it var languageIdentifiers: Set<String> { get set } #if !os(Linux) /// Color of the background to be used with the Injector var backgroundColor: Color { get } #endif func inject(in text: String) -> AttributedString } extension BaseInjector: AttributedInjector where Output == AttributedString {}
true
7a40d55a7eee4e12cabea5bd3fef64ae977792f7
Swift
Ella-Han/MyAppStore
/MyAppStore/MyAppStore/Utility/Extension/UIImageView+Extension.swift
UTF-8
1,316
2.9375
3
[]
no_license
// // UIImageView+Extension.swift // MyAppStore // // Created by 한아름 on 2021/03/21. // import Foundation import UIKit import RxSwift extension UIImageView { func setImage(urlString: String, placeholder: UIImage? = nil, bag: DisposeBag) { guard let url = URL(string: urlString) else { return } image = placeholder // From Memory if let cacheImage = AppStoreManager.imageFromCache(url: url) { LogI("Image From Memory!!") image = cacheImage sizeToFit() return } // From Disk if let diskImage = AppStoreManager.imageFromDisk(url: url) { LogI("Image From Disk!!") AppStoreManager.saveToCache(url: url, image: diskImage) image = diskImage sizeToFit() return } // Download AppStoreManager.requestDownloadImage(url: url) .observe(on: MainScheduler.instance) .subscribe { [weak self] (image: UIImage?) in LogI("Image From Server!!") self?.image = image self?.sizeToFit() } onFailure: { (error: Error) in } onDisposed: { }.disposed(by: bag) } }
true
8725ce7235357450bde13df4753caf9ab9180820
Swift
hyemi777/Week-Twelve
/week12/Shared/ContentView.swift
UTF-8
1,650
2.734375
3
[]
no_license
// // ContentView.swift // Shared // // Created by Hyemi Byun on 4/7/21. // import SwiftUI struct ContentView: View { var body: some View { NavigationView(){ Image("background") .resizable() .scaledToFill() .edgesIgnoringSafeArea(.all) .overlay( VStack(alignment: .center){ Text("Week 12 Lists") .font(Font.custom("Zapfino", size: 30)) StitchStyles() modalView() } ) } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } struct homeButtons: ButtonStyle { func makeBody(configuration: Self.Configuration) -> some View { configuration.label .padding() .frame(maxWidth: .infinity) .border(Color.black) .padding() } } struct StitchStyles: View { var body: some View { NavigationLink(destination: week12.listStyle()){ Text("Stitch Styles") .font(Font.custom("Times New Roman", size: 30)) .padding() .foregroundColor(.black) } .buttonStyle(homeButtons()) } } struct modalView: View { var body: some View { NavigationLink(destination: secondList()){ Text("Candidates") .font(Font.custom("Times New Roman", size: 30)) .padding() .foregroundColor(.black) } .buttonStyle(homeButtons()) } }
true
19df1e9401056834fd25649587cdaeb4f57d539a
Swift
haiphan5289/vatoclient
/Vato/App/Migration/MigrationLocationHistory.swift
UTF-8
3,762
2.515625
3
[]
no_license
// File name : MigrationLocationHistory.swift // // Author : Vato // Created date: 10/3/18 // Version : 1.00 // -------------------------------------------------------------- // Copyright © 2018 Vato. All rights reserved. // -------------------------------------------------------------- import FirebaseAuth import FirebaseDatabase import Foundation import FwiCore import RealmSwift final class MigrationLocationHistory { /// Class's public properties. /// Class's constructors. init(database: DatabaseReference) { self.database = database } /// Class's private properties. private let database: DatabaseReference } // MARK: Class's public methods extension MigrationLocationHistory { func execute() { guard let firebaseID = Auth.auth().currentUser?.uid else { return } let node = FireBaseTable.favoritePlace >>> .custom(identify: firebaseID) _ = database.find(by: node, type: .value) { $0.keepSynced(true) return $0 } .take(1) .subscribe(onNext: { snapshot in guard let dictionary = snapshot.value as? [String: [String: Any]] else { return } // Sorted list var list = dictionary.compactMap { try? $1.toData() }.compactMap { try? AddressHistory.toModel(from: $0, block: { $0.dateDecodingStrategy = .customDateFireBase }) } .sorted(by: { (item1, item2) -> Bool in if item1.name != item2.name { return item1.name < item2.name } else { return item1.timestamp > item2.timestamp } }) var results: [String: AddressHistory] = [:] list.forEach({ item in if var record = results[item.name] { record.count += (item.count + 1) } else { if item.count <= 0 { var newItem = item newItem.count = 1 results[item.name] = newItem } else { results[item.name] = item } } }) // Filtered list, we only accept any marker which has counter greater than or equal 5 list = results.compactMap { $0.value }.filter { $0.count > 5 } guard list.count > 0, let realm = try? Realm() else { return } try? realm.write { list.forEach { let markerHistory = MarkerHistory() markerHistory.lastUsedTime = $0.timestamp markerHistory.counter = $0.count markerHistory.lat = $0.location.lat markerHistory.lng = $0.location.lon markerHistory.isOrigin = false markerHistory.isVerifiedV2 = false markerHistory.name = $0.name markerHistory.lines.append($0.address) realm.add(markerHistory) } let appState = realm.object(ofType: AppState.self, forPrimaryKey: 1) appState?.isMigratedToV530 = true } }, onDisposed: { // FwiLog.debug("Event had been disposed.") }) } } // MARK: Class's private methods private extension MigrationLocationHistory {} fileprivate struct AddressHistory: Decodable { let name: String let address: String var count: Int let timestamp: Date let location: Location } fileprivate struct Location: Decodable { let lat: Double let lon: Double }
true