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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
c490d305b3bab6b5f8f18e5eef1a2aec6b1004e0
|
Swift
|
DamienBitrise/wwdc2020-fruta
|
/Shared/FrutaApp.swift
|
UTF-8
| 2,184
| 2.53125
| 3
|
[] |
no_license
|
/*
See LICENSE folder for this sample’s licensing information.
Abstract:
The single entry point for the Fruta app on all platforms.
*/
import SwiftUI
#if APPCLIP
import AppClip
import CoreLocation
#endif
@main
struct FrutaApp: App {
@StateObject private var model = FrutaModel()
#if !APPCLIP
@StateObject private var store = Store()
#endif
@SceneBuilder var body: some Scene {
WindowGroup {
#if APPCLIP
NavigationView {
SmoothieMenu()
}
.environmentObject(model)
.onContinueUserActivity(NSUserActivityTypeBrowsingWeb, perform: handleUserActivity)
#else
ContentView()
.environmentObject(model)
.environmentObject(store)
#endif
}
}
#if APPCLIP
func handleUserActivity(_ userActivity: NSUserActivity) {
guard let incomingURL = userActivity.webpageURL,
let components = NSURLComponents(url: incomingURL, resolvingAgainstBaseURL: true),
let queryItems = components.queryItems else {
return
}
if let smoothieID = queryItems.first(where: { $0.name == "smoothie" })?.value {
model.selectSmoothie(id: smoothieID)
}
guard let payload = userActivity.appClipActivationPayload,
let latitudeValue = queryItems.first(where: { $0.name == "latitude" })?.value,
let longitudeValue = queryItems.first(where: { $0.name == "longitude" })?.value,
let latitude = Double(latitudeValue), let longitude = Double(longitudeValue) else {
return
}
let region = CLCircularRegion(center: CLLocationCoordinate2D(latitude: latitude,
longitude: longitude), radius: 100, identifier: "smoothie_location")
payload.confirmAcquired(in: region) { inRegion, error in
if let error = error {
print(error.localizedDescription)
return
}
DispatchQueue.main.async {
model.applePayAllowed = inRegion
}
}
}
#endif
}
| true
|
44d24a37d434ceb3fad2f8e498351792709d58e0
|
Swift
|
anishmunirathinam/Graph
|
/Graph.playground/Contents.swift
|
UTF-8
| 5,069
| 3.671875
| 4
|
[] |
no_license
|
import Foundation
enum EdgeType {
case directed
case undirected
}
protocol Graph {
associatedtype Element
func createVertex(data: Element) -> Vertex<Element>
func addDirectedEdge(from source: Vertex<Element>, to destination: Vertex<Element>, weight: Double?)
func addUndirectedEdge(between source: Vertex<Element>, and destination: Vertex<Element>, weight: Double?)
func add(_ edge: EdgeType, from source: Vertex<Element>, to destination: Vertex<Element>, weight: Double?)
func edges(from source: Vertex<Element>) -> [Edge<Element>]
func weight(from source: Vertex<Element>, to destination: Vertex<Element>) -> Double?
}
// Graph Implementation - Adjacency List: Each vertex stores the set of outgoing vertex
class AdjacencyList<T: Hashable>: Graph {
var adjacencies: [Vertex<T>: [Edge<T>]] = [:]
init() {
}
typealias Element = T
func createVertex(data: T) -> Vertex<T> {
let vertex = Vertex(index: adjacencies.count, data: data)
adjacencies[vertex] = []
return vertex
}
func addDirectedEdge(from source: Vertex<T>, to destination: Vertex<T>, weight: Double?) {
let edge = Edge(source: source, destination: destination, weight: weight)
adjacencies[source]?.append(edge)
}
func edges(from source: Vertex<T>) -> [Edge<T>] {
adjacencies[source] ?? []
}
func weight(from source: Vertex<T>, to destination: Vertex<T>) -> Double? {
edges(from: source).first {
$0.destination == destination
}?.weight
}
}
extension Graph {
func addUndirectedEdge(between source: Vertex<Element>, and destination: Vertex<Element>, weight: Double?) {
addDirectedEdge(from: source, to: destination, weight: weight)
addDirectedEdge(from: destination, to: source, weight: weight)
}
func add(_ edge: EdgeType, from source: Vertex<Element>, to destination: Vertex<Element>, weight: Double?) {
switch edge {
case .directed:
addDirectedEdge(from: source, to: destination, weight: weight)
case .undirected:
addUndirectedEdge(between: source, and: destination, weight: weight)
}
}
}
extension AdjacencyList: CustomStringConvertible {
var description: String {
var result = ""
for (vertex, edges) in adjacencies {
var edgesString = ""
for (index, edge) in edges.enumerated() {
if index != edges.count - 1 {
edgesString.append("\(edge.destination), ")
} else {
edgesString.append("\(edge.destination)")
}
}
result.append("\(vertex) ---> [\(edgesString)]\n")
}
return result
}
}
let graph = AdjacencyList<String>()
let singapore = graph.createVertex(data: "singapore")
let tokyo = graph.createVertex(data: "tokyo")
let hongKong = graph.createVertex(data: "hong kong")
let detroit = graph.createVertex(data: "detroit")
let sanFrancisco = graph.createVertex(data: "san francisco")
let washington = graph.createVertex(data: "washington")
let seattle = graph.createVertex(data: "seattle")
graph.add(.undirected, from: singapore, to: hongKong, weight: 300)
graph.add(.undirected, from: singapore, to: tokyo, weight: 500)
graph.add(.undirected, from: hongKong, to: washington, weight: 750)
graph.add(.undirected, from: tokyo, to: seattle, weight: 450)
graph.add(.undirected, from: seattle, to: detroit, weight: 100)
graph.add(.undirected, from: washington, to: sanFrancisco, weight: 150)
print(graph)
print("Outgoing flights from singapore")
for edge in graph.edges(from: singapore) {
if let cost = graph.weight(from: edge.source, to: edge.destination) {
print("from: \(edge.source.data) to: \(edge.destination.data), cost: $\(cost)")
}
}
// Adjacency Matrix
class AdjacencyMatrix<T>: Graph {
typealias Element = T
var vertices: [Vertex<T>] = []
var weights: [[Double?]] = []
init() {
}
func createVertex(data: T) -> Vertex<T> {
let vertex = Vertex(index: vertices.count, data: data)
vertices.append(vertex)
for i in 0..<weights.count {
weights[i].append(nil)
}
let row = [Double?].init(repeating: nil, count: vertices.count)
weights.append(row)
return vertex
}
func addDirectedEdge(from source: Vertex<T>, to destination: Vertex<T>, weight: Double?) {
weights[source.index][destination.index] = weight
}
func edges(from source: Vertex<T>) -> [Edge<T>] {
var edges: [Edge<T>] = []
for column in 0..<weights.count {
if let weight = weights[source.index][column] {
edges.append(Edge(source: source, destination: vertices[column], weight: weight))
}
}
return edges
}
func weight(from source: Vertex<T>, to destination: Vertex<T>) -> Double? {
weights[source.index][destination.index]
}
}
| true
|
7d936b48dd7ee499f91a85c2bf10db75af9ec68c
|
Swift
|
assoftssoft/CodesLap
|
/CodeLapTaskOne/TaskViewController.swift
|
UTF-8
| 1,483
| 2.53125
| 3
|
[] |
no_license
|
//
// TaskViewController.swift
// CodeLapTaskOne
//
// Created by Ahmed Baloch on 10/06/2021.
//
import UIKit
class TaskViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func didSelectOnIntergerToRoman(_ sender: Any) {
let storyboard = UIStoryboard.init(name: "Main", bundle: .main)
let IntToRomanViewController = storyboard.instantiateViewController(withIdentifier: "IntergerToRomanViewController") as! IntergerToRomanViewController
self.navigationController?.pushViewController(IntToRomanViewController, animated: true)
}
@IBAction func didSelectOnNewApi(_ sender: Any) {
let storyboard = UIStoryboard.init(name: "Main", bundle: .main)
let newApiControllerViewController = storyboard.instantiateViewController(withIdentifier: "NewApiControllerViewController") as! NewApiControllerViewController
self.navigationController?.pushViewController(newApiControllerViewController, animated: true)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
| true
|
1e423a953c4ac56177299258167f90153ef491be
|
Swift
|
taoyuxuan/algorithm009-class02
|
/Week_01/DesignCircularDeque.playground/Contents.swift
|
UTF-8
| 4,416
| 4.3125
| 4
|
[] |
no_license
|
import UIKit
//641. 设计循环双端队列
//设计实现双端队列。
//你的实现需要支持以下操作:
//
//MyCircularDeque(k):构造函数,双端队列的大小为k。
//insertFront():将一个元素添加到双端队列头部。 如果操作成功返回 true。
//insertLast():将一个元素添加到双端队列尾部。如果操作成功返回 true。
//deleteFront():从双端队列头部删除一个元素。 如果操作成功返回 true。
//deleteLast():从双端队列尾部删除一个元素。如果操作成功返回 true。
//getFront():从双端队列头部获得一个元素。如果双端队列为空,返回 -1。
//getRear():获得双端队列的最后一个元素。 如果双端队列为空,返回 -1。
//isEmpty():检查双端队列是否为空。
//isFull():检查双端队列是否满了。
//
//示例:
//MyCircularDeque circularDeque = new MycircularDeque(3); // 设置容量大小为3
//circularDeque.insertLast(1); // 返回 true
//circularDeque.insertLast(2); // 返回 true
//circularDeque.insertFront(3); // 返回 true
//circularDeque.insertFront(4); // 已经满了,返回 false
//circularDeque.getRear(); // 返回 2
//circularDeque.isFull(); // 返回 true
//circularDeque.deleteLast(); // 返回 true
//circularDeque.insertFront(4); // 返回 true
//circularDeque.getFront(); // 返回 4
// ***************************** 实现 ****************************** //
/// 提交时采用的是当前个数判断队空 队满问题;
/// 现在用空一个位置来判断队空队满;
class MyCircularDeque {
var elements:[Int] = []
var capacity: Int = 0
var front: Int = 0
var rear: Int = 0
/** Initialize your data structure here. Set the size of the deque to be k. */
init(_ k: Int) {
elements = Array.init(repeating: 0, count: k+1)
capacity = k + 1
front = 0
rear = 0
}
/** Adds an item at the front of Deque. Return true if the operation is successful. */
func insertFront(_ value: Int) -> Bool {
if isFull() {
return false
}
let nextFront = (front - 1 + capacity)%capacity
elements[nextFront] = value
front = nextFront
return true
}
/** Adds an item at the rear of Deque. Return true if the operation is successful. */
func insertLast(_ value: Int) -> Bool {
if isFull() {
return false
}
elements[rear] = value
rear = (rear + 1)%capacity
return true
}
/** Deletes an item from the front of Deque. Return true if the operation is successful. */
func deleteFront() -> Bool {
if isEmpty() {
return false
}
elements[front] = 0
front = (front + 1)%capacity
return true
}
/** Deletes an item from the rear of Deque. Return true if the operation is successful. */
func deleteLast() -> Bool {
if isEmpty() {
return false
}
rear = (rear - 1 + capacity) % capacity
elements[rear] = 0
return true
}
/** Get the front item from the deque. */
func getFront() -> Int {
if isEmpty() {
return -1
}
return elements[front]
}
/** Get the last item from the deque. */
func getRear() -> Int {
if isEmpty() {
return -1
}
return elements[(rear - 1 + capacity) % capacity]
}
/** Checks whether the circular deque is empty or not. */
func isEmpty() -> Bool {
return front == rear // 相等即为空
}
/** Checks whether the circular deque is full or not. */
func isFull() -> Bool {
return (rear + 1) % capacity == front
}
}
let obj = MyCircularDeque(3)
let ret_1: Bool = obj.insertLast(1)
let ret_2: Bool = obj.insertLast(2)
let ret_3: Bool = obj.insertFront(3)
let ret_4: Bool = obj.insertFront(4)
let ret_5: Int = obj.getRear()
let ret_6: Bool = obj.isFull()
let ret_7: Bool = obj.deleteLast()
let ret_8: Bool = obj.insertFront(4)
let ret_9: Int = obj.getFront()
print(ret_1)
print(ret_2)
print(ret_3)
print(ret_4)
print(ret_5)
print(ret_6)
print(ret_7)
print(ret_8)
print(ret_9)
| true
|
5cff7389285036566ceec54d288cc6c109db935a
|
Swift
|
mosaic6/DailyCommute
|
/DailyCommute/utils/Router.swift
|
UTF-8
| 2,323
| 2.75
| 3
|
[] |
no_license
|
//
// Router.swift
// DailyCommute
//
// Created by Joshua Walsh on 4/19/18.
// Copyright © 2018 Lucky Penguin. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
public enum Router {
public typealias Id = Int
public typealias Params = [String: Any]?
case activities(id: Id, params: Params)
case athlete
case athleteActivites(params: Params)
case createActivity(params: Params)
case token(code: String)
}
extension Router: URLRequestConvertible {
static var authorizationUrl: URL {
var url = "https://www.strava.com/oauth/authorize?"
StravaService.shared.authParams.forEach {
url.append("\($0)=\($1)&")
}
return URL(string: url)!
}
public func asURLRequest () throws -> URLRequest {
let config = self.requestConfig
var baseURL: URL {
switch self {
case .token:
return URL(string: "https://www.strava.com/oauth")!
default:
return URL(string: "https://www.strava.com/api/v3")!
}
}
var urlRequest = URLRequest(url: baseURL.appendingPathComponent(config.path))
urlRequest.httpMethod = config.method.rawValue
if let token = StravaService.shared.token?.accessToken {
urlRequest.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
}
if let params = config.params {
return try JSONEncoding.default.encode(urlRequest, with: params)
}
return try JSONEncoding.default.encode(urlRequest)
}
}
// MARK: Request Configure
extension Router {
private var requestConfig: (path: String, params: Params, method: Alamofire.HTTPMethod) {
switch self {
case .activities(let id, let params):
return ("/activities/\(id)", params, .get)
case .athlete:
return ("/athlete", nil, .get)
case .athleteActivites(let params):
return ("/athlete/activities", params, .get)
case .createActivity(let params):
return ("/activities", params, .post)
case .token(let code):
return ("/token", StravaService.shared.tokenParams(code), .post)
}
}
}
| true
|
dfa1ae7b03b766fdee728313591f44826b0e61bb
|
Swift
|
dennisvera/Algorithms
|
/BinarySearch.playground/Contents.swift
|
UTF-8
| 1,281
| 4.53125
| 5
|
[] |
no_license
|
import UIKit
/// `Algorithm:` - Binary Search Algorithm
/// Given an array of numbers, return True if the searched number exists in the array, otherwise return False.
var numbers = [Int]()
for i in 1...100 {
numbers.append(i)
}
/// A binary search approach.
func binarySearchFor(searchValue: Int, array: [Int]) -> Bool {
var leftIndex = 0
var rightIndex = array.count - 1
while leftIndex <= rightIndex {
let middleIndex = (leftIndex + rightIndex) / 2
let middleNumber = array[middleIndex]
print("middleNumber: \(middleNumber), leftIndex: \(leftIndex), rightIndex: \(rightIndex), array: \(array[leftIndex]) - \(array[rightIndex])")
if middleNumber == searchValue {
return true
}
if searchValue < middleNumber {
rightIndex = middleIndex - 1
}
if searchValue > middleNumber {
leftIndex = middleIndex + 1
}
}
return false
}
print(binarySearchFor(searchValue: 101, array: numbers))
/// A linear search approach. Slower when the array contains a lot of numbers.
func linearSearchFor(searchValue: Int, array: [Int]) -> Bool {
for number in array {
if number == searchValue {
return true
}
}
return false
}
//print(linearSearchFor(searchValue: 9, array: numbers))
| true
|
8f488818c9ca9ee3650a011700a956661d123d62
|
Swift
|
brunophilipe/MastodonKit
|
/Tests/MastodonKitTests/Requests/ReportsTests.swift
|
UTF-8
| 1,325
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
//
// ReportsTests.swift
// MastodonKit
//
// Created by Ornithologist Coder on 5/17/17.
// Copyright © 2017 MastodonKit. All rights reserved.
//
import XCTest
@testable import MastodonKit
class ReportsTests: XCTestCase {
func testAll() {
let request = Reports.all()
// Endpoint
XCTAssertEqual(request.path, "/api/v1/reports")
// Method
XCTAssertEqual(request.method.name, "GET")
XCTAssertNil(request.method.queryItems)
XCTAssertNil(request.method.httpBody)
}
func testReport() {
let request = Reports.report(accountID: "40",
statusIDs: ["4", "2", "42"],
reason: "Westworld Spoiler!!!")
// Endpoint
XCTAssertEqual(request.path, "/api/v1/reports")
// Method
XCTAssertEqual(request.method.name, "POST")
XCTAssertNil(request.method.queryItems)
XCTAssertNotNil(request.method.httpBody)
let payload = try! JSONSerialization.jsonObject(with: request.method.httpBody!, options: []) as! NSDictionary
XCTAssertEqual(payload["account_id"] as? String, "40")
XCTAssertEqual(payload["status_ids"] as? [String], ["4", "2", "42"])
XCTAssertEqual(payload["comment"] as? String, "Westworld Spoiler!!!")
}
}
| true
|
b1ae8cee3788a6135977d4cc17f9c5546dc81c6c
|
Swift
|
sergiodelr/Compiler
|
/Sources/VirtualMachineLib/MemoryPointer.swift
|
UTF-8
| 922
| 2.796875
| 3
|
[] |
no_license
|
//
// Created by sergio on 19/10/2020.
//
import Foundation
// Initial virtual memory pointers for primitive types.
public enum MemoryPointer {
// Global
public static let globalStartAddress = 0
// Local
public static let localStartAddress = 3000
// Temporary
public static let tempStartAddress = 6000
// Literal
public static let literalStartAddress = 9000
// Addresses per type.
public static let addressesPerType = 500
// Segment size.
public static let segmentSize = 3000
// Start addresses for each type. Actual start address is segmentStartAddress (global, etc) + typeStartAddress.
public static let intStartAddress = 0
public static let floatStartAddress = 500
public static let charStartAddress = 1000
public static let boolStartAddress = 1500
public static let funcStartAddress = 2000
public static let listStartAddress = 2500
}
| true
|
f15c6fbecb3cb9608785b2dcdee34824a099088c
|
Swift
|
RShergold/swiftCalc
|
/swiftCalc/ViewController.swift
|
UTF-8
| 3,374
| 3.125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// swiftCalc
//
// Created by Hatch on 31/10/2014.
// Copyright (c) 2014 Hatch. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
enum Operator {
case Add, Minus, Times, Devide
}
var currentOperator: Operator?
var leftNumber: Double = 0.0
var rightNumber: Double = 0.0
var resultNumber: Double = 0.0
var inputNumber: Double?
var inputText: String = ""
@IBOutlet weak var label: UILabel!
@IBAction func numberButton(sender: UIButton) {
add_number(Array(sender.currentTitle!)[0])
}
@IBAction func ButtonDot(sender: AnyObject) {
if inputText.rangeOfString(".") == nil {
add_number(".")
}
}
@IBAction func buttonAdd(sender: AnyObject) {
calculate()
currentOperator = Operator.Add
}
@IBAction func buttonMinus(sender: AnyObject) {
calculate()
currentOperator = Operator.Minus
}
@IBAction func buttonTimes(sender: AnyObject) {
calculate()
currentOperator = Operator.Times
}
@IBAction func buttonDevide(sender: AnyObject) {
calculate()
currentOperator = Operator.Devide
}
@IBAction func buttonCalc(sender: AnyObject) {
calculate(requireInput: false)
}
@IBAction func buttonClear(sender: AnyObject) {
inputText = ""
inputNumber = nil
label.text = "0"
leftNumber = 0.0
rightNumber = 0.0
currentOperator = nil
}
func add_number(newNumber: Character) {
inputText.append(newNumber)
label.text = inputText
inputNumber = (inputText as NSString).doubleValue
}
func calculate( requireInput: Bool = true ) {
if requireInput && inputNumber == nil {
return
}
if inputNumber != nil {
rightNumber = inputNumber!
}
if let theOperator = currentOperator {
switch theOperator {
case .Add:
resultNumber = leftNumber + rightNumber
case .Minus:
resultNumber = leftNumber - rightNumber
case .Times:
resultNumber = leftNumber * rightNumber
case .Devide:
resultNumber = leftNumber / rightNumber
}
leftNumber = resultNumber
// dont print .00 if result is and integer
var resultText = "\(resultNumber)"
if resultText.hasSuffix(".0") {
label.text = resultText.substringToIndex( advance(resultText.startIndex, countElements(resultText)-2) )
} else {
// float
label.text = resultText
}
} else {
leftNumber = rightNumber
}
inputNumber = nil
inputText = ""
}
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.
}
}
| true
|
bd457c37bc1396496056fdfcead3aa4e0d52947b
|
Swift
|
RahulMukherjee/searchcity
|
/searchcity/View/CitiesVC.swift
|
UTF-8
| 3,495
| 2.640625
| 3
|
[] |
no_license
|
//
// CitiesVC.swift
// searchcity
//
// Created by Rahul Mukherjee on 24/06/19.
// Copyright © 2019 Rahul Mukherjee. All rights reserved.
//
import UIKit
import CoreLocation
class CitiesVC: UIViewController {
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var citiesTable: UITableView!
let searchController = UISearchController(searchResultsController: nil)
var locationManager: CLLocationManager?
private var viewModel: CitiesViewModel?
override func viewDidLoad() {
super.viewDidLoad()
self.setUpSearchBar()
self.activityIndicator.startAnimating()
self.registerCell()
viewModel = CitiesViewModel()
self.registerCallback()
locationManager = CLLocationManager()
locationManager?.requestWhenInUseAuthorization()
locationManager?.delegate = self
self.citiesTable.rowHeight = UITableView.automaticDimension;
self.citiesTable.estimatedRowHeight = 44.0;
}
private func setUpSearchBar() {
searchController.searchResultsUpdater = self
searchController.obscuresBackgroundDuringPresentation = false
searchController.searchBar.placeholder = "Search Cities"
navigationItem.searchController = searchController
definesPresentationContext = true
}
private func registerCell() {
self.citiesTable.register(CityTableViewCell.nib(), forCellReuseIdentifier: CityTableViewCell.identifier)
}
private func registerCallback() {
if let viewModel = viewModel {
viewModel.didUpdated = { [weak self] _ in
DispatchQueue.main.async {
guard let self = self else { return }
self.activityIndicator.stopAnimating()
self.citiesTable.reloadData()
}
}
}
}
}
extension CitiesVC: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let viewModel = viewModel {
return viewModel.numberOfRows()
}
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let viewModel = viewModel else { return UITableViewCell() }
if let cityModel = viewModel.rows(atIndex: indexPath) as? City, let cell = tableView.dequeueReusableCell(withIdentifier: CityTableViewCell.identifier, for: indexPath) as? CityTableViewCell {
cell.configure(city: cityModel)
return cell
}
return UITableViewCell()
}
}
extension CitiesVC: UISearchResultsUpdating {
///SearchBar delegate
func updateSearchResults(for searchController: UISearchController) {
guard let viewModel = viewModel else { return }
if let searchText = searchController.searchBar.text, searchText.trimmingCharacters(in: .whitespacesAndNewlines) != "" {
viewModel.filterCity(prefix: searchText)
} else {
viewModel.resetFilter()
}
}
}
extension CitiesVC : CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if( status == .authorizedWhenInUse ||
status == .authorizedAlways) {
appLog("Got the Permision for Location")
} else {
appLog("Nops! Location permision denied")
}
}
}
| true
|
7420e0942548321fa54650f3a576ca5326339a18
|
Swift
|
zafarivaev/RxSwift-Chaining
|
/RxSwift-Chaining/ViewController.swift
|
UTF-8
| 2,914
| 2.8125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// RxSwift-Chaining
//
// Created by Zafar on 1/31/20.
// Copyright © 2020 Zafar. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
bindTextField()
}
private func animateTextField() -> Observable<Bool> {
return Observable.create { observer -> Disposable in
UIView.animate(withDuration: 0.2, delay: 0, options: [], animations: {
self.textField.backgroundColor = .systemGreen
}, completion: { _ in
UIView.animate(withDuration: 0.2) {
self.textField.backgroundColor = .white
self.textField.text = ""
observer.onNext(true)
}
})
return Disposables.create()
}
}
private let disposeBag = DisposeBag()
private lazy var textField: UITextField = {
let textField = UITextField()
textField.placeholder = "Type here..."
textField
.translatesAutoresizingMaskIntoConstraints = false
textField.layer.borderColor = UIColor.lightGray.cgColor
textField.layer.borderWidth = 1
textField.layer.cornerRadius = 10
return textField
}()
}
// MARK: - Binding
extension ViewController {
private func bindTextField() {
textField.rx.text
.orEmpty
.filter { $0.count == 5 }
.flatMap { self.findSubstring(in: $0) }
.filter { $0 == true }
.flatMap { _ in self.animateTextField() }
.filter { $0 == true }
.subscribe(onNext: { _ in
print("Subscribed")
})
.disposed(by: disposeBag)
}
}
// MARK: - Observables
extension ViewController {
private func findSubstring(in string: String) -> Observable<Bool> {
return Observable.create { observer -> Disposable in
if string.lowercased().contains("rx") {
observer.onNext(true)
} else {
observer.onNext(false)
}
return Disposables.create()
}
}
}
extension ViewController {
private func setupUI() {
overrideUserInterfaceStyle = .light
self.view.backgroundColor = .white
self.view.addSubview(textField)
NSLayoutConstraint.activate([
textField.topAnchor
.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor, constant: 20),
textField.heightAnchor
.constraint(equalToConstant: 50),
textField.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 50),
textField.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: -50)
])
}
}
| true
|
8c5b4002ba760bd102ec8da517f215c3778b080a
|
Swift
|
bogdad/crdttasklist
|
/crdttasklistTests/DeltaTests.swift
|
UTF-8
| 3,947
| 2.515625
| 3
|
[] |
no_license
|
//
// DeltaTests.swift
// crdttasklistTests
//
// Created by Vladimir Shakhov on 6/29/19.
// Copyright © 2019 Vladimir Shakhov. All rights reserved.
//
import XCTest
@testable import crdttasklist
extension Delta where N==RopeInfo {
func apply_to_string(_ s: String) -> String {
var incoming_rope = Rope.from_str(s[...])
let rope = self.apply(incoming_rope)
return String.from(rope: rope)
}
}
extension InsertDelta where N==RopeInfo {
func apply_to_string(_ s: String) -> String {
var incoming_rope = Rope.from_str(s[...])
let rope = self.apply(incoming_rope)
return String.from(rope: rope)
}
}
class DeltaTests: XCTestCase {
let TEST_STR = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
func testSimple() {
let d = Delta.simple_edit(Interval(1, 9), Rope.from_str("era"), 11)
XCTAssertEqual("herald", d.apply_to_string("hello world"))
XCTAssertEqual(6, d.new_document_len())
}
func testFactor() {
let d = Delta.simple_edit(Interval(1, 9), Rope.from_str("era"), 11)
let (d1, ss) = d.factor()
XCTAssertEqual("heraello world", d1.apply_to_string("hello world"))
XCTAssertEqual("hld", ss.delete_from_string("hello world"))
}
func testSynthesize() {
let d = Delta.simple_edit(Interval(1, 9), Rope.from_str("era"), 11)
var (d1, del) = d.factor()
var ins = d1.inserted_subset()
del = del.transform_expand(ins)
var union_str = d1.apply_to_string("hello world")
print("union_str", union_str)
let tombstones = ins.complement().delete_from_string(union_str)
print("tombstones", tombstones)
let new_d = Delta.synthesize(Rope.from_str(tombstones[...]), ins, del)
XCTAssertTrue("herald" == new_d.apply_to_string("hello world"))
let text = del.complement().delete_from_string(&union_str)
print("text", text)
let inv_d = Delta.synthesize(Rope.from_str(text[...]), del, ins)
XCTAssertTrue("hello world" == inv_d.apply_to_string("herald"))
}
func test_transform_expand() {
let str1 = "01259DGJKNQTUVWXYcdefghkmopqrstvwxy"
let s1 = TestHelpers.find_deletions(str1, TEST_STR)
let d = Delta<RopeInfo>.simple_edit(Interval(10, 12), Rope.from_str("+"), str1.len())
assert("01259DGJKN+UVWXYcdefghkmopqrstvwxy" == d.apply_to_string(str1))
let (d2, _ss) = d.factor()
XCTAssertEqual("01259DGJKN+QTUVWXYcdefghkmopqrstvwxy", d2.apply_to_string(str1))
let d3 = d2.transform_expand(s1, false)
XCTAssertEqual(
"0123456789ABCDEFGHIJKLMN+OPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
d3.apply_to_string(TEST_STR)
)
let d4 = d2.transform_expand(s1, true)
XCTAssertEqual(
"0123456789ABCDEFGHIJKLMNOP+QRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
d4.apply_to_string(TEST_STR)
)
}
func test_transform_expand_simple() {
let str1 = "first"
let str1andstuff = "andfiondrstsec"
let s1 = TestHelpers.find_deletions(str1, str1andstuff)
let d = Delta<RopeInfo>.simple_edit(Interval(1, 4), Rope.from_str("+"), str1.len())
XCTAssertEqual("f+t", d.apply_to_string(str1))
let (d2, _) = d.factor()
XCTAssertEqual("f+irst", d2.apply_to_string(str1))
let d3 = d2.transform_expand(s1, false)
XCTAssertEqual(
"andf+iondrstsec",
d3.apply_to_string(str1andstuff)
)
let d4 = d2.transform_expand(s1, true)
XCTAssertEqual(
"andf+iondrstsec",
d4.apply_to_string(str1andstuff)
)
}
func test_inserted_subset() {
let d = Delta.simple_edit(Interval(1, 9), Rope.from_str("era"), 11)
let (d1, _) = d.factor()
XCTAssertEqual("hello world", d1.inserted_subset().delete_from_string("heraello world"))
}
}
| true
|
30178e81700471891f284c78e85b5fcba9d35d61
|
Swift
|
Yaschenko/HereAndNow
|
/HereAndNow/CustomTabbar.swift
|
UTF-8
| 1,605
| 2.96875
| 3
|
[] |
no_license
|
//
// CustomTabbarButton.swift
// HereAndNow
//
// Created by Yurii on 2/29/16.
// Copyright © 2016 Nostris. All rights reserved.
//
import UIKit
class CustomTabbarButton: UIView {
@IBOutlet weak var button:UIButton!
@IBOutlet weak var selectedIndicator:UIImageView!
@IBOutlet weak var tabbarView:CustomTabbarView?
func setSelected(selected:Bool) {
self.selectedIndicator.hidden = !selected
if selected == true {
self.button.alpha = 1
} else {
self.button.alpha = 0.6
}
}
@IBAction func buttonAction(button:UIButton) {
self.setSelected(true)
if self.tabbarView != nil {
self.tabbarView!.selectItem(self)
}
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
}
protocol CustomTabbarViewDelegate:NSObjectProtocol {
func didSelectCustomTabbarItem(item:CustomTabbarButton)
}
class CustomTabbarView: UIView {
@IBOutlet weak var selectedTabbarItem:CustomTabbarButton?
weak var customTabbarDelegate:CustomTabbarViewDelegate?
func selectItem(item:CustomTabbarButton) {
if (self.selectedTabbarItem != nil) && (self.selectedTabbarItem != item) {
self.selectedTabbarItem!.setSelected(false)
}
self.selectedTabbarItem = item
if self.customTabbarDelegate != nil {
self.customTabbarDelegate!.didSelectCustomTabbarItem(item)
}
}
}
| true
|
1756dd938ffc5cef982c9391c8848f388e355ee5
|
Swift
|
DioGnDev/TheMoviee
|
/TheMoviee/Feature/Genre/Presentation/Interactor/GenreInteractor.swift
|
UTF-8
| 1,236
| 2.796875
| 3
|
[] |
no_license
|
//
// GenreInteractor.swift
// TheMoviee
//
// Created by Ilham Hadi Prabawa on 2/23/21.
// Copyright (c) 2021 ___ORGANIZATIONNAME___. All rights reserved.
//
// This file was generated by the VIP Xcode Templates
//
//
import Foundation
protocol GenreInteractorLogic {
func getGenre(param: GenreRequest)
}
class GenreInteractor: GenreInteractorLogic {
//presenter
var presenter: GenrePresenterLogic?
//usecase
var getGenreUsecase: GetGenreUsecase
//initial
init(getGenreUsecase: GetGenreUsecase) {
self.getGenreUsecase = getGenreUsecase
}
//example method
func getGenre(param: GenreRequest) {
getGenreUsecase.execute(param: param) { (result) in
switch result {
case .failure(let error):
//present error to view
self.presenter?.presentAlert(with: error.errorType.description)
break
case .success(let items):
if items.count == 0 || items.isEmpty {
//present empty view
}else {
self.presenter?.presentGenre(entities: items)
}
break
}
}
}
}
| true
|
e81e8ccce057e6b253f376e65940ca90d5fa2016
|
Swift
|
iq3addLi/learn-vapor
|
/Sources/Main/Controller/JWTController.swift
|
UTF-8
| 2,532
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
//
// JWTController.swift
// Main
//
// Created by iq3AddLi on 2019/10/03.
//
import Vapor
import JWT
struct JWTController{
// JWT Issue
func getToken(_ request: Request) throws -> [ String: String ] {
// Get parameter at query
guard let username = request.query[ String.self, at: "username" ] else{
throw Abort(.badRequest, reason: "The username is require in query.")
}
let exp = request.query[ Int.self, at: "exp" ] ?? 60
// create payload
let payload = Payload(username: username, exp: ExpirationClaim(value: Date().addingTimeInterval(TimeInterval(exp))))
// create JWT and sign
let data = try JWT(payload: payload).sign(using: .hs256(key: Constants.secret))
return [ "token": String(data: data, encoding: .utf8) ?? "<encode failed>" ]
}
// JWT Verify (HTTP Body)
func verifyToken(_ request: Request) throws -> Future<Response> {
// JWT Verify (HTTP header bearer)
if let bearer = request.http.headers.bearerAuthorization {
let jwt = try JWT<Payload>(from: bearer.token, verifiedUsing: .hs256(key: Constants.secret))
return request.response( GeneralInfomation("Your username is \(jwt.payload.username)") , as: .json).encode(status: .ok, for: request)
}
if let token = request.http.headers.tokenAuthorization {
let jwt = try JWT<Payload>(from: token.token, verifiedUsing: .hs256(key: Constants.secret))
return request.response( GeneralInfomation("Your username is \(jwt.payload.username)") , as: .json).encode(status: .ok, for: request)
}
// JWT Verify (HTTP Body)
// Get parameter at http body
return try request.content.decode(json: PayloadRequest.self, using: JSONDecoder()).map { (payloadReq) in
// parse JWT from token string, using HS-256 signer
let jwt = try JWT<Payload>(from: payloadReq.token, verifiedUsing: .hs256(key: Constants.secret))
return request.response( GeneralInfomation("Your username is \(jwt.payload.username)") , as: .json)
}
}
// JWT Verify (in Middleware)
func relayedPayload(_ request: Request) throws -> Future<Response> {
let payload = (try request.privateContainer.make(Payload.self))
return request.response( GeneralInfomation("Your username is \(payload.username)") , as: .json).encode(status: .ok, for: request)
}
}
| true
|
fe8eb4fefd71d30d79840e753e11bea0b1c346da
|
Swift
|
magnuskahr/SkakKit
|
/Sources/SkakKit/Position.swift
|
UTF-8
| 255
| 3.015625
| 3
|
[] |
no_license
|
import Foundation
public struct Position {
let file: File
let rank: Rank
public init(file: File, rank: Rank) {
self.file = file
self.rank = rank
}
}
extension Position: Equatable { }
extension Position: Hashable { }
| true
|
44e0f967dfd5b008e91393867b721ad13ee8e18d
|
Swift
|
Huddie/Feed
|
/Feed/Feedable/Feedable Cells/FeedImageCell.swift
|
UTF-8
| 1,918
| 2.5625
| 3
|
[] |
no_license
|
//
// FeedImageCell.swift
// Feed
//
// Created by Ehud Adler on 1/4/20.
// Copyright © 2020 Ehud Adler. All rights reserved.
//
import UIKit
final class FeedImageCell: UITableViewCell, FeedableCell {
//MARK: - FeedableCell
typealias Model = FeedableImageModel
var model: FeedableImageModel?
//MARK: - Private iVars
private let asyncImageView: AsyncImageView = .init(cache: FeedImageCache.shared)
//MARK: - Public inits
init(style: UITableViewCell.CellStyle, reuseIdentifier: String?, model: FeedableModel) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
configure(model: model)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
//MARK: - Private methods
private func setUpImageView() {
addSubview(asyncImageView)
asyncImageView.translatesAutoresizingMaskIntoConstraints = false
if let height = model?.height {
self.heightAnchor.constraint(equalToConstant: height).isActive = true
}
NSLayoutConstraint.activate([
asyncImageView.leftAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leftAnchor),
asyncImageView.rightAnchor.constraint(equalTo: self.safeAreaLayoutGuide.rightAnchor),
asyncImageView.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor),
asyncImageView.bottomAnchor.constraint(equalTo: self.safeAreaLayoutGuide.bottomAnchor),
])
}
//MARK: - FeedableCell Methods
func configure(model: FeedableModel) {
guard let model = model as? FeedableImageModel else { return }
self.model = model
asyncImageView.setImage(forKey: model.url)
setUpImageView()
}
}
| true
|
e86feaf24288e2e0fd92c9bef8e9aeb2b011121a
|
Swift
|
openfoodfacts/openfoodfacts-ios
|
/Sources/Controllers/DeepLinkManager.swift
|
UTF-8
| 735
| 2.640625
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// DeepLinkManager.swift
// OpenFoodFacts
//
// Created by Andrés Pizá Bückmann on 02/01/2018.
// Copyright © 2018 Andrés Pizá Bückmann. All rights reserved.
//
import UIKit
enum DeepLinkType {
case scan
}
class DeepLinkManager {
static let shared = DeepLinkManager()
private init() {}
private var deepLink: DeepLinkType?
@discardableResult
func handleShortcut(item: UIApplicationShortcutItem) -> Bool {
deepLink = ShortcutParser.shared.handleShortcut(item)
return deepLink != nil
}
// check existing deepling and perform action
func checkDeepLink() {
AppDelegate.shared.rootViewController.deepLink = deepLink
// reset deeplink after handling
self.deepLink = nil
}
}
| true
|
46f27f5056e4bc796b0bcf34c767007a473ff3e2
|
Swift
|
JaydenGarrick/HelloRecipes
|
/HelloRecipes/Networking/NetworkEnums.swift
|
UTF-8
| 524
| 3
| 3
|
[] |
no_license
|
//
// NetworkingConstants.swift
// HelloRecipes
//
// Created by Jayden Garrick on 7/18/18.
// Copyright © 2018 Jayden Garrick. All rights reserved.
//
import Foundation
enum HTTPMethod: String {
case get = "GET"
case post = "POST"
}
enum ResponseType<T> {
case success(object: T)
case failure(error: NetworkError)
}
enum NetworkError: Error {
case noServerConnection
case noDataReturned
case unparsable
case unauthorized
case unknown
case internalServerError
case incorrectParameters
}
| true
|
ffcda1c8d6dfde188e001c003e3e72f31ab326ee
|
Swift
|
sonkute96/Learn_IOS
|
/LearnSwift_Array.playground/Contents.swift
|
UTF-8
| 931
| 4.09375
| 4
|
[] |
no_license
|
//: Playground - noun: a place where people can play
import UIKit
var arr_tenSinhVien:[String] = ["son", "minh", "teo", "ti"]; // khai bao tuong minh nhu nay lam cho chuong trinh chay nhanh hon.
print (arr_tenSinhVien[3])
var someVar = [Int]()
someVar.append(20)
someVar.append(30)
someVar.append(40)
arr_tenSinhVien.count;
for item in arr_tenSinhVien {
print (item)
}
// we can create array with any type
var mixData = [1, "Carl"] as [Any];
arr_tenSinhVien.isEmpty // false
// -------- dictionary
var someDict: [Int:String] = [1: "One", 2: "Two", 3 : "Three"]
//var oldVal = someDict.updateValue("new value of one", forKey: 1)
//
//
//someDict.removeValue(forKey: 2)
for (key,value) in someDict {
print ("key \(key) - value = \(value)")
}
var ourData: Dictionary<String,String> = ["Key":"Value"];
ourData["Key"]; // get value into Dictionary
ourData.count
| true
|
dc065fb015c42e5770c79f123f78fb47efc5cf8c
|
Swift
|
Takatoshi-Miura/010-PhotoSharingApp
|
/010-PhotoSharingApp/HomeViewController.swift
|
UTF-8
| 5,864
| 2.71875
| 3
|
[] |
no_license
|
//
// HomeViewController.swift
// 010-PhotoSharingApp
//
// Created by Takatoshi Miura on 2020/06/13.
// Copyright © 2020 Takatoshi Miura. All rights reserved.
//
// <概要>
// ホーム画面での処理をまとめたクラス。
// Firebaseから投稿内容を読み取り、PostTableViewCellのレイアウトで表示する。
// 画面の更新は、ホーム画面が呼ばれる毎に行う。
//
// <機能>
// 投稿読み取り機能
// Firebaseにアクセスして投稿内容を読み取り、PostTableViewCellに格納する。
// 投稿表示機能
// PostTableViewCellに格納した投稿データをPostDataArrayに格納する。
// PostDataArrayをセルとして表示する。
//
import UIKit
import Firebase
import FirebaseAuth
import FirebaseUI
import SVProgressHUD
class HomeViewController: UIViewController , UITableViewDelegate, UITableViewDataSource {
override func viewDidLoad() {
super.viewDidLoad()
// dataSource,delegateの指定
postTableView.dataSource = self
postTableView.delegate = self
// PostTableViewCellを登録
postTableView.register(UINib(nibName: "PostTableViewCell", bundle: nil), forCellReuseIdentifier: "PostTableViewCell")
// テーブルビューの更新
self.postTableView.reloadRows(at:[IndexPath(row: 0, section: 0)],with:UITableView.RowAnimation.fade)
self.postTableView?.reloadData()
}
// テーブルビュー
@IBOutlet var postTableView: UITableView!
// PostDataを格納した配列
var postDataArray = [PostData]()
// HomeViewControllerが呼ばれたときの処理
override func viewWillAppear(_ animated: Bool) {
// HUDで処理中を表示
SVProgressHUD.show()
// データベースの投稿を取得
let databasePostData = PostData()
databasePostData.loadDatabase()
// 投稿データを取得
// データの取得が終わるまで時間待ち
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2.0) {
self.postDataArray = []
self.postDataArray = databasePostData.postDataArray
self.postTableView?.reloadData()
// HUDを非表示
SVProgressHUD.dismiss()
}
}
// セクションの数を返却する
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
// PostDataArray配列の長さ(項目の数)を返却する
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return postDataArray.count
}
// セルの高さ設定
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 450
}
// テーブルの行ごとのセルを返却する
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Storyboardで指定した識別子を利用して再利用可能なセルを取得する
let cell = tableView.dequeueReusableCell(withIdentifier: "PostTableViewCell", for: indexPath) as! PostTableViewCell
// 「返信」ボタンをタップしたときの処理を設定
cell.replyCommentButton.tag = indexPath.row
cell.replyCommentButton.addTarget(self, action: #selector(self.pushReplyCommentButton(_:)), for: .touchUpInside)
// セルに投稿データをセットする
cell.printPostData(postDataArray[indexPath.row])
return cell
}
// 返信ボタンをタップしたときの処理
@objc private func pushReplyCommentButton(_ sender:UIButton) {
// 指定した投稿に返信コメントを追加
addReplyComment(postDataArray[sender.tag].postID)
}
// 返信コメントを作成するメソッド
func addReplyComment(_ postID:Int) {
// 返信コメント格納用
var replyComment:String = ""
// アラートダイアログを生成
let alertController = UIAlertController(title:"返信を追加",message:"コメントを入力してください",preferredStyle:UIAlertController.Style.alert)
// テキストエリアを追加
alertController.addTextField(configurationHandler:nil)
// OKボタンを宣言
let okAction = UIAlertAction(title:"OK",style:UIAlertAction.Style.default){(action:UIAlertAction)in
// OKボタンがタップされたときの処理
if let textField = alertController.textFields?.first {
// 現在のアカウント名を取得
let user = Auth.auth().currentUser
// テキストフィールドの入力値を用いて返信コメントを作成
replyComment = "\(user!.displayName!):\(textField.text!)"
// データベースを更新
let postData = PostData()
postData.addReplyComment(postID, replyComment)
// ビューを更新
self.viewWillAppear(true)
}
}
//CANCELボタンを宣言
let cancelButton = UIAlertAction(title:"CANCEL",style:UIAlertAction.Style.cancel,handler:nil)
// ボタンを追加
alertController.addAction(okAction)
alertController.addAction(cancelButton)
//アラートダイアログを表示
self.present(alertController,animated:true,completion:nil)
}
// HomeViewControllerが呼ばれたときの処理
@IBAction func goToHome(_segue:UIStoryboardSegue){
}
}
| true
|
b6ca3c3a0c75f34c11c366eefe0b1edfec85a1be
|
Swift
|
PauloLeon/ChuckNorris
|
/Desafio/Network/Base Request/ConstantsNetwork.swift
|
UTF-8
| 724
| 2.59375
| 3
|
[] |
no_license
|
//
// ConstantsNetwork.swift
// DesafioGuiaBolso
//
// Created by Paulo Rosa on 24/01/20.
// Copyright © 2020 Paulo Rosa. All rights reserved.
//
struct ConstantsNetwork {
static let baseUrl = "https://api.chucknorris.io/jokes"
struct Parameters {
static let category = "category"
}
struct Paths {
static let category = "/categories"
static let random = "/random"
}
enum HttpHeaderField: String {
case authentication = "Authorization"
case contentType = "Content-Type"
case acceptType = "Accept"
case acceptEncoding = "Accept-Encoding"
}
enum ContentType: String {
case json = "application/json"
}
}
| true
|
0e0742946012e9a085bebaa6bcda7b6cdf094514
|
Swift
|
scottrhoyt/RxTask
|
/Tests/RxTaskTests/TaskTests.swift
|
UTF-8
| 2,454
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
import XCTest
@testable import RxTask
import RxSwift
import RxBlocking
class TaskTests: XCTestCase {
func testStdOut() throws {
let script = try ScriptFile(commands: [
"echo hello world",
"sleep 0.1"
])
let events = try getEvents(for: script)
XCTAssertEqual(events.count, 3)
XCTAssertEqual(events[0], .launch(command: script.path))
XCTAssertEqual(events[1], .stdOut("hello world\n"))
XCTAssertEqual(events[2], .exit(statusCode: 0))
}
func testStdErr() throws {
let script = try ScriptFile(commands: [
"echo hello world 1>&2",
"sleep 0.1"
])
let events = try getEvents(for: script)
XCTAssertEqual(events.count, 3)
XCTAssertEqual(events[0], .launch(command: script.path))
XCTAssertEqual(events[1], .stdErr("hello world\n"))
XCTAssertEqual(events[2], .exit(statusCode: 0))
}
func testExitsWithFailingStatusErrors() throws {
let script = try ScriptFile(commands: ["exit 100"])
do {
_ = try getEvents(for: script)
// If we get this far it is a failure
XCTFail()
} catch {
if let error = error as? TaskError {
XCTAssertEqual(error, .exit(statusCode: 100))
} else {
XCTFail()
}
}
}
func testUncaughtSignalErrors() throws {
let script = try ScriptFile(commands: [
"kill $$",
"sleep 10"
])
do {
_ = try getEvents(for: script)
// If we get this far it is a failure
XCTFail()
} catch {
if let error = error as? TaskError {
XCTAssertEqual(error, .uncaughtSignal)
} else {
XCTFail()
}
}
}
static var allTests: [(String, (TaskTests) -> () throws -> Void)] {
return [
("testStdOut", testStdOut),
("testStdErr", testStdErr),
("testExitsWithFailingStatusErrors", testExitsWithFailingStatusErrors),
("testUncaughtSignalErrors", testUncaughtSignalErrors)
]
}
// MARK: Helpers
func getEvents(for script: ScriptFile) throws -> [TaskEvent] {
return try Task(launchPath: script.path).launch()
.toBlocking()
.toArray()
}
}
| true
|
85b87a10d02d8f59665db3ef575f1a4b6307f9af
|
Swift
|
vishal-chhatwani/App-developers-for-biosensing-Ver-1.0
|
/SensortagBleReceiver/MainInterface.swift
|
UTF-8
| 3,369
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
//
// MainInterface.swift
// Biosensor App
//
// Created by bhansali on 10/8/16.
// Copyright © 2016 Vishal. All rights reserved.
//
import UIKit
open class MainInterface: UIView {
// override open func draw(_ rect: CGRect)
// {
// drawRingFittingInsideView(14,width: 5,height: 5,x: 2,y: 3, rad: 2, color: "red", fracOfCircle: 4.0, fontSize: 28 )
// drawRingFittingInsideView(7,width: 8,height: 8,x: 4,y: 1.4, rad: 4, color: "green", fracOfCircle: 4.0, fontSize: 23)
// drawRingFittingInsideView(7,width: 8,height: 8,x: 1.35,y: 1.4, rad: 4, color: "blue", fracOfCircle: 4.0, fontSize: 23)
//
// }
//
// func drawRingFittingInsideView(_ lineWidth: CGFloat,width: CGFloat, height: CGFloat, x: CGFloat, y: CGFloat, rad: CGFloat, color: String, fracOfCircle: Double, fontSize: CGFloat) -> CAShapeLayer
// {
// let halfSize:CGFloat = min( bounds.size.width/width, bounds.size.height/height)
// let desiredLineWidth:CGFloat = lineWidth // your desired value
//
// let circlePath = UIBezierPath(
// arcCenter: CGPoint(x:bounds.size.width/x,y:bounds.size.height/y),
// radius: CGFloat( halfSize - (desiredLineWidth/rad) ),
// startAngle: CGFloat(M_PI_2) * 3.0,
// endAngle:CGFloat(M_PI_2) * 3.0 + CGFloat(M_PI) * 2.0,
// clockwise: true)
//
// let shapeLayer = CAShapeLayer()
// let text = CATextLayer()
// shapeLayer.path = circlePath.cgPath
// let fractionOfCircle = fracOfCircle / 4.0
// shapeLayer.fillColor = UIColor.white.cgColor
// if(color=="red"){
// shapeLayer.strokeColor = UIColor.red.cgColor
// }
// else if(color=="green"){
// shapeLayer.strokeColor = UIColor.green.cgColor
// }
// else if(color=="blue"){
// shapeLayer.strokeColor = UIColor.blue.cgColor
// }
//
// shapeLayer.lineWidth = desiredLineWidth
// shapeLayer.borderColor = UIColor.black.cgColor
// shapeLayer.borderWidth=20
//
// // When it gets to the end of its animation, leave it at 0% stroke filled
// shapeLayer.strokeEnd = 1.0
// text.string = "76"
// // set the string
// text.fontSize = fontSize
// text.foregroundColor = UIColor.black.cgColor
// text.frame = CGRect(x: (bounds.size.width/x)-10, y: (bounds.size.height/y)-13, width: 80, height: 40)
//
// // text.foregroundColor = UIColor.blackColor().CGColor
// self.layer.addSublayer(shapeLayer)
// self.layer.addSublayer(text)
// // Configure the animation
// let drawAnimation = CABasicAnimation(keyPath: "strokeEnd")
// drawAnimation.repeatCount = 1.0
//
// // Animate from the full stroke being drawn to none of the stroke being drawn
// drawAnimation.fromValue = NSNumber(value: 0.0 as Float)
// drawAnimation.toValue = NSNumber(value: fractionOfCircle as Double)
//
// drawAnimation.duration = 2.0
//
// drawAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
//
// // Add the animation to the circle
// shapeLayer.add(drawAnimation, forKey: "drawCircleAnimation")
//
// return shapeLayer
// }
}
| true
|
31769fbf15159239bde90553e752c75f75e4ba2e
|
Swift
|
dapacreative/weapon-manager
|
/Weapon Manager/WeaponViewController.swift
|
UTF-8
| 1,366
| 2.546875
| 3
|
[] |
no_license
|
//
// WeaponViewController.swift
// Weapon Manager
//
// Created by dan.smith on 12/18/17.
// Copyright © 2017 dan.smith. All rights reserved.
//
import UIKit
import os.log
class WeaponViewController: UIViewController, UITextFieldDelegate {
//MARK: Properties
@IBOutlet weak var weaponNameLabel: UILabel!
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var saveButton: UIBarButtonItem!
var weapon: Weapon?
override func viewDidLoad() {
super.viewDidLoad()
nameTextField.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
//MARK: Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
guard let button = sender as? UIBarButtonItem, button === saveButton else {
os_log("The save button was not pressed, cancelling", log: OSLog.default, type: .debug)
return
}
let name = nameTextField.text ?? ""
weapon = Weapon(name: name)
}
}
| true
|
a6ba8941fe1189cc2bd8fee6bfe62ea892bbdc75
|
Swift
|
lilcappuccino/newsApi
|
/NewsApi/Model/ArticleModel.swift
|
UTF-8
| 595
| 2.515625
| 3
|
[] |
no_license
|
//
// ArticleModel.swift
// NewsApi
//
// Created by dewill on 13.10.2019.
// Copyright © 2019 lilcappucc. All rights reserved.
//
import Foundation
struct ArticleModel {
let source: SourceModel?
var image: ImageModel?
let author : String?
let content: String?
let articleDescription: String?
let title: String
let url: String
let publishedAt: String
var addedAt: Int64
}
struct SourceModel {
let id: String?
let name: String?
}
struct ImageModel {
let imageUrl: String?
var height: Float
var width: Float
}
| true
|
bcc687eb50052f5881e881bae30679c753a81516
|
Swift
|
efemazlumoglu/MovieSwiftUI
|
/MovieSwift/MovieSwift/views/components/moviesList/MoviesGenreList.swift
|
UTF-8
| 2,606
| 2.609375
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// MoviesGenreList.swift
// MovieSwift
//
// Created by Thomas Ricouard on 15/06/2019.
// Copyright © 2019 Thomas Ricouard. All rights reserved.
//
import SwiftUI
import SwiftUIFlux
// MARK: - Page listener
final class MovieGenrePageListener: MoviesPagesListener {
var genre: Genre
var dispatch: DispatchFunction?
var sort: MoviesSort = .byPopularity {
didSet {
currentPage = 1
loadPage()
}
}
override func loadPage() {
dispatch?(MoviesActions.FetchMoviesGenre(genre: genre, page: currentPage, sortBy: sort))
}
init(genre: Genre) {
self.genre = genre
super.init()
}
}
// MARK: - View
struct MoviesGenreList: ConnectedView {
struct Props {
let movies: [Int]
let dispatch: DispatchFunction
}
let genre: Genre
let pageListener: MovieGenrePageListener
@State var isSortSheetPresented = false
@State var selectedSort: MoviesSort = .byPopularity
init(genre: Genre) {
self.genre = genre
self.pageListener = MovieGenrePageListener(genre: self.genre)
}
func map(state: AppState, dispatch: @escaping DispatchFunction) -> Props {
Props(movies: state.moviesState.withGenre[genre.id] ?? [],
dispatch: dispatch)
}
func body(props: Props) -> some View {
MoviesList(movies: props.movies, displaySearch: false, pageListener: pageListener)
.navigationBarItems(trailing: (
Button(action: {
self.isSortSheetPresented.toggle()
}, label: {
Image(systemName: "line.horizontal.3.decrease.circle")
.imageScale(.large)
.foregroundColor(.steam_gold)
})
))
.navigationBarTitle(Text(genre.name))
.actionSheet(isPresented: $isSortSheetPresented,
content: { ActionSheet.sortActionSheet(onAction: { sort in
if let sort = sort {
self.selectedSort = sort
self.pageListener.sort = sort
}
})
})
.onAppear {
self.pageListener.dispatch = props.dispatch
self.pageListener.loadPage()
}
}
}
#if DEBUG
struct MoviesGenreList_Previews : PreviewProvider {
static var previews: some View {
MoviesGenreList(genre: Genre(id: 0, name: "test")).environmentObject(store)
}
}
#endif
| true
|
dfbb821b95720aef85a3a5f8654c85aa2bdcc003
|
Swift
|
srpunjabi/espresso
|
/Espresso/Espresso/NearbyViewModel.swift
|
UTF-8
| 2,146
| 2.625
| 3
|
[] |
no_license
|
//
// CoffeShopViewModel.swift
// Espresso
//
// Created by Sumit Punjabi on 5/29/16.
// Copyright © 2016 wakeupsumo. All rights reserved.
//
import Foundation
import RxCocoa
import RxSwift
import CoreLocation
import Alamofire
class NearbyViewModel
{
//user's current location (both an Observer and an Observable)
var locationVariable:Variable<CLLocation?> = Variable<CLLocation?>(CLLocation(latitude: 0, longitude: 0))
//coffeeShops near the user (Observable that we bind to the UI)
lazy var coffeeShops:Driver<[CoffeeShop]>! = self.fetchCoffeeShops()
let disposeBag = DisposeBag()
init(){}
//This function observers locationVariable and makes networks calls when locationVariable changes
private func fetchCoffeeShops() -> Driver<[CoffeeShop]>
{
return locationVariable
.asObservable()
.throttle(0.5, scheduler: MainScheduler.instance) //delay network call by a few milliseconds
.observeOn(ConcurrentDispatchQueueScheduler(globalConcurrentQueueQOS:.Background))
.filter() // filter out initial 0, 0 coordinates
{
(location:CLLocation?) -> Bool in
return ((location?.coordinate.latitude != 0) && (location?.coordinate.longitude != 0))
}
.distinctUntilChanged() // only call the network api for distinct location parameters
{
(lhs:CLLocation?, rhs:CLLocation?) -> Bool in
return (lhs?.coordinate.latitude == rhs?.coordinate.latitude) && (lhs?.coordinate.longitude == rhs?.coordinate.longitude)
}
.observeOn(ConcurrentDispatchQueueScheduler(globalConcurrentQueueQOS:.Background))
.flatMapLatest() // get the latest result among all network requests made
{
location in
return FoursquareEndpoint.sharedInstance.getNearyByCoffeeShops(location!)
}.asDriver(onErrorJustReturn:[]) // makes sure that the results are returned on the MainScheduler
}
}
| true
|
9e28a6a60da9e5745dcc1c0d8c2a28af00fd8a07
|
Swift
|
linhaosunny/smallGifts
|
/小礼品/小礼品/Classes/Module/Classify/Views/ClassifySingleListHeadViewModel.swift
|
UTF-8
| 786
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
//
// ClassifySingleListHeadViewModel.swift
// 小礼品
//
// Created by 李莎鑫 on 2017/4/23.
// Copyright © 2017年 李莎鑫. All rights reserved.
//
import UIKit
class ClassifySingleListHeadDataModel: NSObject {
}
class ClassifySingleListHeadViewModel: NSObject {
var dataModel:ClassifySingleListHeadDataModel?
var photoImage:UIImage?
var titleLabelText:String?
var detialLabelText:String?
init(withModel model:ClassifySingleListHeadDataModel) {
self.dataModel = model
photoImage = UIImage(named: "strategy_\(Int(arc4random() % 17) + 1).jpg")
titleLabelText = "简介"
detialLabelText = "做你的私人搭配师,每日搭配治好你的选择困难症,满足你多睡5分钟的小小心愿"
}
}
| true
|
d986525b7bff90c4f6e6cb2a937068af5a1aae60
|
Swift
|
nitinsak95/MovieBrowser
|
/Movie Browser/Controllers/MovieListVC.swift
|
UTF-8
| 5,135
| 2.609375
| 3
|
[] |
no_license
|
//
// MovieListVC.swift
// Movie Browser
//
// Created by Nitin on 17/10/19.
// Copyright © 2019 Nitin. All rights reserved.
//
import UIKit
class MovieListVC: UIViewController {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var searchBar: UISearchBar!
var totalResults: Int?
var data = [MovieData]()
var genreData: Genres?
var pageNumber = 1
override func viewDidLoad() {
super.viewDidLoad()
searchBar.delegate = self
self.title = genreData?.name
let barButton = UIBarButtonItem(image: #imageLiteral(resourceName: "descendant"), style: .plain, target: self, action: #selector(sortMovieList))
navigationItem.rightBarButtonItem = barButton
tableView.register(UINib(nibName: "MovieListTableCell", bundle: nil), forCellReuseIdentifier: "MovieListTableCell")
getMovieList()
}
// fetch movie list
func getMovieList(){
guard let id = genreData?.id else { return }
APIClient.shared.getMovieList(genreId: id, pageNo: pageNumber){ response in
guard let movieList = response?.results, let totalItems = response?.total_results else { return }
self.data.append(contentsOf: movieList)
self.totalResults = totalItems
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
// sort movies
@objc func sortMovieList(){
let alertController = UIAlertController(title: "", message: "Sort By", preferredStyle: .actionSheet)
let mostPopularMovies = UIAlertAction(title: "Most Popular", style: .default, handler: { (alert: UIAlertAction!) -> Void in
self.data = self.data.sorted { Double($0.popularity ?? 0) > Double($1.popularity ?? 0) }
self.tableView.reloadData()
})
let highestRatedMovies = UIAlertAction(title: "Highest Rated", style: .default, handler: { (alert: UIAlertAction!) -> Void in
self.data = self.data.sorted { Double($0.vote_average ?? 0) > Double($1.vote_average ?? 0) }
self.tableView.reloadData()
})
let mostVotedMovies = UIAlertAction(title: "Most Voted", style: .default, handler: { (alert: UIAlertAction!) -> Void in
self.data = self.data.sorted { Int($0.vote_count ?? 0) > Int($1.vote_count ?? 0) }
self.tableView.reloadData()
})
alertController.addAction(mostPopularMovies)
alertController.addAction(highestRatedMovies)
alertController.addAction(mostVotedMovies)
alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self.present(alertController, animated: true, completion: nil)
}
//Search Movies
@objc func searchMovies(){
guard let searchText = searchBar.text else { return }
APIClient.shared.getSearchedMovieList(searchText: searchText){ response in
guard let movieList = response?.results, let totalItems = response?.total_results else { return }
self.data = movieList
self.totalResults = totalItems
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
if searchText == ""{
self.data.removeAll()
getMovieList()
}
}
}
extension MovieListVC: UITableViewDelegate, UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 140
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MovieListTableCell", for: indexPath) as! MovieListTableCell
cell.configureCell(for: data[indexPath.row], index: indexPath.row + 1)
if indexPath.row == data.count - 1 {
if let totalItems = self.totalResults{
if totalItems > data.count {
self.pageNumber += 1
self.getMovieList()
}
}
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "MovieDetailVC") as! MovieDetailVC
vc.data = data[indexPath.row]
self.navigationController?.pushViewController(vc, animated: true)
}
}
extension MovieListVC: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(searchMovies), object: nil)
perform(#selector(searchMovies), with: nil, afterDelay: 0.5)
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar){
searchBar.endEditing(true)
}
}
| true
|
2ec5f8d4c472cc0f1438941373d1cfe4f4092d45
|
Swift
|
mi81ma/BarChart
|
/BarChart/ViewController.swift
|
UTF-8
| 2,311
| 2.765625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// BarChart
//
// Created by masato on 23/10/2018.
// Copyright © 2018 masato. All rights reserved.
//
import UIKit
class ViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
let cellId = "cellId"
let values: [CGFloat] = [200, 300, 400, 500, 600, 100, 50, 20, 10, 5, 650, 2000, 3000, 500]
override func viewDidLoad() {
super.viewDidLoad()
collectionView?.backgroundColor = .white
collectionView?.register(BarCell.self, forCellWithReuseIdentifier: cellId)
(collectionView?.collectionViewLayout as? UICollectionViewFlowLayout)?.scrollDirection = .horizontal
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 4
}
// Scroll Horizontal
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return values.count
}
func maxHeight() -> CGFloat {
return view.frame.height - 20 - 44 - 8
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! BarCell
if let max = values.max() {
let value = values[indexPath.item]
let ratio = value / max
cell.barHeightConstraint?.constant = maxHeight() * ratio
}
return cell
}
// func collectionview(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
// return CGSize(width: 30, height: maxHeight())
// }
//
//
//// func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
//// return UIEdgeInsets(top: 0 , left: 4, bottom: 0, right: 4)
// }
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 30, height: maxHeight())
}
}
| true
|
e1072fe69607a4bf976ae35d932903f9d87c1006
|
Swift
|
jsonify/100DaysOfSwiftUI
|
/P11 Bookworm/Bookworm/ContentView.swift
|
UTF-8
| 1,008
| 2.890625
| 3
|
[] |
no_license
|
//
// ContentView.swift
// Bookworm
//
// Created by Jason on 11/19/19.
// Copyright © 2019 Jason. All rights reserved.
//
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationView {
Form {
Section(header: Text("Fundamentals")) {
NavigationLink("Creating a custom component with @Binding", destination: CustomComponent())
NavigationLink("Using size classes with AnyView type erasure", destination: UsingAnyView())
NavigationLink("How to combine Core Data and SwiftUI", destination: UsingCoreData())
}
Section(header: Text("Main")) {
NavigationLink("Bookworm Application", destination: Application())
}
}
.navigationBarTitle("P11 - Bookworm")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| true
|
fed67d7bf92af7f7894722cba755acaf67dca97c
|
Swift
|
FrankReh/swift-expvar
|
/Sources/expvar/tablebysize.swift
|
UTF-8
| 16,793
| 2.65625
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
// Copyright 2017 Frank Rehwinkel. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// TableBySize manages a particular data set and for it, it builds columns, and
// binds those columns with an NSTableView, and is the delegate and dataSource
// for the data to the NSTableView.
//
// It is expected that calls to this class are done on the main thread as it
// iteracts with an NSTableView when data has changed.
//
// It is initialized with a reference to data, and has full knowledge of the type of data
// to allow it to create the columns necessary. Once an NSTableView has been
// created by the caller and passed in, the NSTableView is retained and columns
// from the data fields are bound with the view.
//
// Delegate and DataSource
// tableView(_: NSTableView, viewFor: NSTableColumn?, row: Int) -> NSView?
// numberOfRows(in: NSTableView) -> Int
// tableView(_: NSTableView, sortDescriptorsDidChange: [NSSortDescriptor])
import AppKit
// Helper class.
class TableBySizeColumn: NSTableColumn {
typealias StringValueFn = (_ memStatsHistory: MemStatsHistory, _ row: Int) -> String
let alignment: NSTextAlignment
let stringValueFn: StringValueFn
init(title: String, tooltip: String?, alignment: NSTextAlignment,
sort: NSSortDescriptor?, stringValueFn: @escaping StringValueFn) {
self.alignment = alignment
self.stringValueFn = stringValueFn
super.init(identifier: NSUserInterfaceItemIdentifier(title))
self.title = title
self.headerToolTip = tooltip
self.sortDescriptorPrototype = sort
self.headerCell.alignment = alignment
}
required init(coder decoder: NSCoder) {
fatalError("not implemented")
}
}
// Box a weak pointer that will be kept in a dictionary.
class TableBySizeBox {
weak var handle: PopoverTable?
init(_ handle: PopoverTable) {
self.handle = handle
}
}
class TableBySize: NSObject {
private static let columns: [TableBySizeColumn] = [
TableBySizeColumn(title: "Size",
tooltip: "/debug/vars top level dictionary name",
alignment: .right,
sort: nil,
stringValueFn: { (_ m: MemStatsHistory, _ row: Int) -> String in
guard row >= 0 && row < m.bySize.count else { return "" }
return "\(m.bySize[row].size)" // TBD store string in MySizeHistory
}),
/*
* First set doesn't look as nice as the third set, so commented out for now.
TableBySizeColumn(title: "Malloc - Free",
tooltip: "For a given size, total mallocs, total frees, and their difference",
alignment: .right,
sort: nil,
stringValueFn: { (_ m: MemStatsHistory, _ row: Int) -> String in
return m.bySize[row].mallocsFrees.historyCurrentDescription() // TBD hack
}),
TableBySizeColumn(title: "Change",
tooltip: "For a given size, last poll's change to mallocs, frees, and their difference",
alignment: .left,
sort: nil,
stringValueFn: { (_ m: MemStatsHistory, _ row: Int) -> String in
return m.bySize[row].mallocsFrees.historyDeltaDescription() // TBD hack
}),
*/
/*
* An intermediate build up that doesn't seem as good as either the first choice or the third.
TableBySizeColumn(title: "Mallocs",
tooltip: "For a given size, total mallocs",
alignment: .right,
sort: nil,
stringValueFn: { (_ m: MemStatsHistory, _ row: Int) -> String in
return toStringInt(m.bySize[row].mallocsFrees.top().mallocs, .current)
}),
TableBySizeColumn(title: "- Frees",
tooltip: "For a given size, total frees",
alignment: .left,
sort: nil,
stringValueFn: { (_ m: MemStatsHistory, _ row: Int) -> String in
return "- " + toStringInt(m.bySize[row].mallocsFrees.top().frees, .current)
}),
TableBySizeColumn(title: "= Difference",
tooltip: "For a given size, total mallocs - frees",
alignment: .left,
sort: nil,
stringValueFn: { (_ m: MemStatsHistory, _ row: Int) -> String in
let top = m.bySize[row].mallocsFrees.top()
return "= " + toStringInt(top.mallocs - top.frees, .current)
}),
*/
TableBySizeColumn(title: "Mallocs (delta)",
tooltip: "For a given size, total mallocs (and delta from last poll)",
alignment: .right,
sort: nil,
stringValueFn: { (_ m: MemStatsHistory, _ row: Int) -> String in
guard row >= 0 && row < m.bySize.count else { return "" }
let mf = m.bySize[row].mallocsFrees
let (delta, found, occurrences) = mf.reportIfLastDelta()
let current = toStringInt(mf.top().mallocs, .current)
if found {
let deltaPart = delta.mallocs
var deltaPartStr = toStringInt(deltaPart, .delta)
if deltaPart > 0 {
deltaPartStr = "+" + deltaPartStr
}
return "\(current) (\(deltaPartStr))"
}
return current
}),
TableBySizeColumn(title: "- Frees (delta)",
tooltip: "For a given size, total frees (and delta from last poll)",
alignment: .left,
sort: nil,
stringValueFn: { (_ m: MemStatsHistory, _ row: Int) -> String in
guard row >= 0 && row < m.bySize.count else { return "" }
let mf = m.bySize[row].mallocsFrees
let (delta, found, occurrences) = mf.reportIfLastDelta()
var current = "- " + toStringInt(mf.top().frees, .current)
if found {
let deltaPart = delta.frees
var deltaPartStr = toStringInt(deltaPart, .delta)
if deltaPart > 0 {
deltaPartStr = "+" + deltaPartStr
}
current += " (\(deltaPartStr))"
}
return current
}),
TableBySizeColumn(title: "= Difference (delta)",
tooltip: "For a given size, total mallocs - frees (and delta from last poll)",
alignment: .left,
sort: nil,
stringValueFn: { (_ m: MemStatsHistory, _ row: Int) -> String in
guard row >= 0 && row < m.bySize.count else { return "" }
let mf = m.bySize[row].mallocsFrees
let top = mf.top()
let (delta, found, occurrences) = mf.reportIfLastDelta()
var current = "= " + toStringInt(top.mallocs - top.frees, .current)
if found {
let deltaPart = delta.mallocs - delta.frees
var deltaPartStr = toStringInt(deltaPart, .delta)
if deltaPart > 0 {
deltaPartStr = "+" + deltaPartStr
}
current += " (\(deltaPartStr))"
} else {
let deltaPartStr = deltaDescriptionWhenNotFound(count: mf.array.count,
occurrences: occurrences)
current += " (\(deltaPartStr))"
}
return current
})
]
private weak var connection: Connection?
private let observable: VarsObservable
private weak var tableview: NSTableView?
init(connection: Connection, observable: VarsObservable) {
self.connection = connection
self.observable = observable
}
// Bind NSTableColumn and tableview with each other.
func bindWith(_ tableview: NSTableView) {
tableview.delegate = self
tableview.dataSource = self
self.tableview = tableview // TBD remove this variable
for tableColumn in TableBySize.columns {
// Bind in both directions.
tableColumn.tableView = tableview
tableview.addTableColumn(tableColumn)
}
config.setColumnWidths(tableview.tableColumns,
forWindow: config.bySizeConfigName, defaultWidths: [55, 100, 100, 160])
tableview.target = self
tableview.action = #selector(singleClick(_:))
tableview.doubleAction = #selector(doubleClick(_:))
}
var handles: [UInt32: TableBySizeBox] = [:]
@objc func singleClick(_ sender: AnyObject) {
guard let bysizetableview = self.tableview else {
return
}
let row = bysizetableview.selectedRow
guard row >= 0 && row < observable.varsHistory.memstats.bySize.count else { return }
let bySizeHistory = observable.varsHistory.memstats.bySize[row]
let rect = (bysizetableview.rowView(atRow: row, makeIfNecessary: false) ?? bysizetableview).frame
if let box = handles[bySizeHistory.size],
let handle = box.handle {
handle.show(relativeTo: rect, of: bysizetableview)
} else {
// could make a title out of the bySizeHistory.size UInt32.
let newtableview = NSTableView()
observable.observers.add(newtableview)
let table = bySizeHistory.mallocsFrees.historyTable()
// Technically the table could be bound to multiple tableviews but the UI doesn't take
// advantage of that yet. Just one for now.
table.bindWith(newtableview)
// No need to retain reference to popover.
handles[bySizeHistory.size] = TableBySizeBox(PopoverTable(tableview: newtableview,
strong: table,
relativeTo: rect,
of: bysizetableview,
size: config.popoverSize(forWindow: "bysize", defaultSize: CGSize(width: 400, height: 0)),
intercellSpacing: config.popoverIntercellSpacing(forWindow: "bysize")
))
}
}
@objc func doubleClick(_ sender: AnyObject) {
guard let tableview = sender as? NSTableView else {
print("sender expected to be NSTableView")
return
}
let clickedColumn = tableview.clickedColumn
// columns can be reordered.
guard clickedColumn >= 0, clickedColumn < tableview.tableColumns.count else {
return
}
guard let column = tableview.tableColumns[clickedColumn] as? TableBySizeColumn else {
fatalError("bad tableColumn type")
}
guard let connection = self.connection else {
print("connection has been closed") // endpoint was deleted, but user hasn't closed window.
return
}
// clickedRow is -1 when column header is clicked
let clickedRow = tableview.clickedRow
let observable = self.observable
let m = observable.varsHistory.memstats
guard clickedRow >= 0 && clickedRow < m.bySize.count else { return }
let name = "\(m.bySize[clickedRow].size)"
let addcell = TableUserCell(
TableUserCellDescription(
UserColumnDesciption(
headerAlignment: column.alignment,
title: column.title,
headerToolTip: column.headerToolTip,
identifier: column.identifier),
UserRowDesciption(name: name)),
cellViewFn: { (_ tableView: NSTableView) -> NSView? in
return cellFn(tableView, column, clickedRow, observable)
})
let errormsg = connection.addCell(addcell)
if errormsg != nil {
print("addCell error: ", errormsg!)
}
}
}
private func cellFn(_ tableView: NSTableView, _ column: TableBySizeColumn, _ row: Int,
_ observable: VarsObservable) -> NSView? {
let id = column.identifier
let cell = tableView.makeView(withIdentifier: id, owner: nil) as? NSTextField ?? NSTextField()
cell.identifier = id
cell.alignment = column.alignment
cell.stringValue = column.stringValueFn(observable.varsHistory.memstats, row)
return cell
}
extension TableBySize: NSTableViewDelegate {
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
guard let column = tableColumn as? TableBySizeColumn else {
fatalError("bad tableColumn type")
}
return cellFn(tableView, column, row, observable)
}
}
extension TableBySize: NSTableViewDataSource {
func numberOfRows(in: NSTableView) -> Int {
return self.observable.varsHistory.memstats.bySize.count
}
func tableView(_: NSTableView, sortDescriptorsDidChange oldDescriptors: [NSSortDescriptor]) {
print("TableBySize.tableView(_,sortDescriptorsDidChange)")
self.tableview?.reloadData()
}
}
private var liveResizing = LiveResizing()
class TableBySizeController: NSObject {
//private var strongSelf: TableBySizeController?
private let tableBySize: TableBySize // Need this one strong pointer.
private let viewController: TableViewController // TBD is this needed?
private var controller: NSWindowController?
init(description: String, frames: Frames, connection: Connection, observable: VarsObservable) {
let newtableview = NSTableView()
newtableview.columnAutoresizingStyle = .noColumnAutoresizing
observable.observers.add(newtableview)
self.tableBySize = TableBySize(connection: connection, observable: observable)
self.tableBySize.bindWith(newtableview)
let configName = config.bySizeConfigName
let contentRect = config.frame(
windowName: configName,
frames: frames,
relativeScreen: true,
top: false,
size: CGSize(width: 450, height: 780),
offset: CGPoint(x: 200, y: 0),
instanceOffset: CGPoint(x: 40, y: 40),
instance: connection.id)
let viewController = TableViewController(tableview: newtableview)
self.viewController = viewController
super.init()
let window = viewController.makeWindow(title: "BySize: " + description,
configName: configName,
contentRect: contentRect,
delegate: self)
liveResizing.track(window: window)
self.controller = NSWindowController(window: window)
//self.strongSelf = self
}
func show() {
guard let controller = self.controller else {
fatalError("controller lost")
}
let wasVisible = controller.window?.isVisible ?? false
controller.showWindow(self)
liveResizing.show(controller.window, wasVisibleBeforeShow: wasVisible)
}
}
extension TableBySizeController: NSWindowDelegate {
//func windowWillClose(_ notification: Notification) {
// self.strongSelf = nil // Let ARC have at it.
//}
func windowDidResize(_ notification: Notification) {
liveResizing.windowDidResize(notification)
}
func windowWillStartLiveResize(_ notification: Notification) {
liveResizing.windowWillStartLiveResize(notification)
}
}
| true
|
e202f28db64c88caea9b601891721bd65620e8f7
|
Swift
|
DShivansh/chatting
|
/chat2/newsFeed/newsFeedPresenterController.swift
|
UTF-8
| 2,852
| 2.53125
| 3
|
[] |
no_license
|
//
// newsFeedPresenterController.swift
// chat2
//
// Created by Shivansh Mishra on 26/12/17.
// Copyright © 2017 Shivansh Mishra. All rights reserved.
//
import UIKit
import Firebase
class newsFeedPresenterController: UICollectionViewController, UICollectionViewDelegateFlowLayout{
let cellID:String = "cellID"
var feedInformation = [newsFeed]()
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView?.backgroundColor = .white
self.collectionView?.register(newsFeedCells.self, forCellWithReuseIdentifier: cellID)
collectionView?.alwaysBounceVertical = true
loadingFeeds()
}
func loadingFeeds(){
let ref = Database.database().reference().child("newsFeed")
ref.observe(.childAdded) { (snapshot) in
if let dictionary = snapshot.value as? [String:AnyObject]{
let data = newsFeed()
data.feedInformation = dictionary["description"] as? String
data.heading = dictionary["heading"] as? String
data.imageURL = dictionary["imageURL"] as? String
data.height = dictionary["height"] as? Double
self.feedInformation.append(data)
self.collectionView?.reloadData()
}
}
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
print(feedInformation.count)
return feedInformation.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath) as! newsFeedCells
cell.heading.text = feedInformation[indexPath.item].heading
cell.details.text = feedInformation[indexPath.item].feedInformation
cell.image.loadingImageUsingCache(imageLocation: URL(string: feedInformation[indexPath.item].imageURL!))
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let descriptionString = (feedInformation[indexPath.item].description)
let size = CGSize(width: collectionView.frame.width, height: 10000)
let rectangle = NSString(string: feedInformation[indexPath.item].feedInformation!).boundingRect(with: size, options: .usesLineFragmentOrigin , attributes: [NSAttributedStringKey.font:UIFont.systemFont(ofSize: 15.5)], context: nil)
let heightAdjustment = CGFloat(feedInformation[indexPath.item].height!)
return CGSize(width: collectionView.frame.width, height: rectangle.height + heightAdjustment - 250)
}
}
| true
|
78d6a809dda09c5f92bb932e33addc4f14c9b4a6
|
Swift
|
gerardgine/swift-store-checker
|
/swift-store-checker/api.swift
|
UTF-8
| 1,833
| 2.890625
| 3
|
[] |
no_license
|
//
// agent.swift
// swift-store-checker
//
// Created by Gerard Giné on 1/4/20.
// Copyright © 2020 Gerard Giné. All rights reserved.
//
import Foundation
import Combine
struct Agent {
struct Response<T> {
let value: T
let response: URLResponse
}
func run<T: Decodable>(_ request: URLRequest, _ decoder: JSONDecoder = JSONDecoder()) -> AnyPublisher<Response<T>, Error> {
return URLSession.shared
.dataTaskPublisher(for: request)
.tryMap { result -> Response<T> in
// TODO: Check what to do on unsuccessful requests: the decoder will fail!
let value = try decoder.decode(T.self, from: result.data)
return Response(value: value, response: result.response)
}
// .receive(on: DispatchQueue.main)
.eraseToAnyPublisher()
}
}
enum AppleRetailAPI {
static let agent = Agent()
static let base = URL(string: "https://www.apple.com/shop/retail")!
static func run<T: Decodable>(_ request: URLRequest) -> AnyPublisher<T, Error> {
return agent.run(request)
.map(\.value)
.eraseToAnyPublisher()
}
static func pickup(store: RetailStore, product: Product) -> AnyPublisher<Agent.Response<PickupMessage>, Error> {
// We ended up not using AppleRetailAPI.run() because we want both the decoded value and the urlResponse
// return run(URLRequest(url: URL(string: "\(base.absoluteString)/pickup-message?parts.0=\(product.partNumber.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!)&store=\(store.code)")!))
return agent.run(URLRequest(url: URL(string: "\(base.absoluteString)/pickup-message?parts.0=\(product.partNumber.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!)&store=\(store.code)")!))
}
}
| true
|
aa31c005e228e581a0c40923cacd6a05aef80da8
|
Swift
|
Skriponj/MovieBrowser
|
/MovieBrowser/Scenes/MovieList/MovieListPresenter.swift
|
UTF-8
| 5,449
| 2.84375
| 3
|
[] |
no_license
|
//
// MovieListPresenter.swift
// MovieBrowser
//
// Created by Anton Skrypnik on 29.09.2020.
//
import Foundation
protocol MovieListView: class {
func showApiError(title: String?, message: String?)
func refreshMovieList()
func addItemsForNextPageAt(indexPaths: [IndexPath])
}
protocol MovieListPresenter {
var movies: [Movie] { get }
func viewDidLoad()
func viewWillAppear()
func getMovieList()
func loadNextPage()
func getMoviePosterForItemAt(indexPath: IndexPath, completion: @escaping (Data?) -> Void)
func cancelDownloadPosterImageForItemAt(indexPath: IndexPath)
func didSelectItemAt(indexPath: IndexPath)
func loadNextPageIfNeeded(lastItemIndex: Int)
}
class AppMovieListPresenter: MovieListPresenter {
enum UseCase {
case downloadPosterUseCase(DownloadMoviePosterUseCase)
case cancelPosterDownload(CancelPosterDownloadUseCase)
case getMovieListUseCase(GetMovieUseCase)
case fetchFavoriteMoviesUseCase(FetchFavoriteMoviesUseCase)
}
private weak var view: MovieListView?
private var getMovieListUseCase: GetMovieUseCase?
private var downloadMoviePosterUseCase: DownloadMoviePosterUseCase?
private var cancelDownloadPosterUseCase: CancelPosterDownloadUseCase?
private var fetchFavoriteMoviesUseCase: FetchFavoriteMoviesUseCase?
private var sceneCoordinator: SceneCoordinator?
private var currentPage: Int = 1
private let isFaforiteList: Bool
private var moviesResponse: MoviesResponse?
private var isNextPageRequest: Bool = false
var movies: [Movie] = []
init(view: MovieListView, useCases: [UseCase], sceneCoordinator: SceneCoordinator?, isFaforiteList: Bool = false) {
self.view = view
self.sceneCoordinator = sceneCoordinator
self.isFaforiteList = isFaforiteList
useCases.forEach { (useCase) in
switch useCase {
case .cancelPosterDownload(let useCase):
cancelDownloadPosterUseCase = useCase
case .downloadPosterUseCase(let useCase):
downloadMoviePosterUseCase = useCase
case .getMovieListUseCase(let useCase):
getMovieListUseCase = useCase
case .fetchFavoriteMoviesUseCase(let useCase):
fetchFavoriteMoviesUseCase = useCase
}
}
}
func viewDidLoad() {
getMovieList()
}
func viewWillAppear() {
if isFaforiteList {
getMovieList()
}
}
func loadNextPage() {
guard let moviesResponse = self.moviesResponse,
currentPage < moviesResponse.totalPages else {
return
}
currentPage += 1
getMovieList()
}
func getMovieList() {
if isFaforiteList {
loadFavoriteMoviesFromDB()
return
}
getMovieListUseCase?.getMovieList(page: currentPage) { [weak self] (result) in
switch result {
case .success(let movieResponse):
self?.handleSuccessApiResponse(movieResponse)
case .failure(let error):
self?.handleApiError(error)
}
}
}
func getMoviePosterForItemAt(indexPath: IndexPath, completion: @escaping (Data?) -> Void) {
let movie = movies[indexPath.item]
let path = movie.posterPath
let cacheKey = ImageCacheKey(value: movie.id)
downloadMoviePosterUseCase?.downloadPoster(path: path, cacheKey: cacheKey.key) {
(result) in
switch result {
case .success(let imageData):
completion(imageData)
case .failure(_):
completion(nil)
}
}
}
func cancelDownloadPosterImageForItemAt(indexPath: IndexPath) {
let movie = movies[indexPath.item]
let cacheKey = ImageCacheKey(value: movie.id)
cancelDownloadPosterUseCase?.cancelDownload(for: cacheKey.key)
}
func didSelectItemAt(indexPath: IndexPath) {
let movie = movies[indexPath.item]
sceneCoordinator?.transition(to: .movieDetails(movie), transitionType: .push)
}
func loadNextPageIfNeeded(lastItemIndex: Int) {
if lastItemIndex == movies.count - 1 {
isNextPageRequest = true
loadNextPage()
}
}
}
private extension AppMovieListPresenter {
func handleSuccessApiResponse(_ movieResponse: MoviesResponse) {
self.moviesResponse = movieResponse
let moviesCount = movies.count
movies.append(contentsOf: movieResponse.movies)
if isNextPageRequest {
let newItems = (moviesCount..<movies.count).map { IndexPath(item: $0, section: 0) }
view?.addItemsForNextPageAt(indexPaths: newItems)
isNextPageRequest = false
return
}
view?.refreshMovieList()
}
func handleApiError(_ error: ApiError) {
view?.showApiError(title: "Error", message: error.message)
}
func loadFavoriteMoviesFromDB() {
fetchFavoriteMoviesUseCase?.fetchAllFavouriteMovies(completion: { (movies) in
print(movies)
self.moviesResponse = MoviesResponse(page: 1, totalPages: 1, movies: movies)
self.movies = movies
self.view?.refreshMovieList()
})
}
}
| true
|
12ca9eab85b193c597f04e88296a411e7f6b94ca
|
Swift
|
huy-le/hippo
|
/Hippo/Hippo/Screens/Camera/RecordButton.swift
|
UTF-8
| 5,950
| 2.515625
| 3
|
[] |
no_license
|
//
// RecordButton.swift
// Hippo
//
// Created by Huy Le on 20/7/17.
// Copyright © 2017 Huy Le. All rights reserved.
//
import UIKit
final class RecordButton: UIButton {
lazy private var circleLayer: CAShapeLayer = self.lazy_circleLayer()
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
override func layoutSubviews() {
super.layoutSubviews()
}
var disposedBag: [NSKeyValueObservation] = []
private var isAnimated: Bool = false
private func setupView() {
setBackgroundImage(Style.MyAsset.record_button_outer.image, for: .normal)
adjustsImageWhenHighlighted = false
tintColor = .clear
setTitle(nil, for: .normal)
observe(\.isTracking) { (_, changed) in
if self.isHighlighted == false && self.isSelected == false {
self.circleLayer.add(Animation().path(to: self.highlightedCirclePath()), forKey: nil)
}
if self.isHighlighted == false && self.isSelected == true {
self.circleLayer.add(Animation().path(to: self.highlightedSquarePath()), forKey: nil)
}
}.dispose(by: &disposedBag)
observe(\.isSelected) { (_, changed) in
print(self.isSelected)
if self.isSelected {
self.circleLayer.add(Animation().path(to: self.selectedSquarePath()), forKey: nil)
self.circleLayer.fillColor = Style.RecordButton.selectedColor.cgColor
} else {
self.circleLayer.add(Animation().path(to: self.normalCirclePath()), forKey: nil)
self.circleLayer.fillColor = Style.RecordButton.normalColor.cgColor
}
}.dispose(by: &disposedBag)
layer.addSublayer(circleLayer)
}
private func lazy_circleLayer() -> CAShapeLayer {
let layer = CAShapeLayer()
layer.fillColor = Style.RecordButton.normalColor.cgColor
layer.path = normalCirclePath()
return layer
}
private func normalCirclePath() -> CGPath {
let bezier = CirclePath(center: CGPoint(x: self.bounds.width / 2, y: self.bounds.height / 2),
radius: (self.bounds.width / 2) - 7).bezierPath()
return bezier.cgPath
}
private func highlightedCirclePath() -> CGPath {
let bezier = CirclePath(center: CGPoint(x: self.bounds.width / 2, y: self.bounds.height / 2),
radius: (self.bounds.width / 2) - 10).bezierPath()
return bezier.cgPath
}
private func selectedSquarePath() -> CGPath {
let bezier = SquarePath(center: CGPoint(x: self.bounds.width / 2, y: self.bounds.height / 2), side: 28).bezierPath()
return bezier.cgPath
}
private func highlightedSquarePath() -> CGPath {
let bezier = SquarePath(center: CGPoint(x: self.bounds.width / 2, y: self.bounds.height / 2), side: 24).bezierPath()
return bezier.cgPath
}
}
struct CirclePath {
let center: CGPoint
let radius: CGFloat
func bezierPath() -> UIBezierPath {
let circlePath = UIBezierPath()
circlePath.addArc(withCenter: center, radius: radius, startAngle: -.pi, endAngle: -.pi/2, clockwise: true)
circlePath.addArc(withCenter: center, radius: radius, startAngle: -.pi/2, endAngle: 0, clockwise: true)
circlePath.addArc(withCenter: center, radius: radius, startAngle: 0, endAngle: .pi/2, clockwise: true)
circlePath.addArc(withCenter: center, radius: radius, startAngle: .pi/2, endAngle: .pi, clockwise: true)
circlePath.close()
return circlePath
}
}
struct SquarePath {
let center: CGPoint
let side: CGFloat
let radius: CGFloat = 4
private var halfSide: CGFloat {
return side / 2
}
func bezierPath() -> UIBezierPath {
let squarePath = UIBezierPath()
let beforeUpperLeftArc: CGPoint = CGPoint(x: center.x - halfSide, y: center.y - halfSide + radius)
let beforeUpperRightArc: CGPoint = CGPoint(x: center.x + halfSide - radius, y: center.y - halfSide)
let beforeLowerRightArc: CGPoint = CGPoint(x: center.x + halfSide, y: center.y + halfSide - radius)
let beforeLowerLeftArc: CGPoint = CGPoint(x: center.x - halfSide + radius, y: center.y + halfSide)
var upperLeftArcCenter: CGPoint = beforeUpperLeftArc
var upperRightArcCenter: CGPoint = beforeUpperRightArc
var lowerLeftArcCenter: CGPoint = beforeLowerLeftArc
var lowerRightArcCenter: CGPoint = beforeLowerRightArc
upperLeftArcCenter.x += radius
upperRightArcCenter.y += radius
lowerRightArcCenter.x -= radius
lowerLeftArcCenter.y -= radius
squarePath.addArc(withCenter: upperLeftArcCenter, radius: radius, startAngle: -.pi, endAngle: -1/2 * .pi, clockwise: true)
squarePath.addArc(withCenter: upperRightArcCenter, radius: radius, startAngle: -1/2 * .pi, endAngle: 0, clockwise: true)
squarePath.addArc(withCenter: lowerRightArcCenter, radius: radius, startAngle: 0, endAngle: 1/2 * .pi, clockwise: true)
squarePath.addArc(withCenter: lowerLeftArcCenter, radius: radius, startAngle: 1/2 * .pi, endAngle: .pi, clockwise: true)
squarePath.close()
return squarePath
}
}
struct Animation {
func path(to value: CGPath) -> CABasicAnimation {
let animation = CABasicAnimation(keyPath: "path")
animation.duration = 0.3
animation.toValue = value
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
animation.fillMode = kCAFillModeForwards
animation.isRemovedOnCompletion = false
return animation
}
}
| true
|
602969f7c9cba3ce0adbb72d75bc96119d9afae6
|
Swift
|
RTUITLab/Tele2-iOS-Widget
|
/State/DataReceiving.swift
|
UTF-8
| 3,060
| 2.625
| 3
|
[] |
no_license
|
//
// DataReceiving.swift
// Tele2 Widget
//
// Created by Student on 22.08.2020.
//
enum LolError: Error {
case LolErr
}
import Foundation
struct LimitsLoader {
static func fetch(completion: @escaping(Result<ModelEntry, Error>) -> Void) {
let branchContentsURL = URL(string: "https://35f5d8bc8dc9.ngrok.io/api/widgetapi/entry")!
let task = URLSession.shared.dataTask(with: branchContentsURL) {
(data, response, error) in
guard error == nil else {
completion(.failure(error!))
return
}
do {
let model: ModelEntry
try model = getCommitInfo(fromData: data!)
completion(.success(model))
} catch {
completion(.failure(LolError.LolErr))
}
}
task.resume()
}
static func updateWidgetSettings(completion: @escaping(Result<Int, Error>) -> Void, settings: WidgetSettings) {
let branchContentsURL = URL(string: "https://35f5d8bc8dc9.ngrok.io/api/widgetapi/widget/\(settings.smallType)/\(settings.mediumLeftType)/\(settings.mediumRightType)")!
let task = URLSession.shared.dataTask(with: branchContentsURL) {
(data, response, error) in
guard error == nil else {
completion(.failure(error!))
return
}
completion(.success(0))
}
task.resume()
}
static func getCommitInfo(fromData data: Foundation.Data) throws -> ModelEntry {
let json = try! JSONSerialization.jsonObject(with: data, options: []) as! [String: Any]
let limitsObject = json["limits"] as! [String: Any]
let minutesObject = limitsObject["minutes"] as! [String: Any]
let dataObject = limitsObject["data"] as! [String: Any]
let smsObject = limitsObject["sms"] as! [String: Any]
let phone = limitsObject["phone"] as! String
let balance = limitsObject["balance"] as! String
let minTotal = minutesObject["total"] as! Int
let minLeft = minutesObject["left"] as! Int
let dataTotal = dataObject["total"] as! Int
let dataLeft = dataObject["left"] as! Int
let smsTotal = smsObject["total"] as! Int
let smsLeft = smsObject["left"] as! Int
let settingsObject = json["settings"] as! [String: Any]
let smallType = settingsObject["smallType"] as! String
let mediumLeftType = settingsObject["mediumLeftType"] as! String
let mediumRightType = settingsObject["mediumRightType"] as! String
let offer = json["offer"] as! String
return ModelEntry(limits: Limits(phone: phone, balance: balance, minutes: Limit(total: minTotal, left: minLeft), data: Limit(total: dataTotal, left: dataLeft), sms: Limit(total: smsTotal, left: smsLeft)), settings: WidgetSettings(smallType: smallType, mediumLeftType: mediumLeftType, mediumRightType: mediumRightType), offer: offer)
}
}
| true
|
4f2ac6b2888a5602ac74a4c2380712f9e5235713
|
Swift
|
leonjohnson/mealplan_App
|
/MealPlan/MPTableViewCell.swift
|
UTF-8
| 4,498
| 2.640625
| 3
|
[] |
no_license
|
//
// MPTableViewCell.swift
// MealPlan
//
// Created by Leon Johnson on 25/10/2016.
// Copyright © 2016 Meals. All rights reserved.
//
import UIKit
protocol MPTableViewCellDelegate {
// indicates that the given item has been deleted
func editFoodItemAtIndexPath(_ indexPath: IndexPath, editType: String)
}
class MPTableViewCell: UITableViewCell {
@IBOutlet var foodNameLabel : UILabel!
@IBOutlet var foodQuantityLabel : UILabel!
@IBOutlet var foodCaloryLabel : UILabel!
@IBOutlet var mealArrowImage : UIImageView!
var originalCenter = CGPoint()
var deleteOnDragRelease = false
var completeOnDragRelease = false
var tickLabel: UILabel!
var crossLabel: UILabel!
var delegate: MPTableViewCellDelegate? // The object that acts as delegate for this cell.
var foodItemIndexPath: IndexPath? // The item that this cell renders.
override func awakeFromNib() {
// add a pan recognizer
let recognizer = UIPanGestureRecognizer(target: self, action: #selector(MPTableViewCell.handlePan(_:)))
recognizer.delegate = self
addGestureRecognizer(recognizer)
// tick and cross labels for context cues
tickLabel = createCueLabel()
tickLabel.text = "\u{2713}"
tickLabel.textAlignment = .right
addSubview(tickLabel)
crossLabel = createCueLabel()
crossLabel.text = "\u{2717}"
crossLabel.textAlignment = .left
addSubview(crossLabel)
}
// utility method for creating the contextual cues
func createCueLabel() -> UILabel {
let label = UILabel(frame: CGRect.null)
label.textColor = UIColor.white
label.font = UIFont.boldSystemFont(ofSize: 32.0)
label.backgroundColor = UIColor.clear
return label
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
//MARK: - horizontal pan gesture methods
func handlePan(_ recognizer: UIPanGestureRecognizer) {
// 1
if recognizer.state == .began {
// when the gesture begins, record the current center location
originalCenter = center
}
// 2
if recognizer.state == .changed {
let translation = recognizer.translation(in: self)
center = CGPoint(x: originalCenter.x + translation.x, y: originalCenter.y)
// has the user dragged the item far enough to initiate a delete/complete?
deleteOnDragRelease = frame.origin.x < -frame.size.width / 2.0
completeOnDragRelease = frame.origin.x > frame.size.width / 2.0
}
// 3
if recognizer.state == .ended {
// the frame this cell had before user dragged it
let originalFrame = CGRect(x: 0, y: frame.origin.y,
width: bounds.size.width, height: bounds.size.height)
if !deleteOnDragRelease {
// if the item is not being deleted, snap back to the original location
UIView.animate(withDuration: 0.2, animations: {self.frame = originalFrame})
}
if deleteOnDragRelease {
if delegate != nil && foodItemIndexPath != nil {
// notify the delegate that this item should be deleted
delegate!.editFoodItemAtIndexPath(foodItemIndexPath!, editType: Constants.DELETE)
}
}
else if completeOnDragRelease {
if foodItemIndexPath != nil {
delegate!.editFoodItemAtIndexPath(foodItemIndexPath!, editType: Constants.EDIT)
}
UIView.animate(withDuration: 0.2, animations: {self.frame = originalFrame})
} else {
UIView.animate(withDuration: 0.2, animations: {self.frame = originalFrame})
}
}
}
override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
if let panGestureRecognizer = gestureRecognizer as? UIPanGestureRecognizer {
let translation = panGestureRecognizer.translation(in: superview!)
if fabs(translation.x) > fabs(translation.y) {
return true
}
return false
}
return false
}
}
| true
|
4fcd7332fb9c852e090ace78ba21393241d93323
|
Swift
|
kostaslei/Virtual-Tourist
|
/Virtual Tourist/Model/FlickerClient/FlickerClient.swift
|
UTF-8
| 4,736
| 3.078125
| 3
|
[] |
no_license
|
//
// FlickerClient.swift
// Virtual Tourist
//
// Created by Kostas Lei on 29/04/2021.
//
import Foundation
import CoreData
import UIKit
class FlickerClient {
// ENDPOINTS ENUM: Stores all of my urls as strings and then it transforms them to URL type
enum Endpoints{
static let key = "&api_key=11ae8dc296220a7263ae248d40d615df"
static let baseSearch = "https://www.flickr.com/services/rest"
static let searchPhotoMethod = "/?method=flickr.photos.search"
static let searchPhotoMethodEnd = "&radius=5&format=json&nojsoncallback=1"
case searchPhoto(Double,Double, Int)
case downloadPhoto(String, String, String)
var stringValue:String {
switch self {
case .searchPhoto(let lat, let lon, let page): return (Endpoints.baseSearch + Endpoints.searchPhotoMethod + Endpoints.key + "&lat=\(lat)" + "&lon=\(lon)" + "&page=\(page)" + Endpoints.searchPhotoMethodEnd)
case .downloadPhoto(let server, let id, let secret): return "https://live.staticflickr.com/\(server)/\(id)_\(secret)_w.jpg"
}
}
// Make url's from strings
var url: URL{
return URL(string: stringValue)!
}
}
// TASK_FOR_GET_REQUEST FUNC: It communicates with a given url and return the
// data with a completion handler
@discardableResult class func taskForGETRequest<ResponseType:Decodable>(url:URL, response:ResponseType.Type, completion: @escaping (ResponseType?, Error?) -> Void) -> URLSessionTask{
let task = URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data else {
DispatchQueue.main.async{
completion(nil, error)
}
return
}
let decoder = JSONDecoder()
do {
let responseObject = try decoder.decode(ResponseType.self, from: data)
DispatchQueue.main.async {
completion(responseObject, nil)
}
} catch {
do{
let errorResponse = try decoder.decode(ErrorResponse.self, from: data)
DispatchQueue.main.async {
completion(nil,errorResponse)
}
} catch {
DispatchQueue.main.async{
completion(nil, error)}
}
}
}
task.resume()
return task
}
// Downloads and stores the photos
class func downloadPhotos(dataController: DataController, pin: Pin, noImagesLabel: UILabel, pageNumber: Int) {
FlickerClient.taskForGETRequest(url: FlickerClient.Endpoints.searchPhoto(pin.latitude, pin.longitude, pageNumber).url, response: SearchPhotosResponse.self) { response, error in
let backgroundContext:NSManagedObjectContext! = dataController.backgroundContext
let pinID = pin.objectID
if let response = response{
// If there are photos for the given location
if response.photos.photo.count > 0 {
// Download and store photos on a background thread
backgroundContext.perform {
// Makes an instance of the pin using the id, stores number of pages, download status and the photos
let backgroundPin = backgroundContext.object(with: pinID) as! Pin
backgroundPin.pages = Int16(response.photos.pages)
backgroundPin.downloadStatus = true
for i in response.photos.photo {
let photo = Photo(context: dataController.backgroundContext)
let url = FlickerClient.Endpoints.downloadPhoto(i.server, i.id, i.secret).url
if let data = try? Data(contentsOf: url) {
// Create Image and Update Image View
photo.img = data
photo.pin = backgroundPin
}
try? backgroundContext.save()
}
backgroundPin.downloadStatus = false
try? backgroundContext.save()
}
}
// If there are no photos for this location
else{
noImagesLabel.isHidden = false
}
}
else {
print("Error", fatalError())
}
}
}
}
| true
|
036bf736b6f4c31cebd9c380c548a19402cd31c2
|
Swift
|
smarus/stepik-ios
|
/ExamEGERussian/Sources/BusinessLogicLayer/Services/UserRegistrationService/UserRegistrationService.swift
|
UTF-8
| 1,718
| 2.765625
| 3
|
[] |
no_license
|
//
// UserRegistrationService.swift
// ExamEGERussian
//
// Created by Ivan Magda on 03/07/2018.
// Copyright © 2018 Alex Karpov. All rights reserved.
//
import Foundation
import PromiseKit
enum UserRegistrationServiceError: Error {
case notRegistered
case notLoggedIn
case noProfileFound
case notUnregisteredFromEmails
}
struct UserRegistrationParams {
let firstname: String
let lastname: String
let email: String
let password: String
}
protocol UserRegistrationService {
/// Register new user.
///
/// - Parameter params: User registration parameters contains of:
/// - firstname
/// - lastname
/// - email
/// - password
/// - Returns: Promise object with tuple of email and password.
func register(with params: UserRegistrationParams) -> Promise<(email: String, password: String)>
/// Signs user into account.
///
/// - Parameters:
/// - email: User email address.
/// - password: User account password.
/// - Returns: Signed in user account.
func signIn(email: String, password: String) -> Promise<User>
/// Unregister user from email list notifications.
///
/// - Parameter user: User to remove from email notifications.
/// - Returns: Updated User object.
func unregisterFromEmail(user: User) -> Promise<User>
/// Sequentially performs registration and sign in actions.
///
/// - Parameter params: User registration parameters contains of:
/// - firstname
/// - lastname
/// - email
/// - password
/// - Returns: Returns Promise object with newly registered User object.
func registerAndSignIn(with params: UserRegistrationParams) -> Promise<User>
}
| true
|
9922d88cbf319ed24a796b6d9df11d1ff19ffb94
|
Swift
|
juanpahernan/MLItems
|
/LibraryComponents/Classes/MLABMTitlesViewController/MLABMTitlesViewController.swift
|
UTF-8
| 3,071
| 2.75
| 3
|
[
"MIT"
] |
permissive
|
//
// MLABMTitlesViewController.swift
// MLItems
//
// Created by Juan Pablo Hernandez on 14/04/2021.
//
import UIKit
class MLABMTitlesViewController: UIViewController {
static let titleKey = "Title"
static let subtitleKey = "Subtitle"
static let priceKey = "Price"
static let descKey = "Descriptions"
static let imageKey = "Image"
@IBOutlet private var nextButton: UIButton!
@IBOutlet private var prevButton: UIButton!
@IBOutlet private var addItemButton: UIButton!
@IBOutlet private var contentView: UIView!
private var defaults: UserDefaults?
private var stepsArray = [String]()
private var step = 0
override func viewDidLoad() {
super.viewDidLoad()
initializeArray()
defaults = UserDefaults.standard
if #available(iOS 11.0, *){navigationItem.backButtonTitle = "Back"}
}
@IBAction func nextButtonPressed(sender: UIButton) {
saveUserDefaults()
nextStep()
}
@IBAction func prevButtonPressed(sender: UIButton) {
saveUserDefaults()
prevStep()
}
@IBAction func addItemButtonPressed(sender: UIButton) {
createViewWithText(stepsArray[step])
nextButton.isHidden = false
addItemButton.isHidden = true
}
private func initializeArray() {
stepsArray.append(MLABMTitlesViewController.titleKey)
stepsArray.append(MLABMTitlesViewController.subtitleKey)
stepsArray.append(MLABMTitlesViewController.priceKey)
stepsArray.append(MLABMTitlesViewController.descKey)
}
private func nextStep() {
step += 1
prevButton.isHidden = false
if (step < stepsArray.count){
createViewWithText(stepsArray[step])
} else {
self.step = stepsArray.count - 1
navigateNextController()
}
}
private func prevStep() {
step -= 1
if (step == 0) { prevButton.isHidden = true }
if (step < 0) { step = 0 }
else { createViewWithText(stepsArray[step]) }
}
private func createViewWithText(_ text: String) {
if (contentView.subviews.count > 0) {
contentView.subviews.first?.removeFromSuperview()
}
let titleView = MLTitleView(frame: contentView.bounds)
titleView.titleLabel.text = text
titleView.titleTextField.placeholder = text
if (text == "Price") {
titleView.titleTextField.keyboardType = .decimalPad
}
titleView.titleTextField.text = defaults?.string(forKey: text)
contentView.addSubview(titleView)
}
private func navigateNextController() {
let controller = MLABMImageUploadViewController()
navigationController?.pushViewController(controller, animated: true)
}
private func saveUserDefaults() {
let mlTitleView = contentView.subviews.first as! MLTitleView
let textFieldText = mlTitleView.titleTextField.text
defaults?.setValue(textFieldText, forKey: stepsArray[step])
}
}
| true
|
25e1cc0587a20614ef53fbef31c6387d13a7ab31
|
Swift
|
eskimo/SimpleBattery
|
/SimpleBattery WatchKit Extension/ComplicationController.swift
|
UTF-8
| 2,929
| 2.5625
| 3
|
[] |
no_license
|
//
// ComplicationController.swift
// SimpleBattery WatchKit Extension
//
// Created by Jordan Koch on 3/2/19.
// Copyright © 2019 Jordan Koch. All rights reserved.
//
import WatchKit
import ClockKit
class ComplicationController: NSObject, CLKComplicationDataSource {
// MARK: - Timeline Configuration
func getSupportedTimeTravelDirections(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTimeTravelDirections) -> Void) {
//handler([.forward, .backward])
handler([])
}
func getTimelineStartDate(for complication: CLKComplication, withHandler handler: @escaping (Date?) -> Void) {
handler(nil)
}
func getTimelineEndDate(for complication: CLKComplication, withHandler handler: @escaping (Date?) -> Void) {
handler(nil)
}
func getPrivacyBehavior(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationPrivacyBehavior) -> Void) {
handler(.showOnLockScreen)
}
// MARK: - Timeline Population
func getCurrentTimelineEntry(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTimelineEntry?) -> Void) {
// Call the handler with the current timeline entry
let device = WKInterfaceDevice.current()
device.isBatteryMonitoringEnabled = true
let battery = device.batteryLevel
let theTemplate = CLKComplicationTemplateUtilitarianSmallFlat()
theTemplate.textProvider = CLKSimpleTextProvider(text: String(format: "%.0f", (battery * 100))+"%")
let entry = CLKComplicationTimelineEntry(date: Date(), complicationTemplate: theTemplate)
handler(entry)
}
func getTimelineEntries(for complication: CLKComplication, before date: Date, limit: Int, withHandler handler: @escaping ([CLKComplicationTimelineEntry]?) -> Void) {
// Call the handler with the timeline entries prior to the given date
handler(nil)
}
func getTimelineEntries(for complication: CLKComplication, after date: Date, limit: Int, withHandler handler: @escaping ([CLKComplicationTimelineEntry]?) -> Void) {
// Call the handler with the timeline entries after to the given date
handler(nil)
}
// MARK: - Placeholder Templates
func getLocalizableSampleTemplate(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTemplate?) -> Void) {
// This method will be called once per supported complication, and the results will be cached
switch complication.family {
case .utilitarianSmall:
let theTemplate = CLKComplicationTemplateUtilitarianSmallFlat()
theTemplate.textProvider = CLKSimpleTextProvider(text: "50%")
handler(theTemplate)
default:
handler(nil)
}
}
}
| true
|
36406f91cdc3c248b2e3f80324ba6045c26008c1
|
Swift
|
hiawc/fakeTwitter
|
/fakeTwitter/TweetViewController.swift
|
UTF-8
| 2,491
| 2.546875
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// TweetViewController.swift
// fakeTwitter
//
// Created by Nhat Truong on 3/26/16.
// Copyright © 2016 Nhat Truong. All rights reserved.
//
import UIKit
import BDBOAuth1Manager
class TweetViewController: UIViewController {
let POSTString = "1.1/statuses/update.json"
var user: User?
var tweetID: String!
var replyView = true
@IBOutlet weak var profileImg: UIImageView!
@IBOutlet weak var screenname: UILabel!
@IBOutlet weak var username: UILabel!
@IBAction func onCancel(sender: AnyObject) {
dismissViewControllerAnimated(true, completion: nil)
}
@IBOutlet weak var tweetView: UITextView!
@IBAction func sendTweet(sender: AnyObject) {
var params = [String: AnyObject]()
if replyView == true {
params["status"] = tweetView.text
params["in_reply_to_status_id"] = tweetID
} else {
params["status"] = tweetView.text
params["in_reply_to_status_id"] = ""
}
TwitterClient.sharedInstance.POST(self.POSTString, parameters: params , success: { (task: NSURLSessionDataTask, response: AnyObject?) in
self.dismissViewControllerAnimated(true, completion: nil)
}) { (task: NSURLSessionDataTask?, error: NSError) in
print("error \(error.localizedDescription)")
}
}
override func viewDidLoad() {
super.viewDidLoad()
username.text = ""
screenname.text = ""
if replyView == true {
navigationItem.title = "Reply"
} else {
navigationItem.title = "Tweet"
}
TwitterClient.sharedInstance.currentAccount({ (user: User) in
self.user = user
let imgUrl = self.user?.profileUrl
if imgUrl == nil {
self.profileImg.image = nil
} else {
self.profileImg.setImageWithURL(imgUrl!)
}
self.username.text = self.user?.name as? String
let screen_name = self.user?.screenname as? String
if screen_name == nil {
self.screenname.text = ""
} else {
self.screenname.text = "@\(screen_name!)"
}
}) { (error: NSError) in
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| true
|
741fde9932ba5c9bbf479a064b641d8bf6f7a89f
|
Swift
|
JackShort/LYK
|
/LYK/NFCollectionCell.swift
|
UTF-8
| 1,159
| 2.640625
| 3
|
[] |
no_license
|
//
// NFCollectionCell.swift
// LYK
//
// Created by Jack Short on 2/19/17.
// Copyright © 2017 Jack Short. All rights reserved.
//
import Foundation
import UIKit
class NFCollectionCell: UICollectionViewCell {
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var likePhotoButton: UIButton!
var color: UIColor!
var photos: [UIImage]!
override func layoutSubviews() {
super.layoutSubviews()
self.imageView.layer.borderWidth = 2
self.imageView.layer.borderColor = UIColor.flatWhite().cgColor
self.imageView.layer.masksToBounds = true
self.imageView.layer.cornerRadius = self.imageView.frame.size.height / 2
}
func setColor(color: UIColor) {
self.backgroundColor = color
self.color = color
}
func setPhotos(photos: [UIImage]) {
self.photos = photos
self.imageView.image = self.photos.last
}
@IBAction func liked(_ sender: Any) {
self.likePhotoButton.setImage(UIImage(named: "liked"), for: .normal)
}
}
| true
|
581cfca90c4c9ab1cd6e56b86985aa35ccd13329
|
Swift
|
mavfarm/Satin
|
/Example/Shared/Math.swift
|
UTF-8
| 1,857
| 3.65625
| 4
|
[
"MIT"
] |
permissive
|
//
// Math.swift
//
// Created by Colin Duffy on 10/11/19.
// Copyright © 2019 Mav Farm. All rights reserved.
//
import Foundation
///
/// Doubles
///
func toRad(value:Double) -> Double {
return value * (Double.pi / 180.0)
}
func clamp(value:Double, minimum:Double, maximum:Double) -> Double {
return min(maximum, max(minimum, value))
}
func lerp(value:Double, minimum:Double, maximum:Double) -> Double {
return minimum * (1.0 - value) + maximum * value;
}
func normalize(value:Double, minimum:Double, maximum:Double) -> Double {
return(value - minimum) / (maximum - minimum);
}
func map(value:Double, minimum1:Double, maximum1:Double, minimum2:Double, maximum2:Double) -> Double {
return lerp(
value: normalize(value: value, minimum: minimum1, maximum: maximum1),
minimum: minimum2,
maximum: maximum2
)
}
func cosRange(value:Double, range:Double, minValue:Double) -> Double {
return (((1.0 + cos(toRad(value: value))) * 0.5) * range) + minValue;
}
///
/// Floats
///
func toRad(value:Float) -> Float {
return value * (Float.pi / 180.0)
}
func clamp(value:Float, minimum:Float, maximum:Float) -> Float {
return min(maximum, max(minimum, value))
}
func lerp(value:Float, minimum:Float, maximum:Float) -> Float {
return minimum * (1.0 - value) + maximum * value;
}
func normalize(value:Float, minimum:Float, maximum:Float) -> Float {
return(value - minimum) / (maximum - minimum);
}
func map(value:Float, minimum1:Float, maximum1:Float, minimum2:Float, maximum2:Float) -> Float {
return lerp(
value: normalize(value: value, minimum: minimum1, maximum: maximum1),
minimum: minimum2,
maximum: maximum2
)
}
func cosRange(value:Float, range:Float, minValue:Float) -> Float {
return (((1.0 + cos(toRad(value: value))) * 0.5) * range) + minValue;
}
| true
|
ef229afa6d6502556d2975382a03195894500e40
|
Swift
|
rintos/moviesDB
|
/moviesDB/Utils/ErrorManager.swift
|
UTF-8
| 491
| 2.625
| 3
|
[] |
no_license
|
//
// ErrorManager.swift
// moviesDB
//
// Created by Victor Soares de Almeida on 03/02/20.
// Copyright © 2020 Victor Soares de Almeida. All rights reserved.
//
import UIKit
class ErrorManager: NSObject {
static func createAnError(domain: String = "Movie", code: Int, message: String? = "gerou erro" ) -> NSError {
let userInfo: [String: Any] = [
NSLocalizedDescriptionKey: message!
]
return NSError(domain: domain, code: 500, userInfo: userInfo)
}
}
| true
|
eaecaafa5112e09c7b94e14f89d25f737fda5457
|
Swift
|
azuiev/Kuna
|
/Kuna/Source/Models/CurrenciesModel/CurrenciesModel.swift
|
UTF-8
| 883
| 2.78125
| 3
|
[] |
no_license
|
//
// CurrenciesModel.swift
// Kuna
//
// Created by Aleksey Zuiev on 14/02/2018.
// Copyright © 2018 Aleksey Zuiev. All rights reserved.
//
import Foundation
import RealmSwift
class CurrencyiesModel {
// MARK: Private Properties
private var currencies: [String : CurrencyModel] = [:]
// MARK: Initialization
static let shared = CurrencyiesModel(CurrencyModel.loadProperty())
private init(_ currencies: [CurrencyModel]) {
for currency in currencies {
self.currencies[currency.code] = currency
}
}
// Public Methods
func getCurrency(with code: String) -> CurrencyModel {
if let result = self.currencies[code] {
return result
}
let currency = CurrencyModel(code: code)
self.currencies[code] = currency
return currency
}
}
| true
|
9987e8f7265a75a48a2c6a05ee6721213ed05ac4
|
Swift
|
wonhee009/Algorithm
|
/bin/Programmers/GetMiddleStringSwift.swift
|
UTF-8
| 358
| 2.671875
| 3
|
[] |
no_license
|
func solution(_ s:String) -> String {
var result: String = ""
if(s.count % 2 == 0) {
result.append(s[s.index(s.startIndex, offsetBy: s.count / 2 - 1)])
result.append(s[s.index(s.startIndex, offsetBy: s.count / 2)])
}
else {
result.append(s[s.index(s.startIndex, offsetBy: s.count / 2)])
}
return result
}
| true
|
93ddd6f1176a1fe12f5017cc71de593036fd903b
|
Swift
|
chinmaysukhadia/aboutMe360
|
/AboutMe360/Modules/Notification/View/View&Cell/NotificationCell.swift
|
UTF-8
| 2,956
| 2.546875
| 3
|
[] |
no_license
|
//
// NotificationCell.swift
// AboutMe360
//
// Created by Himanshu Pal on 17/09/19.
// Copyright © 2019 Appy. All rights reserved.
//
import UIKit
protocol NotificationCellDelegate: class {
func didTapAcceptNotificationCell(cell: NotificationCell)
func didTapDeclinNotificationCell(cell: NotificationCell)
}
class NotificationCell: BaseTableViewCell {
//MARK: - IBOUtlets
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var ratedLabel: UILabel!
@IBOutlet weak var profileImageView: UIImageView!
@IBOutlet weak var acceptButton: UIButton!
@IBOutlet weak var declineButton: UIButton!
@IBOutlet weak var buttonView : UIView!
@IBOutlet weak var bgView: UIView!
@IBOutlet weak var statusLabel: UILabel!
var delegate: NotificationCellDelegate?
//MARK: - Life Cycle
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
bgView.roundCorners(10)
profileImageView.roundCorners(4)
bgView.setViewShadow(color: UIColor.gray, cornerRadius: 10, shadowRadius: 2, shadowOpacity: 0.3)
declineButton.roundCorners(10)
acceptButton.roundCorners(10)
declineButton.makeLayer(color: .red, boarderWidth: 1, round: 10)
// Configure the view for the selected state
}
//MARK: - Public Methods
func configureCell(cellData: NotifiData) {
nameLabel.text = cellData.name
if let profileIgm = cellData.pimg {
self.profileImageView.setImage(urlStr:profileIgm, placeHolderImage: UIImage(named: "Blank"))
}
if cellData.isAcceptable == false {
self.buttonView.isHidden = true
self.statusLabel.isHidden = true
} else {
if cellData.status == "1" {
self.buttonView.isHidden = true
self.statusLabel.isHidden = false
self.statusLabel.text = StringConstants.accepted
self.statusLabel.textColor = color.appBlueColor
} else if cellData.status == "2" {
self.buttonView.isHidden = true
self.statusLabel.isHidden = false
self.statusLabel.textColor = UIColor.red
self.statusLabel.text = StringConstants.declined
} else {
self.buttonView.isHidden = false
self.statusLabel.isHidden = true
}
}
}
@IBAction func acceptTapped(_ sender: Any) {
if let delegate = delegate {
delegate.didTapAcceptNotificationCell(cell: self)
}
}
@IBAction func decineTapped(_ sender: Any) {
if let delegate = delegate {
delegate.didTapDeclinNotificationCell(cell: self)
}
}
}
| true
|
45a89a004f582c5d0bbf53a5b5db982b2f033f4b
|
Swift
|
confusionhill/TodayWIshlist
|
/TodayWIshlist/ItemView.swift
|
UTF-8
| 2,660
| 2.84375
| 3
|
[] |
no_license
|
//
// ItemView.swift
// TodayWIshlist
//
// Created by Farhandika Zahrir Mufti guenia on 03/06/21.
//
import SwiftUI
struct ItemView: View {
var price:Float = 999.99
var name:String = "Lorem Ipsum DUi Amet minum Amer di Kubus"
var desc:String = ""
var imeg:String = "https://fakestoreapi.com/img/81fPKd-2AYL._AC_SL1500_.jpg"
var body: some View {
ZStack{
Color(customcolor).ignoresSafeArea()
ScrollView(showsIndicators:false) {
VStack{
//Mark : Image View
ImageView(imeg: imeg)
.padding(.bottom)
// Name and Price View
NameAndPrice(price: price,name: name)
.padding(.bottom)
//DescriptionView
Description(isiDesc: desc)
//.navigationTitle("Fjall Raven - Foldsack No.1 Backpack, fits 15 laptops")
//.navigationBarTitleDisplayMode(.large)
//. navigationBarHidden(true)
Spacer()
}
}
}
}
}
struct ItemView_Previews: PreviewProvider {
static var previews: some View {
ItemView()
}
}
struct NameAndPrice: View {
var price:Float
var name:String
var body: some View {
RoundedRectangle(cornerRadius: 15)
.foregroundColor(.white)
.padding(.horizontal)
.frame(height:80)
.overlay(
HStack{
Text(name)
.foregroundColor(.black)
.font(.headline)
.multilineTextAlignment(.leading)
.frame(width:UIScreen.width-200,height: 60)
.padding(.horizontal)
Spacer()
Text("$\(String(format: "%.2f", price))")
.fontWeight(.semibold)
.padding()
.foregroundColor(.green)
}.padding()
)
}
}
struct ImageView: View {
var imeg:String = "https://fakestoreapi.com/img/81fPKd-2AYL._AC_SL1500_.jpg"
var body: some View {
RoundedRectangle(cornerRadius: 15)
.foregroundColor(.white)
.padding(.horizontal)
.frame(height:UIScreen.width)
.overlay(VStack{
RemoteImage(url: imeg)
.aspectRatio(contentMode: .fit)
/*
.resizable()
.aspectRatio(contentMode: .fit)*/
}.padding()
)
}
}
| true
|
b28a428b30cad0c8021cc2d6c2415b43e38d99e9
|
Swift
|
AbleLHOne/SwiftLeetCode
|
/SwiftLeetCode/SwiftLeetCode/数组/剑指 Offer 29. 顺时针打印矩阵.swift
|
UTF-8
| 1,864
| 3.65625
| 4
|
[] |
no_license
|
//
// 剑指 Offer 29. 顺时针打印矩阵.swift
// SwiftLeetCode
//
// Created by lihao on 2021/1/3.
//
/**
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
示例 2:
输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shun-shi-zhen-da-yin-ju-zhen-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
import Foundation
/*
思路:
→ → → →
↑ ↓
↑ ↓
↑ ← ← ↓
*/
func spiralOrder(_ matrix: [[Int]]) -> [Int] {
if matrix.count <= 1 {
return matrix.first ?? []
}
let maxRow = matrix.count
let maxColumn = matrix[0].count
let maxCount = maxRow * maxColumn
var row = 0
var column = 0
var newArr:[Int] = []
var start = 0
while newArr.count < maxCount {
// 从左到右
while column < maxColumn-start {
newArr.append(matrix[row][column])
column += 1
}
column -= 1
// 从上到下
while row < maxRow-start-1 {
row += 1
newArr.append(matrix[row][column])
}
// 从右到左
while column > start+1 {
column -= 1
newArr.append(matrix[row][column])
}
// 从下到上
if column > start {
column -= 1
while row >= start+1 {
newArr.append(matrix[row][column])
row -= 1
}
}
start += 1
row = start
column = start
}
return newArr
}
| true
|
91dc9414bf3e44129496f4e7f14db5bfad3a6322
|
Swift
|
amanshuraikwar/amanshuraikwar.github.io
|
/project-files/Portfolio/iosApp/iosApp/PrimaryButton.swift
|
UTF-8
| 844
| 3.078125
| 3
|
[] |
no_license
|
//
// PrimaryButton.swift
// iosApp
//
// Created by Amanshu Raikwar on 31/12/21.
// Copyright © 2021 orgName. All rights reserved.
//
import SwiftUI
struct PrimaryButton: View {
let text: String
let action: () -> Void
let iconSystemName: String?
var body: some View {
Button(action: action) {
HStack {
Text(text)
.font(PortfolioFonts.body)
.fontWeight(.bold)
if let iconSystemName = iconSystemName {
Image(systemName: iconSystemName)
}
}
}
.foregroundColor(.primary)
.padding(14)
.frame(
maxWidth: .infinity,
alignment: .center
)
.background(Color.accentColor)
.cornerRadius(16)
}
}
| true
|
24c6aba59b76e59edeceae4e95477b08c946477f
|
Swift
|
agibson73/AGEasyFrameworkExample
|
/AGEasyFramework/AGEasyCache.swift
|
UTF-8
| 854
| 2.765625
| 3
|
[] |
no_license
|
//
// EasyCache.swift
// Easy
//
// Created by Alex Gibson on 1/2/16.
// Copyright © 2016 AG. All rights reserved.
//
import UIKit
class AGEasyCache: NSObject {
var imageDataDict = NSMutableDictionary()
class var sharedInstance: AGEasyCache {
struct Static {
static let instance : AGEasyCache = AGEasyCache()
}
return Static.instance
}
func addData(_ imageData:Data,forKey:String){
imageDataDict.setObject(imageData, forKey: forKey as NSCopying)
}
func getDataForKey(_ forKey:String!)->Data?{
if forKey != nil{
if let data = imageDataDict.object(forKey: forKey) as? Data{
return data
}
else{
return nil
}
}
else{
return nil
}
}
}
| true
|
d6e0836ec22ef584caf37d2dddbcca9a8f59e074
|
Swift
|
WillTomaz-dev/ConsultarTabelaFipe
|
/Desafio App Moobie/Models/CarManager.swift
|
UTF-8
| 1,038
| 2.9375
| 3
|
[] |
no_license
|
//
// Car.swift
// Desafio App Moobie
//
// Created by da Silva, William on 09/07/20.
// Copyright © 2020 William Tomaz. All rights reserved.
//
import CoreData
class CarManager {
static let shared = CarManager()
var carDetail: [CarDetail] = []
func loadCars(with context: NSManagedObjectContext){
let fetchRequest: NSFetchRequest<CarDetail> = CarDetail.fetchRequest()
let sortDescriptor = NSSortDescriptor(key: "modelo", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor]
do{
carDetail = try context.fetch(fetchRequest)
} catch {
print(error.localizedDescription)
}
}
func deleteCars(index: Int, context: NSManagedObjectContext) {
let car = carDetail[index]
context.delete(car) //excluiu do contexto
do {
try context.save()
carDetail.remove(at: index)
} catch {
print(error.localizedDescription)
}
}
private init() {
}
}
| true
|
060c61d4ff31d4c8ef612c224406051f193e71e2
|
Swift
|
zhangirtastemir/MovieApp
|
/MovieApp/Network/NetworkManager.swift
|
UTF-8
| 5,135
| 2.625
| 3
|
[] |
no_license
|
//
// NetworkManager.swift
// MovieApp
//
// Created by Zhangir Tastemir on 3/7/20.
// Copyright © 2020 Akysh Akan. All rights reserved.
//
import Moya
protocol Networkable {
static var provider: MoyaProvider<ApiManager> { get }
static func getTopRatedMovies(page: Int, completion: @escaping ([Movie])->())
}
struct NetworkManager: Networkable {
// static var provider = MoyaProvider<ApiManager>(plugins: [NetworkLoggerPlugin(verbose: true)])
static var provider = MoyaProvider<ApiManager>()
static func getTopRatedMovies(page: Int, completion: @escaping ([Movie]) -> ()) {
provider.request(.topRatedMovies(page: page)) { result in
switch result {
case let .success(response):
do {
let results = try JSONDecoder().decode(MovieResponse.self, from: response.data)
completion(results.movies)
} catch let error as NSError {
print(error)
}
case let .failure(error):
print(error)
}
}
}
static func getPopularMovies(page: Int, completion: @escaping ([Movie]) -> ()) {
provider.request(.popularMovies(page: page)) { result in
switch result {
case let .success(response):
do {
let results = try JSONDecoder().decode(MovieResponse.self, from: response.data)
completion(results.movies)
} catch let error as NSError {
print(error)
}
case let .failure(error):
print(error)
}
}
}
static func getUpcomingMovies(page: Int, completion: @escaping ([Movie]) -> ()) {
provider.request(.upcomingMovies(page: page)) { result in
switch result {
case let .success(response):
do {
let results = try JSONDecoder().decode(MovieResponse.self, from: response.data)
completion(results.movies)
} catch let error as NSError {
print(error)
}
case let .failure(error):
print(error)
}
}
}
static func getNowPlayingMovies(page: Int, completion: @escaping ([Movie]) -> ()) {
provider.request(.nowPlaying(page: page)) { result in
switch result {
case let .success(response):
do {
let results = try JSONDecoder().decode(MovieResponse.self, from: response.data)
completion(results.movies)
} catch let error as NSError {
print(error)
}
case let .failure(error):
print(error)
}
}
}
static func getGenres(completion: @escaping ([Genre]) -> ()) {
provider.request(.genres) { result in
switch result {
case let .success(response):
do {
let results = try JSONDecoder().decode(GenreResponse.self, from: response.data)
completion(results.genres)
} catch let error as NSError {
print(error)
}
case let .failure(error):
print(error)
}
}
}
static func getVideos(id: Int, completion: @escaping ([Video]) -> ()) {
provider.request(.videos(id: id)) { result in
switch result {
case let .success(response):
do {
let results = try JSONDecoder().decode(VideoResponse.self, from: response.data)
completion(results.videos)
} catch let error as NSError {
print(error)
}
case let .failure(error):
print(error)
}
}
}
static func searchMovies(query: String, completion: @escaping ([Movie]) -> ()) {
provider.request(.search(query: query)) { result in
switch result {
case let .success(response):
do {
let results = try JSONDecoder().decode(MovieResponse.self, from: response.data)
completion(results.movies)
} catch let error as NSError {
print(error)
}
case let .failure(error):
print(error)
}
}
}
static func getSimilarMovies(id: Int, completion: @escaping ([Movie]) -> ()) {
provider.request(.similarMovies(id: id)) { result in
switch result {
case let .success(response):
do {
let results = try JSONDecoder().decode(MovieResponse.self, from: response.data)
completion(results.movies)
} catch let error as NSError {
print(error)
}
case let .failure(error):
print(error)
}
}
}
}
| true
|
37bafc23ff0343a76f24aedb0b2d14ef16377bfa
|
Swift
|
TaiHsin/Travel
|
/Travel/Views/Triplist/DayCollectionHeader.swift
|
UTF-8
| 816
| 2.59375
| 3
|
[] |
no_license
|
//
// DayCollectionHeader.swift
// Travel
//
// Created by TaiHsinLee on 2018/10/22.
// Copyright © 2018 TaiHsinLee. All rights reserved.
//
import UIKit
protocol DayHeaderDelegate: AnyObject {
func showTriplist(for header: DayCollectionHeader)
}
class DayCollectionHeader: UICollectionReusableView {
@IBOutlet weak var selectedView: UIView!
@IBOutlet weak var headerButton: UIButton!
@IBAction func tapHeader(_ sender: UIButton) {
delegate?.showTriplist(for: self)
}
weak var delegate: DayHeaderDelegate?
override func awakeFromNib() {
super.awakeFromNib()
selectedView.layer.cornerRadius = 4.0
selectedView.layer.masksToBounds = true
selectedView.isHidden = true
}
}
| true
|
a1548cc46114b494e36986b804424ca3286e6308
|
Swift
|
andrewtokeley/trapr
|
/trapr/VisitSummaryFirebaseService.swift
|
UTF-8
| 8,973
| 2.59375
| 3
|
[] |
no_license
|
//
// VisitSummaryFirebaseService.swift
// trapr
//
// Created by Andrew Tokeley on 15/11/18.
// Copyright © 2018 Andrew Tokeley . All rights reserved.
//
import Foundation
class VisitSummaryFirebaseService: FirestoreService, VisitSummaryServiceInterface {
let visitService = ServiceFactory.sharedInstance.visitFirestoreService
let trapTypeService = ServiceFactory.sharedInstance.trapTypeFirestoreService
let stationService = ServiceFactory.sharedInstance.stationFirestoreService
let routeService = ServiceFactory.sharedInstance.routeFirestoreService
let speciesService = ServiceFactory.sharedInstance.speciesFirestoreService
private func createVisitSummary(date: Date, routeId: String, visits: [Visit], completion: ((VisitSummary?, Error?) -> Void)?) {
let visitSummary = VisitSummary(dateOfVisit: date, routeId: routeId)
visitSummary.visits = visits
// calculated the totals
var totalPoisonAdded: Int = 0
var totalKills: Int = 0
var totalKillsBySpecies = [String: Int]()
var totalBaitAddedByLure = [String: Int]()
self.speciesService.get { (species, error) in
// need details from the trapTypes to get some extra stats
self.trapTypeService.get(completion: { (trapTypes, error) in
// ids of all the poison traptypes
let poisonTrapTypes = trapTypes.filter( { $0.killMethod == _KillMethod.poison }).map( { $0.id! } )
// iterate over visits for lure and catch counts
for visit in visits {
if poisonTrapTypes.contains(visit.trapTypeId) {
totalPoisonAdded += visit.baitAdded
}
if let lureId = visit.lureId {
if let _ = totalBaitAddedByLure[lureId] {
totalBaitAddedByLure[lureId]! += visit.baitAdded
} else {
totalBaitAddedByLure[lureId] = visit.baitAdded
}
}
if let speciesId = visit.speciesId {
totalKills += 1
if let _ = totalKillsBySpecies[speciesId] {
totalKillsBySpecies[speciesId]! += 1
} else {
totalKillsBySpecies[speciesId] = 1
}
}
}
visitSummary.totalPoisonAdded = totalPoisonAdded
visitSummary.totalKills = totalKills
visitSummary.totalKillsBySpecies = totalKillsBySpecies
visitSummary.totalBaitAddedByLure = totalBaitAddedByLure
// We also need to know how many traps/stations are on the route
self.stationService.get(routeId: routeId, completion: { (stations) in
visitSummary.stationsOnRoute = stations
let numberOfTrapsOnRoute = stations.reduce(0, { (result, station) -> Int in
return result + station.trapTypes.count
})
visitSummary.numberOfTrapsOnRoute = numberOfTrapsOnRoute
// And the route itself.
self.routeService.get(routeId: routeId, completion: { (route, error) in
visitSummary.route = route
// All done
completion?(visitSummary, error)
})
})
})
}
}
func createNewVisitSummary(date: Date, routeId: String, completion: ((VisitSummary?, Error?) -> Void)?) {
self.createVisitSummary(date: date, routeId: routeId, visits: [Visit]()) { (visitSummary, error) in
completion?(visitSummary, error)
}
}
func get(date: Date, routeId: String, completion: ((VisitSummary?, Error?) -> Void)?) {
self.visitService.get(recordedOn: date, routeId: routeId) { (visits, error) in
self.createVisitSummary(date: date, routeId: routeId, visits: visits, completion: { (summaries, error) in
completion?(summaries, error)
})
}
}
func get(recordedBetween startDate: Date, endDate: Date, routeId: String, completion: (([VisitSummary], Error?) -> Void)?) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "ddMMyyyy"
var summaries = [VisitSummary]()
visitService.get(recordedBetween: startDate, dateEnd: endDate, routeId: routeId) { (visits, error) in
// Find the unique days where visits were recorded
var uniqueDates = [String]()
for visit in visits {
let visitDate = dateFormatter.string(from: visit.visitDateTime)
if !uniqueDates.contains(visitDate) {
uniqueDates.append(visitDate)
}
}
// Create a VisitSummary for each day's visit
let dispatchGroup = DispatchGroup()
for aDate in uniqueDates {
let visits = visits.filter({ dateFormatter.string(from: $0.visitDateTime) == aDate })
dispatchGroup.enter()
// all days will be the same, but use the time of the first visit
let visitDateTime = visits.first!.visitDateTime
self.createVisitSummary(date: visitDateTime, routeId: routeId, visits: visits) { (visitSummary, error) in
if let visitSummary = visitSummary {
summaries.append(visitSummary)
}
dispatchGroup.leave()
}
}
dispatchGroup.notify(queue: .main, execute: {
completion?(summaries.sorted(by: { $0.dateOfVisit > $1.dateOfVisit}), nil)
})
}
}
func get(mostRecentOn routeId: String, completion: ((VisitSummary?, Error?) -> Void)?) {
self.get(recordedBetween: Date().add(0, -3, 0), endDate: Date(), routeId: routeId) { (visitSummaries, error) in
if let error = error {
completion?(nil, error)
} else {
// latest
let mostRecent = visitSummaries.sorted(by: { $0.dateOfVisit > $1.dateOfVisit }).first
completion?(mostRecent, nil)
}
}
}
func getStatistics(from visitSummaries: [VisitSummary], completion: ((VisitSummariesStatistics?, Error?) -> Void)?) {
var visitStats = VisitSummariesStatistics()
// Get all the visits across all the visitSummaries
let visits = visitSummaries.flatMap { (summary) -> [Visit] in
return summary.visits
}
// Need details from the trapTypes to get some extra stats
self.trapTypeService.get { (trapTypes, error) in
// ids of all the poison traptypes
let poisonTrapTypes = trapTypes.filter( { $0.killMethod == _KillMethod.poison }).map( { $0.id! } )
// iterate over visits to count poison and kills
for visit in visits {
if poisonTrapTypes.contains(visit.trapTypeId) {
visitStats.totalPoisonAdded += visit.baitAdded
}
if let speciesId = visit.speciesId {
visitStats.totalKills += 1
if let _ = visitStats.totalKillsBySpecies[speciesId] {
visitStats.totalKillsBySpecies[speciesId]! += 1
} else {
visitStats.totalKillsBySpecies[speciesId] = 1
}
}
}
// for average and fastest times only consider when all traps were visited.
let fullyVisitedSummaries = visitSummaries.filter({ $0.numberOfTrapsOnRoute == $0.numberOfTrapsVisited }).sorted(by: { $0.timeTaken < $1.timeTaken })
// Average time
let totalTimeTakenOnFullyVisitedSummaries = fullyVisitedSummaries.reduce(0, { $0 + $1.timeTaken })
visitStats.averageTimeTaken = totalTimeTakenOnFullyVisitedSummaries/Double(fullyVisitedSummaries.count)
// Fastest time
if let fastestTime = fullyVisitedSummaries.first?.timeTaken {
visitStats.fastestTimeTaken = fastestTime
}
completion?(visitStats, nil)
}
}
}
| true
|
6e9df64087664c957b1b93e839a580b570f34215
|
Swift
|
841766048/QRScan
|
/QRCodeScanning/QRCodeScanning/Scan/ScanLineAnimation.swift
|
UTF-8
| 3,667
| 2.671875
| 3
|
[] |
no_license
|
//
// ScanLineAnimation.swift
// GridOperation
//
//
import Foundation
class ScanLineAnimation: UIImageView {
var num:Int32 = 0
var down = false
var timer:Timer?
var isAnimationing = false
var animationRect:CGRect?
@objc private func stepAnimation() {
if !isAnimationing {
return
}
let leftx = animationRect!.origin.x + 5
let width = animationRect!.size.width - 10
self.frame = CGRect(x: leftx, y: animationRect!.origin.y, width: width, height: 8)
self.alpha = 0.0
self.isHidden = false
UIView.animate(withDuration: 0.5, animations: {[weak self] in
self?.alpha = 1.0
})
UIView.animate(withDuration: 3, animations: { [unowned self] in
let leftx = self.animationRect!.origin.x + 5
let width = self.animationRect!.size.width - 10
let y = self.animationRect!.origin.y + self.animationRect!.size.height - 8
self.frame = CGRect(x: leftx, y: y , width: width, height: 4)
}, completion: { [weak self] (finished) in
self?.isHidden = true
//延迟5秒执行
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
self?.stepAnimation()
}
// self.perform(#selector(stepAnimation), with: nil, afterDelay: 0.3)
})
}
private func startAnimating_UIViewAnimation() {
stepAnimation()
}
func startAnimating(animationRect:CGRect , parentView:UIView ,image:UIImage?) {
if isAnimationing {
return
}
isAnimationing = true
self.animationRect = animationRect
down = true
num = 0
let centery = animationRect.minY + animationRect.height/2
let leftx = animationRect.origin.x + 5;
let width = animationRect.size.width - 10;
let y = centery + CGFloat((2 * num))
self.frame = CGRect(x: leftx, y:y , width: width, height: 2)
self.image = image
parentView.addSubview(self)
startAnimating_UIViewAnimation()
}
private func startAnimating_NSTimer() {
timer = Timer.scheduledTimer(timeInterval: 0.02, target: self, selector: #selector(scanLineAnimation), userInfo: nil, repeats: true)
}
@objc private func scanLineAnimation() {
let centery = animationRect!.minY + animationRect!.height/2
let leftx = animationRect!.origin.x + 5;
let width = animationRect!.size.width - 10;
if down {
num += 1
let y = centery + CGFloat((2 * num))
self.frame = CGRect(x: leftx, y:y , width: width, height: 2)
if y > (animationRect!.minY + animationRect!.height - 5) {
down = false
}
}else{
num -= 1
let y = centery + CGFloat((2 * num))
self.frame = CGRect(x: leftx, y:y , width: width, height: 2)
if y < (animationRect!.minY + 5) {
down = true
}
}
}
func stopLineAnimating() {
if isAnimationing {
isAnimationing = false
if let _ = self.timer {
self.timer!.invalidate()
self.timer = nil
}
self.removeFromSuperview()
}
NSObject.cancelPreviousPerformRequests(withTarget: self)
}
deinit {
stopLineAnimating()
}
}
| true
|
5707bd9f5f22f660bef36b561b392d11276b1291
|
Swift
|
n8chur/Listable
|
/ListableUI/Tests/Layout/Retail Grid/RetailGridListLayoutTests.swift
|
UTF-8
| 3,864
| 2.546875
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// RetailGridListLayoutTests.swift
// ListableUI-Unit-Tests
//
// Created by Gabriel Hernandez Ontiveros on 2021-07-27.
//
import XCTest
import Snapshot
@testable import ListableUI
class RetailGridAppearanceTests : XCTestCase
{
func test_init()
{
let appearance = RetailGridAppearance()
XCTAssertEqual(appearance.layout, RetailGridAppearance.Layout())
}
}
class RetailGridAppearance_LayoutTests : XCTestCase
{
func test_init()
{
let layout = RetailGridAppearance.Layout()
XCTAssertEqual(layout.padding, .zero)
XCTAssertEqual(layout.itemSpacing, .zero)
XCTAssertEqual(layout.columns, 1)
XCTAssertEqual(layout.rows, .infinite(tileAspectRatio: 1))
}
}
class RetailGridListLayoutTests : XCTestCase
{
func test_layout_infiniteScoll()
{
let listView = self.list(columns: 2, rows: .infinite(tileAspectRatio: 1))
let snapshot = Snapshot(for: SizedViewIteration(size: listView.contentSize), input: listView)
snapshot.test(output: ViewImageSnapshot.self)
snapshot.test(output: LayoutAttributesSnapshot.self)
}
func test_layout_rows()
{
let listView = self.list(columns: 2, rows: .rows(2))
let snapshot = Snapshot(for: SizedViewIteration(size: listView.contentSize), input: listView)
snapshot.test(output: ViewImageSnapshot.self)
snapshot.test(output: LayoutAttributesSnapshot.self)
}
func list(columns: Int, rows: RetailGridAppearance.Layout.Rows) -> ListView
{
let listView = ListView(frame: CGRect(origin: .zero, size: CGSize(width: 200.0, height: 200.0)))
listView.configure { list in
list.layout = .retailGrid {
$0.layout = .init(
padding: UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10),
itemSpacing: 10,
columns: columns,
rows: rows
)
}
list += Section("RetailGrid") { section in
section += Item(TestingItemContent(color: .init(white: 0.0, alpha: 0.1))) {
$0.layouts.retailGrid = RetailGridAppearance.ItemLayout(
origin: .init(x: 0, y: 0), size: .single
)
}
section += Item(TestingItemContent(color: .init(white: 0.0, alpha: 0.2))) {
$0.layouts.retailGrid = RetailGridAppearance.ItemLayout(
origin: .init(x: 1, y: 0), size: .tall
)
}
section += Item(TestingItemContent(color: .init(white: 0.0, alpha: 0.3))) {
$0.layouts.retailGrid = RetailGridAppearance.ItemLayout(
origin: .init(x: 0, y: 1), size: .single
)
}
section += Item(TestingItemContent(color: .init(white: 0.0, alpha: 0.4))) {
$0.layouts.retailGrid = RetailGridAppearance.ItemLayout(
origin: .init(x: 0, y: 2), size: .wide
)
}
}
}
listView.collectionView.layoutIfNeeded()
return listView
}
}
fileprivate struct TestingItemContent : ItemContent {
var color : UIColor
var identifierValue: String {
""
}
func apply(to views: ItemContentViews<Self>, for reason: ApplyReason, with info: ApplyItemContentInfo)
{
views.content.backgroundColor = self.color
}
func isEquivalent(to other: TestingItemContent) -> Bool {
false
}
typealias ContentView = UIView
static func createReusableContentView(frame: CGRect) -> UIView {
UIView(frame: frame)
}
}
| true
|
a9c0c30fad2d308e100d817b2036de5b8c20f388
|
Swift
|
crisrodfe/Cassini
|
/Cassini/ImageViewController.swift
|
UTF-8
| 5,128
| 3.046875
| 3
|
[] |
no_license
|
//
// ImageViewController.swift
// Cassini
//
// Created by Cristina Rodriguez Fernandez on 7/7/16.
// Copyright © 2016 CrisRodFe. All rights reserved.
//
import UIKit
class ImageViewController: UIViewController, UIScrollViewDelegate
{
//Modelo
var imageURL: URL?
{
didSet {
image = nil
//Coge la imagen de la URL y la asigna a la variable image de tipo UIImage
//Pero solo queremos que descargue la imagen si nuestra view está mostrandose en la pantalla
if view.window != nil {
fetchImage()
}
}
}
//Crearemos nuestra ImageView con código
fileprivate var imageView = UIImageView()
//Vamos a configurar nuestra ImageView.
//Le tenemos que poner una imagen al imageView y reseter el marco para que quepa la imagen que le hemos puesto.
fileprivate var image: UIImage?
{
set {
imageView.image = newValue
imageView.sizeToFit()
//Ademas tenemos que configurar el contentSize para que funcione el scrollView
scrollView?.contentSize = imageView.frame.size
spinner?.stopAnimating()
}
get{
return imageView.image
}
}
//Este método va a mirar en el NSURL?, ya sea en internet o en archivos locales.
fileprivate func fetchImage()
{
if let url = imageURL
{
spinner?.startAnimating()
//Queremos hacerlo con multihilo
//Como el ultimo argumento es una closure lo podemos poner fuera del paréntesis sino pondriamos:
//dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), {closure})
DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated).async
{
let contentsOfURL = try? Data(contentsOf: url)
//Como queremos que tenga lugar en la main queue....
DispatchQueue.main.async
{
if url == self.imageURL //Nos aseguramos que la url donde vamos a buscar la foto es la misma que se nos ha pedido
//Es por si se le da a un boton detras de otro antes de que se cargue la imagen
{
if let imageData = contentsOfURL //Si no es nil... cogemos los datos del url del modelo
{ //Coge los bits de una url
self.image = UIImage(data: imageData) //Inicializador de UIImage
} else {
self.spinner?.stopAnimating()
}
}
else
{
print("Ignored data returned from url\(url)")
}
}
}
}
}
@IBOutlet weak var scrollView: UIScrollView!
{
didSet {
scrollView.contentSize = imageView.frame.size
//Además de ScrollView queremos que en nuestra imagen podamos hacer zoom.
//Para ello necesitamos configurarnos como el delegate del scrollview
//Basicamente le decimos que pregunte aqui cualquier pregunta que le surja(que hago si hacen el gesto X en la pantalla?)
//Como self es ImageViewController y es diferentes de ScrollViewController del .delegate tenemos que hacer que nuestro controlador herede de ScrollViewDelegate, todos sus metodos/propiedades son opcionales
scrollView.delegate = self
scrollView.minimumZoomScale = 0.03
scrollView.maximumZoomScale = 1.0
}
}
//Pero si queremos implementar el metodo del Zoom
func viewForZooming(in scrollView: UIScrollView) -> UIView?
{
return imageView
}
@IBOutlet weak var spinner: UIActivityIndicatorView!
override func viewWillAppear(_ animated: Bool)
{
super.viewWillAppear(animated)
if image == nil
{
fetchImage()
}
}
override func viewDidLoad()
{
super.viewDidLoad()
//Añadimos nuestra imagen que hemos creado a la vista.
//"view" es la variable que se refiera a la vista completa, la de jerarquía más superior, en este caso es la pantalla entera.
//view.addSubview(imageView)
//Pero queremos recorrer la imagen asique la añadimos a nuestra scrollView no a la pantlla vacía.
scrollView.addSubview(imageView)
//Configuramos nuestro modelo. Como .Stanford es un string NSURL nos construye una url a partir de un string
//imageURL = NSURL(string: DemoURL.Stanford) Esto lo usabamos antes de poner los botones para elegir una u otra foto
//Por defecto esto nos dará un error al cargar la fuente http,por no ser segura, tenemos que configurar esto a traves del archivo Info.plist. Boton derecho, add Row -> App Transport Security Settings -> add Allow Arbitrary Loads -> YES
}
}
| true
|
189b98b6b1d74d4fda60865938618902410ef0d1
|
Swift
|
powerforward741852/52
|
/52WorkHelper/52WorkHelper/Class/ViewControllers/WorkInstrument/Controller/CRM/View/QRHistoryView.swift
|
UTF-8
| 3,166
| 2.609375
| 3
|
[] |
no_license
|
//
// QRHistoryView.swift
// 52WorkHelper
//
// Created by 秦榕 on 2018/10/12.
// Copyright © 2018年 chenqihang. All rights reserved.
//
import UIKit
class QRHistoryView: UIView {
/// 头像
let iconImageView: UIImageView = UIImageView(image: UIImage(named: "CQIndexPersonDefault"))
/// 用户名
let userName: UILabel = UILabel(title: "小明爱睡觉", fontSize: 15 )
/// 发布时间
let creatTime: UILabel = UILabel(title: "五分钟前", textColor: UIColor.gray, fontSize: 11)
/// 微博的正文
let statusText: UILabel = UILabel(title: " ", textColor: kColorRGB(r: 132, g: 131, b: 132), fontSize: 14,alignment: NSTextAlignment.left, numberOfLines: 0)
lazy var customerFromLab: UIButton = {
let customerFromLab = UIButton()
customerFromLab.titleLabel?.text = "电话销售:"
customerFromLab.setTitleColor(UIColor.white, for: .normal)
customerFromLab.titleLabel?.font = kFontSize13
customerFromLab.backgroundColor = kLightBlueColor
customerFromLab.layer.cornerRadius = AutoGetHeight(height: 20)/2
customerFromLab.clipsToBounds = true
return customerFromLab
}()
init() {
super.init(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
setupUi()
}
func setupUi() {
//添加子视图
addSubview(iconImageView)
addSubview(userName)
addSubview(creatTime)
addSubview(statusText)
addSubview(customerFromLab)
iconImageView.layer.cornerRadius = AutoGetWidth(width: 18)
iconImageView.clipsToBounds = true
userName.font = kFontBoldSize15
iconImageView.mas_makeConstraints { (make) in
make?.left.mas_equalTo()(self)?.setOffset(kLeftDis)
make?.top.mas_equalTo()(self)?.setOffset(18)
make?.width.mas_equalTo()(AutoGetWidth(width: 36))
make?.height.mas_equalTo()(AutoGetWidth(width: 36))
}
userName.mas_makeConstraints { (make) in
make?.left.mas_equalTo()(iconImageView.mas_right)?.setOffset(kLeftDis)
make?.top.mas_equalTo()(iconImageView)
}
creatTime.mas_makeConstraints { (make) in
make?.left.mas_equalTo()(iconImageView.mas_right)?.setOffset(kLeftDis)
make?.top.mas_equalTo()(userName.mas_bottom)?.setOffset(5)
}
customerFromLab.mas_makeConstraints { (make) in
make?.left.mas_equalTo()(userName.mas_right)?.setOffset(5)
make?.centerY.mas_equalTo()(userName)
make?.width.mas_equalTo()(80)
make?.height.lessThanOrEqualTo()(AutoGetHeight(height: 20))
}
statusText.mas_makeConstraints { (make) in
make?.left.mas_equalTo()(iconImageView)
make?.top.mas_equalTo()(iconImageView.mas_bottom)?.setOffset(12)
make?.right.mas_equalTo()(self)?.setOffset(-kLeftDis)
make?.bottom.mas_equalTo()(self)?.setOffset(0)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| true
|
c48c5464e9ff60f44f5f987918202b8de6d8e3f7
|
Swift
|
sadyojat/letusswift
|
/swiftplaygrounds/problems/InterviewPrep.playground/Pages/Untitled Page.xcplaygroundpage/Contents.swift
|
UTF-8
| 1,217
| 3.234375
| 3
|
[] |
no_license
|
import UIKit
var str = "Hello, playground"
func generateRandomList(count: Int) -> [Int] {
var list = [Int]()
for _ in 0..<count {
list.append(Int(arc4random_uniform(UInt32(100))))
}
return list
}
func countUniques<T:Comparable> (_ array: [T]) -> Int {
let sorted = array.sorted()
let initial:(T?, Int) = (.none, 0)
let reduced = sorted.reduce(initial) {
($1, $0.0 == $1 ? $0.1 : $0.1 + 1)
}
return reduced.1
}
extension Array where Element: Comparable {
func countUniques() -> Int {
var sorted = self.sorted()
let initial:(Element?, Int) = (.none, 0)
var reduced = sorted.reduce(initial) { ($1, $0.0 == $1 ? $0.1 : $0.1 + 1)}
return reduced.1
}
func countDuplicates() -> Int {
var sorted = self.sorted()
let initial:(Element?, Int) = (.none, 0)
var reduced = sorted.reduce(initial) {
($1, $0.0 == $1 ? $0.1 + 1 : $0.1)
}
return reduced.1
}
}
//let list = generateRandomList(count: 10)
let list = [0, 12, 0, 12, 4, 3, 4, 3, 5 ,6, 6]
countUniques(list)
list.countUniques()
list.countDuplicates()
struct EmptyStruct {
}
| true
|
e559c84589ed924d348f7aff5d96a2e284e6e99e
|
Swift
|
jivison/OrbitPlayer
|
/OrbitPlayer/Views/MainView/Sidebar.swift
|
UTF-8
| 1,343
| 3.390625
| 3
|
[] |
no_license
|
//
// Sidebar.swift
// OrbitPlayer
//
// Created by John Ivison on 2021-05-01.
//
import SwiftUI
enum Tab: String, CaseIterable, Identifiable {
case home, library, search
var id: String { self.rawValue }
}
struct Sidebar: View {
@Binding var tab: Tab
var body: some View {
VStack {
ForEach(Tab.allCases) { tab in
SidebarItem(tab: tab, tabBinding: $tab).padding(.bottom)
}
}
}
}
struct SidebarItem: View {
var tab: Tab
@Binding var tabBinding: Tab
var body: some View {
VStack {
self.getIcon()
.resizeKeepingAspectRatio(width: 50, height: 50)
}.onTapGesture(perform: onClick)
}
private func onClick() {
self.tabBinding = self.tab
}
private func getIcon() -> Image {
var systemName = "questionmark"
switch self.tab {
case .home:
systemName = "house"
case .library:
systemName = "books.vertical"
case .search:
systemName = "magnifyingglass"
}
return Image(systemName: systemName)
}
}
struct Sidebar_Previews: PreviewProvider {
static var previews: some View {
return Group {
Sidebar(tab: .constant(.home))
}
}
}
| true
|
4d1166964a68e0f16de8ad38b7f4a859a4c7f199
|
Swift
|
Hitesh136/Swift-Playground
|
/Enums/Enum vs Class.playground/Contents.swift
|
UTF-8
| 405
| 3.890625
| 4
|
[] |
no_license
|
import UIKit
//1. Inistializing enum with default value gives nil if case is not definde with value in enum. But in class or struct it is not nil
enum ApiError: Int {
case notFound = 404
case internalServerError = 501
}
let someError = ApiError(rawValue: 400)
print(someError)
//nil
struct ApiErrorSt {
var errorCode: Int
}
let someError2 = ApiErrorSt(errorCode: 400)
print(someError2)
| true
|
62ecd623e57d468cc5bf27db68b7e172b6956865
|
Swift
|
JansenGuan/CustomTimer
|
/Example/CustomTimer/ViewController.swift
|
UTF-8
| 3,386
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
//
// ViewController.swift
// CustomTimer
//
// Created by guan_xiang on 2019/4/18.
// Copyright © 2019 iGola_iOS. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
private lazy var formatDate : DateFormatter = {
let format = DateFormatter()
format.calendar = Calendar(identifier: Calendar.Identifier.gregorian)
format.dateFormat = "HH:mm:ss"
format.isLenient = true
return format
}()
/// 倒计时
lazy var coutDownTimer = iGolaCustomTimer()
/// 常规定时器
lazy var timer = iGolaCustomTimer()
/// 间隔不等定时器
lazy var unequalTimer = iGolaCustomTimer()
@IBOutlet weak var coutDownLabel: UILabel!
@IBOutlet weak var timerLabel: UILabel!
@IBOutlet weak var unequalLabel: UILabel!
private var totalTime : TimeInterval = 10
private var count : Int = 0
private var timeArray : [TimeInterval] = [3,4,2,4,1,3,2]
private var index : Int = 0
override func viewDidLoad() {
super.viewDidLoad()
coutDownLabel.text = "\(totalTime)"
timerLabel.text = "第\(self.count)次(间隔2s)"
unequalLabel.text = "第\(self.count)次(间隔2s)"
}
@IBAction func startCoutDownAction(_ sender: UIButton) {
coutDownTimer.startCountDownTimer(totalTime: totalTime) { (isOver) in
if isOver{
self.totalTime = 10
self.coutDownLabel.text = "倒计时结束了"
}else{
self.totalTime -= 1
self.coutDownLabel.text = self.formatDate.string(from: Date())
}
}
}
@IBAction func startTimerAction(_ sender: UIButton) {
timer.startTimer(duration: 2) {
self.count += 1
self.timerLabel.text = self.formatDate.string(from: Date())
}
}
@IBAction func startUnequalTimerAction(_ sender: UIButton) {
unequalTimer.startUnEqualTimer(timeArray: timeArray) { (isOver) in
if isOver{
self.unequalLabel.text = self.formatDate.string(from: Date()) + "结束了"
}else{
self.unequalLabel.text = self.formatDate.string(from: Date())
self.index += 1
}
}
}
@IBAction func suspendCoutDownTime(_ sender: Any) {
coutDownTimer.suspendTimer()
}
@IBAction func resumeCoutDownTime(_ sender: Any) {
coutDownTimer.resumeCountDownTimer()
}
@IBAction func cancelCoutDownTime(_ sender: Any) {
coutDownTimer.cancelTimer()
}
@IBAction func suspendTime(_ sender: Any) {
timer.suspendTimer()
}
@IBAction func resumeTime(_ sender: Any) {
timer.resumeTimer()
}
@IBAction func cancelTime(_ sender: Any) {
timer.cancelTimer()
}
@IBAction func suspendUnequalTime(_ sender: Any) {
unequalTimer.suspendTimer()
}
@IBAction func resumeUnequalTime(_ sender: Any) {
unequalTimer.resumeUnequalTimer()
}
@IBAction func cancelUnequalTime(_ sender: Any) {
unequalTimer.cancelTimer()
}
}
| true
|
ee88a4a2f9371f51499c3256bb7588c360985fbc
|
Swift
|
LucasCoelho/Pentagram
|
/Pentagram/Classes/PentagramPresenter.swift
|
UTF-8
| 4,379
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
//
// PentagramPresenter.swift
// Pods
//
// Created by Lucas Coelho on 7/26/16.
//
//
import UIKit
public enum NoteId: String {
case Mi2 = "MI2"
case Fa2 = "FA2"
case Sol2 = "SOL2"
case La2 = "LA2"
case Si2 = "SI2"
case Do3 = "DO3"
case Re3 = "RE3"
case Mi3 = "MI3"
case Fa3 = "FA3"
case Sol3 = "SOL3"
case La3 = "LA3"
case Si3 = "SI3"
case Do4 = "DO4"
case Re4 = "RE4"
case Mi4 = "MI4"
case Fa4 = "FA4"
case Sol4 = "SOL4"
case La4 = "LA4"
case Si4 = "SI4"
case Do5 = "DO5"
case Re5 = "RE5"
case Mi5 = "MI5"
case Fa5 = "FA5"
case Sol5 = "SOL5"
case La5 = "LA5"
public func getName() -> String {
return NSLocalizedString("_\(rawValue.substring(to: rawValue.characters.index(before: rawValue.endIndex)).lowercased())", comment: "").uppercased()
}
public static func getAllNotes() -> [NoteId] {
return [.Do4, .Re4, .Mi4, .Fa4, .Sol4, .La4, .Si4, .Do5, .Re5, .Mi5, .Fa5, .Sol5, .La5]
}
}
public enum MusicKey {
case g
case f
}
struct PentagramPresenter {
var key: MusicKey = .g {
didSet {
updateFinalPositionsArray()
}
}
var spaceBetweenLines: CGFloat!
var topPosition: CGFloat!
var lineWidth: CGFloat!
var positionsToAddSupplementaryLine: [CGFloat]!
var finalPositions: [NoteId: CGFloat]!
init(topPosition: CGFloat, lineWidth: CGFloat, spaceBetweenLines: CGFloat) {
self.topPosition = topPosition
self.lineWidth = lineWidth
self.spaceBetweenLines = spaceBetweenLines
updateFinalPositionsArray()
}
mutating func updateFinalPositionsArray() {
let firstLine = topPosition + lineWidth/2
let note1 = firstLine - spaceBetweenLines
let note2 = firstLine - 0.5 * spaceBetweenLines
let note3 = firstLine
let note4 = firstLine + 0.5 * (spaceBetweenLines + lineWidth)
let note5 = firstLine + 1.0 * (spaceBetweenLines + lineWidth)
let note6 = firstLine + 1.5 * (spaceBetweenLines + lineWidth)
let note7 = firstLine + 2.0 * (spaceBetweenLines + lineWidth)
let note8 = firstLine + 2.5 * (spaceBetweenLines + lineWidth)
let note9 = firstLine + 3.0 * (spaceBetweenLines + lineWidth)
let note10 = firstLine + 3.5 * (spaceBetweenLines + lineWidth)
let note11 = firstLine + 4.0 * (spaceBetweenLines + lineWidth)
let note12 = firstLine + 4.5 * (spaceBetweenLines + lineWidth)
let note13 = firstLine + 5.0 * (spaceBetweenLines + lineWidth)
if key == .g {
finalPositions = [.La5: note1, .Sol5: note2, .Fa5: note3, .Mi5: note4, .Re5: note5, .Do5: note6,
.Si4: note7, .La4: note8, .Sol4: note9, .Fa4: note10, .Mi4: note11, .Re4: note12, .Do4: note13]
} else {
finalPositions = [.Do4: note1, .Si3: note2, .La3: note3, .Sol3: note4, .Fa3: note5, .Mi3: note6,
.Re3: note7, .Do3: note8, .Si2: note9, .La2: note10, .Sol2: note11, .Fa2: note12, .Mi2: note13]
}
positionsToAddSupplementaryLine = [note1, note13]
}
func getNameForNoteInPosition(_ position: CGFloat) -> String {
return getNoteIdForPosition(position).rawValue
}
func getNoteIdForPosition(_ position: CGFloat) -> NoteId {
for (key, value) in finalPositions {
if getFinalPositionForPosition(position) == value {
return key
}
}
return .Do4
}
func getFinalPositionForPosition(_ position: CGFloat) -> CGFloat {
var smallerValue = abs(finalPositions[.Do4]! - position)
var finalPosition = finalPositions[.Do4]
for note in finalPositions {
if abs(position - note.1) < smallerValue {
finalPosition = note.1
smallerValue = abs(position - note.1)
}
}
return finalPosition!
}
func getFinalPositionForNote(_ note: NoteId) -> CGFloat {
return finalPositions[note]!
}
func shouldAddSupplementaryLine(_ position: CGFloat) -> Bool {
if positionsToAddSupplementaryLine.contains(getFinalPositionForPosition(position)) {
return true
} else {
return false
}
}
}
| true
|
18af9ddefbbb56053f17a6ab6c1b5ec56010645c
|
Swift
|
buptwsg/SwiftyGitClient
|
/GitBucket/App/SGFoundation/API/BaseModels/SGObject.swift
|
UTF-8
| 628
| 2.6875
| 3
|
[
"MIT"
] |
permissive
|
//
// SGObject.swift
// GitBucket
//
// Created by sulirong on 2018/2/7.
// Copyright © 2018年 CleanAirGames. All rights reserved.
//
import Foundation
import ObjectMapper
/**
The base model class for any objects retrieved through the GitHub API.
*/
class SGObject: ImmutableMappable {
/// The unique ID for this object. This is only guaranteed to be unique among
/// objects of the same type, from the same server.
let objectID: UInt
///JSON -> Model
required init(map: Map) throws {
objectID = try map.value("id")
}
///Model -> JSON
func mapping(map: Map) {
}
}
| true
|
2a16f01becd9593f00a3be91a4ce5d4f49fda8db
|
Swift
|
yiqin/WWDC-Scholarship-2015
|
/WWDC/AppDataManager.swift
|
UTF-8
| 1,996
| 2.84375
| 3
|
[] |
no_license
|
//
// AppDataManager.swift
// WWDC
//
// Created by Yi Qin on 4/26/15.
// Copyright (c) 2015 Yi Qin. All rights reserved.
//
import UIKit
public class AppDataManager: NSObject {
public static let shareInstance = AppDataManager()
var apps:[App] = []
override init() {
super.init()
let app1 = App()
app1.title = "Allpick - Groupon Food Delivery"
app1.iconImage = UIImage(named: "allpick")
app1.tag = 0
app1.urlString = "https://itunes.apple.com/us/app/allpick/id698213315?mt=8"
app1.moreDetail = "This is my first iOS app. It's a food delivery app for students at Purdue. I spent 7 months to finish the first version and spent another two months to get my first user. I have successfully made the number of active daily users grow up to 200."
let app2 = App()
app2.title = "1337Coding - Review Coding Interview Questions"
app2.iconImage = UIImage(named: "1337Coding")
app2.tag = 1
app2.urlString = "https://itunes.apple.com/us/app/1337coding-review-coding-interview/id963066061?mt=8"
app2.moreDetail = "I want to help my friends and me to prepare tech interviews in a more convenient way. So I created 1337Coding to let you review coding interview questions in your phone. "
let app3 = App()
app3.title = "Git Inspired - the best inspiring open source projects, every day."
app3.iconImage = UIImage(named: "gitinspired")
app3.tag = 2
app3.urlString = "https://itunes.apple.com/us/app/git-inspired-best-inspiring/id953710137?mt=8"
app3.moreDetail = "The reason that we will go through open source projects is to get inspired, instead of to use these code in our projects. We want to 100% control our codes. Git Inspired focuses on how to make developers get inspired from open source projects."
apps = [app1, app2, app3]
}
}
| true
|
3d1a8f62260a1d9519e7047355ed2ad1abb1468a
|
Swift
|
scar1992210/Audile
|
/Audile/Audile/Models/Song/Song.swift
|
UTF-8
| 397
| 2.6875
| 3
|
[
"MIT"
] |
permissive
|
//
// User.swift
// YALLayoutTransitioning
//
// Created by Roman on 23.02.16.
// Copyright © 2016 Yalantis. All rights reserved.
//
import UIKit
class Song {
var name: String
var title: String
var avatar: UIImage
init(name: String, songTitle: String, avatar: UIImage) {
self.name = name
self.title = songTitle
self.avatar = avatar
}
}
| true
|
6a388f9699ef85542f953f0bf58c7829e010ab2c
|
Swift
|
NicholasTD07/HarvestAPI.swift
|
/Sources/HarvestAPI.swift
|
UTF-8
| 8,768
| 2.96875
| 3
|
[
"MIT"
] |
permissive
|
import Foundation
import enum Alamofire.HTTPMethod
import class Alamofire.SessionManager
import class Alamofire.Request
import enum Result.Result
import Argo
import Curry
import Runes
public protocol APIType {
typealias DayHandler = (_ date: Date) -> (_: Result<Model.Day, API.Error>) -> Void
typealias ProjectsHandler = (_: Result<[Model.Project], API.Error>) -> Void
typealias UserHandler = (_: Result<Model.User, API.Error>) -> Void
func days(_ days: [Date], handler: @escaping APIType.DayHandler)
func day(at date: Date, handler: @escaping APIType.DayHandler)
func projects(handler: @escaping ProjectsHandler)
func user(handler: @escaping UserHandler)
}
extension API {
public enum Error: Swift.Error {
case networkFailed(Swift.Error)
case decodingFailed(DecodeError)
}
}
public struct API: APIType {
public typealias HTTPBasicAuth = (username: String, password: String)
public let company: String
private let auth: HTTPBasicAuth
private let sessionManager: SessionManager
public init(company: String, auth: HTTPBasicAuth) {
self.company = company
self.auth = auth
let configuration = URLSessionConfiguration.default
let authorizationHeader = Request.authorizationHeader(
user: auth.username,
password: auth.password
)!
configuration.httpAdditionalHeaders = [
"Accept": "application/json",
authorizationHeader.key: authorizationHeader.value,
]
self.sessionManager = SessionManager(configuration: configuration)
}
public func days(_ days: [Date], handler: @escaping APIType.DayHandler) {
days.forEach { day(at: $0, handler: handler) }
}
public func day(at date: Date, handler: @escaping APIType.DayHandler) {
request(Router.day(at: date), with: handler(date))
}
public func projects(handler: @escaping APIType.ProjectsHandler) {
request(Router.today) { (result: Result<Model.Day, API.Error>) in
switch result {
case let .success(day):
handler(.success(day.projects))
case let .failure(error):
handler(.failure(error))
}
}
}
public func user(handler: @escaping APIType.UserHandler) {
request(Router.whoami, with: handler)
}
private func request<Value>(_ route: Router, with handler: @escaping (_: Result<Value, API.Error>) -> Void)
where Value: Decodable, Value.DecodedType == Value {
sessionManager.request(route.request(forCompany: company))
.responseJSON { response in
guard let json = response.result.value else {
handler(.failure(.networkFailed(response.result.error!)))
return
}
let decoded: Decoded<Value> = decode(json)
switch decoded {
case let .success(value):
handler(.success(value))
case let .failure(decodeError):
handler(.failure(.decodingFailed(decodeError)))
}
}
}
// Note: This is here for requesting `[Decodable]` types
// Difference to the one above is where `Value` is used, it is replaced with `[Value]`
// FIXME: Investigate whether there's a better/more clever way to solve it
// without duplicating 98% of the code
private func request<Value>(_ route: Router, with handler: @escaping (_: Result<[Value], API.Error>) -> Void)
where Value: Decodable, Value.DecodedType == Value {
sessionManager.request(route.request(forCompany: company))
.responseJSON { response in
guard let json = response.result.value else {
handler(.failure(.networkFailed(response.result.error!)))
return
}
let decoded: Decoded<[Value]> = decode(json)
switch decoded {
case let .success(value):
handler(.success(value))
case let .failure(decodeError):
handler(.failure(.decodingFailed(decodeError)))
}
}
}
}
public enum Router {
case whoami
case today
case day(at: Date)
case addEntry
public func request(forCompany company: String) -> URLRequest {
let baseURL = URL(string: "https://\(company).harvestapp.com")!
var request = URLRequest(url: baseURL.appendingPathComponent(path))
request.httpMethod = method.rawValue
// encode param
return request
}
public var method: HTTPMethod {
switch self {
case .whoami, .today, .day:
return .get
case .addEntry:
return .post
}
}
public var path: String {
switch self {
case .whoami:
return "/account/who_am_i"
case .today:
return "/daily"
case let .day(date):
let day = calendar.ordinality(of: .day, in: .year, for: date)!
let year = calendar.component(.year, from: date)
return "/daily/\(day)/\(year)"
case .addEntry:
return "/daily/add"
}
}
}
private let calendar = Calendar.current
public enum Model {
public struct User {
public let firstName: String
public let lastName: String
public var name: String {
return "\(firstName) \(lastName)"
}
}
public struct Day {
public let dateString: String
public let entries: [Entry]
public let projects: [Project]
public func date() -> Date {
return Day.dateFormatter.date(from: dateString)!
}
public static let dateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
return dateFormatter
}()
}
public struct Entry {
public let hours: Float
}
public struct Project {
public let id: Int
public let name: String
public let billable: Bool
public let tasks: [Task]
}
public struct Task {
public let id: Int
public let name: String
public let billable: Bool
}
}
extension Model.User: Decodable {
public static func decode(_ json: JSON) -> Decoded<Model.User> {
return curry(Model.User.init)
<^> json <| ["user", "first_name"]
<*> json <| ["user", "last_name"]
}
}
extension Model.Day: Decodable {
public static func decode(_ json: JSON) -> Decoded<Model.Day> {
return curry(Model.Day.init)
<^> json <| "for_day"
<*> json <|| "day_entries"
<*> json <|| "projects"
}
}
extension Model.Entry: Decodable {
public static func decode(_ json: JSON) -> Decoded<Model.Entry> {
return curry(Model.Entry.init)
<^> json <| "hours"
}
}
extension Model.Project: Decodable {
public static func decode(_ json: JSON) -> Decoded<Model.Project> {
return curry(Model.Project.init)
<^> json <| "id"
<*> json <| "name"
<*> json <| "billable"
<*> json <|| "tasks"
}
}
extension Model.Task: Decodable {
public static func decode(_ json: JSON) -> Decoded<Model.Task> {
return curry(Model.Task.init)
<^> json <| "id"
<*> json <| "name"
<*> json <| "billable"
}
}
extension Model.Project: Equatable { }
public func == (rhs: Model.Project, lhs: Model.Project) -> Bool {
return rhs.id == lhs.id
}
extension Model.Task: Equatable { }
public func == (rhs: Model.Task, lhs: Model.Task) -> Bool {
return rhs.id == lhs.id
}
// ViewModel candidates
extension Model.Day {
public func hours() -> Float {
return entries.reduce(0) { $0 + $1.hours }
}
}
extension Model.Project {
public var description: String {
let billableString = billable ? "Billable" : "Non-billable"
return "\(billableString) \(name)"
}
}
extension Model.Task {
public var description: String {
let billableString = billable ? "Billable" : "Non-billable"
return "\(billableString) \(name)"
}
}
/** From: https://github.com/NicholasTD07/TTTTT/blob/master/2016-08---Py---Harvest-Season/harvest_season.py
entry_post_payload = {
'notes': notes,
'hours': hours,
'project_id': project.id,
'task_id': task.id,
'spent_at': spent_at,
}
*/
| true
|
6889fcca88d5376dd513512b0ff2da6daa26192b
|
Swift
|
GregoryCremins/SwiftOS
|
/DeviceDriverKeyboard.swift
|
UTF-8
| 14,816
| 3.046875
| 3
|
[] |
no_license
|
//
// DeviceDriverKeyboard.swift
// XCodeOS3
//
// Created by Marist User on 5/7/16.
// Copyright © 2016 Marist User. All rights reserved.
//
import Foundation
///<reference path="deviceDriver.ts" />
/* ----------------------------------
DeviceDriverKeyboard.ts
Requires deviceDriver.ts
The Kernel Keyboard Device Driver.
---------------------------------- */
// Extends DeviceDriver
class DeviceDriverKeyboard : DeviceDriver {
init() {
// Override the base method pointers.
super.init(driverEntry: "keyboard", isr: "KeyboardEvent");
}
func krnKbdDriverEntry() {
// Initialization routine for this, the kernel-mode Keyboard Device Driver.
self.status = "loaded";
// More?
}
func krnKbdDispatchKeyPress(params:[String]) {
// Parse the params. TODO: Check that they are valid and osTrapError if not.
let keyCodeStr = params[0];
let keyCode = Int(keyCodeStr)!;
let isShiftedStr = params[1];
let isShifted = isShiftedStr == "true";
_Kernel.krnTrace("Key code:" + keyCodeStr + " shifted:" + isShiftedStr);
var chr = "";
// Check to see if we even want to deal with the key that was pressed.
//first check if it was backspace or tab
if(keyCode == 126)
{
_KernelInputQueue.enqueue("upArrow");
}
if(keyCode == 125)
{
_KernelInputQueue.enqueue("downArrow");
}
//backspace
if(keyCode == 51)
{
//chr = String.fromCharCode(keyCode);
chr = String(UnicodeScalar(8))
_KernelInputQueue.enqueue(chr);
}
//tab
if(keyCode == 48)
{
//chr = String.fromCharCode(keyCode);
chr = String(UnicodeScalar(9))
_KernelInputQueue.enqueue(chr);
}
// if (((keyCode >= 65) && (keyCode <= 90)) || // A..Z
// ((keyCode >= 97) && (keyCode <= 123))){ // a..z
if(((keyCode >= 0) && (keyCode <= 9)) || ((keyCode >= 11) && (keyCode <= 17)) || ((keyCode >= 31) && (keyCode <= 32)) || ((keyCode >= 34) && (keyCode <= 35)) || ((keyCode >= 37) && (keyCode <= 38)) || (keyCode == 40) || keyCode == 46 || keyCode == 45)
{
var correctCode = 0;
switch(keyCode)
{
//a
case 0:
correctCode = 65;
case 11:
correctCode = 66;
case 8:
correctCode = 67;
case 2:
correctCode = 68;
case 14:
correctCode = 69;
case 3:
correctCode = 70;
case 5:
correctCode = 71;
case 4:
correctCode = 72;
case 34:
correctCode = 73;
case 38:
correctCode = 74;
case 40:
correctCode = 75;
case 37:
correctCode = 76;
case 46:
correctCode = 77;
case 45:
correctCode = 78;
case 31:
correctCode = 79;
case 35:
correctCode = 80;
case 12:
correctCode = 81;
case 15:
correctCode = 82;
case 1:
correctCode = 83;
case 17:
correctCode = 84;
case 32:
correctCode = 85;
case 9:
correctCode = 86;
case 13:
correctCode = 87;
case 7:
correctCode = 88;
case 16:
correctCode = 89;
case 6:
correctCode = 90;
default:
//return nothing
break;
}
// Determine the character we want to display.
// Assume it's lowercase...
correctCode = correctCode + 32;
// chr = String.fromCharCode(keyCode + 32);
//chr = String(UnicodeScalar(keyCode + 32));
// ... then check the shift key and re-adjust if necessary.
// if (isShifted) {
//chr = String.fromCharCode(keyCode);
// chr = String(UnicodeScalar(keyCode));
// print(chr);
// print(keyCode);
// }
// TODO: Check for caps-lock and handle as shifted if so.
if(_RootController.isShifted)
{
correctCode = correctCode - 32;
}
_KernelInputQueue.enqueue(String(UnicodeScalar(correctCode)));
} else
if (((keyCode >= 18) && (keyCode <= 29)) || // digits
(keyCode == 49) || // space
(keyCode == 36)) { // enter
var correctCode = 0;
if(isShifted && ((keyCode >= 48) && (keyCode <= 57)))
{
switch(keyCode)
{
case 29:
// close parenthesis
correctCode = 41;
break;
case 18:
// exclamation point
correctCode = 33;
break;
case 19:
// at symbol
correctCode = 64;
break;
case 20:
//hashtag
correctCode = 35;
break;
case 21:
//dolla dolla bill yall
correctCode = 36;
break;
case 23:
//percent
correctCode = 37;
break;
case 22:
//hat
correctCode = 94;
break;
case 26:
//and symbol
correctCode = 38;
break;
case 28:
//star
correctCode = 42;
break;
case 25:
//open parenthesis
correctCode = 40;
break;
default:
//keyCode = keyCode;
break
}
}
else
{
switch(keyCode)
{
case 29:
// 0
correctCode = 48;
break;
case 18:
// 1
correctCode = 49;
break;
case 19:
// 2
correctCode = 50;
break;
case 20:
//3
correctCode = 51;
break;
case 21:
//4
correctCode = 52;
break;
case 23:
//5
correctCode = 53;
break;
case 22:
//6
correctCode = 54;
break;
case 26:
//7
correctCode = 55;
break;
case 28:
//8
correctCode = 56;
break;
case 25:
//9
correctCode = 57;
break;
default:
//keyCode = keyCode;
break
}
}
if(keyCode == 49)
{
correctCode = 32;
}
if(keyCode == 36)
{
correctCode = 13;
}
//chr = String.fromCharCode(keyCode);
chr = String(UnicodeScalar(correctCode));
_KernelInputQueue.enqueue(chr);
}
else
{
var correctCode = 0;
//handle all punctuation marks
var foundPunctMark = false;
if(keyCode == 47 && !foundPunctMark) //period
{
correctCode = 46;
if(isShifted)
{
correctCode = 62;
}
foundPunctMark = true;
//chr = String.fromCharCode(keyCode);
chr = String(UnicodeScalar(correctCode));
_KernelInputQueue.enqueue(chr);
}
if(keyCode == 43 && !foundPunctMark) //comma
{
correctCode = 44;
if(isShifted)
{
correctCode = 60;
}
foundPunctMark = true;
// chr = String.fromCharCode(keyCode);
chr = String(UnicodeScalar(correctCode));
_KernelInputQueue.enqueue(chr);
}
if(keyCode == 44 && !foundPunctMark) //forward slash
{
correctCode = 191;
if(isShifted)
{
correctCode = 63;
}
foundPunctMark = true;
//chr = String.fromCharCode(keyCode);
chr = String(UnicodeScalar(correctCode));
_KernelInputQueue.enqueue(chr);
}
if(keyCode == 41 && !foundPunctMark) //semicolon
{
correctCode = 59;
if(isShifted)
{
correctCode = 58;
}
foundPunctMark = true;
//chr = String.fromCharCode(keyCode);
chr = String(UnicodeScalar(correctCode));
_KernelInputQueue.enqueue(chr);
}
if(keyCode == 39 && !foundPunctMark) //apostrophe
{
correctCode = 39;
if(isShifted)
{
correctCode = 34;
}
foundPunctMark = true;
//chr = String.fromCharCode(keyCode);
chr = String(UnicodeScalar(correctCode));
_KernelInputQueue.enqueue(chr);
}
if(keyCode == 33 && !foundPunctMark) //open bracket
{
correctCode = 91;
if(isShifted)
{
correctCode = 123;
}
foundPunctMark = true;
//chr = String.fromCharCode(keyCode);
chr = String(UnicodeScalar(correctCode));
_KernelInputQueue.enqueue(chr);
}
if(keyCode == 30 && !foundPunctMark) //close bracket
{
correctCode = 93;
if(isShifted)
{
correctCode = 125;
}
foundPunctMark = true;
//chr = String.fromCharCode(keyCode);
chr = String(UnicodeScalar(correctCode));
_KernelInputQueue.enqueue(chr);
}
if(keyCode == 42 && !foundPunctMark) //backslash
{
correctCode = 92;
if(isShifted)
{
correctCode = 124;
}
foundPunctMark = true;
//chr = String.fromCharCode(keyCode);
chr = String(UnicodeScalar(correctCode));
_KernelInputQueue.enqueue(chr);
}
if(keyCode == 27 && !foundPunctMark) //dash
{
correctCode = 45;
if(isShifted)
{
correctCode = 95;
}
foundPunctMark = true;
// chr = String.fromCharCode(keyCode);
chr = String(UnicodeScalar(correctCode));
_KernelInputQueue.enqueue(chr);
}
if(keyCode == 24 && !foundPunctMark) //equals sign
{
correctCode = 61;
if(isShifted)
{
correctCode = 43;
}
foundPunctMark = true;
// chr = String.fromCharCode(keyCode);
chr = String(UnicodeScalar(correctCode));
_KernelInputQueue.enqueue(chr);
}
if(keyCode == 50 && !foundPunctMark) //tilda a.k.a. tildashmerde
{
correctCode = 96;
if(isShifted)
{
correctCode = 126;
}
foundPunctMark = true;
//chr = String.fromCharCode(keyCode);
chr = String(UnicodeScalar(correctCode));
_KernelInputQueue.enqueue(chr) ;
}
}
}
}
| true
|
132f04a1515f1a05352cb8061bd815bb45d9d9c6
|
Swift
|
Dofsevenn/InstantComics
|
/InstantComics/Views/ComicsLargeView.swift
|
UTF-8
| 7,462
| 2.859375
| 3
|
[] |
no_license
|
//
// ComicsLargeView.swift
// InstantComics
//
// Created by Kjetil Skyldstad Bjelldokken on 18/03/2021.
//
import SwiftUI
struct ComicsLargeView: View {
@ObservedObject var comicsVM = ComicsViewModel()
@State var showAlert = false
@State var buttonAction: Int? = 0
@State private var description = ""
var body: some View {
HStack {
Spacer()
// Left container
VStack {
Spacer()
// Comic title
Text(comicsVM.title)
.bold()
.frame(minWidth: 0, maxWidth: .infinity, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/)
.font(.system(size: 30))
Spacer()
// Top button container
HStack {
Button(action: {
comicsVM.onClickPreviousButton()
}) {
Text("< Previous")
.padding()
.frame(width: 120, height: 40, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/)
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(10)
}
Button(action: {
comicsVM.onClickRandomButton()
}) {
Text("Random")
.padding()
.frame(width: 120, height: 40, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/)
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(10)
}
Button(action: {
comicsVM.onClickNextButton()
}) {
Text("next >")
.frame(width: 120, height: 40, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/)
.background(buttonColor)
.foregroundColor(.white)
.cornerRadius(10)
}
.disabled(isNewestComic)
}
.frame(minWidth: 0, maxWidth: .infinity, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/)
Spacer()
// Bottom buttons container
HStack{
Button(action: {
comicsVM.onClickSkipToTheStartButton()
}) {
Text("|<")
.frame(width: 50, height: 40, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/)
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(10)
}
.padding(.leading, 20)
Spacer()
// Passing the description variable to the Description view through Navigation link
NavigationLink(destination: DescriptionView(description: self.$description), tag: 1, selection: $buttonAction) {
EmptyView()
}
Button(action: {
self.description = comicsVM.description
self.buttonAction = 1
}) {
Text("Description")
.frame(width: 120, height: 40, alignment: .center)
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(10)
}
Spacer()
Button(action: actionSheet) {
Image(systemName: "square.and.arrow.up")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 40, height: 40)
}
Spacer()
Button(action: {
comicsVM.onClickSkipToTheEndButton()
}) {
Text(">|")
.frame(width: 50, height: 40, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/)
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(10)
}
.padding(.trailing, 20)
}
Spacer()
// Information container
HStack {
Text("No: \(comicsVM.num)")
Spacer()
Text("Day: \(comicsVM.month)")
Spacer()
Text("Month: \(comicsVM.month)")
Spacer()
Text("Year: \(comicsVM.year)")
}
.padding()
}
// Image container, and right container
VStack{
Image(uiImage: comicsVM.image.load())
.resizable()
.scaledToFit()
.frame(minWidth: 0, idealWidth: 400, maxWidth: .infinity, minHeight: 0, idealHeight: 350, maxHeight: .infinity, alignment: .center)
.padding(.top, 10)
.padding(.bottom, 10)
.onLongPressGesture {
print("pressed")
self.showAlert = true
}
.alert(isPresented: $showAlert) {
Alert(title: Text(""), message: Text(comicsVM.alt), dismissButton: .default(Text("Close")))
}
Text("Press and hold the image to se the description!")
.padding(.bottom, 17)
}
Spacer()
}
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/)
.onAppear {
comicsVM.fetchCurrentComicData()
}
}
func actionSheet() {
guard let data = URL(string: comicsVM.image) else { return }
let activityVC = UIActivityViewController(activityItems: [data], applicationActivities: nil)
UIApplication.shared.windows.first?.rootViewController?.present(activityVC, animated: true, completion: nil)
}
var isNewestComic: Bool {
return comicsVM.currentComicNumber == comicsVM.newestComicNumber
}
var buttonColor: Color {
return isNewestComic ? .gray : .blue
}
}
struct ComicsLargeView_Previews: PreviewProvider {
static var previews: some View {
ComicsLargeView().previewLayout(.fixed(width: 896, height: 414))
}
}
| true
|
c27672a46e6e32c9e8379b6dbb20d4ddc755d42d
|
Swift
|
PacktPublishing/Swift-5-Projects
|
/chapter-1/13-URLSession.playground/Contents.swift
|
UTF-8
| 7,347
| 2.84375
| 3
|
[
"MIT"
] |
permissive
|
import Foundation
// DOWNLOADING
func moveFile(file: URL, dst: URL) {
do {
let savedUrl = dst.appendingPathComponent(file.lastPathComponent)
print ("file error: \(savedUrl)")
try FileManager.default.moveItem(at: file, to: savedUrl)
} catch {
print ("file error: \(error)")
}
}
func downloadFileInOneShot(url : URL?, dstUrl : URL) {
guard let url = url else {
print("No URL provided")
return
}
let downloadTask = URLSession.shared.downloadTask(with: url) {
urlOrNil, responseOrNil, errorOrNil in
if let error = errorOrNil {
print("Download error \(error)")
return
}
guard let response = responseOrNil as? HTTPURLResponse else {
print("Unexpected error")
return
}
if (response.statusCode < 200 && response.statusCode > 299) {
print("Server returned HTTP error: \(response.statusCode)")
return
}
guard let fileUrl = urlOrNil else {
print("Unexpected error: missing local path")
return
}
moveFile(file: fileUrl, dst: dstUrl)
}
downloadTask.resume()
}
let downloadURL = URL(string: "http://placehold.it/1200x1200&text=image1")
do {
let documentsUrl = try
FileManager.default.url(for: .documentDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: true)
downloadFileInOneShot(url: downloadURL, dstUrl : documentsUrl)
} catch {
print ("Could not find destination directory")
}
// DOWNLOAD AND SHOW PROGRESS INFO
class FileDownloader : NSObject, URLSessionDownloadDelegate {
private var task : URLSessionDownloadTask?
private var dstDir : URL?
private lazy var urlSession = URLSession(configuration: .default,
delegate: self,
delegateQueue: nil)
func startDownload(url: URL, dstDir: URL) {
self.dstDir = dstDir
let downloadTask = urlSession.downloadTask(with: url)
downloadTask.resume()
self.task = downloadTask
}
// While download progresses:
func urlSession(_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didWriteData bytesWritten: Int64,
totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64) {
if downloadTask == self.task {
let progress = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)
print("Progress: \(progress)")
}
}
// If download fails
func urlSession(_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didFinishDownloadingTo location: URL) {
guard let response = downloadTask.response as? HTTPURLResponse else {
print("File Downloader unexpected error")
return
}
if (response.statusCode < 200 && response.statusCode > 299) {
print("Server returned HTTP error: \(response.statusCode)")
return
}
moveFile(file: location, dst: dstDir!)
}
}
do {
let dstDir = try
FileManager.default.url(for: .documentDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: true)
FileDownloader().startDownload(url: downloadURL!, dstDir: dstDir)
} catch {
print ("Could not find destination directory")
}
// UPLOADING
func uploadDataInOneShot<T : Codable>(url : URL, data : T) {
guard let uploadData = try? JSONEncoder().encode(data) else {
return
}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let task = URLSession.shared.uploadTask(with: request, from: uploadData) { data, response, error in
if let error = error {
print ("UploadData error: \(error)")
return
}
guard let response = response as? HTTPURLResponse else {
print("Unexpected error")
return
}
if (response.statusCode < 200 && response.statusCode > 299) {
print("Server returned HTTP error: \(response.statusCode)")
return
}
if let mimeType = response.mimeType, mimeType == "application/json",
let data = data,
let dataString = String(data: data, encoding: .utf8) {
print ("Upload response data: \(dataString)")
}
}
task.resume()
}
struct JSONPlaceholderTodo : Codable {
let userId : Int
let id : Int?
let title : String
let completed : Bool
}
let td = JSONPlaceholderTodo(userId: 100, id: nil, title: "Doing Laundry", completed: true)
let postUrl = URL(string: "https://jsonplaceholder.typicode.com/todos")!
uploadDataInOneShot(url: postUrl, data: td)
// REST GET
func get<T: Codable>(url: URL, callback: @escaping (T?, Error?) -> Void) -> URLSessionTask {
let task = URLSession.shared.dataTask(with: url) { data, response, error in
if let error = error {
callback(nil, error)
return
}
guard let data = data else {
//callback(nil, makeError)
return
}
do {
let result = try JSONDecoder().decode(T.self, from: data)
callback(result, nil)
} catch let error {
callback(nil, error)
}
}
task.resume()
return task
}
func post<T: Codable>(url: URL, value : T, callback: @escaping (T?, Error?) -> Void) {
do {
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = try JSONEncoder().encode(value)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
callback(nil, error)
return
}
if let data = data {
do {
let result = try JSONDecoder().decode(T.self, from: data)
callback(result, nil)
} catch let error {
callback(nil, error)
}
}
}
task.resume()
} catch let error {
print("Post Error: \(error)")
}
}
let getUrl = URL(string: "https://jsonplaceholder.typicode.com/todos/1")!
get(url: getUrl) { (result : JSONPlaceholderTodo?, error) in
// error handling left as an exercise to the reader
print("Get Request result: \(String(describing: result))")
print("Get Request error: \(String(describing: error))")
}
post(url: postUrl, value: td) { (result : JSONPlaceholderTodo?, error) in
// error handling left as an exercise to the reader
print("Post Request result: \(String(describing: result))")
print("Post Request error: \(String(describing: error))")
}
| true
|
b1c6b215f16d401859682f7e14d32d79c0553439
|
Swift
|
McKayne/CloudServices
|
/CloudServices/FileViewController.swift
|
UTF-8
| 3,616
| 2.625
| 3
|
[] |
no_license
|
//
// FileViewController.swift
// CloudServices
//
// Created by Nikolay Taran on 25.10.18.
// Copyright © 2018 Nikolay Taran. All rights reserved.
//
import UIKit
class FileViewController: UIViewController {
var file: FilesTree?
var backgroundColor: UIColor
// Имя выбранного файла
let fileName = UILabel()
// Превью
let preview = UIImageView()
// Строка аттрибутов
let fileAttributes = UILabel()
// URL файла в Dropbox
let fileURL = UILabel()
convenience init(backgroundColor: UIColor) {
self.init(nibName: nil, bundle: nil)
self.backgroundColor = backgroundColor
}
convenience init(backgroundColor: UIColor, file: FilesTree) {
self.init(nibName: nil, bundle: nil)
self.backgroundColor = backgroundColor
self.file = file
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
backgroundColor = .white
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
view.backgroundColor = backgroundColor
// Имя выбранного файла
fileName.textAlignment = .center
fileName.numberOfLines = 0
view.addSubview(fileName)
ViewController.performAutolayoutConstants(subview: fileName, view: view, left: 0.0, right: 0.0, top: 0, bottom: -(view.frame.height / 2 + 2 * view.frame.height / 2 / 3))
// URL файла в Dropbox
fileURL.textAlignment = .center
fileURL.numberOfLines = 0
fileURL.textColor = .lightGray
view.addSubview(fileURL)
ViewController.performAutolayoutConstants(subview: fileURL, view: view, left: 0.0, right: 0.0, top: view.frame.height / 2 - 2 * view.frame.height / 2 / 3, bottom: -(view.frame.height / 2 + view.frame.height / 2 / 3))
// Строка аттрибутов
fileAttributes.textAlignment = .center
fileAttributes.numberOfLines = 0
fileAttributes.textColor = .lightGray
view.addSubview(fileAttributes)
ViewController.performAutolayoutConstants(subview: fileAttributes, view: view, left: 0.0, right: 0.0, top: view.frame.height / 2 - view.frame.height / 2 / 3, bottom: -view.frame.height / 2)
// Превью
view.addSubview(preview)
ViewController.performAutolayoutConstants(subview: preview, view: view, left: 15.0, right: -15.0, top: view.frame.height / 2 + 15, bottom: -15)
appendUI()
}
// Вызывается при обновлении информации о текущем файле
func appendUI() {
if file == nil {
fileName.text = "No file selected"
preview.image = UIImage(named: "dummyFile.jpg")
fileAttributes.text = ""
fileURL.text = ""
} else {
fileName.text = file?.name
if let previewImage = file?.preview {
preview.image = previewImage
} else {
preview.image = UIImage(named: "dummyFile.jpg")
}
fileAttributes.text = FilesDelegateDataSource.attributesString(fileName: file!)
fileURL.text = file?.urlString ?? ""
}
fileName.sizeToFit()
fileURL.sizeToFit()
fileAttributes.sizeToFit()
}
}
| true
|
83ea8309d415508e52cdcd52dc6fee41618c8a5f
|
Swift
|
Hel-len/SliderGame
|
/SliderGame/Helper.swift
|
UTF-8
| 3,337
| 2.625
| 3
|
[] |
no_license
|
//
// Helper.swift
// LoginApp
//
// Created by Елена Дранкина on 08.06.2021.
//
import SwiftUI
struct CustomColors {
let coldWhite: UIColor = .init(
red: 240 / 255,
green: 255 / 255,
blue: 255 / 255,
alpha: 1
)
let warmBlack: UIColor = .init(
red: 6 / 255,
green: 0,
blue: 0,
alpha: 1
)
let pastelYellow: UIColor = .init(
red: 1.0,
green: 1.0,
blue: 196 / 255,
alpha: 1
)
let lightYellow: UIColor = .init(
red: 1.0,
green: 1.0,
blue: 152 / 255,
alpha: 1
)
let deepYellow: UIColor = .init(
red: 1.0,
green: 1.0,
blue: 118 / 255,
alpha: 1
)
let deepMint: UIColor = .init(
red: 128 / 255,
green: 1.0,
blue: 128 / 255,
alpha: 1
)
let pastelTurquois: UIColor = .init(
red: 179 / 255,
green: 236 / 255,
blue: 236 / 255,
alpha: 1
)
let lightTurquois: UIColor = .init(
red: 137 / 255,
green: 236 / 255,
blue: 218 / 255,
alpha: 1
)
let deepTurquois: UIColor = .init(
red: 59 / 255,
green: 214 / 255,
blue: 198 / 255,
alpha: 1
)
let turquois: UIColor = .init(
red: 64 / 255,
green: 1.0,
blue: 192 / 255,
alpha: 1
)
let deepBlue: UIColor = .init(
red: 68 / 255,
green: 128 / 255,
blue: 1.0,
alpha: 1
)
let darkBlue: UIColor = .init(
red: 0,
green: 0,
blue: 128 / 255,
alpha: 1
)
}
struct GradientColors {
let warmBlack: Array<Color>.ArrayLiteralElement = .init(
red: 6 / 255,
green: 0,
blue: 0
)
let pastelYellow: Array<Color>.ArrayLiteralElement = .init(
red: 1.0,
green: 1.0,
blue: 196 / 255
)
let lightYellow: Array<Color>.ArrayLiteralElement = .init(
red: 1.0,
green: 1.0,
blue: 152 / 255
)
let deepYellow: Array<Color>.ArrayLiteralElement = .init(
red: 1.0,
green: 1.0,
blue: 118 / 255
)
let deepMint: Array<Color>.ArrayLiteralElement = .init(
red: 128 / 255,
green: 1.0,
blue: 128 / 255
)
let pastelTurquois: Array<Color>.ArrayLiteralElement = .init(
red: 179 / 255,
green: 236 / 255,
blue: 236 / 255
)
let lightTurquois: Array<Color>.ArrayLiteralElement = .init(
red: 137 / 255,
green: 236 / 255,
blue: 218 / 255
)
let deepTurquois: Array<Color>.ArrayLiteralElement = .init(
red: 59 / 255,
green: 214 / 255,
blue: 198 / 255
)
let turquois: Array<Color>.ArrayLiteralElement = .init(
red: 64 / 255,
green: 1.0,
blue: 192 / 255
)
let deepBlue: Array<Color>.ArrayLiteralElement = .init(
red: 68 / 255,
green: 128 / 255,
blue: 1.0
)
let darkBlue: Array<Color>.ArrayLiteralElement = .init(
red: 0,
green: 0,
blue: 128 / 255
)
}
| true
|
b391d33e0e80f7af19e7b9064642b852b40be954
|
Swift
|
ywangnon/YooHanSub_iOS_School6
|
/Project/SkillTest/SkillTest/DisplayView.swift
|
UTF-8
| 1,617
| 2.875
| 3
|
[] |
no_license
|
//
// DisplayView.swift
// SkillTest
//
// Created by Hansub Yoo on 2018. 2. 7..
// Copyright © 2018년 hansub yoo. All rights reserved.
//
import UIKit
class DisplayView: UIView {
var resultDisplay: UILabel?
var BalanceDisplay: UILabel?
static var sum: Int = 0
override init(frame: CGRect) {
super.init(frame: frame)
createDisplayUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func createDisplayUI() {
let reulstSize: CGRect = CGRect(x: 0, y: 0, width: self.bounds.size.width, height: self.bounds.size.height/2)
resultDisplay = UILabel(frame: reulstSize)
guard let result = resultDisplay else {
return
}
self.addSubview(result)
let balanceSize: CGRect = CGRect(x: 0, y: self.bounds.size.height/2, width: self.bounds.size.width, height: self.bounds.size.height/2)
BalanceDisplay = UILabel(frame: balanceSize)
guard let balance = BalanceDisplay else {
return
}
self.addSubview(balance)
changeText(result: "결과 Text", balance: DisplayView.sum)
}
func changeText(result: String, balance: Int) {
resultDisplay?.text = result
resultDisplay?.textAlignment = NSTextAlignment.right
resultDisplay?.font = UIFont.systemFont(ofSize: 30)
BalanceDisplay?.text = "잔액 : " + String(balance) + "원"
BalanceDisplay?.textAlignment = .right
BalanceDisplay?.font = UIFont.systemFont(ofSize: 30)
}
}
| true
|
3c1de283687c70e772684a439d042fa8d9ac94bf
|
Swift
|
SnehaKalariya/Shopping_app
|
/ShoppingApp/CommonClasses/CustomPopOverMenuVC.swift
|
UTF-8
| 1,985
| 2.703125
| 3
|
[] |
no_license
|
//
// CustomPopOverMenuVC.swift
// BajajFinserv
//
// Created by PRAVIN TEPAN on 01/10/19.
// Copyright © 2019 Sushant Patil. All rights reserved.
//
import UIKit
@objc protocol CustomPopOverMenuDelegate {
func customPopOverView(_ tag: Int, didSelectMenuAt index: Int)
}
@objc class CustomPopOverMenuVC: UITableViewController {
var customPopOverDelegate: CustomPopOverMenuDelegate?
@objc var sourceTag = -1
@objc var menuDataSource = Array<String>()
var cellHeight = 40
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillLayoutSubviews() {
preferredContentSize = CGSize(width: 280, height: self.tableView.contentSize.height)
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return self.menuDataSource.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "PopOverMenuCell", for: indexPath)
cell.textLabel?.text = self.menuDataSource[indexPath.row]
cell.textLabel?.textColor = UIColor.white
cell.textLabel?.textAlignment = .center
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 40
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.dismiss(animated: true) { [weak self] in
self?.customPopOverDelegate?.customPopOverView(self?.sourceTag ?? -1, didSelectMenuAt: indexPath.row)
}
}
}
| true
|
6f67b6b59bc752bdf8307f09a013c8e93c3ecfed
|
Swift
|
rickychauhk/CodeTestWeather
|
/CodeTestWeather/CodeTestWeather/Controller/SearchViewController.swift
|
UTF-8
| 5,825
| 2.53125
| 3
|
[] |
no_license
|
//
// SearchViewController.swift
// CodeTestWeather
//
// Created by Ricky on 17/7/2021.
//
import Foundation
import UIKit
import MapKit
class SearchViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet var searchBar: UISearchBar!
@IBOutlet var tableView: UITableView!
@IBOutlet var gpsBarBtn: UIBarButtonItem!
let searchViewModel: SearchViewModel = SearchViewModel()
var cities = [String]()
var searchedCities = [String]()
var searching = false
var selected: String = ""
var locationManger: CLLocationManager!
var lat: String = ""
var lon: String = ""
override func viewDidLoad() {
super.viewDidLoad()
self.tableView = searchViewModel.setupTableView(tableView: self.tableView)
self.searchBar = searchViewModel.setupSearchbar(searchBar: self.searchBar)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(false)
self.listOfCities()
resetData()
}
@IBAction func getUserLLocation() {
if (CLLocationManager.locationServicesEnabled()) {
locationManger = CLLocationManager()
locationManger.delegate = self
locationManger.desiredAccuracy = kCLLocationAccuracyBest
locationManger.requestWhenInUseAuthorization()
locationManger.requestLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.last {
if location.horizontalAccuracy < 0 {
return
}
self.lon = String(location.coordinate.longitude)
self.lat = String(location.coordinate.latitude)
if !self.lon.isEmpty && !self.lat.isEmpty {
performSegue(withIdentifier: Constants.detailViewId, sender: self)
resetData()
}
}
}
func listOfCities() {
let userDefaults = UserDefaults.standard
self.cities = (userDefaults.object(forKey: Constants.storeKey) as? [String] ?? [])
tableView.reloadData()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == Constants.detailViewId {
let detailViewController = segue.destination as? DetailViewController
detailViewController?.searchedCity = self.selected as String
detailViewController?.lat = self.lat as String
detailViewController?.lon = self.lon as String
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
debugPrint(error.localizedDescription)
}
func resetData() {
self.searchBar.searchTextField.text = ""
self.lon = ""
self.lat = ""
self.selected = ""
self.searching = false
}
}
extension SearchViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return searchViewModel.setupNumberOfRowsInSection(searching: self.searching, section: section, cities: self.cities, searchedCity: self.searchedCities)
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if (editingStyle == .delete) {
self.cities.remove(at: indexPath.row)
tableView.beginUpdates()
tableView.deleteRows(at: [indexPath], with: .middle)
tableView.endUpdates()
searchViewModel.updateCities(cities: cities)
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = searchViewModel.setupCellForRowAt(searching: self.searching, tableView: tableView, indexPath: indexPath, cities: self.cities, searchedCity: self.searchedCities)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
var selectedCountry: String = ""
if self.searching {
selectedCountry = searchedCities[indexPath.row]
selectedCountry = searchViewModel.textEncode(text: selectedCountry)
} else {
selectedCountry = cities[indexPath.row]
selectedCountry = searchViewModel.textEncode(text: selectedCountry)
}
self.selected = selectedCountry
performSegue(withIdentifier: Constants.detailViewId, sender: self)
tableView.deselectRow(at: indexPath, animated: true)
self.searchBar.searchTextField.endEditing(true)
}
}
extension SearchViewController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
self.searchedCities = cities.filter { $0.lowercased().prefix(searchText.count) == searchText.lowercased() }
self.searching = true
tableView.reloadData()
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
self.searching = false
searchBar.text = ""
resetData()
tableView.reloadData()
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
if let city = searchBar.text {
searchViewModel.insetCity(searchText: city, cities: self.cities)
self.selected = searchViewModel.textEncode(text: city)
performSegue(withIdentifier: Constants.detailViewId, sender: self)
resetData()
}
}
}
| true
|
9bdf2fed8e9ce667214aa17952a721a48584d3f4
|
Swift
|
jin-awoo/Concentration
|
/Concentration 2/ViewController.swift
|
UTF-8
| 4,758
| 2.8125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Concentration 2
//
// Created by JINGYA HAN on 19/3/19.
// Copyright © 2019 JINGYA HAN. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
// UIViewController is the superclass
private lazy var game = Concentration(numberOfPairsOfCards: numberOfPairsOfCards)
var numberOfPairsOfCards: Int {
return cardButtons.count/2
}
@IBAction func newGame(_ sender: UIButton) {
Card.identifierFactory = 0
emoji = [Int: String]()
game = Concentration(numberOfPairsOfCards: numberOfPairsOfCards)
getEmojiChoises()
getColors()
updateViewFromModel()
}
@IBOutlet private var cardButtons: [UIButton]!
@IBOutlet private weak var flipCountLabel: UILabel!
@IBOutlet private weak var score: UILabel!
@IBOutlet weak var speedBonus: UILabel!
@IBAction private func touchCard(_ sender: UIButton) {
if let cardNumber = cardButtons.firstIndex(of: sender){
game.chooseCard(at: cardNumber)
updateViewFromModel()
} else {
print("Not Set.")
}
}
private func updateViewFromModel(){
self.view.backgroundColor = themeOfColorsChoice[2]
for index in cardButtons.indices{
let card = game.cards[index]
let button = cardButtons[index]
if card.isFaceUp == true {
button.setTitle(emoji(for: card), for: UIControl.State.normal)
button.backgroundColor = themeOfColorsChoice[0]
} else {
button.setTitle("", for: UIControl.State.normal)
button.backgroundColor = card.isMatched ? #colorLiteral(red: 1, green: 0.5763723254, blue: 0, alpha: 0) : themeOfColorsChoice[1]
}
}
flipCountLabel.text = "flip count: \(game.flipCount)"
score.text = "score: \(game.Score)"
speedBonus.text = "Speed Bonus: \(game.speedBonus)"
}
var indexOfRandomTheme = 0
private func getEmojiChoises() {
var themes = [[String]]()
themes.append(["😀","😁","🤪","😋","😎","😏","😛","😤","😵","😬"])
themes.append(["💟","☮️","✝️","☪️","🕉","☸️","✡️","🔯","🕎","☯️"])
themes.append(["Ⓜ️","💤","🏧","🚾","♿️","🅿️","🈳","🈂️","🛂","🛄"])
themes.append(["🉐","㊙️","㊗️","🈲","🅰️","🆘","🈵","‼️","🈴","🈹"])
indexOfRandomTheme = themes.count.arc4random
emojiChoises = themes[indexOfRandomTheme]
}
private var themeOfColorsChoice = [#colorLiteral(red: 1, green: 1, blue: 1, alpha: 1),#colorLiteral(red: 1, green: 0.5763723254, blue: 0, alpha: 1),#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)]
private func getColors() {
var themeOfColors = [[UIColor]]()
themeOfColors.append([#colorLiteral(red: 1, green: 1, blue: 1, alpha: 1),#colorLiteral(red: 1, green: 0.5763723254, blue: 0, alpha: 1),#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)])
themeOfColors.append([#colorLiteral(red: 0.2745098174, green: 0.4862745106, blue: 0.1411764771, alpha: 1),#colorLiteral(red: 0.4745098054, green: 0.8392156959, blue: 0.9764705896, alpha: 1),#colorLiteral(red: 0.9686274529, green: 0.78039217, blue: 0.3450980484, alpha: 1)])
themeOfColors.append([#colorLiteral(red: 0.5058823824, green: 0.3372549117, blue: 0.06666667014, alpha: 1),#colorLiteral(red: 0.6000000238, green: 0.6000000238, blue: 0.6000000238, alpha: 1),#colorLiteral(red: 0.2588235438, green: 0.7568627596, blue: 0.9686274529, alpha: 1)])
themeOfColors.append([#colorLiteral(red: 0.5568627715, green: 0.3529411852, blue: 0.9686274529, alpha: 1),#colorLiteral(red: 0.1019607857, green: 0.2784313858, blue: 0.400000006, alpha: 1),#colorLiteral(red: 0.9098039269, green: 0.4784313738, blue: 0.6431372762, alpha: 1)])
themeOfColorsChoice = themeOfColors[indexOfRandomTheme]
}
private var emojiChoises = ["😀","😁","🤪","😋","😎","😏","😛","😤","😵","😬"]
private var emoji = [Int: String]()
private func emoji(for card: Card) -> String{
if emoji[card.identifier] == nil, emojiChoises.count > 0 {
emoji[card.identifier] = emojiChoises.remove(at: emojiChoises.count.arc4random)
}
return emoji[card.identifier] ?? "?"
}
}
extension Int {
var arc4random: Int {
if self > 0 {
return Int(arc4random_uniform(UInt32(self)))
} else if self < 0 {
return Int(arc4random_uniform(UInt32(abs(self))))
} else {
return 0
}
}
}
| true
|
e265b1f97c91b9dc8c8b99a139563b63ac47bcd9
|
Swift
|
PeqNP/SimpleAnalytics
|
/Analytics/SimpleAnalytics/AnalyticsService.swift
|
UTF-8
| 2,496
| 2.65625
| 3
|
[] |
no_license
|
/**
Provides a way to track analytics.
@copyright 2022 Bithead, LLC. All rights reserved.
*/
import Foundation
class AnalyticsService {
private let listeners: [AnalyticsListener]
private var transactions = [String /* Event location */: DispatchTime /* Time started */]()
init(listeners: [AnalyticsListener]) {
self.listeners = listeners
}
func send(_ event: AnalyticsEvent) {
listeners.forEach { (listener) in
listener.receive(event)
}
}
func start( _ event: AnalyticsEvent) {
let id = eventId(for: event)
guard transactions[id] == nil else {
print("WARN: Attempting to start a transaction event for \(event) which has already been started")
return
}
let startTime = DispatchTime.now()
transactions[id] = startTime
listeners.forEach { (listener) in
let context: AnalyticsTransaction = .start(AnalyticsStartedTransaction(
startTime: Double(startTime.uptimeNanoseconds) / 1_000_000_000
))
listener.transaction(event, context)
}
}
func cancel( _ event: AnalyticsEvent) {
finishTransaction(event, status: .stopped)
}
func stop( _ event: AnalyticsEvent) {
finishTransaction(event, status: .stopped)
}
func publisher<T: AnalyticsEvent>() -> AnalyticsPublisher<T> {
return AnalyticsPublisher<T>(service: self)
}
// MARK: - Private methods
private func eventId(for event: AnalyticsEvent) -> String {
return String(describing: event)
}
private func finishTransaction(_ event: AnalyticsEvent, status: AnalyticsTransaction.Status) {
let id = eventId(for: event)
guard let startTime = transactions[id] else {
return
}
transactions.removeValue(forKey: id)
let stopTime = DispatchTime.now()
let nanoTime = stopTime.uptimeNanoseconds - startTime.uptimeNanoseconds
let totalTime = Double(nanoTime) / 1_000_000_000
listeners.forEach { (listener) in
let context: AnalyticsTransaction = .finish(AnalyticsFinishedTransaction(
status: status,
startTime: Double(startTime.uptimeNanoseconds) / 1_000_000_000,
stopTime: Double(stopTime.uptimeNanoseconds) / 1_000_000_000,
totalTime: totalTime
))
listener.transaction(event, context)
}
}
}
| true
|
501700b620ed7c1e4551c86dc5c7a756e1fe0a65
|
Swift
|
joanroig/GnomeContactsVIPER
|
/GnomeContacts/GnomeList/Protocols/GnomeListProtocols.swift
|
UTF-8
| 1,668
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
//
// GnomeListProtocols.swift
// GnomeContacts
//
// Created by Joan Roig on 3/3/18.
// Copyright © 2018 Joan Roig. All rights reserved.
//
import UIKit
protocol GnomeListRouterProtocol: class {
static func createGnomeList() -> UIViewController
// Presenter -> Router
func presentGnomeDetailScreen(from view: GnomeListViewProtocol, gnome: Gnome)
}
protocol GnomeListPresenterProtocol: class {
var view: GnomeListViewProtocol? {get set}
var interactor: GnomeListInteractorInputProtocol? {get set}
var router: GnomeListRouterProtocol? { get set }
// View -> Presenter
func viewDidLoad()
func showGnomeDetail(gnomeData gnome: Gnome)
}
protocol GnomeListInteractorInputProtocol: class {
var presenter: GnomeListInteractorOutputProtocol? { get set }
var entityManager: GnomeListEntityManagerInputProtocol? { get set }
// Presenter -> Interactor
func retrieveContactDirectory()
}
protocol GnomeListEntityManagerInputProtocol: class {
var requestHandler: GnomeListEntityManagerOutputProtocol? { get set }
// Interactor -> EntityManager
func requestContactDirectory()
}
protocol GnomeListEntityManagerOutputProtocol: class {
// EntityManager -> Interactor
func dataRetrieved(_ data: ContactDirectory)
func error()
}
protocol GnomeListInteractorOutputProtocol: class {
// Interactor -> Presenter
func presentData(_ data: ContactDirectory)
func error()
}
protocol GnomeListViewProtocol: UsesInternetProtocol {
var presenter: GnomeListPresenterProtocol? { get set }
// Presenter -> View
func showContactDirectory(data: ContactDirectory)
}
| true
|
86a6c4609987fe86ff196fa78516134caaa65169
|
Swift
|
Lomovsky/Wach-2night
|
/WorkTask/ViewControllers/SuggestionsVC/SuggestionsVC+Extensions/SuggestionsVC+CollectionViewDataSource.swift
|
UTF-8
| 12,642
| 2.515625
| 3
|
[] |
no_license
|
//
// ViewController + CollectionViewDelegate.swift
// WorkTask
//
// Created by Алекс Ломовской on 10.12.2020.
//
import UIKit
extension SuggestionsViewController: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
//MARK: numberOfItemsInSection-
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
switch collectionView {
case recommendationsCollectionView:
return SuggestionsViewController.films.count
case genreCollectionView:
return SuggestionsViewController.genres.count
case favouriteFilmsCollectionView:
if SuggestionsViewController.favouriteFilms.isEmpty {
return 3
}
return SuggestionsViewController.favouriteFilms.count
default: return 0
}
}
//MARK: sizeForItemAt -
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
switch collectionView {
case self.genreCollectionView:
return CGSize(width: collectionView.frame.width * 0.35, height: collectionView.frame.height * 0.5)
case self.recommendationsCollectionView:
return CGSize(width: view.frame.width - 125, height: collectionView.frame.size.height * 0.90)
case self.favouriteFilmsCollectionView:
return CGSize(width: view.frame.width - 125, height: collectionView.frame.size.height * 0.90)
default:
return CGSize(width: 0, height: 0)
}
}
// DistanceBetween Cells
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
minimumLineSpacingForSectionAt section: Int) -> CGFloat {
switch collectionView {
case recommendationsCollectionView:
return 34
case genreCollectionView:
return 10
case favouriteFilmsCollectionView:
return 34
default:
return 0
}
}
//MARK: cellForItemAt -
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
switch collectionView {
case recommendationsCollectionView:
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: RecommendationsCollectionViewCell.reuseIdentifier,for: indexPath) as? RecommendationsCollectionViewCell {
let film = SuggestionsViewController.films[indexPath.row]
if let poster = film.poster {
if let posterImage = UIImage(data: poster) {
let newPoster = posterImage.resizeImageUsingVImage(size: CGSize.init(width: cell.frame.size.width,
height: cell.frame.size.height))
cell.imageView.image = newPoster
cell.layer.shadowColor = UIColor.black.cgColor
cell.layer.shadowRadius = 5
cell.layer.shadowOpacity = 0.4
cell.layer.shadowOffset = CGSize.init(width: 2.5, height: 2.5)
cell.layer.masksToBounds = false
return cell
}
} else {
cell.imageView.image = #imageLiteral(resourceName: "1024px-No_image_available.svg")
cell.layer.shadowColor = UIColor.black.cgColor
cell.layer.shadowRadius = 5
cell.layer.shadowOpacity = 0.4
cell.layer.shadowOffset = CGSize.init(width: 2.5, height: 2.5)
cell.layer.masksToBounds = false
return cell
}
}
case genreCollectionView:
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: GenreCollectionViewCell.reuseIdentifier, for: indexPath) as? GenreCollectionViewCell {
let genre = SuggestionsViewController.genres[indexPath.row]
cell.backgroundColor = .systemGray6
cell.layer.cornerRadius = 12
cell.genreLabel.text = genre.name?.capitalized
return cell
}
case favouriteFilmsCollectionView:
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: FavouriteFilmsCollectionViewCell.reuseIdentifier, for: indexPath) as? FavouriteFilmsCollectionViewCell {
if SuggestionsViewController.favouriteFilms.isEmpty {
cell.backgroundColor = .systemGray6
cell.imageView.isHidden = true
cell.layer.cornerRadius = 10
cell.imagePlaceholder.text = "Нет фильма"
cell.imagePlaceholder.isHidden = false
return cell
} else {
let film = SuggestionsViewController.favouriteFilms.reversed()[indexPath.row]
cell.imageView.isHidden = false
if let poster = film.poster {
if let posterImage = UIImage(data: poster) {
let newPoster = posterImage.resizeImageUsingVImage(size: CGSize.init(width: cell.frame.size.width,
height: cell.frame.size.height))
cell.imageView.image = newPoster
return cell
}
} else {
cell.imageView.image = #imageLiteral(resourceName: "1024px-No_image_available.svg")
return cell
}
}
}
default:
return UICollectionViewCell()
}
return UICollectionViewCell()
}
//MARK: didSelectItemAt-
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
switch collectionView {
case genreCollectionView:
break
case recommendationsCollectionView:
guard let cell = collectionView.cellForItem(at: indexPath) else { return }
let film = SuggestionsViewController.films[indexPath.row]
if let poster = film.poster {
if let posterImage = UIImage(data: poster) {
let resizedPoster = posterImage.resizeImageUsingVImage(size: CGSize.init(width: view.frame.width,
height: view.frame.height * 0.6))
animateCell(cell: cell)
let previewVC = PreviewViewController(poster: resizedPoster ?? #imageLiteral(resourceName: "1024px-No_image_available.svg"), filmTitle: film.title ?? "Нет данных", filmOverview: film.overview ?? "Нет данных")
previewVC.film = film
navigationController?.present(previewVC, animated: true, completion: {
previewVC.favoriteButton.setTitle("Добавить в избранное", for: .normal)
previewVC.favoriteButton.addTarget(previewVC.self, action: #selector(previewVC.addToFavorites), for: .touchUpInside)
previewVC.suggestionsDelegate = self
})
} else {
let previewVC = PreviewViewController(poster: #imageLiteral(resourceName: "1024px-No_image_available.svg"), filmTitle: film.title ?? "Нет данных", filmOverview: film.overview ?? "Нет данных")
previewVC.film = film
navigationController?.present(previewVC, animated: true, completion: {
previewVC.favoriteButton.setTitle("Добавить в избранное", for: .normal)
previewVC.favoriteButton.addTarget(previewVC.self, action: #selector(previewVC.addToFavorites), for: .touchUpInside)
previewVC.suggestionsDelegate = self
})
}
}
case favouriteFilmsCollectionView:
if SuggestionsViewController.favouriteFilms.isEmpty {
} else {
guard let cell = collectionView.cellForItem(at: indexPath) else { return }
// let previewVC = PreviewViewController()
let film = SuggestionsViewController.favouriteFilms.reversed()[indexPath.row]
// let some = SuggestionsViewController.favouriteFilms.enumerated()
let filmIndex = indexPath.row
// let filmIndex2 = SuggestionsViewController.favouriteFilms[indexPath.index]
if let poster = film.poster {
guard let posterImage = UIImage(data: poster) else { return }
let resizedPoster = posterImage.resizeImageUsingVImage(size: CGSize.init(width: view.frame.width,
height: view.frame.height * 0.6))
animateCell(cell: cell)
PreviewViewController.filmToDelete = film
PreviewViewController.indexOfFilmToDelete = filmIndex
let previewVC = PreviewViewController(poster: resizedPoster ?? #imageLiteral(resourceName: "1024px-No_image_available.svg"), filmTitle: film.title ?? "Нет данных", filmOverview: film.overview ?? "Нети данных ")
self.navigationController?.present(previewVC, animated: true, completion: {
previewVC.favoriteButton.setTitle("Удалить из избранного", for: .normal)
previewVC.favoriteButton.addTarget(previewVC.self, action: #selector(previewVC.deleteFromFavorites), for: .touchUpInside)
previewVC.suggestionsDelegate = self
})
} else {
animateCell(cell: cell)
PreviewViewController.filmToDelete = film
PreviewViewController.indexOfFilmToDelete = filmIndex
let previewVC = PreviewViewController(poster: #imageLiteral(resourceName: "1024px-No_image_available.svg"), filmTitle: film.title ?? "Нет данных", filmOverview: film.overview ?? "Нети данных ")
self.navigationController?.present(previewVC, animated: true, completion: {
previewVC.favoriteButton.setTitle("Удалить из избранного", for: .normal)
previewVC.favoriteButton.addTarget(previewVC.self, action: #selector(previewVC.deleteFromFavorites), for: .touchUpInside)
previewVC.suggestionsDelegate = self
}) }
}
default:
break
}
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
//настройка ползунка при прокручивании
if #available(iOS 13, *) {
(scrollView.subviews[(scrollView.subviews.count - 1)].subviews[0]).backgroundColor = UIColor.white
//verticalIndicator
(scrollView.subviews[(scrollView.subviews.count - 2)].subviews[0]).isHidden = true
//horizontalIndicator
} else {
if let verticalIndicator: UIImageView = (scrollView.subviews[(scrollView.subviews.count - 1)] as? UIImageView) {
verticalIndicator.backgroundColor = UIColor.systemGray6
}
if let horizontalIndicator: UIImageView = (scrollView.subviews[(scrollView.subviews.count - 2)] as? UIImageView) {
horizontalIndicator.isHidden = true
}
}
}
}
| true
|
509cbda108facd6db62d50d7204de50220d702cd
|
Swift
|
vladweinstein/A_Table_Swift
|
/A Table/Views/Recipes/RecipeRow.swift
|
UTF-8
| 1,079
| 3.203125
| 3
|
[] |
no_license
|
//
// RecipeRow.swift
// A Table
//
// Created by Vladimir Weinstein on 6/8/21.
//
import SwiftUI
struct RecipeRow: View {
var recipe: Recipe
var body: some View {
NavigationLink(destination: RecipeDetail(recipe: recipe)) {
HStack {
recipe.image
.resizable()
.aspectRatio(contentMode: .fit)
.frame(height: 60)
.cornerRadius(5)
Text(recipe.name)
Spacer()
if recipe.isFavorite {
Image(systemName:"star.circle")
.symbolRenderingMode(.palette)
.foregroundStyle(.yellow)
.imageScale(.large)
}
}
}
}
}
struct RecipeRow_Previews: PreviewProvider {
static var recipes = ModelData().recipes
static var previews: some View {
Group {
RecipeRow(recipe: recipes[0])
RecipeRow(recipe: recipes[1])
}
.previewLayout(.fixed(width: 300, height: 70))
}
}
| true
|
581e39c543eee661d61886eeb62cbd43772cab3b
|
Swift
|
fermoya/BrewdogV2
|
/Brewery/Business Logic/RecipeStep.swift
|
UTF-8
| 2,563
| 3.265625
| 3
|
[
"MIT"
] |
permissive
|
//
// RecipeStep.swift
// BusinessUseCases
//
import Foundation
import APIKit
public enum RecipeStepType {
case malt, hop, method, twist
}
public protocol RecipeStep {
var name: String { get }
var metaInfo: String { get }
var type: RecipeStepType { get }
var duration: Int? { get }
var timing: Timing { get }
}
extension Malt: RecipeStep {
public var metaInfo: String { return "\(amount.value ?? 0) \(amount.measureType.rawValue)" }
public var type: RecipeStepType { return .malt }
public var duration: Int? { return nil }
public var timing: Timing { return .none }
}
extension Hop: RecipeStep {
public var type: RecipeStepType { return .hop }
public var duration: Int? { return nil }
public var metaInfo: String { return "\(amount.value ?? 0) \(amount.measureType.rawValue). Timing: \(timing.rawValue)" }
}
extension Ingredients {
public var recipe: [RecipeStep] {
return malts.map { $0 as RecipeStep } + hops.map { $0 as RecipeStep }
}
}
extension BrewMethod {
public var recipe: [RecipeStep] {
var steps = mashTemperatures.map { $0 as RecipeStep }
steps.append(fermentation)
if let twist = self.twist {
steps.append(Twist(description: twist))
}
return steps
}
}
extension MashTemperature: RecipeStep {
public var metaInfo: String { return "\(temperature.value ?? 0) \(temperature.measureType.rawValue)" }
public var name: String {
return "Mash Temperature \(temperature.value ?? 0) \(temperature.measureType.rawValue)"
}
public var type: RecipeStepType {
return .method
}
public var timing: Timing {
return .none
}
}
extension Fermentation: RecipeStep {
public var metaInfo: String { return "\(temperature.value ?? 0) \(temperature.measureType.rawValue)" }
public var name: String {
return "Fermentation \(temperature.value ?? 0) \(temperature.measureType.rawValue)"
}
public var type: RecipeStepType {
return .method
}
public var duration: Int? {
return nil
}
public var timing: Timing {
return .none
}
}
public struct Twist: RecipeStep {
public var description: String
public var name: String { return "Twist" }
public var metaInfo: String { return description }
public var type: RecipeStepType { return .twist }
public var duration: Int? { return nil }
public var timing: Timing { return .none }
}
| true
|
7f6ffef62f8b8b3735e208101e763d8242dbc8f7
|
Swift
|
dusheees/Quiz
|
/Quiz/View Controllers/QuestionViewController.swift
|
UTF-8
| 4,325
| 2.875
| 3
|
[] |
no_license
|
//
// QuestionViewController.swift
// Quiz
//
// Created by Андрей on 04.11.2021.
//
import UIKit
class QuestionViewController: UIViewController {
@IBOutlet weak var questionLabel: UILabel!
@IBOutlet weak var singleStackView: UIStackView!
@IBOutlet var singleButtons: [UIButton]!
@IBOutlet weak var multiplyStackView: UIStackView!
@IBOutlet var multyLabels: [UILabel]!
@IBOutlet var multiSwitches: [UISwitch]!
@IBOutlet weak var rangedStackView: UIStackView!
@IBOutlet weak var rangedSlider: UISlider!
@IBOutlet var rangedLabels: [UILabel]!
@IBOutlet weak var questionProgressView: UIProgressView!
private var answersChoosen = [Answer]() {
didSet {
print(#line, #function, answersChoosen)
}
}
// Можем вызвать любое из вычислимых свойств в любом месте
private var currentAnswers: [Answer] {
currentQuestion.answers
}
private var currentQuestion: Question {
Question.all[questionIndex]
}
var questionIndex = 0
override func viewDidLoad() {
super.viewDidLoad()
rangedSlider.maximumValue = 0.99999
updateUI()
}
func updateUI() {
func updateSingleStack() {
singleStackView.isHidden = false
for (index, button) in singleButtons.enumerated() {
button.tag = index
button.setTitle(nil, for: [])
}
for (button, answer) in zip(singleButtons, currentAnswers) {
button.setTitle(answer.text, for: [])
}
}
func updateMultipleStack() {
multiplyStackView.isHidden = false
for label in multyLabels {
label.text = nil
}
for (label, answer) in zip(multyLabels, currentAnswers) {
label.text = answer.text
}
}
func updateRangedStack() {
rangedStackView.isHidden = false
rangedLabels.first?.text = currentAnswers.first?.text
rangedLabels.last?.text = currentAnswers.last?.text
}
for stackView in [singleStackView, multiplyStackView, rangedStackView] {
stackView?.isHidden = true
}
let totalProgress = Float(questionIndex) / Float(Question.all.count)
navigationItem.title = "Вопрос № \(questionIndex + 1)"
questionLabel.text = currentQuestion.text
questionProgressView.setProgress(totalProgress, animated: true)
switch currentQuestion.type {
case .single:
updateSingleStack()
case .multiply:
updateMultipleStack()
case .range:
updateRangedStack()
}
}
func nextQuestion() {
// TODO: change to segue to results screen
questionIndex += 1
if questionIndex < Question.all.count{
updateUI()
} else {
performSegue(withIdentifier: "Results Segue", sender: nil)
}
}
@IBAction func singleButtonPressed(_ sender: UIButton) {
let answers = Question.all[questionIndex].answers
let index = sender.tag
guard index >= 0 && index < answers.count else {
return
}
let answer = answers[index]
answersChoosen.append(answer)
nextQuestion()
}
@IBAction func multiButtonPressed() {
for (index, multiSwitch) in multiSwitches.enumerated() {
if multiSwitch.isOn && index < currentAnswers.count {
let answer = currentAnswers[index]
answersChoosen.append(answer)
}
}
nextQuestion()
}
@IBAction func rangedButtonPressed() {
let index = Int(round(rangedSlider.value * Float(currentAnswers.count - 1)))
if index < currentAnswers.count {
let answer = currentAnswers[index]
answersChoosen.append(answer)
}
nextQuestion()
}
@IBSegueAction func resultsSegue(_ coder: NSCoder) -> ResultsViewController? {
return ResultsViewController(coder: coder, answersChoosen)
}
}
| true
|
3e9c13027a971339cb5d0c897e3530ac21ea7a4a
|
Swift
|
mdubus/piscine-swift
|
/d03/d03-vp/CollectionViewController.swift
|
UTF-8
| 2,708
| 2.65625
| 3
|
[] |
no_license
|
//
// CollectionViewController.swift
// d03-vp
//
// Created by Morgane DUBUS on 3/21/19.
// Copyright © 2019 Morgane DUBUS. All rights reserved.
//
import Foundation
import UIKit
let queue = DispatchQueue.global(qos: DispatchQoS.background.qosClass)
class CollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
override func viewDidLoad() {
super.viewDidLoad()
}
// Return number of cells
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return imagesURL.count
}
// Populate Cell
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "imageCell", for: indexPath) as! CollectionViewCell
cell.imageLink = imagesURL[indexPath.row]
return cell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "displayBigImage" {
guard let dest = segue.destination as? ImageViewController,
let cell = sender as? CollectionViewCell,
cell.imageView.image != nil else {return}
dest.image = cell.imageView.image
}
}
/* DESIGN */
let sectionInsets = UIEdgeInsets(top: 20.0, left: 20.0, bottom: 20.0, right: 20.0)
// Disposition of the pictures
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
let itemsPerRow: CGFloat = 2
let paddingSpace = sectionInsets.left * (itemsPerRow + 1)
let availableWidth = view.frame.width - paddingSpace
let availableHeight = view.frame.height - paddingSpace
let widthPerItem = availableWidth / itemsPerRow
let heightPerItem = availableHeight / 5
return CGSize(width: widthPerItem, height: heightPerItem)
}
// Return inset for section
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
insetForSectionAt section: Int) -> UIEdgeInsets {
return sectionInsets
}
// Return spacing for section
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return sectionInsets.left
}
}
| true
|
bd1523a1196bf3870f51196bdfdca1cb1e74201b
|
Swift
|
ryan9gray/SkillboxTestersApp
|
/SkillBoxTester/Workers/LocalStore.swift
|
UTF-8
| 802
| 2.921875
| 3
|
[] |
no_license
|
//
// LocalStore.swift
// Mems
//
// Created by Evgeny Ivanov on 02.12.2019.
// Copyright © 2019 Eugene Ivanov. All rights reserved.
//
import UIKit
struct LocalStore {
fileprivate static let userDefaults = UserDefaults.standard
@Storage(userDefaults: userDefaults, key: "notFirstLaunch", defaultValue: false)
static var notFirstLaunch: Bool
}
@propertyWrapper
struct Storage<T> {
private let key: String
private let defaultValue: T
let userDefaults: UserDefaults
init(userDefaults: UserDefaults = UserDefaults.standard, key: String, defaultValue: T) {
self.key = key
self.defaultValue = defaultValue
self.userDefaults = userDefaults
}
var wrappedValue: T {
get {
userDefaults.object(forKey: key) as? T ?? defaultValue
}
set {
userDefaults.set(newValue, forKey: key)
}
}
}
| true
|
6b845bfd1ea5ac7944916ad10d5e20a330bd1b63
|
Swift
|
FuzzyBuckBeak/LeetCode
|
/LeetCode/LeetCode/236. Lowest Common Ancestor of a Binary Tree.swift
|
UTF-8
| 1,598
| 3.8125
| 4
|
[] |
no_license
|
//
// 236. Lowest Common Ancestor of a Binary Tree.swift
// DataStructures
//
// Created by: FuzzyBuckBeak on 1/22/19
// Copyright © 2018 FuzzyBuckBeak. All rights reserved.
/*****************************************************************************************************************************
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as
the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3
Explanation: The LCA of nodes 5 and 1 is 3.
*****************************************************************************************************************************/
import Foundation
class TreeNode: CustomStringConvertible {
var val: Int
var left: TreeNode?
var right: TreeNode?
init(val: Int) {
self.val = val
}
var description: String {
return String(self.val)
}
}
class BinaryTree {
func lowestCommonAncestor(root: TreeNode?, p: TreeNode, q:TreeNode) -> TreeNode? {
if root == nil { return root }
if root === p || root === q { return root }
let left = lowestCommonAncestor(root: root?.left, p: p, q: q)
let right = lowestCommonAncestor(root: root?.right, p: p, q: q)
if left != nil && right != nil { return root }
else { return left != nil ? left : right }
}
}
| true
|
79f5d8755365d614f9be1eba90c9d6dd9a6f9e85
|
Swift
|
javiermelo1672/Notes
|
/Notes WatchKit Extension/Component/HeaderView.swift
|
UTF-8
| 845
| 2.953125
| 3
|
[] |
no_license
|
//
// HeaderView.swift
// Notes WatchKit Extension
//
// Created by Javier Duvan Hospital Melo on 13/07/21.
//
import SwiftUI
struct HeaderView: View {
var title: String = ""
var body: some View {
VStack {
//title
if title != "" {
Text(title.uppercased()).font(.title3).fontWeight(/*@START_MENU_TOKEN@*/.bold/*@END_MENU_TOKEN@*/).foregroundColor(.accentColor)
}
//separator
HStack{
Capsule().frame(height:1)
Image(systemName: "note.text")
Capsule().frame(height:1)
}.foregroundColor(.accentColor)
}
}
}
struct HeaderView_Previews: PreviewProvider {
static var previews: some View {
Group {
HeaderView(title:"Credits")
HeaderView()
}
}
}
| true
|
078962ae25bbeeacd78e5adef4b56155966789c3
|
Swift
|
mohamedreda1993/object-library
|
/collectionview.swift
|
UTF-8
| 1,488
| 3.046875
| 3
|
[] |
no_license
|
// ViewController.swift
// Created by mohamed reda on 2/9/18.
// Copyright © 2018 mohamed reda. All rights reserved.
import UIKit
class ViewController: UIViewController,UICollectionViewDataSource,UICollectionViewDelegate {
@IBOutlet weak var collectioview: UICollectionView!
var animals=["1","2","3","4","5","6","1","2","3","4","5","6"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//adjust size of each view
let itemsize=UIScreen.main.bounds.width/3 - 3
let layout=UICollectionViewFlowLayout()
layout.sectionInset=UIEdgeInsets(top: 20, left: 0, bottom: 10, right: 0)
layout.itemSize=CGSize(width: itemsize, height: itemsize)
layout.minimumLineSpacing=3
layout.minimumInteritemSpacing=3
collectioview.collectionViewLayout=layout
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return animals.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell=collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)as! animal_cell
cell.img.image=UIImage(named: animals[indexPath.row])
return cell
}
}
| true
|
add9a06dcc3208a05d41b5960df20dbb42d4a436
|
Swift
|
knpwrs/Render
|
/samples/Demo/Example2ViewController.swift
|
UTF-8
| 1,141
| 2.75
| 3
|
[
"BSD-3-Clause",
"MIT"
] |
permissive
|
import UIKit
import Render
class Example2ViewController: ViewController, ComponentViewDelegate {
private let fooComponent = FooComponentView()
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
override func viewDidLoad() {
super.viewDidLoad()
fooComponent.delegate = self
view.addSubview(fooComponent)
generateRandomStates()
}
private func generateRandomStates() {
fooComponent.state = FooComponentViewState()
fooComponent.update(in: view.bounds.size, options: [
// Renders the component with an animation.
.animated(duration: 0.5, options: .curveEaseInOut, alongside: {
self.fooComponent.center = self.view.center
})
])
// Generates a new random state every 2 seconds.
DispatchQueue.main.asyncAfter(deadline: .now() + 2) { [weak self] in
self?.generateRandomStates()
}
}
override func viewDidLayoutSubviews() {
fooComponent.update(in: view.bounds.size)
self.componentDidRender(fooComponent)
}
func componentDidRender(_ component: AnyComponentView) {
component.center = self.view.center
}
}
| true
|
39ce8f5fa95c5e795bbc33faea9019d37877ba04
|
Swift
|
VasiliyEgorov/DrinkAndGoApp
|
/DrinkAndGoApp/AlcoholCellVM.swift
|
UTF-8
| 470
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
//
// AlcoholCellVM.swift
// DrinkAndGoApp
//
// Created by Vasiliy Egorov on 03.01.2018.
// Copyright © 2018 VasiliyEgorov. All rights reserved.
//
import Foundation
struct AlcoholCellViewModel {
var alcoholImage : Data?
var alcoholTitle : String!
var alcPercent : String!
init(image: Data?, title: String, alcPercent: String) {
self.alcoholImage = image
self.alcoholTitle = title
self.alcPercent = alcPercent + " %"
}
}
| true
|
565089398a0a3a407f2dd0603a9a675e53e1d8c2
|
Swift
|
bbanderson/Calculator-Advanced-Swift-iOS13
|
/Calculator/Controller/ViewController.swift
|
UTF-8
| 1,946
| 3.46875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Calculator
//
// Created by Angela Yu on 10/09/2019.
// Copyright © 2019 London App Brewery. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let calculateLogic = CalculateLogic()
@IBOutlet weak var displayLabel: UILabel!
private var isChanged: Bool = true
private var displayValue: Double {
get {
guard let number = Double(displayLabel.text!) else { fatalError("Cannot convert String into Double.") }
return number
}
set {
displayLabel.text = "\(newValue)"
}
}
@IBAction func calcButtonPressed(_ sender: UIButton) {
//What should happen when a non-number button is pressed
isChanged = true
let calculate = calculateLogic.calculate(symbol: sender.currentTitle!)
displayValue *= calculate
}
@IBAction func numButtonPressed(_ sender: UIButton) {
//What should happen when a number is entered into the keypad
if let currentPressedBtn = sender.currentTitle {
if isChanged {
isChanged = false
displayLabel.text = currentPressedBtn
} else {
if currentPressedBtn == "." {
// 내림한 것과 안한 것이 같다면 isInt에는 true가 저장된다.
let isInt = floor(displayValue) == displayValue
// 만약 isInt가 false라면 현재 함수를 더 이상 가지 않고 그냥 끝내버리기. true인 경우 = 소수점을 누르기 직전까지 화면 상 모든 수가 정수여야 함.
if !isInt {
return
}
}
displayLabel.text! += currentPressedBtn
}
}
}
}
| true
|
e2f43b67f525f6472da1806a4d695ec114218a74
|
Swift
|
FcoJosePerez/Challenge
|
/Challenge/Scennes/CharacterDetail/CharacterDetailWireframe.swift
|
UTF-8
| 927
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
import Foundation
import UIKit
protocol CharacterDetailWireframe {
}
class CharacterDetailWireframeiOS : CharacterDetailWireframe {
weak var navigationController: UINavigationController?
init(navigationController: UINavigationController?) {
self.navigationController = navigationController
}
static func createScenne(character:Character, navigationController: UINavigationController?) -> CharacterDetailViewController {
let vc = CharacterDetailViewController.initFromStoryboard()
let wireFrame = CharacterDetailWireframeiOS(navigationController: navigationController)
vc.presenter = DefaultCharacterDetailPresenter(view: vc,
wireframe: wireFrame,
interactor: DefaultCharacterDetailInteractor(character: character))
return vc
}
}
| true
|
505d4000535a0525458cb42a0835edb7c565bbec
|
Swift
|
blick9/Meily_9VERY
|
/Project/Meily/ColorButtonStyle.swift
|
UTF-8
| 710
| 2.90625
| 3
|
[
"MIT"
] |
permissive
|
//
// ColorButtonStyle.swift
// Maily
//
// Created by nueola on 2017. 4. 3..
// Copyright © 2017년 Febrix. All rights reserved.
//
import UIKit
class ColorButtonStyle: UIButton {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.addTarget(self, action: #selector(toggle), for: .touchUpInside)
self.layer.cornerRadius = CGFloat(self.frame.height / 2)
self.layer.borderColor = UIColor.white.cgColor
self.alpha = 0.5
self.isSelected = false
}
func toggle() {
self.isSelected = !self.isSelected
self.alpha = self.isSelected ? 1 : 0.5
self.layer.borderWidth = self.isSelected ? 3 : 0
}
}
| true
|
10ec260071d705c74008d2b06e74b79d201b514c
|
Swift
|
colorfull-proj/colorfull_iOS
|
/Colorful/Colorful/Sources/Scene/Content/CollectionView/ContentCell.swift
|
UTF-8
| 1,007
| 2.640625
| 3
|
[] |
no_license
|
//
// ContentCell.swift
// Colorful
//
// Created by 윤동민 on 2020/12/11.
//
import UIKit
class ContentCell: UICollectionViewCell {
static let identifier = "ContentCell"
// MARK: - UI
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var nicknameLabel: UILabel!
@IBOutlet weak var likeLabel: UILabel!
@IBOutlet weak var commentLabel: UILabel!
// MARK: - Init
func bind(_ dto: ContentDTO) {
imageView.image = dto.image
titleLabel.text = dto.title
nicknameLabel.text = "by " + dto.nickname
likeLabel.text = "\(dto.likeCount)"
commentLabel.text = "\(dto.commentCount)"
}
// MARK: - Life Cycle
override func awakeFromNib() {
super.awakeFromNib()
contentView.clipsToBounds = true
contentView.layer.cornerRadius = self.bounds.width/20
}
override func prepareForReuse() {
super.prepareForReuse()
}
}
| true
|
45cc60a93b61cdcc208964b74233a73a24f29301
|
Swift
|
PriyamDutta/Papr
|
/Papr/Models/Category.swift
|
UTF-8
| 420
| 2.53125
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// Category.swift
// Papr
//
// Created by Joan Disho on 19.02.18.
// Copyright © 2018 Joan Disho. All rights reserved.
//
import Foundation
struct Category: Codable {
let id: Int?
let title: String?
let photoCount: Int?
let links: Links?
enum CodingKeys: String, CodingKey {
case id
case title = "exposure_time"
case photoCount = "photo_count"
case links
}
}
| true
|
d871534aabe6ac29365aebe37ee67067c7d63a44
|
Swift
|
masumcsedu/snakegame
|
/Snake/Utility/GameUtility.swift
|
UTF-8
| 1,364
| 3.046875
| 3
|
[] |
no_license
|
//
// GameUtility.swift
// Snake
//
// Created by Shamsur Rahman on 6/8/20.
// Copyright © 2020 Shamsur Rahman. All rights reserved.
//
import UIKit
class GameUtility {
static func initializeGame() {
let defaults = UserDefaults.standard
if !defaults.bool(forKey: "IsInitialized") {
defaults.set(true, forKey: "IsInitialized")
defaults.set(true, forKey: "AudioKey")
defaults.set(0, forKey: "HighScore")
}
}
static func isAudioEnabled() -> Bool {
return UserDefaults.standard.bool(forKey: "AudioKey")
}
static func writeAudio(isEnabled: Bool) {
UserDefaults.standard.set(isEnabled, forKey: "AudioKey")
UserDefaults.standard.synchronize()
}
static func highScore() -> Int {
return UserDefaults.standard.integer(forKey: "HighScore")
}
static func writeHighScore(highScore: Int) {
UserDefaults.standard.set(highScore, forKey: "HighScore")
UserDefaults.standard.synchronize()
}
static func snakeColor() -> UIColor {
return UserDefaults.standard.value(forKey: "SnakeColor") as? UIColor ?? GameColor.snakeColor
}
static func writeSnakeColor(color: UIColor) {
UserDefaults.standard.set(color, forKey: "SnakeColor")
UserDefaults.standard.synchronize()
}
}
| true
|
d50fadc73671e2f04749ab42a0493250a0dbc453
|
Swift
|
Roy15668659936/SmartQ
|
/SmartQ/Bank/Map/MapReveseViewController.swift
|
UTF-8
| 3,411
| 2.671875
| 3
|
[] |
no_license
|
//
// MapReveseViewController.swift
// SmartQ
//
// Created by Roy on 2019/7/28.
// Copyright © 2019 tiny. All rights reserved.
//
import UIKit
import CoreLocation
import MapKit
class MapReveseViewController: UIViewController ,CLLocationManagerDelegate {
@IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
reverseGeocode()
}
//地理信息反编码
func reverseGeocode(){
let geocoder = CLGeocoder()
let currentLocation = CLLocation(latitude: 32.029171, longitude: 118.788231)
geocoder.reverseGeocodeLocation(currentLocation, completionHandler: {
(placemarks:[CLPlacemark]?, error:Error?) -> Void in
//强制转成简体中文
let array = NSArray(object: "zh-hans")
UserDefaults.standard.set(array, forKey: "AppleLanguages")
//显示所有信息
if error != nil {
//print("错误:\(error.localizedDescription))")
self.textView.text = "错误:\(error!.localizedDescription))"
return
}
if let p = placemarks?[0]{
print(p) //输出反编码信息
var address = ""
if let country = p.country {
address.append("国家:\(country)\n")
}
if let administrativeArea = p.administrativeArea {
address.append("省份:\(administrativeArea)\n")
}
if let subAdministrativeArea = p.subAdministrativeArea {
address.append("其他行政区域信息(自治区等):\(subAdministrativeArea)\n")
}
if let locality = p.locality {
address.append("城市:\(locality)\n")
}
if let subLocality = p.subLocality {
address.append("区划:\(subLocality)\n")
}
if let thoroughfare = p.thoroughfare {
address.append("街道:\(thoroughfare)\n")
}
if let subThoroughfare = p.subThoroughfare {
address.append("门牌:\(subThoroughfare)\n")
}
if let name = p.name {
address.append("地名:\(name)\n")
}
if let isoCountryCode = p.isoCountryCode {
address.append("国家编码:\(isoCountryCode)\n")
}
if let postalCode = p.postalCode {
address.append("邮编:\(postalCode)\n")
}
if let areasOfInterest = p.areasOfInterest {
address.append("关联的或利益相关的地标:\(areasOfInterest)\n")
}
if let ocean = p.ocean {
address.append("海洋:\(ocean)\n")
}
if let inlandWater = p.inlandWater {
address.append("水源,湖泊:\(inlandWater)\n")
}
self.textView.text = address
} else {
print("No placemarks!")
}
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.