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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
628094f59799b66a0c4dce13fc201eb1f26e6ebb
|
Swift
|
Switfor/aide
|
/Dames/Dames/Model/Game.swift
|
UTF-8
| 3,866
| 3.28125
| 3
|
[] |
no_license
|
//
// Game.swift
// Dames
//
// Created by Eric Le Maître on 28/05/2018.
// Copyright © 2018 Eric Le Maître. All rights reserved.
//
import CoreGraphics
import Foundation
//TODO: Swift 4.2 : make Player an enum : CaseIterable to count the number of cases
struct Player: CustomStringConvertible {
var color: PuckColor
var description: String {
switch color {
case .Black:
return "Noir"
case .White:
return "Blanc"
}
}
}
protocol GameDelegate {
func eatPuckAt(position: IndexPath)
}
struct Game {
var pucks : [IndexPath:Puck]
var currentPlayer: Player
var turnNumber = 0
var delegate: GameDelegate?
init(with pucks: [IndexPath:Puck] = initPucks()) {
self.pucks = pucks
self.currentPlayer = Player(color: .White)
}
private static func initPucks() -> [IndexPath:Puck] {
var pucks = [IndexPath:Puck]()
for i in 0..<10 {
for j in 0..<10 {
guard j <= 3 || j >= 6 else {
continue
}
if j % 2 == 0 {
if i % 2 == 1 {
pucks[IndexPath(row: i, section: j)] = Puck(color: j < 5 ? .Black : .White)
}
} else {
if i % 2 == 0 {
pucks[IndexPath(row: i, section: j)] = Puck(color: j < 5 ? .Black : .White)
}
}
}
}
return pucks
}
mutating func nextTurn() {
currentPlayer = currentPlayer.color == .White ? Player(color: .Black) : Player(color: .White)
turnNumber += 1
}
mutating func canPuck(_ puck: Puck, atPosition startPosition: IndexPath, moveTo endPosition: IndexPath) -> Bool {
guard isDiagonalBetween(position1: startPosition, position2: endPosition) && pucks[endPosition] == nil else {
return false
}
if checkIfPosition(startPosition, isNextTo: endPosition) {
return isPuckMovingForward(puck, startPosition: startPosition, endPosition: endPosition)
} else {
let positionBetween = getPositionBetween(position1: startPosition, and: endPosition)
let puckBetween = pucks[positionBetween]
if let puckBetween = puckBetween, puckBetween == Puck(color: puck.color == .Black ? .White : .Black) {
pucks.removeValue(forKey: positionBetween)
delegate?.eatPuckAt(position: positionBetween)
return true
}
}
return false
}
private func isDiagonalBetween(position1: IndexPath, position2: IndexPath) -> Bool {
return position1.row != position2.row && position1.section != position2.section
}
private func checkIfPosition(_ position: IndexPath, isNextTo currentPosition: IndexPath) -> Bool {
return abs(position.section - currentPosition.section) == 1 && abs(position.row - currentPosition.row) == 1
}
private func isPuckMovingForward(_ puck: Puck, startPosition: IndexPath, endPosition: IndexPath) -> Bool {
switch puck.color {
case .Black:
return startPosition.section - endPosition.section == -1
case .White:
return startPosition.section - endPosition.section == 1
}
}
private func getPositionBetween(position1: IndexPath, and position2: IndexPath) -> IndexPath {
let line = max(position1.section, position2.section) - 1
let column = max(position1.row, position2.row) - 1
return IndexPath(row: column, section: line)
}
private func getAllPositionsBetween(position1: IndexPath, and position2: IndexPath) -> [IndexPath] {
var lines = [Int]()
var columns = [Int]()
var positions = [IndexPath]()
for line in min(position1.section, position2.section)+1..<max(position1.section, position2.section) {
lines.append(line)
}
for column in min(position1.row, position2.row)+1..<max(position1.row, position2.row) {
columns.append(column)
}
for i in 0..<lines.count {
positions.append(IndexPath(row: columns[i], section: lines[i]))
}
return positions
}
}
| true
|
3bceefd688591926198cf67b4f732943620dcd71
|
Swift
|
denisbohm/firefly-ice-api
|
/iOS/Firefly Activity/Firefly Activity/ActivityView.swift
|
UTF-8
| 4,912
| 2.515625
| 3
|
[
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
//
// ActivityView.swift
// Firefly Activity
//
// Created by Denis Bohm on 12/28/17.
// Copyright © 2017 Firefly Design LLC. All rights reserved.
//
import UIKit
@IBDesignable
class ActivityView: PlotView {
var spans: [Activity.Span] = []
func setTimeAxisAll() {
if spans.isEmpty {
setTimeAxis(min: 0.0, max: 1.0)
return
}
let min = spans.first!.timeRange().start
let max = spans.last!.timeRange().end
setTimeAxis(min: min, max: max)
}
func setVmaAxisAll() {
let epsilon: Float = 0.0
valueAxis.max = Double(spans.reduce(epsilon) { max($0, $1.vmas.reduce(epsilon) { max($0, $1) }) })
}
override func setTimeAxisEnded() {
}
func setSpans(spans: [Activity.Span]) {
self.spans = spans
}
override func query(identifier: String, start: Date, end: Date) {
let datastore = Datastore(identifier: identifier)
self.spans = datastore.query(start: start.timeIntervalSince1970, end: end.timeIntervalSince1970)
}
func gaps() -> [(start: TimeInterval, end: TimeInterval)] {
var gaps: [(start: TimeInterval, end: TimeInterval)] = []
if spans.count > 1 {
var end = spans.first!.timeRange().end
for span in spans.suffix(from: 1) {
let (start, nextEnd) = span.timeRange()
gaps.append((start: end, end: start))
end = nextEnd
}
}
return gaps
}
func summarize(currentPath: UIBezierPath, previousCount: Int, previousX: Int, previousSum: Float, previousMin: Float, previousMax: Float) {
let px = Double(plotInsets.left) + Double(previousX)
let mean = Double(previousSum) / Double(previousCount)
let h = Double(self.frame.size.height - plotInsets.bottom)
let valueScale = valueAxis.scale(CGFloat(h))
let y = h - (mean - valueAxis.min) * valueScale
addPoint(path: currentPath, x: px, y: y)
let y0 = h - (Double(previousMin) - valueAxis.min) * valueScale
let y1 = h - (Double(previousMax) - valueAxis.min) * valueScale
let height = y0 - y1
UIBezierPath(rect: CGRect(x: px, y: y1, width: 1.0, height: height)).fill()
}
override func drawContent(_ dirtyRect: CGRect) {
let timeScale = timeAxis.scale(bounds.size.width)
for span in spans {
let timeRange = span.timeRange()
if (timeRange.end < timeAxis.min) || (timeRange.start > timeAxis.max) {
continue
}
// for performance, calculate which vmas will just extend outside view and only draw between those...
let first = Swift.max(Int(timeAxis.min - timeRange.start) / span.interval - 1, 0)
let last = Swift.min(Int(timeAxis.max - timeRange.start) / span.interval + 1, span.vmas.count)
var time = timeRange.start + Double(first * span.interval)
let vmas = span.vmas[first ..< last]
var previousCount = 0
var previousX = 0
var previousSum: Float = 0.0
var previousMin: Float = 0.0
var previousMax: Float = 0.0
UIColor.lightGray.setFill()
UIColor.black.setStroke()
let currentPath = UIBezierPath()
for vma in vmas {
let x = Int(round((time - timeAxis.min) * timeScale))
if (previousCount == 0) {
previousX = x
previousMin = vma
previousMax = vma
} else {
if x != previousX {
summarize(currentPath: currentPath, previousCount: previousCount, previousX: previousX, previousSum: previousSum, previousMin: previousMin, previousMax: previousMax)
previousCount = 0
previousX = x
previousSum = 0.0
previousMin = vma
previousMax = vma
}
}
previousCount += 1
previousSum += vma
if vma < previousMin {
previousMin = vma
}
if vma > previousMax {
previousMax = vma
}
time += TimeInterval(span.interval)
}
if previousCount > 0 {
summarize(currentPath: currentPath, previousCount: previousCount, previousX: previousX, previousSum: previousSum, previousMin: previousMin, previousMax: previousMax)
}
currentPath.stroke()
}
UIColor.red.setFill()
drawGaps(gaps: gaps())
}
}
| true
|
7580c69bb0eaf2d0a889f99d3fec69f6293af616
|
Swift
|
EvangelosBoudis/couchbase-contacts-ios
|
/CouchbaseDemo/Classes/Data/ContactRepository.swift
|
UTF-8
| 786
| 2.953125
| 3
|
[] |
no_license
|
//
// ContactRepository.swift
// CouchbaseDemo
//
// Created by Damiano Giusti on 05/02/2020.
//
import Foundation
enum ContactsRepositoryError: Error {
case errorGettingContact(Error)
case errorSavingContact(Error)
case errorDeletingContact(Error)
case errorInvalidContact
case errorContactNotFound
}
typealias ContactsResult<T> = Result<T, ContactsRepositoryError>
protocol ContactsRepository {
func getAllContacts(callback: @escaping (ContactsResult<[Contact]>) -> ()) -> Disposable
func getContact(byId contactId: String, callback: @escaping (ContactsResult<Contact>) -> ())
func save(contact: Contact, callback: @escaping (ContactsResult<Contact>) -> ())
func delete(contact contactId: String, callback: @escaping (ContactsResult<Void>) -> ())
}
| true
|
6d142e6b0663f140e2d314f140e1ce972a183f4d
|
Swift
|
AlexInntekt/ItemsPlanner
|
/play/VCs/Admin/ImageVC.swift
|
UTF-8
| 1,515
| 2.734375
| 3
|
[] |
no_license
|
//
// ImageVC.swift
// play
//
// Created by Alexandru-Mihai Manolescu on 13/08/2019.
// Copyright © 2019 Alexandru-Mihai Manolescu. All rights reserved.
//
import Foundation
import UIKit
class ImageVC: UIViewController
{
@IBOutlet weak var currentImage: UIImageView!
var imageIndex = 0
var currentItem = Item()
@IBAction func backButton(_ sender: Any) {
self.performSegue(withIdentifier: "back", sender: nil)
}
@IBAction func deleteImage(_ sender: Any)
{
let title = "Ștergere imagine"
let message = "Sigur doriți să eliminați imaginea?"
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Nu, anulează", style: UIAlertAction.Style.cancel, handler: { _ in
}))
alert.addAction(UIAlertAction(title: "Da, șterge", style: UIAlertAction.Style.destructive, handler: { _ in
cauchedImagesToCreate.remove(at: self.imageIndex)
self.dismiss(animated: true, completion: nil)
}))
self.present(alert, animated: true)
}
override func viewDidLoad()
{
self.currentImage.image=cauchedImagesToCreate[imageIndex]
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if(segue.identifier=="back")
{
let defVC = segue.destination as! AddItemAdminVC
defVC.currentItem=currentItem
}
}
}
| true
|
374c34dfb268004b73dd988b0873ba8e143d4b8a
|
Swift
|
novpeter/BudgetTrackerApp
|
/Budget Tracker/Modules/SignInScreen/Interactor/SignInScreenInteractorInput.swift
|
UTF-8
| 744
| 2.71875
| 3
|
[] |
no_license
|
//
// SignInScreenInteractorInput.swift
// Budget Tracker
//
// Created by Петр on 10/04/2019.
// Copyright © 2019 DreamTeam. All rights reserved.
//
import Foundation
protocol SignInScreenInteractorInput: AnyObject {
/// Signs in
///
/// - Parameters:
/// - email: user email
/// - password: password
func signIn(email: String?, password: String?)
/// Signs in via google account
///
/// - Parameters:
/// - token: token
/// - email: user email
/// - fullName: user full name
func googleSignIn(token: String, email: String, fullName: String)
/// Recovers password
///
/// - Parameter email: user email
func forgotPassword(email: String?)
}
| true
|
cf1555d149fe3f600b17d3886c1b16cac6ad396a
|
Swift
|
jorjuela33/Recipes
|
/Application/Connection/Monitor/RequestMonitor.swift
|
UTF-8
| 2,086
| 2.765625
| 3
|
[] |
no_license
|
//
// RequestMonitor.swift
// Application
//
// Created by Jorge Orjuela on 11/20/19.
// Copyright © 2019 Jorge Orjuela. All rights reserved.
//
import Alamofire
enum RequestMonitorState {
case canceled
case finished
case resumed
case suspended
}
class RequestMonitor: ClosureEventMonitor {
private let lock = NSLock()
private var observers: [RequestMonitorObserver] = []
// MARK: Initializers
init() {
super.init(queue: DispatchQueue(label: "com.requestMonitor"))
}
// MARK: Instance methods
func observeRequestStateUpdates(
_ connectionRequest: ConnectionRequest,
callback: @escaping RequestMonitorObserver.RequestMonitorCallback
) {
queue.sync {
let observer = RequestMonitorObserver(connectionRequest: connectionRequest, callback: callback)
observers.append(observer)
}
}
// MARK: Overrided methods
override func requestDidCancel(_ request: Request) {
super.requestDidCancel(request)
notify(request, newState: .canceled)
removeObserver(for: request)
}
override func requestDidFinish(_ request: Request) {
super.requestDidFinish(request)
notify(request, newState: .finished)
removeObserver(for: request)
}
override func requestDidResume(_ request: Request) {
super.requestDidResume(request)
notify(request, newState: .resumed)
}
override func requestDidSuspend(_ request: Request) {
super.requestDidSuspend(request)
notify(request, newState: .suspended)
}
// MARK: Private methods
private func notify(_ request: Request, newState state: RequestMonitorState) {
lock.lock()
let observers = self.observers.filter({ $0.connectionRequest.matches(request) })
lock.unlock()
observers.forEach({ $0.notify(state) })
}
private func removeObserver(for request: Request) {
lock.lock()
observers = observers.filter({ !$0.connectionRequest.matches(request) })
lock.unlock()
}
}
| true
|
87eb400b7fe35517dca31d6798c5dba9d100c8ad
|
Swift
|
danielmurillo2021/delipollo-ios
|
/DeliPollo/Source/Common/Extensions/Number+Extensions.swift
|
UTF-8
| 1,664
| 3.109375
| 3
|
[] |
no_license
|
//
// Double+Extensions.swift
// DeliPollo
//
// Created by Daniel Murillo on 10/31/20.
// Copyright © 2020 Daniel Murrillo. All rights reserved.
//
import Foundation
extension Formatter {
static let number = NumberFormatter()
}
extension Locale {
static let esNICA: Locale = .init(identifier: "es_NI")
}
extension Numeric {
func formatted(style: NumberFormatter.Style, locale: Locale = .current, with groupingSeparator: String? = nil) -> String {
Formatter.number.locale = locale
Formatter.number.numberStyle = style
Formatter.number.roundingMode = .halfDown
if let groupingSeparator = groupingSeparator {
Formatter.number.groupingSeparator = groupingSeparator
}
return Formatter.number.string(for: self) ?? ""
}
var currencyNI: String { formatted(style: .currency, locale: .esNICA) }
}
extension Double {
var currency: String {
let value = PriceFormatter.shared.format(self)
return value.currencyNI
}
var intValue: Int {
Int(self)
}
var suggestedCash: Double {
let mod = Int(self) % 100
let value = Int(self) - (mod)
return Double(mod == 0 ? value : value + 100)
}
}
extension Int {
var doubleValue: Double {
Double(self)
}
var boolValue: Bool {
self == 1
}
}
struct PriceFormatter {
static var shared = PriceFormatter()
private var priceFormatter: NumberFormatter = {
let decimalFormatter = NumberFormatter()
decimalFormatter.minimumFractionDigits = 2
decimalFormatter.maximumFractionDigits = 2
decimalFormatter.roundingMode = .halfUp
return decimalFormatter
}()
func format(_ value: Double) -> Double {
return priceFormatter.string(from: NSNumber(value: value))?.doubleValue ?? 0
}
}
| true
|
f6eb0c3046795120188e4abba61ca045c44ddeb6
|
Swift
|
enre1008/swift
|
/swift/30Days/15_TumblrMenu/TumblrMenu/TumblrMenu/ViewController.swift
|
UTF-8
| 2,205
| 2.546875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// TumblrMenu
//
// Created by Sunny-Joy on 2018/2/8.
// Copyright © 2018年 Sunny. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var blurView: UIVisualEffectView!
var alphaBtn: UIButton!
let dampingRate: CGFloat = 0.7
override func viewDidLoad() {
super.viewDidLoad()
let bgImg = UIImageView(frame: self.view.frame)
bgImg.image = #imageLiteral(resourceName: "[email protected]")
self.view.addSubview(bgImg)
let tapGest = UITapGestureRecognizer(target: self, action: #selector(tapAction))
self.view.addGestureRecognizer(tapGest)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@objc func tapAction() {
self.setupFunctions()
let tapGest = UITapGestureRecognizer(target: self, action: #selector(removeBlur))
blurView.addGestureRecognizer(tapGest)
UIView.animate(withDuration: 0.5) {
self.blurView.alpha = 1
}
UIView.animate(withDuration: 0.3, delay: 0.2, usingSpringWithDamping: dampingRate, initialSpringVelocity: 10, options: .allowAnimatedContent, animations: {
self.alphaBtn.frame.origin.x = 80
}, completion: nil)
}
func setupFunctions() {
let blurEffect = UIBlurEffect(style: .dark)
blurView = UIVisualEffectView(effect: blurEffect)
blurView.frame = self.view.bounds
self.view.addSubview(blurView)
self.alphaBtn = UIButton(frame: CGRect(x: -88, y: 80, width: 88, height: 88))
alphaBtn.setImageAndTitle(imageName: "alpha", title: "Message", type: .PositionTop, Space: 10)
blurView.contentView.addSubview(alphaBtn)
}
@objc func removeBlur() {
UIView.animate(withDuration: 0.3, delay: 0.2, usingSpringWithDamping: 3, initialSpringVelocity: 5, options: .allowAnimatedContent, animations: {
self.alphaBtn.frame.origin.x = -88
}) { (isFinished) in
self.alphaBtn.removeFromSuperview()
self.blurView.removeFromSuperview()
}
}
}
| true
|
70752e3d94179a598ff3d7b2ef889c62a537e9f5
|
Swift
|
adiazdiaz/example_tv_shows_swiftui
|
/ExampleTVShowsSwiftUI/Model/TVShowDetail.swift
|
UTF-8
| 480
| 2.765625
| 3
|
[] |
no_license
|
//
// TVShowDetail.swift
// ExampleTVShowsSwiftUI
//
// Created by Alberto Díaz Díaz on 14/11/2020.
//
import Foundation
struct TVShowDetail: Codable {
let id: Int
let name: String?
let posterPath: String?
let overview: String?
enum CodingKeys: String, CodingKey {
case id, name, overview
case posterPath = "poster_path"
}
func getCompletePosterPath() -> URL? { URL(string: "\(Bundle.main.theMovieDbImagesPath)\(posterPath ?? "")") }
}
| true
|
ab19dc7fb63c3f03ea5b666bc80bf5d8e6b93b6e
|
Swift
|
vicentecc/Deborafood
|
/DeboraFood/Produto.swift
|
UTF-8
| 1,136
| 3.1875
| 3
|
[] |
no_license
|
//
// File.swift
// DeboraFood
//
// Created by admin on 07/04/17.
// Copyright © 2017 admin. All rights reserved.
//
import Foundation
class Produto: NSObject, NSCoding{
var nome: String!
var preco: Double!
var qtd: Int!
override var description: String{
return self.nome + " --------> R$: " + String(self.preco)
}
var descriptionCarrinho: String{
var total: Double = self.preco * Double(self.qtd)
return String(self.qtd) + " | " + self.nome + " -------- " + "R$" + String(total)
}
init(nome:String, preco:Double) {
self.nome = nome
self.preco = preco
}
required init?(coder aDecoder: NSCoder){
self.nome = aDecoder.decodeObject(forKey: "nome") as! String
self.preco = aDecoder.decodeObject(forKey: "preco") as! Double
self.qtd = aDecoder.decodeObject(forKey: "qtd") as! Int
}
func encode(with aCoder: NSCoder){
aCoder.encode(self.nome, forKey: "nome")
aCoder.encode(self.preco, forKey: "preco")
aCoder.encode(self.qtd, forKey: "qtd")
}
}
| true
|
37cf8c58cc34fdeb65aa92318f7b4e99be5c5464
|
Swift
|
evgenyneu/Dodo
|
/Dodo/Utils/DodoColor.swift
|
UTF-8
| 1,790
| 3.515625
| 4
|
[
"MIT"
] |
permissive
|
import UIKit
/**
Creates a UIColor object from a string.
Examples:
DodoColor.fromHexString('#340f9a')
// With alpha channel
DodoColor.fromHexString('#f1a2b3a6')
*/
public class DodoColor {
/**
Creates a UIColor object from a string.
- parameter rgba: a RGB/RGBA string representation of color. It can include optional alpha value. Example: "#cca213" or "#cca21312" (with alpha value).
- returns: UIColor object.
*/
public class func fromHexString(_ rgba: String) -> UIColor {
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var alpha: CGFloat = 1.0
if !rgba.hasPrefix("#") {
print("Warning: DodoColor.fromHexString, # character missing")
return UIColor()
}
let index = rgba.index(rgba.startIndex, offsetBy: 1)
let hex = String(rgba.suffix(from: index))
let scanner = Scanner(string: hex)
var hexValue: CUnsignedLongLong = 0
if !scanner.scanHexInt64(&hexValue) {
print("Warning: DodoColor.fromHexString, error scanning hex value")
return UIColor()
}
if hex.count == 6 {
red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0
green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0
blue = CGFloat(hexValue & 0x0000FF) / 255.0
} else if hex.count == 8 {
red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0
green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0
blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0
alpha = CGFloat(hexValue & 0x000000FF) / 255.0
} else {
print("Warning: DodoColor.fromHexString, invalid rgb string, length should be 7 or 9")
return UIColor()
}
return UIColor(red: red, green: green, blue: blue, alpha: alpha)
}
}
| true
|
0d9fea2349226d179709a9e2d728c51fc2268529
|
Swift
|
kvstumph/BeadTheory
|
/BeadTheory/Game Shizz/Scenes/SandboxScene.swift
|
UTF-8
| 926
| 2.859375
| 3
|
[] |
no_license
|
import MetalKit
class SandboxScene: Scene {
var debugCamera = DebugCamera()
override func buildScene() {
addCamera(debugCamera)
debugCamera.position.z = 30
// addCubes()
addIcosohedrons()
}
var cubeCollection: CubeCollection!
func addCubes() {
cubeCollection = CubeCollection(cubesWide: 20, cubesHigh: 20, cubesBack: 20)
addChild(cubeCollection)
}
var icosohedronCollection: IcosohedronCollection!
func addIcosohedrons() {
icosohedronCollection = IcosohedronCollection(icosohedronsWide: 4, icosohedronsHigh: 4, icosohedronsBack: 4)
addChild(icosohedronCollection)
}
override func update(deltaTime: Float) {
// cubeCollection.rotation.z += deltaTime
// icosohedronCollection.rotation.z += deltaTime / 10.0
super.update(deltaTime: deltaTime)
}
}
| true
|
cf43d0263933721f67f521d290cdcd527e891ed1
|
Swift
|
shox050/Data-list
|
/Data-list/ViewModels/Implementation/AuthorizationViewModel.swift
|
UTF-8
| 2,041
| 3.296875
| 3
|
[] |
no_license
|
//
// AuthorizationViewModel.swift
// Data-list
//
// Created by Vladimir on 02/10/2019.
// Copyright © 2019 VladimirYakutin. All rights reserved.
//
import UIKit
class AuthorizationViewModel {
private let tokenRepository: TokenStorable = TokenRepository()
private let networkService: NetworkRequestable = NetworkService()
}
extension AuthorizationViewModel {
func authorization(with name: String, email: String, _ completion: @escaping() -> Void) {
networkService.getToken(byName: name, email: email) { [weak self] response in
switch response {
case .failure(let error):
print("Method authorization get error from response: ", error)
case .success(let responseData):
guard let token = self?.fetchToken(from: responseData) else {
print("Token not got, authorization is failed")
return
}
self?.tokenRepository.setToken(token)
completion()
}
}
}
private func fetchToken(from data: Data) -> String? {
guard let responseString = String(data: data, encoding: .utf8) else {
print("Cant get string from data - method fetchToken")
return nil
}
guard responseString.contains("token") else {
print("responseString not contain token")
return nil
}
let char = ":"
let separatedString = responseString.components(separatedBy: "\"").filter {
let a = $0
if a == char {
return false
}
return true
}
var token: String?
for (i, element) in separatedString.enumerated() {
if element == "token" {
token = separatedString[i + 1]
break
}
}
return token
}
}
| true
|
b0204d5071ec25858c4eb26c7c1a54a4ed3cdedd
|
Swift
|
Kilo-Loco/Users-List
|
/Dem Users Doe/UsersVC.swift
|
UTF-8
| 859
| 2.703125
| 3
|
[] |
no_license
|
//
// UsersVC.swift
// Dem Users Doe
//
// Created by Kyle Lee on 6/15/18.
// Copyright © 2018 Kyle Lee. All rights reserved.
//
import UIKit
class UsersVC: UITableViewController {
let temporaryUsers = ["Jannie", "Jessica", "Kyle L.", "Kyle N.", "Steven"]
override func viewDidLoad() {
super.viewDidLoad()
print("ohai")
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return temporaryUsers.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
let user = temporaryUsers[indexPath.row]
cell.textLabel?.text = user
return cell
}
}
| true
|
acec0775b8c58e607e177990444d5108c4793bf2
|
Swift
|
tomtom5005/yogi
|
/Advanced Swift (2016-10-20).playgroundbook/Contents/Chapters/01-Introduction.playgroundchapter/Pages/Who Is This Book For?.playgroundpage/Contents.swift
|
UTF-8
| 1,257
| 3.75
| 4
|
[] |
no_license
|
/*:
## Who Is This Book For?
This book targets experienced (though not necessarily expert) programmers — such
as existing Apple-platform developers, or those coming from other languages such
as Java or C++ — who want to bring their knowledge of Swift to the same level as
that of Objective-C or some other language. It's also suitable for new
programmers who started on Swift, have grown familiar with the basics, and are
looking to take things to the next level.
It's not meant as an introduction to Swift; it assumes you're familiar with the
syntax and structure of the language. If you want some good, compact coverage of
the basics of Swift, the best source is the official Apple Swift book (available
on
[iBooks](https://itunes.apple.com/us/book/swift-programming-language/id1002622538)
or on [Apple's website](https://developer.apple.com/swift/resources/)). If
you're already a confident programmer, you could try reading both our book and
the Apple Swift book in parallel.
This is also not a book about programming for OS X or iOS devices. Of course,
since Swift is currently mainly used on Apple platforms, we've tried to include
examples of practical use, but we hope this book will be useful for
non-Apple-platform programmers as well.
*/
| true
|
eacda37a8f032973ac1df9d9501acf258840a678
|
Swift
|
cebroker/emerald-ios
|
/EmeraldIOS/Utils/Extensions+UIViewController.swift
|
UTF-8
| 627
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
//
// Extensions+UIViewController.swift
// EmeraldIOS
//
// Created by Genesis Sanguino on 5/9/19.
// Copyright © 2019 Condor Labs. All rights reserved.
//
extension UIViewController {
func showAlert(_ message: String) {
showAlert(message, andTitle: "")
}
func showAlert(_ message: String, andTitle title: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
// show the alert
self.present(alert, animated: true, completion: nil)
}
}
| true
|
eedac23ec1c05f3bfb89b288a25963c6e62563c3
|
Swift
|
bruno94silva/challenge
|
/ChallengeUITests/ChallengeUITests.swift
|
UTF-8
| 3,668
| 2.6875
| 3
|
[] |
no_license
|
//
// ChallengeUITests.swift
// ChallengeUITests
//
// Created by Bruno dos Santos Silva on 07/08/21.
//
import XCTest
class ChallengeUITests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testRegisterUserAndLoginAndLogout() throws {
/* Se ocorrer um erro ao rodar no simulador, por favor verifique que a opção no menu "I\O > Keyboard > Connect Hardware Keyboard" do simulador esteja desabilitada. */
let app = XCUIApplication()
app.launch()
sleep(1)
app.buttons["REGISTRE-SE"].tap()
app.textFields["Nome Completo"].tap()
app.textFields["Nome Completo"].typeText("Bruno Silva")
app/*@START_MENU_TOKEN@*/.buttons["Next:"]/*[[".keyboards",".buttons[\"next\"]",".buttons[\"Next:\"]"],[[[-1,2],[-1,1],[-1,0,1]],[[-1,2],[-1,1]]],[0]]@END_MENU_TOKEN@*/.tap()
app.textFields["E-mail"].typeText("[email protected]")
app/*@START_MENU_TOKEN@*/.buttons["Next:"]/*[[".keyboards",".buttons[\"next\"]",".buttons[\"Next:\"]"],[[[-1,2],[-1,1],[-1,0,1]],[[-1,2],[-1,1]]],[0]]@END_MENU_TOKEN@*/.tap()
sleep(1)
app.textFields["CPF"].typeText("42587366860")
app.textFields["Celular"].tap()
app.textFields["Celular"].typeText("11945339755")
app.secureTextFields["Senha"].tap()
sleep(1)
app.secureTextFields["Senha"].typeText("BrunoSilva94")
app/*@START_MENU_TOKEN@*/.buttons["Next:"]/*[[".keyboards",".buttons[\"next\"]",".buttons[\"Next:\"]"],[[[-1,2],[-1,1],[-1,0,1]],[[-1,2],[-1,1]]],[0]]@END_MENU_TOKEN@*/.tap()
app.secureTextFields["Confirmação de Senha"].typeText("BrunoSilva94")
app/*@START_MENU_TOKEN@*/.buttons["continue"]/*[[".keyboards.buttons[\"continue\"]",".buttons[\"continue\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.tap()
app.buttons["REGISTRAR"].tap()
sleep(5)
if app.alerts.element.collectionViews.buttons["Ok"].exists {
app.alerts.element.collectionViews.buttons["Ok"].tap()
}
app.buttons["LOGIN"].tap()
app.textFields["E-mail"].tap()
app.textFields["E-mail"].typeText("[email protected]")
app/*@START_MENU_TOKEN@*/.buttons["Next:"]/*[[".keyboards",".buttons[\"seguinte\"]",".buttons[\"Next:\"]"],[[[-1,2],[-1,1],[-1,0,1]],[[-1,2],[-1,1]]],[0]]@END_MENU_TOKEN@*/.tap()
app.secureTextFields["Senha"].typeText("BrunoSilva94")
app/*@START_MENU_TOKEN@*/.buttons["continue"]/*[[".keyboards.buttons[\"continue\"]",".buttons[\"continue\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.tap()
app.buttons["LOGIN"].tap()
sleep(5)
if app.buttons["Logout"].exists {
app.buttons["Logout"].tap()
}
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| true
|
40fc5d62f0b5a2084ce6df532eb1a25fe1580132
|
Swift
|
ChungChoon/iOS
|
/ChungChul_iOS/Extensions/UIViewControllerExtension.swift
|
UTF-8
| 2,436
| 2.609375
| 3
|
[] |
no_license
|
//
// UIViewControllerExtension.swift
// ChungChul_iOS
//
// Created by ParkSungJoon on 13/11/2018.
// Copyright © 2018 Park Sung Joon. All rights reserved.
//
import UIKit
import Lottie
extension UIViewController {
//MARK: Navigation Bar Setting
func navigationBarSetting(title: String, isTranslucent: Bool){
self.title = title
self.navigationController?.navigationBar.largeTitleTextAttributes = [NSAttributedString.Key.font: UIFont(name: "NotoSansCJKkr-Bold", size: 24)!]
self.navigationController?.navigationBar.backgroundColor = UIColor.white
self.navigationController?.navigationBar.isTranslucent = isTranslucent
self.navigationController?.navigationBar.shadowImage = UIImage()
}
//MARK: Indicator View Setting Because of Downloading Klaytn Data
func indicatorViewSetting(_ indicatorView: UIView, _ animationView: LOTAnimationView) {
UIApplication.shared.keyWindow!.addSubview(indicatorView)
indicatorView.contentMode = .scaleAspectFill
indicatorView.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0.4)
animationView.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
animationView.center = indicatorView.center
animationView.loopAnimation = true
indicatorView.addSubview(animationView)
animationView.play()
}
}
extension UIViewController : UITextFieldDelegate, UIScrollViewDelegate{
override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return (true)
}
//MARK: Optional Binding for String
func gsno(_ data: String?) -> String {
guard let str = data else {
return ""
}
return str
}
//MARK: Optional Binding for Int
func gino(_ data: Int?) -> Int {
guard let num = data else {
return 0
}
return num
}
//MARK: Simple Alert Controller with Title and Message
func simpleAlert(title: String, msg: String) {
let alert = UIAlertController(title: title, message: msg, preferredStyle: .alert)
let okAction = UIAlertAction(title: "확인", style: .default)
alert.addAction(okAction)
present(alert, animated: true)
}
}
| true
|
a3097c7cf530dcda47174fdbe6fc8c11268b94ef
|
Swift
|
brjennin/BestPracticesSwift
|
/BestPracticesTests/Networking/ActivityIndicatorSpec.swift
|
UTF-8
| 867
| 2.609375
| 3
|
[] |
no_license
|
import Quick
import Nimble
@testable import BestPractices
class ActivityIndicatorSpec: QuickSpec {
override func spec() {
var subject: ActivityIndicator!
beforeEach {
subject = ActivityIndicator()
}
describe(".start") {
it("shows the status bar indicator") {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
subject.start()
expect(UIApplication.shared.isNetworkActivityIndicatorVisible).to(beTruthy())
}
}
describe(".stop") {
it("shows the status bar indicator") {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
subject.stop()
expect(UIApplication.shared.isNetworkActivityIndicatorVisible).to(beFalsy())
}
}
}
}
| true
|
fbff3807db9cd035d753a0921e0776b894d31883
|
Swift
|
litsdm/ToDos-iOS
|
/ToDos/Controllers/ToDoTableViewController.swift
|
UTF-8
| 4,119
| 2.65625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// ToDos
//
// Created by Carlos Diez on 11/18/16.
// Copyright © 2016 cdiezm. All rights reserved.
//
import UIKit
class ToDoTableViewController: UITableViewController {
// MARK: Properties
var sectionTitles = ["Undone", "Done"]
var toDos: [[ToDo]] = [[], []] {
didSet {
tableView.reloadData()
}
}
// MARK: View controller's life cycle
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.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showToDo" {
let displayToDoViewController = segue.destination as! DisplayToDoViewController
let indexPath = tableView.indexPathForSelectedRow!
let toDo = toDos[indexPath.section][indexPath.row]
displayToDoViewController.toDo = toDo
displayToDoViewController.delegate = self
}
else if segue.identifier == "addToDo" {
let addToDoViewController = segue.destination as! AddToDoViewController
addToDoViewController.delegate = self
}
}
@IBAction func unwindToMyToDos(segue: UIStoryboardSegue) {
}
// MARK: Table view methods
override func numberOfSections(in tableView: UITableView) -> Int {
return toDos.count
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section < sectionTitles.count {
return sectionTitles[section]
}
return nil
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return toDos[section].count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "toDoCell") as! ToDoTableViewCell
let toDo = toDos[indexPath.section][indexPath.row]
cell.toDo = toDo
cell.delegate = self
return cell
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
toDos[indexPath.section].remove(at: indexPath.row)
}
}
// MARK: Helper methods
func toggleCompleted(toDo: ToDo) {
remove(toDo: toDo)
toDo.completed = !toDo.completed
if toDo.completed {
toDos[1].append(toDo)
}
else {
toDos[0].append(toDo)
}
tableView.reloadData()
}
func remove(toDo: ToDo) {
for section in 0..<2 {
for index in 0..<toDos[section].count {
if toDos[section][index] === toDo {
toDos[section].remove(at: index)
return
}
}
}
}
func modify(toDo: ToDo, title: String, deadline: Date) {
toDo.title = title
toDo.deadline = deadline
tableView.reloadData()
}
}
// MARK: Extensions
extension ToDoTableViewController: ToDoTableViewCellDelegate {
func toDoTableViewCell(_: ToDoTableViewCell, toggleCompletedFor toDo: ToDo) {
toggleCompleted(toDo: toDo)
}
}
extension ToDoTableViewController: DisplayToDoViewControllerDelegate {
func displayToDoViewController(_: DisplayToDoViewController, toggleCompletedFor toDo: ToDo) {
toggleCompleted(toDo: toDo)
}
func displayToDoViewController(_: DisplayToDoViewController, remove toDo: ToDo) {
remove(toDo: toDo)
}
func displayToDoViewController(_: DisplayToDoViewController, modify toDo: ToDo, withTitle title: String, withDeadline deadline: Date) {
modify(toDo: toDo, title: title, deadline: deadline)
}
}
extension ToDoTableViewController: AddToDoViewControllerDelegate {
func addToDoViewController(_: AddToDoViewController, add toDo: ToDo) {
toDos[0].append(toDo)
}
func addToDoViewController(_: AddToDoViewController, modify toDo: ToDo, withTitle title: String, withDeadline deadline: Date) {
}
}
| true
|
67e0d7134fef4380d8d7752f5c2063a85aa35703
|
Swift
|
zhubin10811010025/sunwallet-ios
|
/SunWallet/Extensions/Button.swift
|
UTF-8
| 194
| 2.71875
| 3
|
[] |
no_license
|
import SwiftUI
extension Button {
init(animationAction: @escaping () -> Void, label: () -> Label) {
self.init(action: { withAnimation { animationAction() } }, label: label)
}
}
| true
|
d754dec1e023f045b62f16e1d07df629ea29c59d
|
Swift
|
arisinfotech/Garrtech
|
/Garrtech/Garrtech/Extension/Extension/UIView.swift
|
UTF-8
| 4,024
| 2.65625
| 3
|
[] |
no_license
|
//
// UIView.swift
// SlideMenuControllerSwift
//
// Created by Yuji Hato on 11/5/15.
// Copyright © 2015 Yuji Hato. All rights reserved.
//
import UIKit
extension UIView {
class func loadNib<T: UIView>(viewType: T.Type) -> T {
let className = String.className(aClass: viewType)
return Bundle(for: viewType).loadNibNamed(className, owner: nil, options: nil)!.first as! T
}
/*
class func loadNib() -> Self {
return loadNib(self)
}
*/
func setShadowView(width:CGFloat=0.5, height:CGFloat=0.5, Opacidade:Float=0.7, maskToBounds:Bool=false, radius:CGFloat=0.5){
// SET SHADOW
self.layer.shadowColor = UIColor.black.cgColor
self.layer.shadowOffset = CGSize(width: width, height: height)
self.layer.shadowRadius = radius
self.layer.shadowOpacity = Opacidade
self.layer.masksToBounds = maskToBounds
}
func setCornerradius(radius:CGFloat){
// SET CORNERRADIUS
self.layer.cornerRadius = radius
self.clipsToBounds = true
}
func setFrameBorder(color:UIColor , width:CGFloat) {
// SET BORDER
self.layer.borderColor = color.cgColor
self.layer.borderWidth = width
}
func setBluarView() {
// SET BLUAR VIEW
let toolbar : UIToolbar = UIToolbar()
toolbar.frame = self.frame
toolbar.backgroundColor = UIColor.black
toolbar.alpha = 0.14
self.addSubview(toolbar)
}
func setUpperShadow(radius: CGFloat) {
// SET UPPER SHADOW
let viewlayer1 = self.layer
viewlayer1.shadowOffset = CGSize(width: 0, height: -self.frame.height)
viewlayer1.shadowColor = UIColor.darkGray.cgColor
viewlayer1.shadowPath = UIBezierPath(rect: self.bounds).cgPath
viewlayer1.shadowRadius = radius
viewlayer1.shadowOpacity = 1.0
}
func setBottomShadow(radius: CGFloat) {
// SET BOTTOM SHADOW
let viewlayer1 = self.layer
viewlayer1.shadowOffset = CGSize(width: 0, height: frame.height)
viewlayer1.shadowColor = UIColor.black.cgColor
viewlayer1.shadowPath = UIBezierPath(rect: self.bounds).cgPath
viewlayer1.shadowRadius = radius
viewlayer1.shadowOpacity = 1.0
}
func setDefaultBottomShadow() {
self.layer.shadowColor = UIColor.black.cgColor
self.layer.shadowOpacity = 0.3
self.layer.shadowOffset = CGSize.zero
self.layer.shadowRadius = 7
}
func setGradientView(colors: NSArray!, with alpha:CGFloat) {
// SET GRADIENT COLOR VIEW
let gradientLayer: CAGradientLayer = CAGradientLayer()
// 2
gradientLayer.frame = self.bounds
//3
var arrayColor : [Any] = [Any]()
for i in 0..<colors.count {
let color = (colors.object(at: i) as! UIColor).withAlphaComponent(alpha).cgColor as CGColor
arrayColor.append(color)
}
gradientLayer.colors = arrayColor
// 4
var number : [NSNumber] = [NSNumber]()
for i in 0..<colors.count {
let value : Float = Float(1/Float(colors.count)) * Float(i)
number.append(value as NSNumber)
}
gradientLayer.locations = number
// 5
self.layer.addSublayer(gradientLayer)
/*
gradientLayer.frame = self.bounds
let color1 = UIColor.yellowColor().CGColor as CGColorRef
let color2 = UIColor(red: 1.0, green: 0, blue: 0, alpha: 1.0).CGColor as CGColorRef
let color3 = UIColor.clearColor().CGColor as CGColorRef
let color4 = UIColor(white: 0.0, alpha: 0.7).CGColor as CGColorRef
gradientLayer.colors = [color1, color2, color3, color4]
gradientLayer.locations = [0.0, 0.25, 0.75, 1.0]
self.layer.addSublayer(gradientLayer)
*/
}
}
| true
|
7ba4af898b33b13d1797e464b5ae4cb3bb24de3d
|
Swift
|
shiyuwudi/1--
|
/1-对象存档/ViewController.swift
|
UTF-8
| 2,218
| 3
| 3
|
[] |
no_license
|
//
// ViewController.swift
// 1-对象存档
//
// Created by apple2 on 16/1/4.
// Copyright © 2016年 shiyuwudi. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var one_piece:Anime?
let path = NSHomeDirectory() + "/Documents/animations"
override func viewDidLoad() {
super.viewDidLoad()
archive()
// resume()
}
func archive(){
one_piece = Anime.init(name: "one piece", chapters: 640, lastUpdate: NSDate.init(), comment: ["shiyu":"good fighting anime!"])
let dragonBall = Anime.init(name: "Dragon-Balls", chapters: 1000, lastUpdate: NSDate(), comment: ["young shiyu":"too expensive to rent DVD"])
// let animes = [one_piece, dragonBall]
print(NSHomeDirectory())
assert(dragonBall != nil)
NSKeyedArchiver.archiveRootObject(dragonBall!, toFile: path)
}
func resume(){
let maybe_anime = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? Anime
if let anime = maybe_anime{
print(anime)
}else{
print("no anime archived!")
}
}
}
class Anime:NSObject,NSCoding {
var name:NSString?
var chapters:NSInteger = 0
var lastUpdate:NSDate?
var comment:NSDictionary?
@objc func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(name, forKey: "name")
aCoder.encodeInteger(chapters, forKey: "chapters")
aCoder.encodeObject(lastUpdate, forKey: "lastUpdate")
aCoder.encodeObject(comment, forKey: "comment")
}
@objc required init?(coder aDecoder: NSCoder) {
self.name = aDecoder.decodeObjectForKey("name") as? NSString
self.chapters = aDecoder.decodeIntegerForKey("chapters")
self.lastUpdate = aDecoder.decodeObjectForKey("lastUpdate") as? NSDate
self.comment = aDecoder.decodeObjectForKey("comment") as? NSDictionary
}
@objc override init(){
}
@objc init?(name:String, chapters:Int, lastUpdate:NSDate, comment:[String:String]){
self.name = name
self.chapters = chapters
self.lastUpdate = lastUpdate
self.comment = comment
}
}
| true
|
e7dc7b634cf07218819107957e0d2df92ffe21ed
|
Swift
|
XDeric/Parsing-JSON-Lab
|
/ParsingJson_lab/Controller/PeopleViewController.swift
|
UTF-8
| 2,916
| 3.140625
| 3
|
[] |
no_license
|
//
// PeopleViewController.swift
// ParsingJson_lab
//
// Created by EricM on 8/27/19.
// Copyright © 2019 EricM. All rights reserved.
//
import UIKit
class PeopleViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var peopleTableViewOutlet: UITableView!
var humans = [People]()
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return humans.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = peopleTableViewOutlet.dequeueReusableCell(withIdentifier: "randCell", for: indexPath)
cell.textLabel?.text = "First Name: \(humans[indexPath.row].name.first) Last Name: \(humans[indexPath.row].name.last)"
cell.detailTextLabel?.text = "Age: \(humans[indexPath.row].dob.age)"
return cell
}
override func viewDidLoad() {
super.viewDidLoad()
peopleTableViewOutlet.dataSource = self
peopleTableViewOutlet.delegate = self
loadData()
// Do any additional setup after loading the view.
}
private func loadData(){
// just the string for the name of the file
guard let pathToJSONFile =
Bundle.main.path(forResource: "people", ofType: "json") else {fatalError("couldn't Find json file")}
print(pathToJSONFile)
// is a reference to the ctual location of the json file
let url = URL(fileURLWithPath: pathToJSONFile)
do{
let data = try Data(contentsOf: url)
humans = try People.getPeople(from: data)
// if either try fails the catch will catch both of them
} catch{
fatalError("couldn't get weather from JSON")
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let segueIdentifier = segue.identifier else { fatalError("No identifier in segue") }
switch segueIdentifier {
case "humanSegway" :
guard let humanVC = segue.destination as? HumanViewController else {
fatalError("Unexpected segue VC")
}
guard let selectedIndexPath = peopleTableViewOutlet.indexPathForSelectedRow else {
fatalError("No row was selected")
}
humanVC.person = humans[selectedIndexPath.row]
default:
fatalError("Nice Try")
}
}
/*
// 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
|
303def107c3c8fc2d43d518be663e238fab82493
|
Swift
|
danwallacenz/Primes
|
/PrimeFramework/views/ContentView.swift
|
UTF-8
| 1,354
| 2.75
| 3
|
[] |
no_license
|
//
// ContentView.swift
// Primes
//
// Created by Daniel Wallace on 13/09/19.
// Copyright © 2019 danwallacenz. All rights reserved.
//
import SwiftUI
import ComposableArchitecture
public struct ContentView: View {
@ObservedObject var store: Store<AppState, AppAction>
public var body: some View {
NavigationView {
List {
NavigationLink(destination: CounterView(store: self.store.view { ($0.count, $0.favouritePrimes) })) {
Text("Counter demo")
}
NavigationLink(destination: FavoritePrimesView(
store: self.store.view { $0.favouritePrimes }
)
) {
Text("Favourite primes")
}
NavigationLink(destination: ActivityFeedView(store: self.store)) {
Text("Activity feed")
}
}.navigationBarTitle("State management")
}
}
public init(store: Store<AppState, AppAction>) {
self.store = store
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView(
store: Store(
initialValue: AppState.loadOrCreateAppState(),
reducer: activityFeed(appReducer)
)
)
}
}
| true
|
990bd8ce1ce48dfaf2d8f129b50a3992aa7bacf0
|
Swift
|
sarasara1013/Apoli2
|
/yoteikakunin/Views/ListTableView.swift
|
UTF-8
| 1,955
| 2.625
| 3
|
[] |
no_license
|
//
// ListTableView.swift
// yoteikakunin
//
// Created by Master on 2015/05/17.
// Copyright (c) 2015年 srrn. All rights reserved.
//
import UIKit
class ListTableView: UITableView, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate {
var listArray: Array<Any>!
var inputField: UITextField!
init(frame: CGRect) {
super.init(frame: frame, style: .Plain)
self.delegate = self
self.dataSource = self
self.separatorInset = UIEdgeInsetsZero
listArray = []
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
self.delegate = self
self.dataSource = self
self.separatorInset = UIEdgeInsetsZero
listArray = []
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//return listArray.count
if listArray.count < 1 {
listArray.append("")
}
return listArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("ListCell", forIndexPath: indexPath) as UITableViewCell!
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "ListCell")
}
self.inputField = cell!.viewWithTag(1) as! UITextField
self.inputField.delegate = self;
//self.inputField.placeholder = "もちものを入力"
self.inputField.text = String(format: "%@", listArray[indexPath.row] as! String)
return cell!
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
| true
|
cc1aab3ccbaf0c7e29a48fc6cfd5dcd537e15499
|
Swift
|
Swapnil0308/1mgAssignment
|
/1mgAssignment/PagingScrollerFooter/PagingScrollerFooterReusableView.swift
|
UTF-8
| 1,664
| 2.671875
| 3
|
[] |
no_license
|
//
// PagingScrollerFooterReusableView.swift
// 1mgAssignment
//
// Created by Swapnil on 26/06/20.
// Copyright © 2020 Swapnil. All rights reserved.
//
// scroller footer view class
import UIKit
import Foundation
class PagingScrollerFooterReusableView: UICollectionReusableView
{
@IBOutlet weak var scrollerIndicator: UIActivityIndicatorView!
var isAnimating:Bool = false
var transformView: CGAffineTransform?
override func awakeFromNib()
{
super.awakeFromNib()
self.prepareInitialAnimation()
}
override func layoutSubviews()
{
super.layoutSubviews()
}
func transformView(transformVal:CGAffineTransform, scaleFactor:CGFloat)
{
if isAnimating
{
return
}
self.transformView = transformVal
self.scrollerIndicator?.transform = CGAffineTransform.init(scaleX: scaleFactor, y: scaleFactor)
}
func prepareInitialAnimation()
{
self.isAnimating = false
self.scrollerIndicator?.stopAnimating()
self.scrollerIndicator?.transform = CGAffineTransform.init(scaleX: 0.0, y: 0.0)
}
func startAnimate()
{
self.isAnimating = true
self.scrollerIndicator?.startAnimating()
}
func stopAnimate()
{
self.isAnimating = false
self.scrollerIndicator?.stopAnimating()
}
func animateView()
{
if isAnimating
{
return
}
self.isAnimating = true
UIView.animate(withDuration: 0.2)
{
self.scrollerIndicator?.transform = CGAffineTransform.identity
}
}
}
| true
|
1a8fb9bc24497d4ac0790ed51d9eac0041914d26
|
Swift
|
tanghan123/THSwiftBaseAction
|
/Swift方法/swift 一些函数使用/main.swift
|
UTF-8
| 1,134
| 4.34375
| 4
|
[] |
no_license
|
//
// main.swift
// swift 一些函数使用
//
// Created by chaomeng on 2019/4/3.
// Copyright © 2019年 TangHan. All rights reserved.
//
import Foundation
// MARK: stride 循环
// stride 是 Strideable 协议中定义的一个方法, 它可以按照指定的递进值生成一个序列。可以用在 Swift 的循环语法结构中
// 1
var numbers = [10 , 20 , 30 , 40 ,50]
//stride(from: 60, through: 100, by: 10)
numbers.append(contentsOf: stride(from: 60, through: 100, by: 10))
print(numbers)
//MARK: 自定义下标(Subscript)
// class structures和enum都可以定义subscript ,subscirpt可以帮助我们更方便的访问或者设置一个集合中的某个成员 ,也是访问集合,列表或序列的成员元素
// 下标语法
//subscript(index :Int) -> Int{
// get {
// return index
// }
// set(newValue){
//
// }
//}
// 例子
struct TimesTable {
let multiplier :Int
subscript(index :Int) -> Int {
return multiplier * index
}
}
let threeTimesTable = TimesTable(multiplier: 3)
print(threeTimesTable)
print("six times three is \(threeTimesTable[6])")
| true
|
54e6df9bdfd443b7224181a3856aed89b276acd2
|
Swift
|
stevethucpham/iOS_AccessMap
|
/AccessibilityMap/AccessibilityMap/Shared/Extensions/String.swift
|
UTF-8
| 401
| 2.875
| 3
|
[] |
no_license
|
//
// String.swift
// AccessibilityMap
//
// Created by iOS Developer on 5/24/18.
// Copyright © 2018 Swinburne. All rights reserved.
//
import Foundation
import UIKit
extension String {
func capitalizingFirstLetter() -> String {
return prefix(1).uppercased() + dropFirst()
}
mutating func capitalizeFirstLetter() {
self = self.capitalizingFirstLetter()
}
}
| true
|
ed365b7c038e24c256ec7a98dd9d44248ccc2583
|
Swift
|
hedypamungkas15/pokedex-ios
|
/pokedex-ios/Helper/Coordinator/Base/Presentable.swift
|
UTF-8
| 300
| 2.5625
| 3
|
[] |
no_license
|
//
// Presentable.swift
// pokedex-ios
//
// Created by Hedy on 07/08/21.
//
import Foundation
import UIKit
protocol Presentable {
func toPresent() -> UIViewController?
}
extension UIViewController: Presentable {
func toPresent() -> UIViewController? {
return self
}
}
| true
|
62fd37ee02aa690721a12e84fa48bfd95a390911
|
Swift
|
jorgela92/ChatApp-iOS
|
/ChatApp/filesuport/SwiftUtils.swift
|
UTF-8
| 744
| 3.03125
| 3
|
[
"MIT"
] |
permissive
|
//
// SwiftUtils.swift
// ChatApp
//
// Created by Jorge Lapeña Antón on 24/04/2019.
// Copyright © 2019 Jorge Lapeña Antón. All rights reserved.
//
import Foundation
final class SwiftUtils {
func shortUser(user: String) -> String {
var currentUser = user
if let indexSender = (currentUser.range(of: "@")?.lowerBound) {
currentUser = String(currentUser.prefix(upTo: indexSender))
}
return currentUser
}
func formatHour(dateString: String) -> String {
let dfmatter = DateFormatter()
dfmatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = dfmatter.date(from: dateString)
dfmatter.dateFormat = "HH:mm"
return dfmatter.string(from: date ?? Date())
}
}
| true
|
c034663b7da695284fc4c974b8d3928ccb3b57f2
|
Swift
|
zqrtalent/Rustavi2App
|
/Rustavi2TvShared/Model/ShowDetail.swift
|
UTF-8
| 2,562
| 2.5625
| 3
|
[] |
no_license
|
//
// ShowDetail.swift
// Rustavi2TvShared
//
// Created by Zaqro Butskrikidze on 11/23/18.
// Copyright © 2018 Zakaria Butskhrikidze. All rights reserved.
//
import Foundation
public class ShowDetail : JsonSerializable {
init(pageUrl:String?, name:String, desc: String?, mainVideo:ShowVideoItem?, videoItemsBySection:[String:[ShowVideoItem]?]?) {
self.pageUrl = pageUrl
self.name = name
self.desc = desc
self.mainVideo = mainVideo
self.videoItemsBySection = videoItemsBySection
super.init(json: [:])
}
required public init(json: [String : Any]) {
/*
"id": "string",
"desc": "string",
"mainVideo": {
"id": "string",
"title": "string",
"videoPageUrl": "string",
"coverImageUrl": "string"
},
"sectionVideoItems": [
{
"section": "string",
"videoItems": [
{
"id": "string",
"title": "string",
"videoPageUrl": "string",
"coverImageUrl": "string"
}
]
}
]
*/
if let id = json["id"] as? String{
self.id = id
}
self.name = ""
if let desc = json["desc"] as? String{
self.desc = desc
}
if let mainVideo = json["mainVideo"] as? [String: Any]{
self.mainVideo = ShowVideoItem(json: mainVideo)
}
if let videoSections = json["sectionVideoItems"] as? [[String:Any]]{
var videosBySection:[String:[ShowVideoItem]?] = [:]
for section in videoSections{
if let name = section["section"] as? String{
if let videoItems = section["videoItems"] as? [[String:Any]]{
var videos:[ShowVideoItem] = []
for videoItem in videoItems{
videos.append(ShowVideoItem(json: videoItem))
}
videosBySection[name] = videos
}
}
}
self.videoItemsBySection = videosBySection
}
super.init(json: json)
}
public var pageUrl:String?
public var id:String?
public var name:String
public var desc: String?
public var mainVideo:ShowVideoItem?
public var videoItemsBySection:[String:[ShowVideoItem]?]?
}
| true
|
9c134c3b30bd1a770c008799578e11b225344125
|
Swift
|
JLee141/swiftStuff
|
/Dates.playground/Contents.swift
|
UTF-8
| 286
| 2.578125
| 3
|
[] |
no_license
|
import UIKit
var todaysDate = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd" // "MMMM dd yyyy" for Month date year
dateFormatter.dateFormat = "MMddyyyy"
var todaysDateInt = Int(dateFormatter.string(from: todaysDate))
dateFormatter.string(from: todaysDate)
| true
|
186fd0081ea1ca4755d39d0dd3c67aac0ddcfe2a
|
Swift
|
Razzile/HackyMachy
|
/SwiftDebugTest/Breakpoint.swift
|
UTF-8
| 995
| 3.25
| 3
|
[] |
no_license
|
//
// Breakpoint.swift
// SwiftDebugTest
//
// Created by callum taylor on 18/02/2017.
// Copyright © 2017 Satori. All rights reserved.
//
import Foundation
class Breakpoint {
enum BreakpointArch : Int {
case x86 = 0
case x64 = 1
static var currentArch: BreakpointArch {
if (MemoryLayout<UInt>.size == 4) {
return .x86
}
else {
return .x64
}
}
}
enum BreakpointType : Int {
case Software = 0
case Hardware = 1
}
let arch: BreakpointArch
let type: BreakpointType
let address: UInt
init(_ address: UInt, _ arch: BreakpointArch = .currentArch, _ type: BreakpointType = .Software) {
(self.address, self.type, self.arch) = (address, type, arch)
}
func install() -> Bool {
print("installing breakpoint at \(String(format: "0x%X", self.address))")
return true
}
}
| true
|
97230dff1e539c393fa5b21025526fca60c978b4
|
Swift
|
StasyHard/FamilyBalance
|
/FamilyBalance/Base/Buttons/BlueRoundedButton.swift
|
UTF-8
| 450
| 2.625
| 3
|
[] |
no_license
|
import UIKit
class BlueRoundedButton: UIButton {
//MARK: - Init
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setupUI()
}
//MARK: - Private metods
private func setupUI() {
tintColor = .white
backgroundColor = AppColors.primaryColor
layer.cornerRadius = 5
}
}
| true
|
ddd9574b686beded28f6b740e232ceb661c0ca8e
|
Swift
|
GeoMod/MatchingGameAR
|
/MatchingGameAR/ConfirmCancelButtons.swift
|
UTF-8
| 977
| 3.0625
| 3
|
[] |
no_license
|
//
// ConfirmCancelButtons.swift
// MatchingGameAR
//
// Created by Daniel O'Leary on 5/3/21.
//
import SwiftUI
struct AROverlayButton: View {
let systemImageName: String
let color: Color
let fontSize: Font
let action: () -> Void
var body: some View {
Button(action: action, label: {
Image(systemName: systemImageName)
.font(fontSize)
.foregroundColor(color)
})
}
}
struct ConfirmCancelButtons: View {
@Binding var selectionConfirmed: Bool
var body: some View {
HStack(spacing: 75) {
Spacer()
AROverlayButton(systemImageName: "xmark.octagon.fill", color: .red, fontSize: .largeTitle) {
selectionConfirmed = false
}
AROverlayButton(systemImageName: "checkmark.circle.fill", color: .green, fontSize: .largeTitle) {
selectionConfirmed = true
}
Spacer()
}
}
}
struct ConfirmCancelButtons_Previews: PreviewProvider {
static var previews: some View {
ConfirmCancelButtons(selectionConfirmed: .constant(false))
}
}
| true
|
fadbdb26101011e849572a1443bd6fdc65731ef5
|
Swift
|
iamsuperflying/Swagger
|
/Swagger/Reformer.swift
|
UTF-8
| 2,431
| 2.796875
| 3
|
[
"MIT"
] |
permissive
|
//
// Reformer.swift
// Swagger
//
// Created by 李鹏飞 on 2020/4/20.
// Copyright © 2020 LPF. All rights reserved.
//
import UIKit
import HandyJSON
typealias Structure = Dictionary<String, Dictionary<String, Any>>
protocol Definition: HandyJSON {
var name: String! { get set }
}
extension Definition {
}
class Reformer<T:Definition> {
static func Reformer<T:Definition>() -> TransformOf<Array<T>, Structure> {
return TransformOf<Array<T>, Structure> (
fromJSON: { (apis) -> Array<T>? in
apis?.compactMap({
var t:T? = T.deserialize(from: $0.value)
t?.name = $0.key
return t
})
}, toJSON:{ (model) -> Structure? in
return nil
})
}
}
extension CodeThemeProtocol {
}
extension String {
func jsonFormatPrint() -> String {
if (self.starts(with: "{") || self.starts(with: "[")){
var level = 0
var jsonFormatString = String()
func getLevelStr(level:Int) -> String {
var string = ""
for _ in 0..<level {
string.append("\t")
}
return string
}
for char in self {
if level > 0 && "\n" == jsonFormatString.last {
jsonFormatString.append(getLevelStr(level: level))
}
switch char {
case "{":
fallthrough
case "[":
level += 1
jsonFormatString.append(char)
jsonFormatString.append("\n")
case ",":
jsonFormatString.append(char)
jsonFormatString.append("\n")
case "}":
fallthrough
case "]":
level -= 1;
jsonFormatString.append("\n")
jsonFormatString.append(getLevelStr(level: level));
jsonFormatString.append(char);
break;
default:
jsonFormatString.append(char)
}
}
return jsonFormatString;
}
return self
}
}
| true
|
e3ffbfc8bb3a2a4e3996009fba0427af7ac63da8
|
Swift
|
pgbuilder/narrativeCommunityPrototype
|
/Views/Comment.swift
|
UTF-8
| 1,260
| 2.640625
| 3
|
[] |
no_license
|
import UIKit
import SpriteKit
class Comment:UIViewFromNib{
//MARK: VARIABLES
@IBOutlet var mugshot: UIImageView!
@IBOutlet var sparkleContainer: UIView!
@IBOutlet var usernameLabel: UILabel!
@IBOutlet var commentLabel: UILabel!
//MARK: OVERRIDES
override public var intrinsicContentSize:CGSize{
get {
return frame.size
}
}
override func getNibName() -> String{
return "CommentLayout"
}
override func customSetup() {
}
//MARK: FUNCTIONS
func populate(mugshot:UIImage, username:String, comment:String){
self.mugshot.image = mugshot
usernameLabel.text = username
commentLabel.text = comment
}
func sparkle(){
layoutIfNeeded()
let skView = SKView(frame: sparkleContainer.bounds)
sparkleContainer.addSubview(skView)
let scene = SKScene(size: skView.frame.size)
scene.scaleMode = .resizeFill
skView.allowsTransparency = true
scene.backgroundColor = .clear
skView.presentScene(scene)
let sparkler = SKEmitterNode(fileNamed: "Sparkle")!
sparkler.position = scene.getCenter()
scene.addChild(sparkler)
}
}
| true
|
b2e4ea4653cf978db3bf7e18de239853a63ae340
|
Swift
|
gmohit197/tynor
|
/tynorios/tablecell_adapters/Complaintapater.swift
|
UTF-8
| 619
| 2.578125
| 3
|
[] |
no_license
|
//
// Complaintapater.swift
// tynorios
//
// Created by Acxiom Consulting on 02/11/18.
// Copyright © 2018 Acxiom. All rights reserved.
//
import Foundation
class Complaintapater {
var cno: String?
var type: String?
var date: String?
var status: String?
var cretedBy: String?
var statusImage: String?
init(cno: String?, type: String?, date: String?, status: String?,cetedBy: String?,statusImage: String?) {
self.cno = cno
self.type = type
self.date = date
self.status = status
self.cretedBy = cetedBy
self.statusImage = statusImage
}
}
| true
|
daba7792b59d312df7c4e316edba7fdbd9027712
|
Swift
|
MavinSao/iOS-rx-WeatherApp
|
/iOS-rx-Weather/Extensions/URL+Extensions.swift
|
UTF-8
| 319
| 2.609375
| 3
|
[] |
no_license
|
//
// URL + Extensions.swift
// iOS-rx-Weather
//
// Created by Mavin on 1/21/21.
//
import Foundation
extension URL {
static func urlForWeatherAPI(city: String) -> URL? {
return URL(string: "https://api.openweathermap.org/data/2.5/weather?q=\(city),uk&appid=429b5536fe47d611b66365c34dc4bf3c")
}
}
| true
|
7200d262dcfc6fd45f77a8fd2311cde3a09c6dc7
|
Swift
|
MikaQ56/TravelKit
|
/TravelKit/Model/Rates.swift
|
UTF-8
| 325
| 2.609375
| 3
|
[] |
no_license
|
//
// ChangeRate.swift
// TravelKit
//
// Created by Mickael on 04/09/2018.
// Copyright © 2018 Mickael. All rights reserved.
//
import Foundation
// Data struct for rates from fixer.io api. Protocol Codable used
struct Rates: Codable {
let timestamp: Int
let date: String
let rates: [String : Double]
}
| true
|
0b7e9916d35793522b5538a7d63046d8085aaa9a
|
Swift
|
ryzer19/Kode4Kids
|
/Kode4Kids/View Controllers/ProfileViewController.swift
|
UTF-8
| 5,159
| 2.78125
| 3
|
[] |
no_license
|
//
// ProfileViewController.swift
// Kode4Kids
//
// Created by Caleb Clegg on 17/06/2020.
// Copyright © 2020 Group9. All rights reserved.
//
//imports
import UIKit
import Firebase
import FirebaseAuth
import FirebaseFirestore
import FirebaseStorage
import FirebaseDatabase
class ProfileViewController: UIViewController {
//inputs from main.storyboard
@IBOutlet weak var avatar: UIImageView!
@IBOutlet weak var variableLabel: UILabel!
@IBOutlet weak var todayTask: UITextField!
//declaring image variable to be optional
var image: UIImage? = nil
//getting current logged in users email
let email : String = (Auth.auth().currentUser?.email)!
//user defaults to save default data
let defaults = UserDefaults.standard
//structured variables declared
struct Keys {
static let todaysTask = "todaysTask"
}
//first function ran when the page loads successfully
override func viewDidLoad() {
super.viewDidLoad()
//callingt functions
setUpAvatar()
checkForTask()
//set variableLabel as current users email
variableLabel.text = email
// Do any additional setup after loading the view.
}
//styling for the imageview avatar
func setUpAvatar(){
avatar.layer.cornerRadius = 40
avatar.clipsToBounds = true
avatar.isUserInteractionEnabled = true
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(presentPicker))
avatar.addGestureRecognizer(tapGesture)
}
//objective c function to present image picker to user
@objc func presentPicker(){
let picker = UIImagePickerController()
picker.sourceType = .photoLibrary
picker.allowsEditing = true
picker.delegate = self
self.present(picker, animated: true, completion: nil)
}
//back button on nav bar tapped brings user back a step
@IBAction func backTapped(_ sender: Any) {
let homeViewController = self.storyboard?.instantiateViewController(identifier: Constants.Storyboard.homeViewController) as? HomeViewController
self.view.window?.rootViewController = homeViewController
self.view.window?.makeKeyAndVisible()
}
//check if a user has previously entered their daily tasks
func checkForTask(){
let today = defaults.value(forKey: Keys.todaysTask) as? String ?? ""
todayTask.text = today
}
//button to save new daily task
@IBAction func saveToday(_ sender: Any) {
saveTask()
}
//function to save new daily task from text field
func saveTask(){
defaults.set(todayTask.text!, forKey: Keys.todaysTask)
}
@IBAction func logoutTapped(_ sender: Any) {
let loginViewController = self.storyboard?.instantiateViewController(identifier: Constants.Storyboard.loginViewController) as? LoginViewController
self.view.window?.rootViewController = loginViewController
self.view.window?.makeKeyAndVisible()
}
}
//extension to allow the image picker function
extension ProfileViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
//updates image view with new image
if let imageSelected = info[UIImagePickerController.InfoKey.editedImage] as?
UIImage {
image = imageSelected
avatar.image = imageSelected
}
//sets as original image
if let imageOriginal = info[UIImagePickerController.InfoKey.originalImage] as?
UIImage {
image = imageOriginal
avatar.image = imageOriginal
}
//dismiss picker after choosing photo
picker.dismiss(animated: true, completion: nil)
}
//button to save image to DB
@IBAction func imageSaved(_ sender: Any){
guard let imageSelected = self.image else {
print("Avatar is nil")
return
}
//sets data type & quality for the saved image
guard let imageData = imageSelected.jpegData(compressionQuality: 0.4) else {
return
}
//variables to access DB references
let storageRef = Storage.storage().reference(forURL: "gs://kode4kids-b877c.appspot.com/")
let storageProfileRef = storageRef.child("profile").child(Auth.auth().currentUser!.uid)
//metadata displayed on database within the image
let metadata = StorageMetadata()
metadata.contentType = "image/jpeg"
storageProfileRef.putData(imageData, metadata: metadata, completion: { (StorageMetadata, error) in
if error != nil {
print(error?.localizedDescription as Any)
return
}
})
}
}
| true
|
f6341b133abfce4554cee6a19008bfc7406f95a8
|
Swift
|
mohsinalimat/mysql-swift
|
/Tests/MySQLTests/QueryDecimalTypeTests.swift
|
UTF-8
| 1,911
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
//
// QueryDecimalTypeTests.swift
// MySQLTests
//
// Created by Yusuke Ito on 5/1/18.
//
import XCTest
@testable import MySQL
import Foundation
extension QueryDecimalTypeTests {
static var allTests : [(String, (QueryDecimalTypeTests) -> () throws -> Void)] {
return [
("testDecimalType", testDecimalType)
]
}
}
extension Row {
fileprivate struct DecimalRow: Codable, QueryParameter, Equatable {
let valueDouble: Decimal
let valueText: Decimal
private enum CodingKeys: String, CodingKey {
case valueDouble = "value_double"
case valueText = "value_text"
}
}
}
final class QueryDecimalTypeTests: XCTestCase, QueryTestType {
var constants: TestConstantsType!
var pool: ConnectionPool!
override func setUp() {
super.setUp()
prepare()
try! createDecimalTestTable()
}
private func createDecimalTestTable() throws {
try dropTestTable()
let conn = try pool.getConnection()
let query = """
CREATE TABLE `\(constants.tableName)` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`value_double` DOUBLE NOT NULL DEFAULT 0,
`value_text` MEDIUMTEXT,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
"""
_ = try conn.query(query)
}
func testDecimalType() throws {
let value = Decimal(1.23e100)
let row = Row.DecimalRow(valueDouble: value, valueText: value)
try pool.execute { conn in
_ = try conn.query("INSERT INTO ?? SET ? ", [constants.tableName, row])
}
let rows: [Row.DecimalRow] = try pool.execute {
try $0.query("SELECT * FROM ?? ORDER BY id ASC", [constants.tableName])
}
XCTAssertEqual(rows[0], row)
}
}
| true
|
0cd41cc85fcd58268e42e7bd4b338d603138ec2d
|
Swift
|
Chris-McElroy/aoc2016
|
/aoc2016/day14.swift
|
UTF-8
| 1,910
| 3.28125
| 3
|
[] |
no_license
|
//
// day14.swift
// aoc2016
//
// Created by Chris McElroy on 6/15/21.
//
import Foundation
func day14() {
let input = inputLines(14)[0]
var hashIndex = 0
var checkIndex = 0
var threes1: [Int: Character] = [:]
var fives1: [Character: [Int]] = [:]
var numKeys1 = 0
var a1: Int = 1
var threes2: [Int: Character] = [:]
var fives2: [Character: [Int]] = [:]
var numKeys2 = 0
var a2: Int = 2
while numKeys1 < 64 || numKeys2 < 64 {
if hashIndex > checkIndex + 1000 {
if let c1 = threes1[checkIndex] {
for j in fives1[c1] ?? [] {
if j > checkIndex && j <= checkIndex + 1000 {
numKeys1 += 1
if numKeys1 == 64 { a1 = checkIndex }
break
}
}
}
if let c2 = threes2[checkIndex] {
for j in fives2[c2] ?? [] {
if j > checkIndex && j <= checkIndex + 1000 {
numKeys2 += 1
if numKeys2 == 64 { a2 = checkIndex }
break
}
}
}
checkIndex += 1
} else {
checkNext()
}
}
func checkNext() {
let hash1 = MD5(of: input+String(hashIndex))
var hash2 = hash1
for _ in 0..<2016 {
hash2 = MD5(of: hash2)
}
threes1[hashIndex] = hash1.repititions(n: 3).first
for c in hash1.repititions(n: 5) {
fives1[c, default: []].append(hashIndex)
}
threes2[hashIndex] = hash2.repititions(n: 3).first
for c in hash2.repititions(n: 5) {
fives2[c, default: []].append(hashIndex)
}
hashIndex += 1
}
print(a1, a2)
}
// 25427 22045
| true
|
5b33d43b540b006aab30dc08a23a63a4d2cc5663
|
Swift
|
aetsyss/Algorithms
|
/Search in Rotated Sorted Array/SearchinRotatedSortedArray.playground/Contents.swift
|
UTF-8
| 804
| 3.5625
| 4
|
[] |
no_license
|
import Foundation
class Solution {
func search(_ nums: [Int], _ target: Int) -> Int {
var start = 0, end = nums.count - 1
while start <= end {
let mid = start + (end - start) / 2
if nums[mid] == target {
return mid
}
if nums[start] <= nums[mid] {
if target >= nums[start] && target < nums[mid] {
end = mid - 1
} else {
start = mid + 1
}
} else {
if target > nums[mid] && target <= nums[end] {
start = mid + 1
} else {
end = mid - 1
}
}
}
return -1
}
}
let s = Solution()
s.search([5, 1, 3], 1)
| true
|
8edf9ecae02ce6e5cd375eca5931bc2806382e06
|
Swift
|
TipBlockchain/TIP-wallet-ios
|
/Kasakasa/Util/Extensions/StringExtension.swift
|
UTF-8
| 1,398
| 2.828125
| 3
|
[] |
no_license
|
//
// StringExtension.swift
// Kasakasa
//
// Created by John Warmann on 2019-01-06.
// Copyright © 2019 Tip Blockchain. All rights reserved.
//
import Foundation
extension String {
var localized: String {
return NSLocalizedString(self, comment: "")
}
func localized(withParams arguments: [CVarArg]) -> String {
let localizedString = self.localized
return String(format: localizedString, arguments: arguments)
}
func containsSpace() -> Bool {
return self.contains(" ")
}
func isUsername() -> Bool {
let regex = "\\w{2,32}"
return NSPredicate(format: "SELF MATCHES %@", regex).evaluate(with: self)
}
func isNumeric() -> Bool {
let regex = "^[0-9]+(\\.)?[0-9]*$"
return NSPredicate(format: "SELF MATCHES %@", regex).evaluate(with: self)
}
func isValidPassword() -> Bool {
let passwordRegex = "\\w{8,255}"
return NSPredicate(format: "SELF MATCHES %@", passwordRegex).evaluate(with: self)
}
func withHexPrefix() -> String {
if !self.hasPrefix("0x") {
return "0x" + self
}
return self
}
func withAtPrefix() -> String {
if !self.hasPrefix("@") {
return "@" + self
}
return self
}
private static func isChecksumAddress(str: String) -> Bool {
return false
}
}
| true
|
d4309bc4a1bb313847ec7fd8805cba29a0cfd4c5
|
Swift
|
lesyk/MVVMSwiftSample
|
/MVVM/ListViewModel.swift
|
UTF-8
| 1,121
| 3.046875
| 3
|
[
"MIT"
] |
permissive
|
import Foundation
public class ListViewModel {
public let context = Context.defaultContext
public var items = [Item]()
public func refresh() {
items = context.paybacks.map { self.itemForPayback($0) }
print(items)
}
func itemForPayback(payback: Payback) -> Item {
let singleLetter = payback.lastName.substringToIndex(payback.lastName.startIndex.successor())
let title = "\(payback.firstName) \(singleLetter)."
let subtitle = NSDateFormatter.localizedStringFromDate(payback.createdAt, dateStyle: NSDateFormatterStyle.LongStyle, timeStyle: NSDateFormatterStyle.NoStyle)
let rounded = NSNumber(double: round(payback.amount)).longLongValue
let amount = "$\(rounded)"
let item = Item(title: title, subtitle: subtitle, amount: amount)
return item
}
func removePayback(index: Int) {
context.removePayback(index)
}
public struct Item {
public let title: String
public let subtitle: String
public let amount: String
}
}
| true
|
ad670c74fc00e7b08587f404171c964bb137be28
|
Swift
|
HunterStanton/Song-Title-Generator-TV
|
/Song Title Generator TV/Controllers/ViewController.swift
|
UTF-8
| 1,036
| 2.703125
| 3
|
[
"WTFPL"
] |
permissive
|
//
// ViewController.swift
// Song Title Generator TV
//
// Created by Hunter Stanton on 2/4/17.
// Copyright © 2017 Hunter Stanton. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
// The label that will show the adjective
@IBOutlet weak var AdjectiveLabel: UILabel!
// The adjective that will show the noun
@IBOutlet weak var NounLabel: UILabel!
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.
}
@IBAction func GenerateButtonPressed(_ sender: Any) {
// Bit long winded, but works
AdjectiveLabel.text = TitleDictionary.adjectives[Int(arc4random_uniform(UInt32(TitleDictionary.adjectives.count)))]
NounLabel.text = TitleDictionary.nouns[Int(arc4random_uniform(UInt32(TitleDictionary.nouns.count)))]
}
}
| true
|
d593b5b5edf76ad7a8bc56095d351a7f96f9773f
|
Swift
|
MityaAndreevich/PlayingWithParsingData
|
/PlayingWithParsingData/Services/NetworkManager.swift
|
UTF-8
| 6,603
| 2.953125
| 3
|
[] |
no_license
|
//
// NetworkManager.swift
// PlayingWithParsingData
//
// Created by Dmitry Logachev on 30.09.2021.
//
import Foundation
import Alamofire
enum Link: String {
case imageUrl = "https://applelives.com/wp-content/uploads/2016/03/iPhone-SE-11.jpeg"
case exampleOne = "https://swiftbook.ru//wp-content/uploads/api/api_course"
case exampleTwo = "https://swiftbook.ru//wp-content/uploads/api/api_courses"
case exampleThree = "https://swiftbook.ru//wp-content/uploads/api/api_website_description"
case exampleFour = "https://swiftbook.ru//wp-content/uploads/api/api_missing_or_wrong_fields"
case exampleFive = "https://swiftbook.ru//wp-content/uploads/api/api_courses_capital"
case postRequest = "https://jsonplaceholder.typicode.com/posts"
case courseImageURL = "https://swiftbook.ru/wp-content/uploads/sites/2/2018/08/notifications-course-with-background.png"
}
enum NetworkError: Error {
case invalidURL
case noData
case decodingError
}
class NetworkManager {
static let shared = NetworkManager()
private init() {}
func fetchImage(from url: String?, completion: @escaping(Result<Data, NetworkError>) -> Void) {
guard let url = URL(string: url ?? "") else {
completion(.failure(.invalidURL))
return
}
DispatchQueue.global().async {
guard let imageData = try? Data(contentsOf: url) else {
completion(.failure(.noData))
return
}
DispatchQueue.main.async {
completion(.success(imageData))
}
}
}
func fetch<T: Decodable>(dataType: T.Type, from url: String, convertFromSnakeCase: Bool = true, comletion: @escaping(Result<T, NetworkError>) -> Void) {
guard let url = URL(string: url) else {
comletion(.failure(.invalidURL))
return
}
URLSession.shared.dataTask(with: url) { data, _, error in
guard let data = data else {
comletion(.failure(.noData))
print(error?.localizedDescription ?? "No error description")
return
}
do {
let decoder = JSONDecoder()
if convertFromSnakeCase {
decoder.keyDecodingStrategy = .convertFromSnakeCase
}
let type = try decoder.decode(T.self, from: data)
DispatchQueue.main.async {
comletion(.success(type))
}
} catch {
comletion(.failure(.decodingError))
}
}.resume()
}
func postRequest(with data: [String: Any], to url: String, completion: @escaping(Result<Any, NetworkError>) -> Void) {
guard let url = URL(string: url) else {
completion(.failure(.invalidURL))
return
}
guard let courseData = try? JSONSerialization.data(withJSONObject: data) else {
completion(.failure(.noData))
return
}
var request = URLRequest(url: url)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
request.httpBody = courseData
URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, let response = response else {
completion(.failure(.noData))
print(error?.localizedDescription ?? "No error description")
return
}
print(response)
do {
let course = try JSONSerialization.jsonObject(with: data)
completion(.success(course))
} catch {
completion(.failure(.decodingError))
}
}.resume()
}
func postRequest(with data: CourseV3, to url: String, completion: @escaping(Result<Any, NetworkError>) -> Void) {
guard let url = URL(string: url) else {
completion(.failure(.invalidURL))
return
}
guard let courseData = try? JSONEncoder().encode(data) else {
completion(.failure(.noData))
return
}
var request = URLRequest(url: url)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
request.httpBody = courseData
URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, let response = response else {
completion(.failure(.noData))
print(error?.localizedDescription ?? "No error description")
return
}
print(response)
do {
let course = try JSONDecoder().decode(CourseV3.self, from: data)
completion(.success(course))
} catch {
completion(.failure(.decodingError))
}
}.resume()
}
func fetchDataWithAlamofire(_ url: String, completion: @escaping(Result<[Course], NetworkError>) -> Void) {
AF.request(Link.exampleTwo.rawValue)
.validate()
.responseJSON { dataResponse in
switch dataResponse.result {
case .success(let value):
let courses = Course.getCourses(from: value)
DispatchQueue.main.async {
completion(.success(courses))
}
case .failure:
completion(.failure(.decodingError))
}
}
}
func postDataWithAlamofire(_ url: String, data: CourseV3, completion: @escaping(Result<Course, NetworkError>) -> Void) {
AF.request(url, method: .post, parameters: data)
.validate()
.responseDecodable(of: CourseV3.self) { dataResponse in
switch dataResponse.result {
case .success(let coursesV3):
let course = Course(
name: coursesV3.name,
imageUrl: coursesV3.imageUrl,
numberOfLessons: Int(coursesV3.numberOfLessons) ?? 0,
numberOfTests: Int(coursesV3.numberOfTests) ?? 0
)
DispatchQueue.main.async {
completion(.success(course))
}
case .failure:
completion(.failure(.decodingError))
}
}
}
}
| true
|
0f04df0f50c58e9de35ded08a6b1601f76324688
|
Swift
|
bhaveshbc/GoogleSignIn
|
/BhaveshPractical/BhaveshPractical/Modules/View/CustomView/BottomCurvedView.swift
|
UTF-8
| 788
| 2.90625
| 3
|
[] |
no_license
|
//
// BottomCurvedView.swift
// BhaveshPractical
//
// Created by Bhavesh Chaudhari on 29/10/21.
//
import UIKit
class BottomCurvedView: UIView {
/// The Boolean used to set textFiled state for Password.
@IBInspectable var isLightBackground: Bool = false {
didSet {
self.backgroundColor = isLightBackground ? .white : .black
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupAppearance()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setupAppearance()
}
/// setup View appearance
private func setupAppearance() {
self.layer.maskedCorners = MaskedCorners.TopCorner
self.layer.cornerRadius = 35
self.layer.masksToBounds = false
}
}
| true
|
fdd82c9268de2eb56d27ab3a25668fb9faa311e2
|
Swift
|
g212gs/Cards
|
/cards/BuisnessLayer/Models/Cards/CardDetail.swift
|
UTF-8
| 2,958
| 3.15625
| 3
|
[
"MIT"
] |
permissive
|
//
// CardDetail.swift
//
// Created by Gaurang Lathiya on 25/12/18
// Copyright (c) . All rights reserved.
//
import Foundation
import SwiftyJSON
public final class CardDetail: NSCoding {
// MARK: Declaration for string constants to be used to decode and also serialize.
private struct SerializationKeys {
static let comments = "comments"
static let message = "message"
static let id = "id"
static let userId = "user_id"
static let image = "image"
}
// MARK: Properties
public var comments: [Comments]?
public var message: String?
public var id: Int?
public var userId: Int?
public var image: String?
// MARK: SwiftyJSON Initializers
/// Initiates the instance based on the object.
///
/// - parameter object: The object of either Dictionary or Array kind that was passed.
/// - returns: An initialized instance of the class.
public convenience init(object: Any) {
self.init(json: JSON(object))
}
/// Initiates the instance based on the JSON that was passed.
///
/// - parameter json: JSON object from SwiftyJSON.
public required init(json: JSON) {
if let items = json[SerializationKeys.comments].array { comments = items.map { Comments(json: $0) } }
message = json[SerializationKeys.message].string
id = json[SerializationKeys.id].int
userId = json[SerializationKeys.userId].int
image = json[SerializationKeys.image].string
}
/// Generates description of the object in the form of a NSDictionary.
///
/// - returns: A Key value pair containing all valid values in the object.
public func dictionaryRepresentation() -> [String: Any] {
var dictionary: [String: Any] = [:]
if let value = comments { dictionary[SerializationKeys.comments] = value.map { $0.dictionaryRepresentation() } }
if let value = message { dictionary[SerializationKeys.message] = value }
if let value = id { dictionary[SerializationKeys.id] = value }
if let value = userId { dictionary[SerializationKeys.userId] = value }
if let value = image { dictionary[SerializationKeys.image] = value }
return dictionary
}
// MARK: NSCoding Protocol
required public init(coder aDecoder: NSCoder) {
self.comments = aDecoder.decodeObject(forKey: SerializationKeys.comments) as? [Comments]
self.message = aDecoder.decodeObject(forKey: SerializationKeys.message) as? String
self.id = aDecoder.decodeObject(forKey: SerializationKeys.id) as? Int
self.userId = aDecoder.decodeObject(forKey: SerializationKeys.userId) as? Int
self.image = aDecoder.decodeObject(forKey: SerializationKeys.image) as? String
}
public func encode(with aCoder: NSCoder) {
aCoder.encode(comments, forKey: SerializationKeys.comments)
aCoder.encode(message, forKey: SerializationKeys.message)
aCoder.encode(id, forKey: SerializationKeys.id)
aCoder.encode(userId, forKey: SerializationKeys.userId)
aCoder.encode(image, forKey: SerializationKeys.image)
}
}
| true
|
529047813cb5cb995a14670ec01d9f43b7be3c78
|
Swift
|
iBrie/swift-classEnum-lab-swift-intro-000
|
/ClassesNenums/Bird.swift
|
UTF-8
| 926
| 3.65625
| 4
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
//
// Bird.swift
// ClassesNenums
//
// Created by James Campagno on 7/29/16.
// Copyright © 2016 Flatiron School. All rights reserved.
//
import Foundation
enum Speed : Int {
case slow,
medium,
fast
func isFaster(thanSpeed speed : Speed) -> Bool {
return self.rawValue > speed.rawValue
}
}
enum Diet : String {
case meatEater,
vegetarian
}
enum Sex : String{
case male,
female
}
class Trex {
var speed: Speed = .fast
let diet : Diet = .meatEater
let name : String
let sex : Sex
var isAlive = true
init(name : String, sex : Sex) {
self.name = name
self.sex = sex
}
func speak() -> String {
return "ROAAAWWWWRRRRR!!!!!!"
}
func isFaster(thanTrex trex: Trex) -> Bool {
return speed.isFaster(thanSpeed: trex.speed)
}
func eat(otherTrex trex:Trex) {
if isFaster(thanTrex: trex) {
trex.isAlive = false
}
}
}
| true
|
f4e1660d6dfbb585f1b76211c8af57f9e46af644
|
Swift
|
AlexChekanov/GeneralExtensions
|
/GeneralExtensions/LocalisedString.swift
|
UTF-8
| 662
| 2.90625
| 3
|
[] |
no_license
|
import Foundation
public struct LocalizedString: ExpressibleByStringLiteral, Equatable {
public let v: String
public init(key: String) {
self.v = NSLocalizedString(key, comment: "")
}
public init(localized: String) {
self.v = localized
}
public init(stringLiteral value:String) {
self.init(key: value)
}
public init(extendedGraphemeClusterLiteral value: String) {
self.init(key: value)
}
public init(unicodeScalarLiteral value: String) {
self.init(key: value)
}
}
public func ==(lhs:LocalizedString, rhs:LocalizedString) -> Bool {
return lhs.v == rhs.v
}
| true
|
079301a97a712844b8641dcacd29c02c90171630
|
Swift
|
Nexters/MNT_iOS
|
/MNT_iOS/Common/Coordinator/CoordinatorType.swift
|
UTF-8
| 867
| 2.6875
| 3
|
[] |
no_license
|
//
// Coordinatable.swift
// MNT_iOS
//
// Created by 최민섭 on 2020/01/28.
// Copyright © 2020 최민섭. All rights reserved.
//
import RxSwift
enum TransitionStyle {
case root
case push
case modal
case present
case popToRoot
case replace((UIViewController) -> Void)
}
enum TransitionError: Error {
case navigationControllerMissing
case cannotPop
case unknown
}
protocol SceneType {
func instantiate() -> UIViewController
}
protocol SceneCoordinatorType {
func showAlert(title: String, message: String) -> Completable
func transition(using style: TransitionStyle) -> Completable
func transition(to scene: SceneType, using style: TransitionStyle, animated: Bool) -> Completable
func close(animated: Bool) -> Completable
func changeCurrentVC(_ currentVC: UIViewController)
}
| true
|
19052c92fce2fed43f87d01464f85fbe88662295
|
Swift
|
Build-week-Anywhere-Fitness-II/iOS
|
/AnywhereFitness2/AnywhereFitness2/Models/Course+Convinience.swift
|
UTF-8
| 2,577
| 2.90625
| 3
|
[
"MIT"
] |
permissive
|
//
// Course+Convinience.swift
// AnywhereFitness2
//
// Created by Zachary Thacker on 10/20/20.
// Copyright © 2020 John McCants. All rights reserved.
//
import Foundation
import CoreData
extension Course {
@discardableResult
convenience init(id: Int,
time: Date,
courseDetails: String,
courseTitle: String,
courseType: String,
durration: String,
image: String,
location: String,
skillLevel: String,
maxCourseSize: Int,
context: NSManagedObjectContext = CoreDataStack.shared.mainContext) {
self.init(context: context)
self.id = Int64(id)
self.time = time
self.courseDetails = courseDetails
self.courseTitle = courseTitle
self.durration = durration
self.image = image
self.location = location
self.skillLevel = skillLevel
self.maxCourseSize = Int64(maxCourseSize)
}
// // Representation convinience init
// @discardableResult
// convenience init(representation: CourseRepresentation) {
// self.init(id: representation.id,
// time: representation.time,
// courseDetails: representation.courseDetails,
// courseTitle: representation.courseTitle,
// courseType: representation.courseType,
// durration: representation.durration,
// image: representation.image,
// location: representation.location,
// skillLevel: representation.skillLevel,
// maxCourseSize: representation.maxCourseSize)
// }
//
// // Computed variable -> representation
// var representation: CourseRepresentation? {
// guard let id = id,
// let courseTitle = courseTitle,
// let location = location else {return nil}
//
// return CourseRepresentation(id = Int(id),
// time = time,
// courseDetails = courseDetails,
// courseTitle = courseTitle,
// durration = durration,
// image = image,
// location = location,
// skillLevel = skillLevel,
// maxCourseSize = Int(maxCourseSize))
// }
//}
}
| true
|
429a2090e5746827dca2efb2e6d7f7ad4380373f
|
Swift
|
sn3ek/nio
|
/Nio/Conversations/ConversationView.swift
|
UTF-8
| 1,783
| 2.65625
| 3
|
[] |
no_license
|
import SwiftUI
import Combine
import KeyboardObserving
import SwiftMatrixSDK
struct ConversationContainerView: View {
static var displayedMessageTypes = [
kMXEventTypeStringRoomMessage,
kMXEventTypeStringRoomMember,
kMXEventTypeStringRoomTopic
]
@EnvironmentObject var store: MatrixStore<AppState, AppAction>
var conversation: MXRoom
var body: some View {
ConversationView(
events: conversation.enumeratorForStoredMessagesWithType(in: Self.displayedMessageTypes)?.nextEventsBatch(50) ?? [],
isDirect: conversation.isDirect
)
.navigationBarTitle(Text(conversation.summary.displayname ?? ""), displayMode: .inline)
.keyboardObserving()
}
}
struct ConversationView: View {
var events: [MXEvent]
var isDirect: Bool
@State private var message = ""
var body: some View {
VStack {
ScrollView {
ForEach(events.reversed()) { event in
EventContainerView(event: event, isDirect: self.isDirect)
.padding(.horizontal)
.padding(.vertical, 10)
}
}
MessageComposerView(message: $message,
onCommit: send)
.padding(.horizontal)
.padding(.bottom, 10)
}
}
private func send() {
// self.messageStore.append(message: message)
message = ""
}
}
//struct ConversationView_Previews: PreviewProvider {
// static var previews: some View {
// NavigationView {
// ConversationView()
// .accentColor(.purple)
// .navigationBarTitle("Morpheus", displayMode: .inline)
// }
// }
//}
| true
|
45a5e4b99b8f3260bc4ef2d32713e0d90a198a22
|
Swift
|
renatomedina/Viper-Demo
|
/zap-challenge-viper/Modules/Login/View/LoginView.swift
|
UTF-8
| 1,207
| 2.8125
| 3
|
[
"MIT"
] |
permissive
|
//
// LoginView.swift
// zap-challenge-viper
//
// Created by Renato Medina on 05/04/19.
// Copyright © 2019 Renato Medina. All rights reserved.
//
import UIKit
class LoginView: UIView, KeyboardControllable {
@IBOutlet private weak var enterButton: UIButton!
@IBOutlet private weak var emailTextField: UITextField!
@IBOutlet private weak var passwordTextField: UITextField!
var validate: ((String?, String?)->Void)?
@IBAction func tapButtonEnter() {
self.validate?(emailTextField.text, passwordTextField.text)
}
func handleKeyboardWillShow(_ notification: Notification) {
let keyboardSize = notification.keyboardSize
let keyboardHeight = keyboardSize?.height ?? 250
if self.frame.origin.y == 0 {
self.frame.origin.y -= keyboardHeight
}
}
func handleKeyboardWillHide(_ notification: Notification) {
if self.frame.origin.y != 0 {
self.frame.origin.y = 0
}
}
}
extension LoginView: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
| true
|
c4e74761e662a8d230cdc21e35ea259ae9750015
|
Swift
|
guoyingtao/Mantis
|
/Sources/Mantis/CropView/CropBoxLockedAspectFrameUpdater.swift
|
UTF-8
| 5,516
| 2.625
| 3
|
[
"MIT",
"CC-BY-3.0"
] |
permissive
|
//
// CropBoxLockedAspectFrameUpdater.swift
// Mantis
//
// Created by Echo on 10/21/18.
// Copyright © 2018 Echo. All rights reserved.
//
import Foundation
import UIKit
struct CropBoxLockedAspectFrameUpdater {
private var contentFrame = CGRect.zero
private var cropOriginFrame = CGRect.zero
private(set) var cropBoxFrame = CGRect.zero
private var tappedEdge = CropViewAuxiliaryIndicatorHandleType.none
init(tappedEdge: CropViewAuxiliaryIndicatorHandleType, contentFrame: CGRect, cropOriginFrame: CGRect, cropBoxFrame: CGRect) {
self.tappedEdge = tappedEdge
self.contentFrame = contentFrame
self.cropOriginFrame = cropOriginFrame
self.cropBoxFrame = cropBoxFrame
}
mutating func updateCropBoxFrame(xDelta: CGFloat, yDelta: CGFloat) {
var xDelta = xDelta
var yDelta = yDelta
// Current aspect ratio of the crop box in case we need to clamp it
let aspectRatio = (cropOriginFrame.size.width / cropOriginFrame.size.height)
func updateHeightFromBothSides() {
cropBoxFrame.size.height = cropBoxFrame.width / aspectRatio
cropBoxFrame.origin.y = cropOriginFrame.midY - (cropBoxFrame.height * 0.5)
}
func updateWidthFromBothSides() {
cropBoxFrame.size.width = cropBoxFrame.height * aspectRatio
cropBoxFrame.origin.x = cropOriginFrame.midX - cropBoxFrame.width * 0.5
}
func handleLeftEdgeFrameUpdate() {
updateHeightFromBothSides()
xDelta = max(0, xDelta)
cropBoxFrame.origin.x = cropOriginFrame.origin.x + xDelta
cropBoxFrame.size.width = cropOriginFrame.width - xDelta
cropBoxFrame.size.height = cropBoxFrame.size.width / aspectRatio
}
func handleRightEdgeFrameUpdate() {
updateHeightFromBothSides()
cropBoxFrame.size.width = min(cropOriginFrame.width + xDelta, contentFrame.height * aspectRatio)
cropBoxFrame.size.height = cropBoxFrame.size.width / aspectRatio
}
func handleTopEdgeFrameUpdate() {
updateWidthFromBothSides()
yDelta = max(0, yDelta)
cropBoxFrame.origin.y = cropOriginFrame.origin.y + yDelta
cropBoxFrame.size.height = cropOriginFrame.height - yDelta
cropBoxFrame.size.width = cropBoxFrame.size.height * aspectRatio
}
func handleBottomEdgeFrameUpdate() {
updateWidthFromBothSides()
cropBoxFrame.size.height = min(cropOriginFrame.height + yDelta, contentFrame.width / aspectRatio)
cropBoxFrame.size.width = cropBoxFrame.size.height * aspectRatio
}
let tappedEdgeCropFrameUpdateRule: TappedEdgeCropFrameUpdateRule = [.topLeft: (xDelta, yDelta),
.topRight: (-xDelta, yDelta),
.bottomLeft: (xDelta, -yDelta),
.bottomRight: (-xDelta, -yDelta)]
func setCropBoxSize() {
guard let delta = tappedEdgeCropFrameUpdateRule[tappedEdge] else {
return
}
var distance = CGPoint()
distance.x = 1.0 - (delta.xDelta / cropOriginFrame.width)
distance.y = 1.0 - (delta.yDelta / cropOriginFrame.height)
let scale = (distance.x + distance.y) * 0.5
cropBoxFrame.size.width = ceil(cropOriginFrame.width * scale)
cropBoxFrame.size.height = ceil(cropOriginFrame.height * scale)
}
func handleTopLeftEdgeFrameUpdate() {
xDelta = max(0, xDelta)
yDelta = max(0, yDelta)
setCropBoxSize()
cropBoxFrame.origin.x = cropOriginFrame.origin.x + (cropOriginFrame.width - cropBoxFrame.width)
cropBoxFrame.origin.y = cropOriginFrame.origin.y + (cropOriginFrame.height - cropBoxFrame.height)
}
func handleTopRightEdgeFrameUpdate() {
xDelta = max(0, xDelta)
yDelta = max(0, yDelta)
setCropBoxSize()
cropBoxFrame.origin.y = cropOriginFrame.origin.y + (cropOriginFrame.height - cropBoxFrame.height)
}
func handleBottomLeftEdgeFrameUpdate() {
setCropBoxSize()
cropBoxFrame.origin.x = cropOriginFrame.maxX - cropBoxFrame.width
}
func handleBottomRightEdgeFrameUpdate() {
setCropBoxSize()
}
func updateCropBoxFrame() {
switch tappedEdge {
case .left:
handleLeftEdgeFrameUpdate()
case .right:
handleRightEdgeFrameUpdate()
case .top:
handleTopEdgeFrameUpdate()
case .bottom:
handleBottomEdgeFrameUpdate()
case .topLeft:
handleTopLeftEdgeFrameUpdate()
case .topRight:
handleTopRightEdgeFrameUpdate()
case .bottomLeft:
handleBottomLeftEdgeFrameUpdate()
case .bottomRight:
handleBottomRightEdgeFrameUpdate()
default:
print("none")
}
}
updateCropBoxFrame()
}
}
| true
|
273d6e4c95881a57f04159e82f5202bfa3b741a7
|
Swift
|
fulstaph/snake-game-ios
|
/SnakeGame/SnakeGame/Views/MainViewController.swift
|
UTF-8
| 8,424
| 2.5625
| 3
|
[] |
no_license
|
//
// MainViewController.swift
// SnakeGame
//
// Created by Svetlana Timofeeva on 09/12/2019.
// Copyright © 2019 jorge. All rights reserved.
//
import UIKit
class MainViewController: UIViewController {
private var startGameButton: UIButton!
//private var currentPlayer: CurrentPlayer?
var data = GameScore.shared.data
private var collectionView = ScoreDataCollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
private var gradient: CAGradientLayer = {
let grad = CAGradientLayer()
grad.colors = [UIColor.white.cgColor, UIColor.green.cgColor]
grad.locations = [0.0, 1.0]
grad.startPoint = CGPoint(x: 0.5, y: 1.0)
grad.endPoint = CGPoint(x: 0.5, y: 0.0)
return grad
}()
init() {
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Hello, \(CurrentPlayerSingleton.shared.player.name)!"
gradient.frame = self.view.bounds
self.view.layer.insertSublayer(gradient, at: 0)
let title = UILabel()
title.translatesAutoresizingMaskIntoConstraints = false
title.text = "Your top 10 scores"
title.font = .boldSystemFont(ofSize: 32)
let description = UILabel()
description.translatesAutoresizingMaskIntoConstraints = false
description.numberOfLines = 0
description.text = "Your best game records will be shown here:"
description.font = .systemFont(ofSize: 24)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(ScoreCollectionViewCell.self, forCellWithReuseIdentifier: ScoreCollectionViewCell.identifier)
collectionView.alwaysBounceVertical = true
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.backgroundColor = .clear
collectionView.layer.cornerRadius = 20
collectionView.layer.borderWidth = 1
collectionView.layer.borderColor = UIColor.black.cgColor
collectionView.layer.addShadow()
//collectionView.layer.masksToBounds = false
//collectionView.layer.insertSublayer(shadowLayer, at: 0)
self.view.addSubview(collectionView)
NSLayoutConstraint.activate([
collectionView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 140),
collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
collectionView.heightAnchor.constraint(equalToConstant: 320)
])
let stack = UIStackView(arrangedSubviews: [title, description])
stack.translatesAutoresizingMaskIntoConstraints = false
stack.axis = .vertical
stack.distribution = .fillProportionally
stack.spacing = 4
view.addSubview(stack)
NSLayoutConstraint.activate([
stack.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 8),
stack.leadingAnchor.constraint(equalTo: view.leadingAnchor),
stack.trailingAnchor.constraint(equalTo: view.trailingAnchor),
stack.bottomAnchor.constraint(equalTo: collectionView.topAnchor, constant: 8)
])
startGameButton = UIButton(frame: .zero)
startGameButton.addTarget(self, action: #selector(onStartGameButtonTapped), for: .touchUpInside)
startGameButton.translatesAutoresizingMaskIntoConstraints = false
startGameButton.setTitle("Start playing!", for: .normal)
startGameButton.setTitleColor(.black, for: .normal)
startGameButton.backgroundColor = .green
startGameButton.layer.shadowColor = UIColor.gray.cgColor
startGameButton.layer.shadowOffset = CGSize(width: 0.0, height: 2.0)
startGameButton.layer.shadowOpacity = 1.0
startGameButton.layer.cornerRadius = 15
view.addSubview(startGameButton)
NSLayoutConstraint.activate([
startGameButton.widthAnchor.constraint(equalToConstant: 150),
startGameButton.heightAnchor.constraint(equalToConstant: 30),
//button.widthAnchor.constraint(equalTo: button.heightAnchor, multiplier: 16/9),
startGameButton.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
startGameButton.centerYAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -100)
])
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Logout", style: .plain, target: self, action: #selector(logout))
self.navigationItem.rightBarButtonItem?.tintColor = .black
print("main")
// Do any additional setup after loading the view.
}
@objc func logout() {
let alert = UIAlertController(title: "Logging out", message: "Are you sure you'd like to log out?", preferredStyle: .alert)
let logout = UIAlertAction(title: "Yes", style: .destructive) { (action:UIAlertAction) in
AppDelegate.shared.rootViewController.switchToAuthScreen()
}
let stay = UIAlertAction(title: "No", style: .default) { (action:UIAlertAction) in }
stay.setValue(UIColor.red, forKey: "titleTextColor")
alert.addAction(stay)
alert.addAction(logout)
self.present(alert, animated: true, completion: nil)
}
@objc func onStartGameButtonTapped() {
navigationController?.pushViewController(GameViewController(), animated: true)
}
}
extension MainViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return self.data.count
}
func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ScoreCollectionViewCell.identifier, for: indexPath) as! ScoreCollectionViewCell
let data = self.data[indexPath.item]
cell.textLabel.text = String(data)
cell.contentView.layer.cornerRadius = 2.0
cell.contentView.layer.borderWidth = 0.3
cell.contentView.layer.borderColor = UIColor.black.cgColor
cell.contentView.layer.masksToBounds = true;
cell.backgroundColor = .clear
cell.layer.shadowColor = UIColor.clear.cgColor
cell.layer.shadowOffset = CGSize(width:0, height: 2.0)
cell.layer.shadowRadius = 2.0
cell.layer.shadowOpacity = 1.0
cell.layer.masksToBounds = true;
cell.layer.shadowPath = UIBezierPath(roundedRect: cell.bounds, cornerRadius: cell.contentView.layer.cornerRadius).cgPath
return cell
}
}
extension MainViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
}
}
extension MainViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.bounds.width, height: 44)
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) //.zero
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
}
| true
|
16c3c5d7ea02ab3aab2c7cc55d6388539056e12e
|
Swift
|
p-morris/WaterfallKit
|
/WaterfallKit/Core/SortingStrategy.swift
|
UTF-8
| 475
| 2.8125
| 3
|
[
"MIT"
] |
permissive
|
//
// SortingStrategy.swift
// iOS Video Interstitial Advert Mediator
//
// Created by Peter Morris on 07/11/2018.
// Copyright © 2018 Pete Morris. All rights reserved.
//
import Foundation
public protocol SortingStrategy {
func sorted(_ array: [VideoAd]) -> [VideoAd]
}
public class AscendingPrioritySorting: SortingStrategy {
public init() { }
public func sorted(_ array: [VideoAd]) -> [VideoAd] {
return array.sorted { $0.priority < $1.priority }
}
}
| true
|
89bd8d7e6481fe8a05aa04590338d3c5a66f50c5
|
Swift
|
AnatolyGurbanov/EducationalProject
|
/Modules/Networking/Networking/CardsNetworkService.swift
|
UTF-8
| 921
| 2.890625
| 3
|
[
"MIT"
] |
permissive
|
import Models
import Moya
import RxSwift
public protocol CardsNetworkServiceProtocol {
func fetchPokemonCards() -> Single<Pokemons>
func fetchPokemonCard(with id: String) -> Single<Pokemon>
}
final class CardsNetworkServiceImpl {
private let provider: MoyaProvider<PokemonsAPI>
init() {
self.provider = MoyaProvider<PokemonsAPI>()
}
}
extension CardsNetworkServiceImpl: CardsNetworkServiceProtocol {
func fetchPokemonCards() -> Single<Pokemons> {
return provider.rx.request(.cards)
.filterSuccessfulStatusCodes()
.map(Pokemons.self)
.catchError(ErrorHandler.handleError)
}
func fetchPokemonCard(with id: String) -> Single<Pokemon> {
return provider.rx.request(.cardsID(id: id))
.filterSuccessfulStatusCodes()
.map(Pokemon.self)
.catchError(ErrorHandler.handleError)
}
}
| true
|
612fa66dbcd1423f61cedf15b5b73c9330505721
|
Swift
|
fachrifaul/PokeDeck
|
/PokeDeck/Scene/Detail/DetailPresenter.swift
|
UTF-8
| 788
| 2.625
| 3
|
[] |
no_license
|
//
// DetailPresenter.swift
// PokeDeck
//
// Created by Fachri Work on 7/27/17.
// Copyright (c) 2017 Decadev. All rights reserved.
//
// This file was generated by the Clean Swift Xcode Templates so
// you can apply clean architecture to your iOS and Mac projects,
// see http://clean-swift.com
//
import UIKit
protocol DetailPresentationLogic
{
func presentPokemonDetail(response: Detail.PokeDex.Response)
}
class DetailPresenter: DetailPresentationLogic
{
weak var viewController: DetailDisplayLogic?
// MARK: Do something
func presentPokemonDetail(response: Detail.PokeDex.Response) {
let viewModel = Detail.PokeDex.ViewModel(success: response.success,pokemon: response.pokemon)
viewController?.displayPokemon(viewModel: viewModel)
}
}
| true
|
fdae775b14ae1455c157bcd1c14b83cd90b70c5c
|
Swift
|
nikhilagr/Colab
|
/Colab/Colab/ViewControllers/LoginViewController.swift
|
UTF-8
| 3,031
| 2.53125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Colab
//
// Created by Nikhil Agrawal on 06/04/19.
// Copyright © 2019 Nikhil Agrawal. All rights reserved.
//
import UIKit
import Firebase
import FirebaseAuth
class LoginViewController: UIViewController {
@IBOutlet weak var userEmailTF: UITextField!
@IBOutlet weak var passwordTF: UITextField!
var email: String = "sdfmks"
var password: String = "sdfkslkf"
override func viewDidAppear(_ animated: Bool) {
// if UserDefaults.standard.bool(forKey: "userloggedIn") == true {
// self.performSegue(withIdentifier: "loginSucess", sender: self)
// }
}
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func onLoginTap(_ sender: Any) {
email = self.userEmailTF.text!
password = self.passwordTF.text!
// Validate if email or password is incomplete
if self.email == "" || self.password == "" {
let alert = UIAlertController(title:"Error" , message: "Please enter email and password", preferredStyle:.alert)
let alertAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alert.addAction(alertAction)
self.present(alert, animated: true,completion: nil)
}else{
Auth.auth().signIn(withEmail: email, password: password) { (authDataResult, error) in
if error == nil{
print("Signed in")
let user = Auth.auth().currentUser
if((user?.isEmailVerified)!){
//Login to HOME controller
UserDefaults.standard.set(true, forKey: "userloggedIn")
self.performSegue(withIdentifier: "loginSucess", sender: self)
}else{
let alert = UIAlertController(title: "Email Verification", message: "Please check your inbox for verification link", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}else{
let alert = UIAlertController(title: "Failed to login", message: error!.localizedDescription, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: { (action) in
}))
self.present(alert, animated: true, completion: nil)
}
}
}
} // end of onTapLogin
}
| true
|
27edb0b402ab42add7456201f8187089f5b00ad5
|
Swift
|
rishabhsri/GSWeather
|
/GSWeatherAssignment/Controller/WeatherViewController.swift
|
UTF-8
| 4,223
| 2.84375
| 3
|
[] |
no_license
|
//
// ViewController.swift
// GSWeatherAssignment
//
// Created by Rishabh on 14/05/21.
//
import UIKit
protocol WeatherSelectionProtocol: class {
func citySelected(model: WeatherModel)
}
class WeatherViewController: UIViewController {
@IBOutlet weak var cityNameLabel: UILabel!
@IBOutlet weak var tempLabel: UILabel!
@IBOutlet weak var windSpeedLabel: UILabel!
@IBOutlet weak var humidityLabel: UILabel!
@IBOutlet weak var visibilityLabel: UILabel!
@IBOutlet weak var sunriseLabel: UILabel!
@IBOutlet weak var sunsetLabel: UILabel!
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var searchWeatherLabel: UILabel!
@IBOutlet weak var parentView: UIView!
private let weatherViewModel = WeatherViewModel()
private let showWeatherSegue = "showFavDestinations"
override func viewDidLoad() {
super.viewDidLoad()
searchBar.searchTextField.delegate = self
}
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let weatherListNavController = segue.destination as? UINavigationController, let weatherListViewController = weatherListNavController.children.first as? WeatherTableViewController {
weatherListViewController.weatherDelegate = self
}
}
}
// Mark:- Extension to conform UITextFieldDelegate and implement utilities methods
extension WeatherViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
if let count = textField.text?.count, count > 2 {
getWeatherInfo(for: textField.text ?? "")
}
return true
}
private func getWeatherInfo(for city: String, completion: ((Bool) -> Void)? = nil) {
if ReachabilityTest.isConnectedToNetwork() {
weatherViewModel.getWeatherDetailsForCity(for: city, completion: {[weak self] (weatherInfo) in
guard let self = self else { return }
if let weatherDetail = weatherInfo {
self.populateData(weatherInfo: weatherDetail)
self.searchBar.searchTextField.text = ""
completion?(true)
} else {
Utility.showAlert(message: "City not found. Please ensure the right name.", on: self)
completion?(false)
}
})
} else {
Utility.showAlert(message: "Ensure you have internet connectivity.", on: self)
completion?(false)
}
}
private func populateData(weatherInfo: WeatherModel) {
self.searchWeatherLabel.isHidden = true
self.parentView.isHidden = false
self.cityNameLabel.text = weatherInfo.cityName
self.tempLabel.text = weatherInfo.temperature
self.humidityLabel.text = weatherInfo.humidity
self.visibilityLabel.text = weatherInfo.visibility
self.windSpeedLabel.text = weatherInfo.windSpeed
self.sunriseLabel.text = weatherInfo.sunrise
self.sunsetLabel.text = weatherInfo.sunset
}
}
// Mark:- Extension to implement IBActions
extension WeatherViewController {
@IBAction func showFavourite(_ sender: Any) {
self.performSegue(withIdentifier: showWeatherSegue, sender: nil)
}
@IBAction func markFavouriteAction(_ sender: Any){
if let weather = weatherViewModel.weatherDetail {
WeatherInfo.storeWeatherInfo(weatherDetail: weather)
}
}
}
extension WeatherViewController: WeatherSelectionProtocol {
func citySelected(model: WeatherModel) {
if ReachabilityTest.isConnectedToNetwork() { // Check if internet is available...
self.getWeatherInfo(for: model.cityName, completion: {success in
if success {
self.markFavouriteAction(AnyClass.self) // Update the the information in local...
}
})
} else {
populateData(weatherInfo: model)
weatherViewModel.weatherDetail = model
}
}
}
| true
|
89752ea6277d1a2280572b24d272e20e44f29445
|
Swift
|
mcrakhman/iOS-university-example-application
|
/GithubItunesViewer/GithubItunesViewer/Classes/PresentationLayer/UserStories/Main/View/MainViewController.swift
|
UTF-8
| 1,446
| 2.515625
| 3
|
[] |
no_license
|
//
// MainViewController.swift
// GithubItunesViewer
//
// Created by m.rakhmanov on 22.01.17.
// Copyright © 2017 m.rakhmanov. All rights reserved.
//
import UIKit
enum SelectedScreen: Int {
case github = 0
case iTunes
}
enum MainViewControllerConstants {
static let throttleDelay: TimeInterval = 1.0
}
class MainViewController: UIViewController, ViewControllerEmbedding, MainViewInput, UISearchBarDelegate {
var container: UIView {
return containerView
}
@IBOutlet weak var segmentedControl: UISegmentedControl!
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var searchBar: UISearchBar!
var output: MainViewOutput?
var throttler: Throttler?
override func viewDidLoad() {
super.viewDidLoad()
searchBar.delegate = self
changeScreen()
}
@IBAction func didChangeSegmentedControlValue(_ sender: Any) {
changeScreen()
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
throttler?.throttle(MainViewControllerConstants.throttleDelay) {
self.output?.didChange(searchText)
self.searchBar.resignFirstResponder()
}
}
private func changeScreen() {
guard let screen = SelectedScreen(rawValue: segmentedControl.selectedSegmentIndex) else {
return
}
output?.didSelect(screen)
}
}
| true
|
a88275fee367aef2c12f1c3a9420e2648e941675
|
Swift
|
Duzj/Algorithm
|
/Algorithm/Algorithm/动态规划/_面试题_47_礼物的最大价值.swift
|
UTF-8
| 2,635
| 3.375
| 3
|
[] |
no_license
|
//
// 面试题_47_礼物的最大价值.swift
// Algorithm
//
// Created by duzj on 2020/4/23.
// Copyright © 2020 duzj. All rights reserved.
//
import Foundation
/**
在一个 m*n 的棋盘的每一格都放有一个礼物,每个礼物都有一定的价值(价值大于 0)。你可以从棋盘的左上角开始拿格子里的礼物,并每次向右或者向下移动一格、直到到达棋盘的右下角。给定一个棋盘及其上面的礼物的价值,请计算你最多能拿到多少价值的礼物?
示例 1:
输入:
[
[1,3,1],
[1,5,1],
[4,2,1]
]
输出: 12
解释: 路径 1→3→5→2→1 可以拿到最多价值的礼物
提示:
0 < grid.length <= 200
0 < grid[0].length <= 200
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/li-wu-de-zui-da-jie-zhi-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
class _面试题_47_礼物的最大价值 {
// func maxValue(_ grid: [[Int]]) -> Int {
// let temp = [Int](repeating: 0, count: grid[0].count)
// //初始化 dp 数组 ,最大价值数组
// var dp = [[Int]](repeating: temp, count: grid.count)
//
// dp[0][0] = grid[0][0]
//
// let m = grid.count
// let n = grid[0].count
//
// var maxV = dp[0][0];
//
// for i in 0 ..< m {
// for j in 0 ..< n {
// if i == 0 && j == 0 {
// continue;
// }
// if i == 0 {
// dp[i][j] = dp[i][j - 1] + grid[i][j]
// }else if j == 0 {
// dp[i][j] = dp[i - 1][j] + grid[i][j];
// }else{
// dp[i][j] = max(dp[i-1][j], dp[i][j-1]) + grid[i][j];
// }
// maxV = dp[i][j];
// }
// }
// return maxV
// }
//优化
func maxValue(_ grid: [[Int]]) -> Int {
let temp = [Int](repeating: 0, count: grid[0].count)
//初始化 dp 数组 ,最大价值数组
var dp = [[Int]](repeating: temp, count: grid.count)
dp[0][0] = grid[0][0]
let m = grid.count
let n = grid[0].count
for i in 1 ..< m {
dp[i][0] = grid[i][0] + dp[i-1][0]
}
for j in 1 ..< n {
dp[0][j] = grid[0][j] + dp[0][j-1]
}
for i in 1 ..< m {
for j in 1 ..< n {
dp[i][j] = max(dp[i-1][j], dp[i][j-1]) + grid[i][j];
}
}
return dp[m-1][n-1]
}
}
| true
|
b416c8c42c7dab84598daa04210c91dd9c6a4843
|
Swift
|
AnthonyCastonzo/Internship-experience-webpage
|
/Whalerock RPG/Whalerock RPG/Mage.swift
|
UTF-8
| 3,037
| 2.765625
| 3
|
[] |
no_license
|
//
// Mage.swift
// Whalerock RPG
//
// Created by Anthony Castonzo on 2/28/17.
// Copyright © 2017 Anthony Castonzo. All rights reserved.
//
import UIKit
import Foundation
class Mage: Character {
init(level: Int){
super.init(namecall: "Mage", maxhit_points: 200, maxmana_points: 100, strg: 10, spd: 4, mag: 40, dfense: 2, turn_num: 1, turn_wait: 0, exp: 0, lev: 1, hit_points: 200, id: 2)
self.setLevel(value: level)
self.image = #imageLiteral(resourceName: "Mage")
}
let appDelegate = UIApplication.shared.delegate as? AppDelegate
//FIRE
override func attack1(target: Character) {
let criticalroll = randomInt(min: 1,max: 100)
var critical = 0.0
if (criticalroll > 95){
critical = 1.5
}
else{
critical = 1.0
}
let firePow = ((50 - target.defense)/50) * (critical * self.magic * randomDouble(min: 1.05, max: 1.375))
target.hp = target.hp - firePow
print("BUUURRRNNN!", "\(target.name) lost \(firePow) HP")
self.turnwait -= 18
appDelegate?.gameManager.attackPower = firePow
self.turn += 1
}
//STAFFWHACK
override func attack2(target: Character){
let accuracyroll = randomInt(min: 0, max: 100)
var accuracy = 0.0
if accuracyroll > 90 {
accuracy = 0.0
}
else {
accuracy = 1.0
}
var critical = 0.0
if accuracy == 1.0 {
let criticalroll = randomInt(min: 1,max: 100)
if (criticalroll > 82){
critical = 8.78
}
else{
critical = 1.0
}
}
let whackPow = ((50 - target.defense)/50) * (self.strength * randomDouble(min: 1.1, max: 1.2) * critical * accuracy)
target.hp = target.hp - whackPow
print("SMACK!", "\(target.name) lost \(whackPow) HP")
self.turnwait -= 9
appDelegate?.gameManager.attackPower = whackPow
self.turn += 1
}
//CARDTRICK
override func attack3(target: Character) {
let card_chance = randomInt(min: 1, max: 100)
var cardpull = 0.0
if card_chance < 50 {
cardpull = randomDouble(min: 0, max: 4)
}
if card_chance >= 50 {
cardpull = randomDouble(min: 13, max: 20)
}
let cardPow = (((50 - target.defense)/50) * (self.strength * cardpull))
target.hp = target.hp - cardPow
if card_chance < 50 {
print("Unlucky draw. \(target.name) lost \(cardPow) HP")
}
if card_chance >= 50 {
print("Your lucky card!! \(target.name) lost \(cardPow) HP")
}
appDelegate?.gameManager.attackPower = cardPow
self.turn = 0
self.turnwait -= 22
pickerview?.reloadAllComponents()
}
override func get_attacks() -> [String] {
return ["Fire", "Staffwhack"]
}
override func get_charge() -> [String] {
return ["Cardtrick"]
}
}
| true
|
b8eeebaa2af0a3610762066c4691c10895455a3b
|
Swift
|
skykywind/SegMenu
|
/Example/SegMenu/SimpleExampleViewController.swift
|
UTF-8
| 1,251
| 2.609375
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// SimpleExampleViewController.swift
// SegMenu_Example
//
// Created by 贾富佳 on 2019/6/28.
// Copyright © 2019 CocoaPods. All rights reserved.
//
import UIKit
import SegMenu
class SimpleExampleViewController: UIViewController {
var menu: SegMenu?
override func viewDidLoad() {
super.viewDidLoad()
setupMenu()
}
private func setupMenu() {
//Create controllers
let colors = [UIColor.black, UIColor.blue, UIColor.red, UIColor.gray, UIColor.green, UIColor.purple, UIColor.orange, UIColor.brown, UIColor.cyan]
let controllers: [UIViewController] = colors.map {
let controller = UIViewController()
controller.view.backgroundColor = $0
return controller
}
//Create page menu
menu = SegMenu(viewControllers: controllers, in: self, with: dummyConfiguration(), usingStoryboards: true)
menu?.view.frame = CGRect(x: 0, y: 84, width: view.bounds.width, height: view.bounds.height - 84)
}
private func dummyConfiguration() -> SegMenuConfiguration {
let configuration = SegMenuConfiguration()
configuration.enableHorizontalBounce = false
return configuration
}
}
| true
|
cc1bda2ed56255f434af72f7b0d3d0ebdf569250
|
Swift
|
miPera/Quiz
|
/Quiz/ViewController.swift
|
UTF-8
| 2,585
| 3.359375
| 3
|
[] |
no_license
|
import UIKit
class ViewController: UIViewController {
@IBOutlet var currentQuestionLabel: UILabel! // Outlet for current question label
@IBOutlet var nextQuestionLabel: UILabel! // Outlet for next question label
@IBOutlet var answerLabel: UILabel! // Outlet to Show Answer UILabel
//questions array containing 3 fixed Strings
let questions: [String] = [
"What is 7+7?",
"What is the capital of Vermont?",
"What is cognac made from?"
]
//answers array containing 3 fixed Strings
let answers: [String] = [
"14",
"Montpelier",
"Grapes"
]
var currentQuestionIndex: Int = 0;
// show initial question on view load. Method is called after view loads.
override func viewDidLoad() {
super.viewDidLoad()
currentQuestionLabel.text = questions[currentQuestionIndex]
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Set the label's intial alpha
nextQuestionLabel.alpha = 0
}
// Action method to show the next question
@IBAction func showNextQuestion(_ sender: UIButton) {
currentQuestionIndex += 1 // go to next question in array
// loop back to start of array if index equals array length
if currentQuestionIndex == questions.count {
currentQuestionIndex = 0
}
// set question text
let question: String = questions[currentQuestionIndex]
nextQuestionLabel.text = question
answerLabel.text = "???"
animateLabelTransitions()
}
// Action method to show answer to current question
@IBAction func showAnswer(_ sender: UIButton) {
let answer: String = answers[currentQuestionIndex]
answerLabel.text = answer
}
//Animation function for label transition
func animateLabelTransitions() {
//Animate by fading into the next question
UIView.animate(
withDuration: 0.5,
delay: 0,
options: [],
animations: {
//update alphas of current and next question as animation
self.currentQuestionLabel.alpha = 0
self.nextQuestionLabel.alpha = 1
},
completion: { _ in
//swap references of current and next question when animation completes
swap(&self.currentQuestionLabel, &self.nextQuestionLabel)
}
)
}
}
| true
|
8a550d56243839648cccb876da87f44208386ab8
|
Swift
|
vapor/vapor
|
/Sources/Vapor/Validation/Validators/In.swift
|
UTF-8
| 1,865
| 3.359375
| 3
|
[
"MIT"
] |
permissive
|
extension Validator where T: Equatable & CustomStringConvertible {
/// Validates whether an item is contained in the supplied array.
public static func `in`(_ array: T...) -> Validator<T> {
.in(array)
}
/// Validates whether an item is contained in the supplied sequence.
public static func `in`<S>(_ sequence: S) -> Validator<T>
where S: Sequence & Sendable, S.Element == T
{
.init {
ValidatorResults.In(item: $0, items: .init(sequence))
}
}
}
extension ValidatorResults {
/// `ValidatorResult` of a validator that validates whether an item is contained in the supplied sequence.
public struct In<T> where T: Equatable & CustomStringConvertible & Sendable {
/// Description of the item.
public let item: T
/// Descriptions of the elements of the supplied sequence.
public let items: [T]
}
}
extension ValidatorResults.In: ValidatorResult {
public var isFailure: Bool {
!self.items.contains(self.item)
}
public var successDescription: String? {
self.makeDescription(not: false)
}
public var failureDescription: String? {
self.makeDescription(not: true)
}
func makeDescription(not: Bool) -> String {
let description: String
switch self.items.count {
case 1:
description = self.items[0].description
case 2:
description = "\(self.items[0].description) or \(self.items[1].description)"
default:
let first = self.items[0..<(self.items.count - 1)]
.map { $0.description }.joined(separator: ", ")
let last = self.items[self.items.count - 1].description
description = "\(first), or \(last)"
}
return "is\(not ? " not" : " ") \(description)"
}
}
| true
|
38e7483f2c8ed0901ccd85076e4f087e681b920f
|
Swift
|
rwbutler/TailorSwift
|
/TailorSwift/Classes/UIViewAdditions.swift
|
UTF-8
| 1,009
| 2.765625
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//
// UIViewAdditions.swift
// TailorSwift
//
// Created by Ross Butler on 10/10/18.
//
import Foundation
import UIKit
extension UIView {
/// Default corner radius
static var cornerRadius: CGFloat = 10.0
/// Rounds specified corners with the given corner radius value.
func roundCorners(_ corners: UIRectCorner = .allCorners, radius: CGFloat = UIView.cornerRadius) {
if #available(iOS 11.0, *) {
clipsToBounds = true
layer.cornerRadius = radius
layer.maskedCorners = CACornerMask(rawValue: corners.rawValue)
} else if corners == .allCorners {
clipsToBounds = true
layer.cornerRadius = radius
} else {
let mask = CAShapeLayer()
mask.path = UIBezierPath(roundedRect: bounds,
byRoundingCorners: corners,
cornerRadii: CGSize(width: radius, height: radius)).cgPath
layer.mask = mask
}
}
}
| true
|
12b6b3db859e00ee1e96831e9c3b021914899c6b
|
Swift
|
KonstantinPimbursky/PhotosLibrary
|
/PhotosLibrary/Models/PhotoDetails.swift
|
UTF-8
| 584
| 2.890625
| 3
|
[] |
no_license
|
//
// PhotoDetails.swift
// PhotosLibrary
//
// Created by Konstantin Pimbursky on 18.10.2021.
//
import Foundation
struct PhotoDetails: Codable {
let id: String
let createdAt: String
let downloads: Int
let location: Location
let user: User
let urls: Urls
enum CodingKeys: String, CodingKey {
case id
case createdAt = "created_at"
case downloads
case location
case user
case urls
}
}
struct Location: Codable {
let city: String?
let country: String?
}
struct User: Codable {
let name: String
}
| true
|
2127e8aa9fbbf7b2ff8782fa13acda7e7efb43bd
|
Swift
|
dmaulikr/workout_tracker
|
/Workout Tracker/Controllers/Exercises/ExerciseTableViewController.swift
|
UTF-8
| 1,762
| 2.71875
| 3
|
[] |
no_license
|
//
// ExerciseTableViewController.swift
// Workout Tracker
//
// Created by Cory Eighan on 6/26/16.
// Copyright © 2016 JoyWhack. All rights reserved.
//
import UIKit
import CoreData
class ExerciseTableViewController: UITableViewController {
private var exercises = [Exercise]()
let reuseIdentifierCell = "exerciseCell"
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
fetchExerciseEntity()
self.tableView.reloadData()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return exercises.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifierCell, forIndexPath: indexPath)
let singleExercise = exercises[indexPath.row]
if let name = singleExercise.name {
cell.textLabel!.text = name
}
return cell
}
private func fetchExerciseEntity() {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "Exercise")
do {
let results = try managedContext.executeFetchRequest(fetchRequest)
exercises = results as! [Exercise]
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
}
}
}
| true
|
5a33f024eecaafe7420817f47773a93b6a1817e4
|
Swift
|
davidoliveira7/foursys
|
/FizzBuzz.playground/Pages/Solução com Switch.xcplaygroundpage/Contents.swift
|
UTF-8
| 1,019
| 4.71875
| 5
|
[] |
no_license
|
/*:
## Solução do FizzBuzz com Switch Case
Uma boa alternativa para solucionar o enigma é utilizando switch e, naturalmente, um loop também:
*/
// Codifique aqui sua solução
//switch <#value#> {
//case <#pattern#>:
// <#code#>
//default:
// <#code#>
//}
//for div in 1...100 {
// switch (div % 5 == 0, div % 3 == 0) {
// case (true,false):
// print("Buzz, \(div)")
// case (true,true):
// print("FrizzBuzz, \(div)")
// case (false,true):
// print("Frizz, \(div)")
// default: break
// }
//}
//let pi = 3.14
//let r = Double(5)
//
//pi * (r * r)
//
////-------
//
//let a = 3.0
//let b = 7.0
//var media = Double()
//let notaA = 5.0
//let notaB = 7.1
//
//media = (notaA * a + notaB * b) / 10
//------
let x = 5
let y = 6
let z = 7
let w = 8
var dif = Int()
dif = (x * y - z * w)
//
//switch (div % 3 == 0, div % 5 == 0)
// {
// case (true, false):
//print("frizz")
// case (true,true):
//}
/*:
[Anterior](@previous) | página 7 of 3
*/
| true
|
0392c96bb21456872ed7f44f1181213b5faf22d1
|
Swift
|
alageev/Jungle
|
/Shared/Beverages/BeverageDetail.swift
|
UTF-8
| 3,258
| 2.828125
| 3
|
[] |
no_license
|
//
// BeverageDetail.swift
// Jungle
//
// Created by Алексей Агеев on 25.09.2020.
//
import SwiftUI
struct BeverageDetail: View {
let beverage: Beverage
let numberFormatter = NumberFormatter()
init(_ beverage: Beverage) {
self.beverage = beverage
numberFormatter.usesSignificantDigits = true
}
var body: some View {
ScrollView {
VStack(alignment: .leading) {
DetailTop(name: beverage.name, imageId: beverage.id.uuidString)
VStack(alignment: .leading) {
if let style = beverage.style {
DetailRow(name: "Style", value: style)
}
if let city = beverage.city {
DetailRow(name: "City", value: city)
}
if let breweryName = beverage.breweryName {
DetailRow(name: "Brewery", value: breweryName)
}
if let alcohol = beverage.alcohol {
DetailRow(name: "ABV", value: alcohol, suffix: "%")
}
if let bitterness = beverage.bitterness {
DetailRow(name: "IBU", value: "\(bitterness)")
}
if let price = beverage.price {
HStack {
if beverage.volume != nil {
Text("Volume|Price")
} else {
Text("Price")
}
Spacer()
HStack {
if let volume = beverage.volume {
VStack(alignment: .leading) {
ForEach (volume, id: \.self) { volume in
Text(numberFormatter.string(from: NSNumber(value: volume)) ?? "")
}
}
}
VStack(alignment: .trailing) {
ForEach (price, id: \.self) { price in
Text("\(price)₽")
}
}
}
}
.padding(.trailing)
Divider()
}
if let description = beverage.description {
DescriptionView(description)
}
}
.padding([.top, .leading, .bottom])
}
}
}
}
#if DEBUG
struct BeverageDetail_Previews: PreviewProvider {
static var previews: some View {
Group {
BeverageDetail(testBeverages[11])
.preferredColorScheme(.light)
.previewLayout(.sizeThatFits)
BeverageDetail(testBeverages[11])
.preferredColorScheme(.dark)
.environment(\.sizeCategory, .extraExtraExtraLarge)
.previewLayout(.sizeThatFits)
}
}
}
#endif
| true
|
8ee750a65019db5e1af5147f25fdf51282119100
|
Swift
|
RonnyTetzlaff/SwiftUI
|
/Cats/CatAPI/CatService.swift
|
UTF-8
| 953
| 2.953125
| 3
|
[] |
no_license
|
//
// CatService.swift
// Cats
//
// Created by Irfan Khatik on 28/11/20.
//
import Foundation
import Combine
import UIKit
protocol CatService {
var apiSession: APIService {get}
func getCatList() -> AnyPublisher<[CatListItem], APIError>
func getCatDetail(catId: String) -> AnyPublisher<[CatDetail], APIError>
func getCatImage(url:String) -> AnyPublisher<UIImage, APIError>
}
extension CatService {
func getCatList() -> AnyPublisher<[CatListItem], APIError> {
return apiSession.request(with: CatEndpoint.catList)
.eraseToAnyPublisher()
}
func getCatDetail(catId: String) -> AnyPublisher<[CatDetail], APIError> {
return apiSession.request(with: CatEndpoint.catDetail(catId))
.eraseToAnyPublisher()
}
func getCatImage(url:String) -> AnyPublisher<UIImage, APIError> {
return apiSession.requestImage(with: url)
.eraseToAnyPublisher()
}
}
| true
|
3c6329064110b7e00c0fc99e11f5699a44f1ec1d
|
Swift
|
matchmore/ios-sdk
|
/Matchmore/Miscellaneous/String+JWT.swift
|
UTF-8
| 1,255
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
//
// String+JWT.swift
// Matchmore
//
// Created by Maciej Burda on 21/02/2018.
// Copyright © 2018 Matchmore. All rights reserved.
//
import Foundation
extension String {
func getWorldIdFromToken() -> String {
var segments: [String] = components(separatedBy: ".")
if segments.count < 2 { return "" }
var base64String: String = segments[1]
let requiredLength: Int = Int(4 * ceil(Float(base64String.count) / 4.0))
let nbrPaddings: Int = requiredLength - base64String.count
if nbrPaddings > 0 {
let padding = String().padding(toLength: nbrPaddings, withPad: "=", startingAt: 0)
base64String = base64String.appending(padding)
}
base64String = base64String.replacingOccurrences(of: "-", with: "+")
base64String = base64String.replacingOccurrences(of: "_", with: "/")
let decodedData: Data = Data(base64Encoded: base64String, options: Data.Base64DecodingOptions(rawValue: UInt(0)))!
if let json = try? JSONSerialization.jsonObject(with: decodedData, options: .mutableContainers) as? [String: Any],
let worldId: String = json?["sub"] as? String {
return worldId
} else {
return ""
}
}
}
| true
|
35d2f9b05fc72a0822e9fa9dec9c66b2fed08722
|
Swift
|
tgyhlsb/iPath
|
/iPath/iPath/Model/Route.swift
|
UTF-8
| 1,289
| 3
| 3
|
[
"MIT"
] |
permissive
|
//
// Route.swift
// iPath
//
// Created by Tanguy Hélesbeux on 09/10/2016.
// Copyright © 2016 Tanguy Helesbeux. All rights reserved.
//
import UIKit
class Route: Equatable {
// MARK: - PUBLIC -
public let map: Map
public let token: String
public let places: [Place]
public let distance: Double
public var start: Place {
return self.places.first!
}
public var end: Place {
return self.places.last!
}
// MARK: Equatable
public static func ==(lhs: Route, rhs: Route) -> Bool {
return lhs.token == rhs.token
}
// MARK: - INTERNAL -
internal init?(map: Map, token: String, json: NSArray) {
guard json.count >= 2 else { return nil }
self.map = map
self.token = token
var places = [Place]()
for data in json {
guard let info = data as? NSDictionary else { return nil }
let id = info.parse(key: "id", defaultValue: 0)
guard let place = map.places[id] else { return nil }
places.append(place)
}
self.places = places
guard let distance = map.distance(of: self.places) else { return nil }
self.distance = distance
}
// MARK: - PRIVATE -
}
| true
|
7aa2417c17931d02fbf0b4db4d2b535ca1c0eee4
|
Swift
|
RSchuitek/GasolinaOuAlcool-ios
|
/GasolinaOuAlcool-ios/ViewController.swift
|
UTF-8
| 1,983
| 3.078125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// GasolinaOuAlcool-ios
//
// Created by Luiz Rodrigo Schuitek on 17/07/19.
// Copyright © 2019 Luiz Rodrigo Schuitek. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var precoAlcoolTextField: UITextField!
@IBOutlet weak var precoGasolinaTextField: UITextField!
@IBOutlet weak var resultadoLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func calcularCombustivelButton(_ sender: Any) {
if let precoAlcool = precoAlcoolTextField.text {
if let precoGasolina = precoGasolinaTextField.text {
let resultado = self.validarCampos(precoAlcool, precoGasolina)
if resultado {
if self.calcularMelhorPreco(precoAlcool, precoGasolina) {
resultadoLabel.text = "Melhor Preço é o Gasolina!"
} else {
resultadoLabel.text = "Melhor Preço é o Alcool!"
}
} else {
resultadoLabel.text = "Digite os preços para calcular"
}
}
}
}
func calcularMelhorPreco(_ precoAlcool: String, _ precoGasolina:String) -> Bool {
if let valorAlcool = Double(precoAlcool) {
if let valorGasolina = Double(precoGasolina) {
let resultadoPreco = valorAlcool / valorGasolina
return resultadoPreco >= 0.7
}
}
return false
}
func validarCampos(_ precoAlcool: String, _ precoGasolina:String) -> Bool {
var camposValidados = true
if precoAlcool.isEmpty {
camposValidados = false
} else if precoGasolina.isEmpty {
camposValidados = false
}
return camposValidados
}
}
| true
|
8253d16f246392e4e0b7ad83cddb5edae30c7aab
|
Swift
|
ruan65/iOs-horizontal-vertical-scrolls-combine
|
/LikeAppStrore/Base.swift
|
UTF-8
| 1,136
| 2.71875
| 3
|
[] |
no_license
|
//
// BaseClasses.swift
// LikeAppStrore
//
// Created by a on 05/05/2017.
// Copyright © 2017 Andreyka. All rights reserved.
//
import UIKit
extension UIView {
func addConstraintsWithFormat(format: String, views: UIView...) {
var viewsDict = [String: UIView]()
for (index, view) in views.enumerated() {
view.translatesAutoresizingMaskIntoConstraints = false
viewsDict["v\(index)"] = view
}
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: format, options: NSLayoutFormatOptions(), metrics: nil, views: viewsDict))
}
func addConstraintsFillEntireView(view: UIView) {
addConstraintsWithFormat(format: "H:|[v0]|", views: view)
addConstraintsWithFormat(format: "V:|[v0]|", views: view)
}
}
class BaseCell: UICollectionViewCell {
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("Init(coder:) has not been implemented")
}
func setupViews() {}
}
| true
|
a36fab50212c3bf609c33400b32805d6f99e966c
|
Swift
|
Denniston/origin
|
/AuthProvider.swift
|
UTF-8
| 972
| 2.703125
| 3
|
[] |
no_license
|
//
// AuthProvider.swift
// MAGyms Coach
//
// Created by Denniston Sutherland on 31/05/2017.
// Copyright © 2017 DennistonSutherland. All rights reserved.
//
import Foundation
import FirebaseAuth
typealias LoginHandler = (_ msg: String?) -> Void
class AuthProvider {
private static let _instance = AuthProvider()
static var Instance: AuthProvider {
return _instance
}
// func login(withEmail: String, password: String, loginHandler: Loginhandler?) {
//
// FIRAuth.auth()?.signIn(withEmail: withEmail, password: password, completion: {(user, error) in
// })
//
// }//login func
func logOut() -> Bool {
if Auth.auth().currentUser != nil {
do {
try Auth.auth().signOut()
return true
} catch {
return false
}
}
return true
}
}//class
| true
|
9ceac5dd0bada5b6bfb4dab9a141c5af6a495df3
|
Swift
|
narizzo/SwiftKit
|
/Source/Shared/Identifiable.swift
|
UTF-8
| 194
| 3.25
| 3
|
[
"MIT"
] |
permissive
|
import Foundation
/// Protocol implemented by types that have a unique identifier
public protocol Identifiable {
/// The object's unique identifier
var identifier: Identifier { get }
}
| true
|
921f8e7043f60e3a675296efb5cea21f64e97343
|
Swift
|
jdubey/Travelogue_old
|
/Travelogue/Data/Model/Region.swift
|
UTF-8
| 628
| 2.609375
| 3
|
[] |
no_license
|
//
// Region.swift
// Travelogue
//
// Created by Dubey, Josh (UK - London) on 23/01/2018.
// Copyright © 2018 Josh Dubey. All rights reserved.
//
import Foundation
import RealmSwift
enum RegionName: String {
case africa = "Africa"
case europe = "Europe"
}
class Region: BaseObject {
static let imageDict: [RegionName: UIImage] = [.africa: Asset.afica.image, .europe: Asset.europe.image]
// @objc dynamic var name = ""
@objc dynamic var id = 0
let countries = LinkingObjects(fromType: Country.self, property: "region")
// override static func primaryKey() -> String? {
// return "id"
// }
}
| true
|
46a8a6e1dc876c0a8ab87d538475822513aa1473
|
Swift
|
enricode/parrot-gherkin
|
/Sources/parrot/Models/Source.swift
|
UTF-8
| 104
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
import Foundation
struct Source: Codable, Equatable {
let location: Location
let uri: String
}
| true
|
028ea870c21a5bf6ff575e776be73c9aadbec683
|
Swift
|
pschneider/rw-iosa-3-mylocations
|
/MyLocations/UIImage+Resize.swift
|
UTF-8
| 901
| 3.078125
| 3
|
[] |
no_license
|
//
// UIImage+Resize.swift
// MyLocations
//
// Created by Patrick Schneider on 22/11/15.
// Copyright © 2015 Patrick Schneider. All rights reserved.
//
import UIKit
extension UIImage {
func resizeImageWithBounds(bounds: CGSize) -> UIImage {
// fetch ratio for width / height so we display every format correctly
let horizontalRatio = bounds.width / size.width
let verticalRatio = bounds.height / size.height
let ratio = min(horizontalRatio, verticalRatio)
// determine new size based on ratio
let newSize = CGSize(width: size.width * ratio, height: size.height * ratio)
// draw the new image
UIGraphicsBeginImageContextWithOptions(newSize, true, 0)
drawInRect(CGRect(origin: CGPoint.zero, size: newSize))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
| true
|
ee1ed91426cb55712f62b672b0b5cfbe7b10c4d0
|
Swift
|
volkzayaz/RR
|
/RhythmicRebellion/Source/Legacy/UI Modules/SelectableList/GenresSelectableListControllerViewModel.swift
|
UTF-8
| 3,149
| 3.109375
| 3
|
[] |
no_license
|
//
// GeneresSelectableListControllerViewModel.swift
// RhythmicRebellion
//
// Created by Alexander Obolentsev on 9/12/18.
// Copyright © 2018 Patron Empowerment, LLC. All rights reserved.
//
import Foundation
import Alamofire
extension Genre: SelectableListItem {
var identifier: String { return String(self.hashValue) }
var title: String { return self.name }
}
protocol GenresDataSource: class {
var genres: [Genre] { get }
func reloadGenres(completion: @escaping (Result<[Genre]>) -> Void)
}
class GenresSelectableListItemsDataProvider: SelectableListItemsDataProvider {
var dataSource: GenresDataSource
typealias Item = Genre
var items: [Item]
private var additionalItems: [Item]
init(with dataSource: GenresDataSource, additionalItems: [Item]?) {
self.dataSource = dataSource
self.additionalItems = additionalItems ?? []
self.items = self.dataSource.genres
}
func reload(completion: @escaping (Result<[Item]>) -> Void) {
self.dataSource.reloadGenres { (genresResult) in
switch genresResult {
case .success(let genres):
self.items = genres
completion(Result.success(self.items))
case .failure(let error):
completion(Result.failure(error))
}
}
}
func filterItems(items: [Item], with searchText: String) -> [Item] {
guard searchText.isEmpty == false else { return items }
return items.filter( {return $0.name.lowercased().contains(searchText.lowercased()) })
}
var isEditable: Bool { return true }
func canAddItem(with name: String) -> Bool {
guard self.isEditable == true else { return false }
guard self.items.count > 0 else { return false }
guard name.isEmpty == false else { return false }
let filteredAdditionalItems = self.additionalItems.filter { $0.name.lowercased() == name.lowercased() }
return filteredAdditionalItems.isEmpty
}
func addItem(with name: String) -> Item? {
let genre = Genre(with: name)
self.items.append(genre)
self.additionalItems.append(genre)
return genre
}
}
final class GenresSelectableListControllerViewModel: SelectableListControllerViewModel<GenresSelectableListItemsDataProvider> {
typealias ItemsSelectionCallback = ([Genre]) -> Void
override var title: String { return NSLocalizedString("Select Genres", comment: "Select Genres Title") }
var itemsSelectionCallback: ItemsSelectionCallback?
init(router: SelectableListRouter, dataSource: GenresDataSource, selectedItems: [Genre]?, additionalItems: [Genre]?, itemsSelectionCallback: ItemsSelectionCallback?) {
super.init(router: router, dataProvider: GenresSelectableListItemsDataProvider(with: dataSource, additionalItems: additionalItems), selectedItems: selectedItems ?? [], isSearchable: true, selectionType: .multiple)
self.itemsSelectionCallback = itemsSelectionCallback
}
override func done() {
self.itemsSelectionCallback?(Array(self.selectedItems))
super.done()
}
}
| true
|
9fbbceb0eddae464c8f1fc1deda0b60811438d4c
|
Swift
|
MamunNY91/Youtube
|
/Youtube/Extension.swift
|
UTF-8
| 810
| 3.015625
| 3
|
[] |
no_license
|
//
// Extension.swift
// Youtube
//
// Created by Abdullah A Mamun on 6/27/17.
// Copyright © 2017 Abdullah A Mamun. All rights reserved.
//
import UIKit
extension UIColor {
static func rgb(red: CGFloat, green: CGFloat, blue: CGFloat) ->UIColor {
return UIColor(red: red/255, green: green/255, blue: blue/255, alpha: 1)
}
}
extension UIView {
func addConstraintWithFormat(format:String,views: UIView...) {
var viewDict = [String:UIView]()
for (index,view) in views.enumerate() {
let key = "v\(index)"
view.translatesAutoresizingMaskIntoConstraints = false
viewDict[key] = view
}
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(format, options: NSLayoutFormatOptions(), metrics: nil, views: viewDict))
}
}
| true
|
ca42e02c65f0b3825afb9262a114cc04f8adc953
|
Swift
|
NKSandip/NK_DataManager
|
/Object_Classes/Canvas/CanvasStreetViewController.swift
|
UTF-8
| 3,002
| 2.59375
| 3
|
[] |
no_license
|
//
// CanvasStreetViewController.swift
// HandyNation
//
// Created by Nirav Shukla on 29/08/18.
// Copyright © 2018 Corway Solution. All rights reserved.
//
import UIKit
import CoreLocation
import GoogleMaps
class CanvasStreetViewController: UIViewController,GMSMapViewDelegate {
@IBOutlet weak var panoramaView : GMSPanoramaView!
public var objPeopleList : PeopleList?
override func viewDidLoad() {
super.viewDidLoad()
self.panoramaView.delegate = self
if self.objPeopleList != nil {
let position = CLLocationCoordinate2D(latitude: (self.objPeopleList?.cllocation?.coordinate.latitude)!, longitude: (self.objPeopleList?.cllocation?.coordinate.longitude)!)
// let marker = GMSMarker(position: position)
// marker.panoramaView = self.panoramaView
self.panoramaView.moveNearCoordinate(position)
}else {
self.panoramaView.moveNearCoordinate(CLLocationCoordinate2D(latitude: AppDelegate.delegate().currentLocation.coordinate.latitude, longitude: AppDelegate.delegate().currentLocation.coordinate.longitude))
}
// Do any additional setup after loading the view.
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2) {
self.panoramaView.camera = GMSPanoramaCamera(heading: 180, pitch: -10, zoom: 10)
}
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(true)
}
// MARK: - backButton
@IBAction func btnBackAction(_ sender: UIButton)
{
self.dismiss(animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
extension CanvasStreetViewController: GMSPanoramaViewDelegate {
func panoramaView(_ view: GMSPanoramaView, error: Error, onMoveNearCoordinate coordinate: CLLocationCoordinate2D) {
// print(error.localizedDescription)
print("\(coordinate.latitude) \(coordinate.longitude) not available")
let alert = UIAlertController(title: "Alert", message: "Can't get the streetView, try after sometimes.", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: { action in
self.view.endEditing(true)
self.dismiss(animated: true, completion: nil)
}))
self.present(alert, animated: true, completion: nil)
}
}
| true
|
961a94946dd51bede107532400145fd5b2a3c6ca
|
Swift
|
cfr/skybonds-test
|
/TestChart/TestChartTests/TestChartTests.swift
|
UTF-8
| 1,505
| 2.734375
| 3
|
[] |
no_license
|
//
// TestChartTests.swift
// TestChartTests
//
// Created by Stan Serebryakov on 23.11.2019.
// Copyright © 2019 Skybonds. All rights reserved.
//
import XCTest
@testable import TestChart
class TestChartTests: XCTestCase {
let range = DateRange.allCases.randomElement()!
var sample: [Markerable]!
override func setUp() {
sample = RandomDataSource(size: 1000).sampleOf(isin: "TEST", type: .price,
in: range)
}
override func tearDown() {
}
func testSampleInRect() {
let rect = CGRect.randomRect()
let pointsInRect = sample.mapTo(rect: rect)
for p in pointsInRect {
XCTAssert(rect.contains(p))
}
}
func testMinMax() {
let values = sample.map { $0.value }
let (min, max) = (values.min()!, values.max()!)
XCTAssert(sample.max == max)
XCTAssert(sample.min == min)
}
// ...
// func testPerformanceExample() {
// // This is an example of a performance test case.
// self.measure {
// // Put the code you want to measure the time of here.
// }
// }
}
extension CGRect {
static func randomRect() -> CGRect {
let max: CGFloat = 1000.0
return CGRect(x: CGFloat.random(in: 0.0...max),
y: CGFloat.random(in: 0.0...max),
width: CGFloat.random(in: 0.0...max),
height: CGFloat.random(in: 0.0...max))
}
}
| true
|
45ca80922720032a1b4b8efde6827da84ada5dbe
|
Swift
|
dan-zheng/swift-apis
|
/Sources/TensorFlow/Operators/NN.swift
|
UTF-8
| 35,196
| 2.828125
| 3
|
[
"Apache-2.0"
] |
permissive
|
// Copyright 2019 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import _Differentiation
//===------------------------------------------------------------------------------------------===//
// Normalization
//===------------------------------------------------------------------------------------------===//
extension Tensor where Scalar: TensorFlowFloatingPoint {
/// Returns a tensor computed from batch-normalizing the input along the specified axis.
///
/// Specifically, returns `(self - mu) / (var + epsilon) * gamma + beta` where `mu` and `var`
/// are respectively the mean and variance of `self` along `axis`.
///
/// - Parameters:
/// - axis: The batch dimension.
/// - offset: The offset, also known as beta.
/// - scale: The scale, also known as gamma.
/// - epsilon: A small value added to the denominator for numerical stability.
@inlinable
@differentiable(wrt: (self, offset, scale))
public func batchNormalized(
alongAxis axis: Int,
offset: Tensor = Tensor(0),
scale: Tensor = Tensor(1),
epsilon: Scalar = 0.001
) -> Tensor {
let moments = self.moments(alongAxes: axis)
let inv = rsqrt(moments.variance + epsilon) * scale
return self * inv + offset - moments.mean * inv
}
}
//===------------------------------------------------------------------------------------------===//
// Convolution and Pooling
//===------------------------------------------------------------------------------------------===//
/// A padding scheme. Used by padding, convolution, and pooling ops.
// @_frozen // SR-9739
public enum Padding {
/// The "valid" padding scheme.
case valid
/// The "same" padding scheme.
case same
}
extension Padding {
@inlinable
public var raw: _Raw.Padding {
switch self {
case .same: return .same
case .valid: return .valid
}
}
@inlinable
internal var raw2: _Raw.Padding1 {
switch self {
case .same: return .same
case .valid: return .valid
}
}
}
/// Returns a 1-D convolution with the specified input, filter, stride, and padding.
///
/// - Parameters:
/// - input: The input.
/// - filter: The convolution filter.
/// - stride: The stride of the sliding filter.
/// - padding: The padding for the operation.
/// - dilation: The dilation factor.
/// - Precondition: `input` must have rank `3`.
/// - Precondition: `filter` must have rank 3.
@differentiable(wrt: (input, filter))
public func conv1D<Scalar: TensorFlowFloatingPoint>(
_ input: Tensor<Scalar>,
filter: Tensor<Scalar>,
stride: Int = 1,
padding: Padding = .valid,
dilation: Int = 1
) -> Tensor<Scalar> {
precondition(input.shape.rank == 3, "The input must have rank 3.")
precondition(filter.shape.rank == 3, "The filter must have rank 3.")
return conv2D(
input.expandingShape(at: 1),
filter: filter.expandingShape(at: 0),
strides: (1, 1, stride, 1),
padding: padding,
dilations: (1, 1, dilation, 1)
).squeezingShape(at: 1)
}
/// Returns a 2-D convolution with the specified input, filter, strides, and padding.
///
/// - Parameters:
/// - input: The input.
/// - filter: The convolution filter.
/// - strides: The strides of the sliding filter for each dimension of the input.
/// - padding: The padding for the operation
/// - dilations: The dilation factor for each dimension of the input.
/// - Precondition: `input` must have rank `4`.
/// - Precondition: `filter` must have rank 4.
@differentiable(wrt: (input, filter))
public func conv2D<Scalar: TensorFlowFloatingPoint>(
_ input: Tensor<Scalar>,
filter: Tensor<Scalar>,
strides: (Int, Int, Int, Int) = (1, 1, 1, 1),
padding: Padding = .valid,
dilations: (Int, Int, Int, Int) = (1, 1, 1, 1)
) -> Tensor<Scalar> {
precondition(input.shape.rank == 4, "The input must have rank 4.")
precondition(filter.shape.rank == 4, "The filter must have rank 4.")
return _Raw.conv2D(
input,
filter: filter,
strides: [Int32(strides.0), Int32(strides.1), Int32(strides.2), Int32(strides.3)],
padding: padding.raw2,
explicitPaddings: [],
dilations: [Int32(dilations.0), Int32(dilations.1), Int32(dilations.2), Int32(dilations.3)]
)
}
@usableFromInline
@derivative(of: conv2D)
func _vjpConv2D<Scalar: TensorFlowFloatingPoint>(
_ x: Tensor<Scalar>,
filter: Tensor<Scalar>,
strides: (Int, Int, Int, Int),
padding: Padding,
dilations: (Int, Int, Int, Int)
) -> (value: Tensor<Scalar>, pullback: (Tensor<Scalar>) -> (Tensor<Scalar>, Tensor<Scalar>)) {
let value = conv2D(x, filter: filter, strides: strides, padding: padding, dilations: dilations)
return (
value,
{ v in
(
conv2DBackpropInput(
v, shape: x.shape.dimensions.map { Int64($0) }, filter: filter,
strides: strides, padding: padding, dilations: dilations),
conv2DBackpropFilter(
v, input: x, filterSizes: filter.shape.dimensions.map { Int64($0) },
strides: strides, padding: padding, dilations: dilations)
)
}
)
}
/// Returns a 2-D transposed convolution with the specified input, filter, strides, and padding.
///
/// - Parameters:
/// - input: The input.
/// - shape: The output shape of the deconvolution operation.
/// - filter: The convolution filter.
/// - strides: The strides of the sliding filter for each dimension of the input.
/// - padding: The padding for the operation
/// - dilations: The dilation factor for each dimension of the input.
/// - Precondition: `input` must have rank `4`.
/// - Precondition: `filter` must have rank 4.
@differentiable(wrt: (input, filter))
public func transposedConv2D<Scalar: TensorFlowFloatingPoint>(
_ input: Tensor<Scalar>,
shape: [Int64],
filter: Tensor<Scalar>,
strides: (Int, Int, Int, Int) = (1, 1, 1, 1),
padding: Padding = .valid,
dilations: (Int, Int, Int, Int) = (1, 1, 1, 1)
) -> Tensor<Scalar> {
precondition(input.shape.rank == 4, "The input must have rank 4.")
precondition(filter.shape.rank == 4, "The filter must have rank 4.")
return conv2DBackpropInput(
input, shape: shape, filter: filter,
strides: strides, padding: padding, dilations: dilations)
}
/// TensorFlow builtin conv2d gradient helper for the input.
@differentiable(wrt: (x, filter))
@usableFromInline
func conv2DBackpropInput<Scalar: TensorFlowFloatingPoint>(
_ x: Tensor<Scalar>,
shape: [Int64],
filter: Tensor<Scalar>,
strides: (Int, Int, Int, Int) = (1, 1, 1, 1),
padding: Padding = .valid,
dilations: (Int, Int, Int, Int) = (1, 1, 1, 1)
) -> Tensor<Scalar> {
return _Raw.conv2DBackpropInput(
inputSizes: shape,
filter: filter,
outBackprop: x,
strides: [Int32(strides.0), Int32(strides.1), Int32(strides.2), Int32(strides.3)],
padding: padding.raw2,
explicitPaddings: [],
dilations: [Int32(dilations.0), Int32(dilations.1), Int32(dilations.2), Int32(dilations.3)])
}
@derivative(of: conv2DBackpropInput)
@usableFromInline
func _vjpConv2DBackpropInput<Scalar: TensorFlowFloatingPoint>(
_ x: Tensor<Scalar>,
_ shape: [Int64],
_ filter: Tensor<Scalar>,
_ strides: (Int, Int, Int, Int),
_ padding: Padding,
_ dilations: (Int, Int, Int, Int)
) -> (value: Tensor<Scalar>, pullback: (Tensor<Scalar>) -> (Tensor<Scalar>, Tensor<Scalar>)) {
let value = conv2DBackpropInput(
x, shape: shape, filter: filter,
strides: strides, padding: padding, dilations: dilations)
return (
value,
{ v in
(
conv2D(v, filter: filter, strides: strides, padding: padding, dilations: dilations),
conv2DBackpropFilter(
x, input: v, filterSizes: filter.shape.dimensions.map { Int64($0) }, strides: strides,
padding: padding, dilations: dilations)
)
}
)
}
/// TensorFlow builtin conv2d gradient helper for the filter.
@differentiable(wrt: (x, input))
@usableFromInline
func conv2DBackpropFilter<Scalar: TensorFlowFloatingPoint>(
_ x: Tensor<Scalar>,
input: Tensor<Scalar>,
filterSizes: [Int64],
strides: (Int, Int, Int, Int) = (1, 1, 1, 1),
padding: Padding = .valid,
dilations: (Int, Int, Int, Int) = (1, 1, 1, 1)
) -> Tensor<Scalar> {
return _Raw.conv2DBackpropFilter(
input,
filterSizes: filterSizes,
outBackprop: x,
strides: [Int32(strides.0), Int32(strides.1), Int32(strides.2), Int32(strides.3)],
padding: padding.raw2,
explicitPaddings: [],
dilations: [Int32(dilations.0), Int32(dilations.1), Int32(dilations.2), Int32(dilations.3)])
}
@usableFromInline
@derivative(of: conv2DBackpropFilter)
func _vjpConv2DBackpropFilter<Scalar: TensorFlowFloatingPoint>(
_ x: Tensor<Scalar>,
_ input: Tensor<Scalar>,
_ filterSizes: [Int64],
_ strides: (Int, Int, Int, Int),
_ padding: Padding,
_ dilations: (Int, Int, Int, Int)
) -> (value: Tensor<Scalar>, pullback: (Tensor<Scalar>) -> (Tensor<Scalar>, Tensor<Scalar>)) {
let value = conv2DBackpropFilter(
x, input: input, filterSizes: filterSizes,
strides: strides, padding: padding, dilations: dilations)
return (
value,
{ v in
(
conv2D(input, filter: v, strides: strides, padding: padding, dilations: dilations),
conv2DBackpropInput(
x, shape: x.shape.dimensions.map { Int64($0) }, filter: v, strides: strides,
padding: padding, dilations: dilations)
)
}
)
}
/// Returns a 3-D convolution with the specified input, filter, strides, padding and dilations.
///
/// - Parameters:
/// - input: The input.
/// - filter: The convolution filter.
/// - strides: The strides of the sliding filter for each dimension of the input.
/// - padding: The padding for the operation.
/// - dilations: The dilation factor for each dimension of the input.
/// - Precondition: `input` must have rank `5`.
/// - Precondition: `filter` must have rank 5.
@differentiable(wrt: (input, filter))
public func conv3D<Scalar: TensorFlowFloatingPoint>(
_ input: Tensor<Scalar>,
filter: Tensor<Scalar>,
strides: (Int, Int, Int, Int, Int) = (1, 1, 1, 1, 1),
padding: Padding = .valid,
dilations: (Int, Int, Int, Int, Int) = (1, 1, 1, 1, 1)
) -> Tensor<Scalar> {
precondition(input.shape.rank == 5, "The input must have rank 5.")
precondition(filter.shape.rank == 5, "The filter must have rank 5.")
return _Raw.conv3D(
input,
filter: filter,
strides: [
Int32(strides.0), Int32(strides.1), Int32(strides.2),
Int32(strides.3), Int32(strides.4),
],
padding: padding.raw,
dilations: [
Int32(dilations.0), Int32(dilations.1), Int32(dilations.2),
Int32(dilations.3), Int32(dilations.4),
]
)
}
@usableFromInline
@derivative(of: conv3D)
func _vjpConv3D<Scalar: TensorFlowFloatingPoint>(
_ x: Tensor<Scalar>,
filter: Tensor<Scalar>,
strides: (Int, Int, Int, Int, Int),
padding: Padding,
dilations: (Int, Int, Int, Int, Int)
) -> (value: Tensor<Scalar>, pullback: (Tensor<Scalar>) -> (Tensor<Scalar>, Tensor<Scalar>)) {
let value = conv3D(
x, filter: filter, strides: strides,
padding: padding, dilations: dilations)
return (
value,
{ v in
(
conv3DBackpropInput(
v, shape: x.shapeTensor, filter: filter,
strides: strides, padding: padding),
conv3DBackpropFilter(
v, input: x, filterSizes: filter.shapeTensor,
strides: strides, padding: padding)
)
}
)
}
/// TensorFlow builtin conv3d gradient helper for the input.
@differentiable(wrt: (x, filter))
@usableFromInline
func conv3DBackpropInput<Scalar: TensorFlowFloatingPoint>(
_ x: Tensor<Scalar>,
shape: Tensor<Int32>,
filter: Tensor<Scalar>,
strides: (Int, Int, Int, Int, Int) = (1, 1, 1, 1, 1),
padding: Padding = .valid,
dilations: (Int, Int, Int, Int, Int) = (1, 1, 1, 1, 1)
) -> Tensor<Scalar> {
return _Raw.conv3DBackpropInputV2(
inputSizes: shape,
filter: filter,
outBackprop: x,
strides: [
Int32(strides.0), Int32(strides.1), Int32(strides.2),
Int32(strides.3), Int32(strides.4),
],
padding: padding.raw,
dilations: [
Int32(dilations.0), Int32(dilations.1), Int32(dilations.2),
Int32(dilations.3), Int32(dilations.4),
]
)
}
@usableFromInline
@derivative(of: conv3DBackpropInput)
func _vjpConv3DBackpropInput<Scalar: TensorFlowFloatingPoint>(
_ x: Tensor<Scalar>,
_ shape: Tensor<Int32>,
_ filter: Tensor<Scalar>,
_ strides: (Int, Int, Int, Int, Int),
_ padding: Padding,
_ dilations: (Int, Int, Int, Int, Int)
) -> (value: Tensor<Scalar>, pullback: (Tensor<Scalar>) -> (Tensor<Scalar>, Tensor<Scalar>)) {
let value = conv3DBackpropInput(
x, shape: shape, filter: filter, strides: strides,
padding: padding, dilations: dilations)
return (
value,
{ v in
(
conv3D(v, filter: filter, strides: strides, padding: padding),
conv3DBackpropFilter(
x, input: v, filterSizes: filter.shapeTensor, strides: strides,
padding: padding)
)
}
)
}
/// TensorFlow builtin conv3d gradient helper for the filter.
@differentiable(wrt: (x, input))
@usableFromInline
func conv3DBackpropFilter<Scalar: TensorFlowFloatingPoint>(
_ x: Tensor<Scalar>,
input: Tensor<Scalar>,
filterSizes: Tensor<Int32>,
strides: (Int, Int, Int, Int, Int) = (1, 1, 1, 1, 1),
padding: Padding = .valid,
dilations: (Int, Int, Int, Int, Int) = (1, 1, 1, 1, 1)
) -> Tensor<Scalar> {
return _Raw.conv3DBackpropFilterV2(
input,
filterSizes: filterSizes,
outBackprop: x,
strides: [
Int32(strides.0), Int32(strides.1), Int32(strides.2),
Int32(strides.3), Int32(strides.4),
],
padding: padding.raw,
dilations: [
Int32(dilations.0), Int32(dilations.1), Int32(dilations.2),
Int32(dilations.3), Int32(dilations.4),
]
)
}
@usableFromInline
@derivative(of: conv3DBackpropFilter)
func _vjpConv3DBackpropFilter<Scalar: TensorFlowFloatingPoint>(
_ x: Tensor<Scalar>,
_ input: Tensor<Scalar>,
_ filterSizes: Tensor<Int32>,
_ strides: (Int, Int, Int, Int, Int),
_ padding: Padding,
_ dilations: (Int, Int, Int, Int, Int)
) -> (value: Tensor<Scalar>, pullback: (Tensor<Scalar>) -> (Tensor<Scalar>, Tensor<Scalar>)) {
let value = conv3DBackpropFilter(
x, input: input, filterSizes: filterSizes,
strides: strides, padding: padding, dilations: dilations)
return (
value,
{ v in
(
conv3D(input, filter: v, strides: strides, padding: padding),
conv3DBackpropInput(
x, shape: x.shapeTensor, filter: v, strides: strides,
padding: padding)
)
}
)
}
/// Returns a 2-D depthwise convolution with the specified input, filter, strides, and padding.
///
/// - Parameters:
/// - input: The input.
/// - filter: The depthwise convolution filter.
/// - strides: The strides of the sliding filter for each dimension of the input.
/// - padding: The padding for the operation.
/// - Precondition: `input` must have rank 4.
/// - Precondition: `filter` must have rank 4.
@differentiable(wrt: (input, filter))
public func depthwiseConv2D<Scalar: TensorFlowFloatingPoint>(
_ input: Tensor<Scalar>,
filter: Tensor<Scalar>,
strides: (Int, Int, Int, Int),
padding: Padding
) -> Tensor<Scalar> {
precondition(input.shape.rank == 4, "The input must have rank 4.")
precondition(filter.shape.rank == 4, "The filter must have rank 4.")
return _Raw.depthwiseConv2dNative(
input,
filter: filter,
strides: [Int32(strides.0), Int32(strides.1), Int32(strides.2), Int32(strides.3)],
padding: padding.raw)
}
@usableFromInline
@derivative(of: depthwiseConv2D)
func _vjpDepthwiseConv2D<Scalar: TensorFlowFloatingPoint>(
_ x: Tensor<Scalar>,
filter: Tensor<Scalar>,
strides: (Int, Int, Int, Int),
padding: Padding
) -> (value: Tensor<Scalar>, pullback: (Tensor<Scalar>) -> (Tensor<Scalar>, Tensor<Scalar>)) {
let value = depthwiseConv2D(
x, filter: filter, strides: strides,
padding: padding)
return (
value,
{ v in
(
depthwiseConv2dBackpropInput(
v, shape: x.shapeTensor, filter: filter,
strides: strides, padding: padding),
depthwiseConv2dBackpropFilter(
v, input: x, filterSizes: filter.shapeTensor,
strides: strides, padding: padding)
)
}
)
}
/// TensorFlow builtin depthwiseConv2D gradient helper for the input.
@differentiable(wrt: (x, filter))
@usableFromInline
func depthwiseConv2dBackpropInput<Scalar: TensorFlowFloatingPoint>(
_ x: Tensor<Scalar>,
shape: Tensor<Int32>,
filter: Tensor<Scalar>,
strides: (Int, Int, Int, Int),
padding: Padding
) -> Tensor<Scalar> {
return _Raw.depthwiseConv2dNativeBackpropInput(
inputSizes: shape,
filter: filter,
outBackprop: x,
strides: [Int32(strides.0), Int32(strides.1), Int32(strides.2), Int32(strides.3)],
padding: padding.raw)
}
@usableFromInline
@derivative(of: depthwiseConv2dBackpropInput)
func _vjpDepthwiseConv2dBackpropInput<Scalar: TensorFlowFloatingPoint>(
_ x: Tensor<Scalar>,
_ shape: Tensor<Int32>,
_ filter: Tensor<Scalar>,
_ strides: (Int, Int, Int, Int),
_ padding: Padding
) -> (value: Tensor<Scalar>, pullback: (Tensor<Scalar>) -> (Tensor<Scalar>, Tensor<Scalar>)) {
let value = depthwiseConv2dBackpropInput(
x, shape: shape, filter: filter, strides: strides,
padding: padding)
return (
value,
{ v in
(
depthwiseConv2D(v, filter: filter, strides: strides, padding: padding),
depthwiseConv2dBackpropFilter(
x, input: v, filterSizes: filter.shapeTensor,
strides: strides, padding: padding)
)
}
)
}
/// TensorFlow builtin depthwiseConv2D gradient helper for the filter.
@differentiable(wrt: (x, input))
@usableFromInline
func depthwiseConv2dBackpropFilter<Scalar: TensorFlowFloatingPoint>(
_ x: Tensor<Scalar>,
input: Tensor<Scalar>,
filterSizes: Tensor<Int32>,
strides: (Int, Int, Int, Int),
padding: Padding
) -> Tensor<Scalar> {
return _Raw.depthwiseConv2dNativeBackpropFilter(
input,
filterSizes: filterSizes,
outBackprop: x,
strides: [Int32(strides.0), Int32(strides.1), Int32(strides.2), Int32(strides.3)],
padding: padding.raw)
}
@usableFromInline
@derivative(of: depthwiseConv2dBackpropFilter)
func _vjpDepthwiseConv2dBackpropFilter<Scalar: TensorFlowFloatingPoint>(
_ x: Tensor<Scalar>,
_ input: Tensor<Scalar>,
_ filterSizes: Tensor<Int32>,
_ strides: (Int, Int, Int, Int),
_ padding: Padding
) -> (value: Tensor<Scalar>, pullback: (Tensor<Scalar>) -> (Tensor<Scalar>, Tensor<Scalar>)) {
let value = depthwiseConv2dBackpropFilter(
x, input: input, filterSizes: filterSizes,
strides: strides, padding: padding)
return (
value,
{ v in
(
depthwiseConv2D(input, filter: v, strides: strides, padding: padding),
depthwiseConv2dBackpropInput(
x, shape: x.shapeTensor, filter: v, strides: strides,
padding: padding)
)
}
)
}
/// Returns a 2-D max pooling, with the specified filter sizes, strides, and
/// padding.
///
/// - Parameters:
/// - input: The input.
/// - filterSize: The dimensions of the pooling kernel.
/// - strides: The strides of the sliding filter for each dimension of the input.
/// - padding: The padding for the operation.
@differentiable(wrt: input)
public func maxPool2D<Scalar: TensorFlowFloatingPoint>(
_ input: Tensor<Scalar>,
filterSize: (Int, Int, Int, Int),
strides: (Int, Int, Int, Int),
padding: Padding
) -> Tensor<Scalar> {
precondition(input.rank == 4, "The rank of the input must be 4.")
return _Raw.maxPoolV2(
input,
ksize: [
Int64(filterSize.0), Int64(filterSize.1),
Int64(filterSize.2), Int64(filterSize.3),
],
strides: [
Int64(strides.0), Int64(strides.1),
Int64(strides.2), Int64(strides.3),
],
padding: padding.raw)
}
@usableFromInline
@derivative(of: maxPool2D)
func _vjpMaxPool2D<Scalar: TensorFlowFloatingPoint>(
_ x: Tensor<Scalar>,
filterSize: (Int, Int, Int, Int),
strides: (Int, Int, Int, Int),
padding: Padding
) -> (value: Tensor<Scalar>, pullback: (Tensor<Scalar>) -> Tensor<Scalar>) {
// TODO: Currently this is not higher order differentiable. Redefine in
// closed form.
let value = maxPool2D(x, filterSize: filterSize, strides: strides, padding: padding)
return (
value,
{ v in
_Raw.maxPoolGradV2(
origInput: x,
origOutput: value,
grad: v,
ksize: [
Int64(filterSize.0), Int64(filterSize.1),
Int64(filterSize.2), Int64(filterSize.3),
],
strides: [
Int64(strides.0), Int64(strides.1),
Int64(strides.2), Int64(strides.3),
],
padding: padding.raw)
}
)
}
/// Returns a 3-D max pooling, with the specified filter sizes, strides, and
/// padding.
///
/// - Parameters:
/// - input: The input.
/// - filterSize: The dimensions of the pooling kernel.
/// - strides: The strides of the sliding filter for each dimension of the input.
/// - padding: The padding for the operation.
@differentiable(wrt: input)
public func maxPool3D<Scalar: TensorFlowFloatingPoint>(
_ input: Tensor<Scalar>,
filterSize: (Int, Int, Int, Int, Int),
strides: (Int, Int, Int, Int, Int),
padding: Padding
) -> Tensor<Scalar> {
precondition(input.rank == 5, "The rank of the input must be 5.")
return _Raw.maxPool3D(
input,
ksize: [
Int32(filterSize.0), Int32(filterSize.1),
Int32(filterSize.2), Int32(filterSize.3), Int32(filterSize.4),
],
strides: [
Int32(strides.0), Int32(strides.1),
Int32(strides.2), Int32(strides.3), Int32(strides.4),
],
padding: padding.raw)
}
@usableFromInline
@derivative(of: maxPool3D)
func _vjpMaxPool3D<Scalar: TensorFlowFloatingPoint>(
_ x: Tensor<Scalar>,
filterSize: (Int, Int, Int, Int, Int),
strides: (Int, Int, Int, Int, Int),
padding: Padding
) -> (value: Tensor<Scalar>, pullback: (Tensor<Scalar>) -> Tensor<Scalar>) {
// TODO: Currently this is not higher order differentiable. Redefine in
// closed form.
let value = maxPool3D(x, filterSize: filterSize, strides: strides, padding: padding)
return (
value,
{ v in
return _Raw.maxPool3DGrad(
origInput: x,
origOutput: value,
grad: v,
ksize: [
Int32(filterSize.0), Int32(filterSize.1), Int32(filterSize.2),
Int32(filterSize.3), Int32(filterSize.4),
],
strides: [
Int32(strides.0), Int32(strides.1), Int32(strides.2), Int32(strides.3),
Int32(strides.4),
],
padding: padding.raw
)
}
)
}
/// Returns a 2-D average pooling, with the specified filter sizes, strides,
/// and padding.
///
/// - Parameters:
/// - input: The input.
/// - filterSize: The dimensions of the pooling kernel.
/// - strides: The strides of the sliding filter for each dimension of the input.
/// - padding: The padding for the operation.
@differentiable(wrt: input)
public func avgPool2D<Scalar: TensorFlowFloatingPoint>(
_ input: Tensor<Scalar>,
filterSize: (Int, Int, Int, Int),
strides: (Int, Int, Int, Int),
padding: Padding
) -> Tensor<Scalar> {
precondition(input.rank == 4, "The rank of the input must be 4.")
return _Raw.avgPool(
value: input,
ksize: [
Int32(filterSize.0), Int32(filterSize.1),
Int32(filterSize.2), Int32(filterSize.3),
],
strides: [Int32(strides.0), Int32(strides.1), Int32(strides.2), Int32(strides.3)],
padding: padding.raw)
}
@usableFromInline
@derivative(of: avgPool2D)
func _vjpAvgPool2D<Scalar: TensorFlowFloatingPoint>(
_ x: Tensor<Scalar>,
filterSize: (Int, Int, Int, Int),
strides: (Int, Int, Int, Int),
padding: Padding
) -> (value: Tensor<Scalar>, pullback: (Tensor<Scalar>) -> Tensor<Scalar>) {
// TODO: Currently this is not higher order differentiable. Redefine in
// closed form.
let value = avgPool2D(x, filterSize: filterSize, strides: strides, padding: padding)
return (
value,
{ v in
_Raw.avgPoolGrad(
origInputShape: x.shapeTensor,
grad: v,
ksize: [
Int32(filterSize.0), Int32(filterSize.1),
Int32(filterSize.2), Int32(filterSize.3),
],
strides: [
Int32(strides.0), Int32(strides.1),
Int32(strides.2), Int32(strides.3),
],
padding: padding.raw
)
}
)
}
/// Returns a 3-D average pooling, with the specified filter sizes, strides,
/// and padding.
///
/// - Parameters:
/// - input: The input.
/// - filterSize: The dimensions of the pooling kernel.
/// - strides: The strides of the sliding filter for each dimension of the input.
/// - padding: The padding for the operation.
@differentiable(wrt: input)
public func avgPool3D<Scalar: TensorFlowFloatingPoint>(
_ input: Tensor<Scalar>,
filterSize: (Int, Int, Int, Int, Int),
strides: (Int, Int, Int, Int, Int),
padding: Padding
) -> Tensor<Scalar> {
precondition(input.rank == 5, "The rank of the input must be 5.")
return _Raw.avgPool3D(
input,
ksize: [
Int32(filterSize.0), Int32(filterSize.1),
Int32(filterSize.2), Int32(filterSize.3), Int32(filterSize.4),
],
strides: [
Int32(strides.0), Int32(strides.1), Int32(strides.2), Int32(strides.3),
Int32(strides.4),
],
padding: padding.raw)
}
@usableFromInline
@derivative(of: avgPool3D)
func _vjpAvgPool3D<Scalar: TensorFlowFloatingPoint>(
_ x: Tensor<Scalar>,
filterSize: (Int, Int, Int, Int, Int),
strides: (Int, Int, Int, Int, Int),
padding: Padding
) -> (value: Tensor<Scalar>, pullback: (Tensor<Scalar>) -> Tensor<Scalar>) {
// TODO: Currently this is not higher order differentiable. Redefine in
// closed form.
let value = avgPool3D(x, filterSize: filterSize, strides: strides, padding: padding)
return (
value,
{ v in
return _Raw.avgPool3DGrad(
origInputShape: x.shapeTensor,
grad: v,
ksize: [
Int32(filterSize.0), Int32(filterSize.1), Int32(filterSize.2),
Int32(filterSize.3), Int32(filterSize.4),
],
strides: [
Int32(strides.0), Int32(strides.1), Int32(strides.2), Int32(strides.3),
Int32(strides.4),
],
padding: padding.raw
)
}
)
}
/// Returns a 2-D fractional max pooling, with the specified pooling ratios.
///
/// Note: `fractionalMaxPool` does not have an XLA implementation, and thus may have performance implications.
///
/// - Parameters:
/// - input: A Tensor. 4-D with shape `[batch, height, width, channels]`.
/// - poolingRatio: A list of `Doubles`. Pooling ratio for each dimension of `input`, currently only
/// supports row and col dimension and should be >= 1.0.
/// - pseudoRandom: An optional `Bool`. Defaults to `false`. When set to `true`,
/// generates the pooling sequence in a pseudorandom fashion, otherwise, in a random fashion.
/// - overlapping: An optional `Bool`. Defaults to `false`. When set to `true`, it means
/// when pooling, the values at the boundary of adjacent pooling cells are used by both cells.
/// - deterministic: An Optional `Bool`. When set to `true`, a fixed pooling region will be
/// used when iterating over a fractionalMaxPool2D node in the computation graph.
/// - seed: An optional `Int64`. Defaults to `0`. If set to be non-zero, the random number
/// generator is seeded by the given seed.
/// - seed2: An optional `Int64`. Defaults to `0`. A second seed to avoid seed collision.
@differentiable(wrt: input)
public func fractionalMaxPool2D<Scalar: TensorFlowFloatingPoint>(
_ input: Tensor<Scalar>,
poolingRatio: (Double, Double, Double, Double),
pseudoRandom: Bool = false,
overlapping: Bool = false,
deterministic: Bool = false,
seed: Int64 = 0,
seed2: Int64 = 0
) -> Tensor<Scalar> {
precondition(input.rank == 4, "The rank of the input must be 4.")
return _Raw.fractionalMaxPool(
value: input,
poolingRatio: [
Double(poolingRatio.0), Double(poolingRatio.1),
Double(poolingRatio.2), Double(poolingRatio.3),
],
pseudoRandom: pseudoRandom,
overlapping: overlapping,
deterministic: deterministic,
seed: seed,
seed2: seed2
).0
}
@usableFromInline
@derivative(of: fractionalMaxPool2D)
func _vjpFractionalMaxPool<Scalar: TensorFlowFloatingPoint>(
_ x: Tensor<Scalar>,
poolingRatio: (Double, Double, Double, Double),
pseudoRandom: Bool = false,
overlapping: Bool = false,
deterministic: Bool = false,
seed: Int64 = 0,
seed2: Int64 = 0
) -> (value: Tensor<Scalar>, pullback: (Tensor<Scalar>) -> Tensor<Scalar>) {
// TODO: Currently this is not higher order differentiable. Redefine in
// closed form.
let (value, rowPoolingSequence, colPoolingSequence) = _Raw.fractionalMaxPool(
value: x,
poolingRatio: [
Double(poolingRatio.0), Double(poolingRatio.1),
Double(poolingRatio.2), Double(poolingRatio.3),
],
pseudoRandom: pseudoRandom,
overlapping: overlapping,
deterministic: deterministic,
seed: seed,
seed2: seed2)
return (
value,
{ v in
_Raw.fractionalMaxPoolGrad(
origInput: x,
origOutput: value,
outBackprop: v,
rowPoolingSequence: rowPoolingSequence,
colPoolingSequence: colPoolingSequence,
overlapping: overlapping
)
}
)
}
//===------------------------------------------------------------------------------------------===//
// Rearrange depth/space
//===------------------------------------------------------------------------------------------===//
/// Returns a copy of `input` where values from the depth dimension are moved in spatial blocks to the height and width dimensions.
///
/// For example, given an input of shape `[1, 2, 2, 1]`, data_format = "NHWC" and
/// block_size = 2:
///
/// ```
/// x = [[[[1], [2]],
/// [[3], [4]]]]
/// ```
///
/// This operation will output a tensor of shape `[1, 1, 1, 4]`:
///
/// ```
/// [[[[1, 2, 3, 4]]]]
/// ```
///
/// Here, the input has a batch of 1 and each batch element has shape `[2, 2, 1]`,
/// the corresponding output will have a single element (i.e. width and height are
/// both 1) and will have a depth of 4 channels (1 * block_size * block_size).
/// The output element shape is `[1, 1, 4]`.
///
/// For an input tensor with larger depth, here of shape `[1, 2, 2, 3]`, e.g.
///
/// ```
/// x = [[[[1, 2, 3], [4, 5, 6]],
/// [[7, 8, 9], [10, 11, 12]]]]
/// ```
///
/// This operation, for block_size of 2, will return the following tensor of shape
/// `[1, 1, 1, 12]`
///
/// ```
/// [[[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]]]]
/// ```
///
/// Similarly, for the following input of shape `[1 4 4 1]`, and a block size of 2:
///
/// ```
/// x = [[[[1], [2], [5], [6]],
/// [[3], [4], [7], [8]],
/// [[9], [10], [13], [14]],
/// [[11], [12], [15], [16]]]]
/// ```
///
/// the operator will return the following tensor of shape `[1 2 2 4]`:
///
/// ```
/// x = [[[[1, 2, 3, 4],
/// [5, 6, 7, 8]],
/// [[9, 10, 11, 12],
/// [13, 14, 15, 16]]]]
/// ```
///
/// - Precondition: `input.rank == 4 && b >= 2`.
/// - Precondition: The number of the features must be divisible by square of `b`.
@differentiable(wrt: input where Scalar: TensorFlowFloatingPoint)
public func depthToSpace<Scalar>(_ input: Tensor<Scalar>, blockSize b: Int) -> Tensor<Scalar> {
precondition(input.rank == 4, "The input must have rank 4.")
precondition(b >= 2, "The size must be greater than 1.")
precondition(
input.shape[3].isMultiple(of: b * b),
"The number of the features must be divisible by square of the block size.")
return _Raw.depthToSpace(input, blockSize: Int64(b))
}
@usableFromInline
@derivative(of: depthToSpace)
func _vjpDepthToSpace<Scalar: TensorFlowFloatingPoint>(
_ input: Tensor<Scalar>,
blockSize b: Int
) -> (value: Tensor<Scalar>, pullback: (Tensor<Scalar>) -> Tensor<Scalar>) {
(depthToSpace(input, blockSize: b), { spaceToDepth($0, blockSize: b) })
}
/// Returns a copy of `input` where values from the height and width dimensions are moved to the depth dimension.
///
/// For example, given an input of shape `[1, 2, 2, 1]`, data_format = "NHWC" and
/// block_size = 2:
///
/// ```
/// x = [[[[1], [2]],
/// [[3], [4]]]]
/// ```
///
/// This operation will output a tensor of shape `[1, 1, 1, 4]`:
///
/// ```
/// [[[[1, 2, 3, 4]]]]
/// ```
///
/// Here, the input has a batch of 1 and each batch element has shape `[2, 2, 1]`,
/// the corresponding output will have a single element (i.e. width and height are
/// both 1) and will have a depth of 4 channels (1 * block_size * block_size).
/// The output element shape is `[1, 1, 4]`.
///
/// For an input tensor with larger depth, here of shape `[1, 2, 2, 3]`, e.g.
///
/// ```
/// x = [[[[1, 2, 3], [4, 5, 6]],
/// [[7, 8, 9], [10, 11, 12]]]]
/// ```
///
/// This operation, for block_size of 2, will return the following tensor of shape
/// `[1, 1, 1, 12]`
///
/// ```
/// [[[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]]]]
/// ```
///
/// Similarly, for the following input of shape `[1 4 4 1]`, and a block size of 2:
///
/// ```
/// x = [[[[1], [2], [5], [6]],
/// [[3], [4], [7], [8]],
/// [[9], [10], [13], [14]],
/// [[11], [12], [15], [16]]]]
/// ```
///
/// the operator will return the following tensor of shape `[1 2 2 4]`:
///
/// ```
/// x = [[[[1, 2, 3, 4],
/// [5, 6, 7, 8]],
/// [[9, 10, 11, 12],
/// [13, 14, 15, 16]]]]
/// ```
///
/// - Precondition: `input.rank == 4 && b >= 2`.
/// - Precondition: The height of the input must be divisible by `b`.
/// - Precondition: The width of the input must be divisible by `b`.
@differentiable(wrt: input where Scalar: TensorFlowFloatingPoint)
public func spaceToDepth<Scalar>(_ input: Tensor<Scalar>, blockSize b: Int) -> Tensor<Scalar> {
precondition(input.rank == 4, "The input must have rank 4.")
precondition(b >= 2, "The block size must be greater than 1.")
precondition(
input.shape[1].isMultiple(of: b),
"The height of the input must be divisible by the block size.")
precondition(
input.shape[2].isMultiple(of: b),
"The width of the input must be divisible by the block size.")
return _Raw.spaceToDepth(input, blockSize: Int64(b))
}
@usableFromInline
@derivative(of: spaceToDepth)
func _vjpSpaceToDepth<Scalar: TensorFlowFloatingPoint>(
_ input: Tensor<Scalar>,
blockSize b: Int
) -> (value: Tensor<Scalar>, pullback: (Tensor<Scalar>) -> Tensor<Scalar>) {
(spaceToDepth(input, blockSize: b), { depthToSpace($0, blockSize: b) })
}
| true
|
4324487f3d39d0f60f778e955df69e18db9a1afb
|
Swift
|
ColinDunne/SwiftAnswerForLeetCode
|
/LeetCode83_RemoveDuplicatesFromSortedList.playground/Contents.swift
|
UTF-8
| 794
| 3.4375
| 3
|
[
"MIT"
] |
permissive
|
/**
* 此题看起来很简单,但实际写起来还是有些别扭的
* 时间复杂度O(n), 空间复杂度O(1)
*/
public class ListNode {
public var val: Int
public var next: ListNode?
public init(_ val: Int) {
self.val = val
self.next = nil
}
}
class Solution {
func deleteDuplicates(_ head: ListNode?) -> ListNode? {
if head == nil || head!.next == nil {
return head
}
var node = head
while node != nil {
if node!.next == nil {
break
}
if node!.val == node!.next?.val {
node!.next = node!.next?.next
} else {
node = node!.next
}
}
return head
}
}
| true
|
42c8cc3e0cf68a2a9431814158d3ceb35b82ca72
|
Swift
|
pmanuelli/fallout-4-map-notes
|
/Fallout Notes/Presentation/Map/MapViewModel.swift
|
UTF-8
| 3,767
| 2.515625
| 3
|
[] |
no_license
|
import RxSwift
import RxCocoa
class MapViewModel {
struct Output {
let userInteractionEnabled: Driver<Bool>
let newLocationPinDrop: Observable<Coordinates>
let locationCreationCancel: Observable<Void>
let locationSelection: Observable<Location>
let locationViewModels: Observable<[MapLocationViewModel]>
}
lazy var output = Output(userInteractionEnabled: userInteractionEnabledSubject.asDriver(onErrorJustReturn: false),
newLocationPinDrop: newLocationPinDropSubject.asObservable(),
locationCreationCancel: locationCreationCancelSubject.asObservable(),
locationSelection: locationSelectionSubject.asObservable(),
locationViewModels: locationViewModelsSubject.asObservable())
private let userInteractionEnabledSubject = BehaviorSubject<Bool>(value: true)
private let newLocationPinDropSubject = PublishSubject<Coordinates>()
private let locationCreationCancelSubject = PublishSubject<Void>()
private let locationSelectionSubject = PublishSubject<Location>()
private let locationViewModelsSubject = ReplaySubject<[MapLocationViewModel]>.create(bufferSize: 1)
private var locationViewModels = [MapLocationViewModel]()
private let disposeBag = DisposeBag()
init(locations: [Location], eventBus: EventBusConsumer) {
eventBus.locationCreated
.subscribe(onNext: { [weak self] in self?.onLocationCreated(location: $0.location) })
.disposed(by: disposeBag)
eventBus.locationEdited
.subscribe(onNext: { [weak self] in self?.onLocationEdited(location: $0.location) })
.disposed(by: disposeBag)
eventBus.locationDeleted
.subscribe(onNext: { [weak self] in self?.onLocationDeleted(locationId: $0.locationId) })
.disposed(by: disposeBag)
eventBus.locationCreationCancel
.subscribe(onNext: { [weak self] _ in self?.onLocationCreationCancelled() })
.disposed(by: disposeBag)
locationViewModels = locations.map { MapLocationViewModel(location: $0) }
locationViewModelsSubject.onNext(locationViewModels)
}
func newLocationPinDropped(coordinates: Coordinates) {
newLocationPinDropSubject.onNext(coordinates)
}
func locationViewModelSelected(_ viewModel: MapLocationViewModel) {
locationSelectionSubject.onNext(viewModel.location)
}
private func onLocationCreated(location: Location) {
locationViewModels.append(MapLocationViewModel(location: location))
locationViewModelsSubject.onNext(locationViewModels)
}
private func onLocationEdited(location: Location) {
guard let index = locationViewModels.firstIndex(where: { $0.id == location.id }) else { return }
locationViewModels[index] = MapLocationViewModel(location: location)
locationViewModelsSubject.onNext(locationViewModels)
}
private func onLocationDeleted(locationId: Location.Id) {
locationViewModels = locationViewModels.filter { $0.id != locationId }
locationViewModelsSubject.onNext(locationViewModels)
}
private func onLocationCreationCancelled() {
locationCreationCancelSubject.onNext(())
}
}
extension EventBusConsumer {
var locationCreated: Observable<LocationCreatedEvent> { observe() }
var locationEdited: Observable<LocationEditedEvent> { observe() }
var locationDeleted: Observable<LocationDeletedEvent> { observe() }
var locationCreationCancel: Observable<LocationCreationCancelledEvent> { observe() }
}
| true
|
1eb5bde75d75826de8845b3f536a72562939e1e7
|
Swift
|
ahoppen/ppdb
|
/Swift Package/Tests/ExecutionHistoryTests/ExecutionHistoryTests.swift
|
UTF-8
| 5,981
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
import AST
import Parser
import TypeChecker
import ExecutionHistory
import XCTest
fileprivate extension SourceRange {
func sourceCode(in sourceCode: String) -> String {
return String(sourceCode[lowerBound.offset..<upperBound.offset])
}
}
class ExecutionHistoryTests: XCTestCase {
private func parse(_ sourceCode: String) throws -> TopLevelCodeStmt {
let parser = Parser(sourceCode: sourceCode)
let ast = try parser.parseFile()
return try TypeCheckPipeline.typeCheck(stmt: ast) as! TopLevelCodeStmt
}
func testGenerateAugmentedExecutionHistoryForStraightLineProgram() {
XCTAssertNoThrow(try {
let source = """
int x = 5
int y = 2
int z = x + y
"""
let ast = try parse(source)
let executionHistory = ExecutionHistory(history: [.stepOver, .stepIntoTrue, .stepOver])
let augmentedExecutionHistory = try executionHistory.augmented(with: ast).history
XCTAssertEqual(augmentedExecutionHistory.count, 3)
XCTAssertEqual(augmentedExecutionHistory[0].command, .stepOver)
XCTAssertEqual(augmentedExecutionHistory[0].stmt.range.sourceCode(in: source), "int x = 5")
XCTAssertEqual(augmentedExecutionHistory[1].command, .stepIntoTrue)
XCTAssertEqual(augmentedExecutionHistory[1].stmt.range.sourceCode(in: source), "int y = 2")
XCTAssertEqual(augmentedExecutionHistory[2].command, .stepOver)
XCTAssertEqual(augmentedExecutionHistory[2].stmt.range.sourceCode(in: source), "int z = x + y")
}())
}
func testGenerateAugmentedExecutionHistoryForSteppedOverProbStatement() {
XCTAssertNoThrow(try {
let source = """
int x = 5
prob 0.5 { x = 2 }
int y = 2
"""
let ast = try parse(source)
let executionHistory = ExecutionHistory(history: [.stepOver, .stepOver, .stepOver])
let augmentedExecutionHistory = try executionHistory.augmented(with: ast).history
XCTAssertEqual(augmentedExecutionHistory.count, 3)
XCTAssertEqual(augmentedExecutionHistory[0].command, .stepOver)
XCTAssertEqual(augmentedExecutionHistory[0].stmt.range.sourceCode(in: source), "int x = 5")
XCTAssertEqual(augmentedExecutionHistory[1].command, .stepOver)
XCTAssertEqual(augmentedExecutionHistory[1].stmt.range.sourceCode(in: source), "prob 0.5 { x = 2 }")
XCTAssertEqual(augmentedExecutionHistory[2].command, .stepOver)
XCTAssertEqual(augmentedExecutionHistory[2].stmt.range.sourceCode(in: source), "int y = 2")
}())
}
func testGenerateAugmentedExecutionHistoryForSteppedIntoTrueProbStatement() {
XCTAssertNoThrow(try {
let source = """
int x = 5
prob 0.5 { x = 2 }
int y = 2
"""
let ast = try parse(source)
let executionHistory = ExecutionHistory(history: [.stepOver, .stepIntoTrue, .stepOver, .stepOver])
let augmentedExecutionHistory = try executionHistory.augmented(with: ast).history
XCTAssertEqual(augmentedExecutionHistory.count, 4)
XCTAssertEqual(augmentedExecutionHistory[0].command, .stepOver)
XCTAssertEqual(augmentedExecutionHistory[0].stmt.range.sourceCode(in: source), "int x = 5")
XCTAssertEqual(augmentedExecutionHistory[1].command, .stepIntoTrue)
XCTAssertEqual(augmentedExecutionHistory[1].stmt.range.sourceCode(in: source), "prob 0.5 { x = 2 }")
XCTAssertEqual(augmentedExecutionHistory[2].command, .stepOver)
XCTAssertEqual(augmentedExecutionHistory[2].stmt.range.sourceCode(in: source), "x = 2")
XCTAssertEqual(augmentedExecutionHistory[3].command, .stepOver)
XCTAssertEqual(augmentedExecutionHistory[3].stmt.range.sourceCode(in: source), "int y = 2")
}())
}
func testGenerateAugmentedExecutionHistoryForSteppedIntoFalseProbStatement() {
XCTAssertNoThrow(try {
let source = """
int x = 5
prob 0.5 { x = 2 }
int y = 2
"""
let ast = try parse(source)
let executionHistory = ExecutionHistory(history: [.stepOver, .stepIntoFalse, .stepOver])
let augmentedExecutionHistory = try executionHistory.augmented(with: ast).history
XCTAssertEqual(augmentedExecutionHistory.count, 3)
XCTAssertEqual(augmentedExecutionHistory[0].command, .stepOver)
XCTAssertEqual(augmentedExecutionHistory[0].stmt.range.sourceCode(in: source), "int x = 5")
XCTAssertEqual(augmentedExecutionHistory[1].command, .stepIntoFalse)
XCTAssertEqual(augmentedExecutionHistory[1].stmt.range.sourceCode(in: source), "prob 0.5 { x = 2 }")
XCTAssertEqual(augmentedExecutionHistory[2].command, .stepOver)
XCTAssertEqual(augmentedExecutionHistory[2].stmt.range.sourceCode(in: source), "int y = 2")
}())
}
func testGenerateAugmentedExecutionHistoryForLoop() {
XCTAssertNoThrow(try {
let source = """
int x = 5
while 0 < x { x = x - 1 }
int y = 2
"""
let ast = try parse(source)
let executionHistory = ExecutionHistory(history: [.stepOver, .stepIntoTrue, .stepOver, .stepOver])
let augmentedExecutionHistory = try executionHistory.augmented(with: ast).history
XCTAssertEqual(augmentedExecutionHistory.count, 4)
XCTAssertEqual(augmentedExecutionHistory[0].command, .stepOver)
XCTAssertEqual(augmentedExecutionHistory[0].stmt.range.sourceCode(in: source), "int x = 5")
XCTAssertEqual(augmentedExecutionHistory[1].command, .stepIntoTrue)
XCTAssertEqual(augmentedExecutionHistory[1].stmt.range.sourceCode(in: source), "while 0 < x { x = x - 1 }")
XCTAssertEqual(augmentedExecutionHistory[2].command, .stepOver)
XCTAssertEqual(augmentedExecutionHistory[2].stmt.range.sourceCode(in: source), "x = x - 1")
XCTAssertEqual(augmentedExecutionHistory[3].command, .stepOver)
XCTAssertEqual(augmentedExecutionHistory[3].stmt.range.sourceCode(in: source), "while 0 < x { x = x - 1 }")
}())
}
}
| true
|
5ecb06d9e40c85fdf67ac5b3e3876cdcb3ea153f
|
Swift
|
tesla-nikola/Assignments
|
/3.ArticleImplementation/ViperTest/ArticleList/Presenter/ArticlesListPresenter.swift
|
UTF-8
| 1,151
| 2.515625
| 3
|
[] |
no_license
|
//
// ArticlesListPresenter.swift
// ViperTest
//
// Created User-81-Mac on 01/10/18.
// Copyright © 2018 User-81-Mac. All rights reserved.
//
//
import UIKit
class ArticlesListPresenter: ArticlesListPresenterProtocol {
weak private var view: ArticlesListViewProtocol?
private let interactor: ArticlesListInteractorInputProtocol
private let wireframe: ArticlesListWireframeProtocol
init(interface: ArticlesListView, interactor: ArticlesListInteractorInputProtocol, wireframe: ArticlesListWireframeProtocol) {
self.view = interface
self.interactor = interactor
print("Hello darkness m old friend, i have to talk with you again, because of the scens that keep criping in")
self.wireframe = wireframe
self.interactor.presenter = self
}
func loadArticleDataFromServer() {
// call to interactor
view?.startActivityIndicator()
interactor.loadArticlesFromServer()
}
func fetchDataError(error: APIError) {
view?.stopActivityIndicator()
}
func fetchDataSuccessful(withData data: ArticleFeedResponse) {
view?.reloadData(data: data)
view?.stopActivityIndicator()
}
}
| true
|
76319b8bbeb0e5d862a3f2bef9523a3d2e0e4b06
|
Swift
|
RuiAAPeres/SquareStock
|
/SquareStock/API/Model/Stock.swift
|
UTF-8
| 939
| 3.171875
| 3
|
[] |
no_license
|
//
// Stock.swift
// SquareStock
//
// Created by Rui Peres on 05/05/2015.
// Copyright (c) 2015 Rui Peres. All rights reserved.
//
import Foundation
public struct Stock {
let symbol : String
let name : String
let currency : String
let price : Double
let delta : Double
}
extension Stock: JSONDecodable {
static func decode(json: JSON) -> Stock? {
return _JSONObject(json) >>= { d in
if let symbol = d["symbol"] >>= _JSONString,
let name = d["name"] >>= _JSONString,
let currency = d["currency"] >>= _JSONString,
let price = d["price"] >>= _JSONDouble,
let delta = d["delta"] >>= _JSONDouble
{
return Stock(symbol: symbol, name: name, currency: currency, price: price, delta: delta)
}
return nil
}
}
}
| true
|
c760f25bbccf074a0b28245200a82af3d386f920
|
Swift
|
alsauce/70K-Bands
|
/swift/70000TonsBands/externalUrls.swift
|
UTF-8
| 1,378
| 2.90625
| 3
|
[] |
no_license
|
//
// externalDataSources.swift
// 70000TonsBands
//
// Created by Ron Dorn on 1/4/15.
// Copyright (c) 2015 Ron Dorn. All rights reserved.
//
import Foundation
func getWikipediaPage (_ bandName: String) -> String{
var wikipediaUrl = String()
if (wikipediaLink[bandName]?.isEmpty == false){
wikipediaUrl = wikipediaLink[bandName]!;
let language: String = Locale.current.languageCode!
print ("Language is " + language);
if (language != "en"){
let replacement: String = language + ".wikipedia.org";
wikipediaUrl = wikipediaUrl.replacingOccurrences(of: "en.wikipedia.org", with:replacement)
}
}
return (wikipediaUrl)
}
func getYouTubePage (_ bandName: String) -> String{
var youTubeUrl = String()
if (youtubeLinks[bandName]?.isEmpty == false){
youTubeUrl = youtubeLinks[bandName]!;
let language: String = Locale.preferredLanguages[0]
if (language != "en"){
youTubeUrl = youTubeUrl + "&hl=" + language
}
}
return (youTubeUrl)
}
func getMetalArchives (_ bandName: String) -> String {
var metalArchives = String();
if (metalArchiveLinks[bandName]?.isEmpty == false){
metalArchives = metalArchiveLinks[bandName]!;
}
return (metalArchives)
}
| true
|
df412d2c0ce7447433f95e1c0e037280f62799a7
|
Swift
|
CoolCodeFactory/Antidote
|
/AntidoteArchitectureExample/UserFlowCoordinator.swift
|
UTF-8
| 14,349
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
//
// UserFlowCoordinator.swift
// AntidoteArchitectureExample
//
// Created by Dmitriy Utmanov on 16/09/16.
// Copyright © 2016 Dmitry Utmanov. All rights reserved.
//
import UIKit
class UserFlowCoordinator: CoordinatorProtocol {
var childCoordinators: [CoordinatorProtocol] = []
weak var navigationController: NavigationViewController!
var closeHandler: () -> () = { fatalError() }
let viewControllersFactory = UserViewControllersFactory()
func start(animated: Bool) {
fatalError()
}
@objc func end(_ sender: UIBarButtonItem) {
fatalError()
}
func finish(animated: Bool) {
fatalError()
}
fileprivate func presentUserViewController(withName name: String) {
fatalError()
}
}
class UserModalFlowCoordinator: UserFlowCoordinator, ModalCoordinatorProtocol {
weak var presentingViewController: UIViewController!
required init(presentingViewController: UIViewController) {
self.presentingViewController = presentingViewController
}
override func start(animated: Bool) {
let viewController = viewControllersFactory.usersTableViewController()
viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(end(_:)))
viewController.selectUserHandler = { [unowned self] name in
self.presentUserViewController(withName: name)
}
let navVC = viewControllersFactory.navigationController()
navVC.setViewControllers([viewController], animated: false)
presentingViewController.present(navVC, animated: true, completion: nil)
navigationController = navVC
}
override func finish(animated: Bool) {
removeAllChildCoordinators()
navigationController.dismiss(animated: animated, completion: nil)
let alertController = UIAlertController(title: "Finished!", message: "\(String(describing: self)) did finish", preferredStyle: UIAlertControllerStyle.alert)
let defaultAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)
alertController.addAction(defaultAction)
presentingViewController.present(alertController, animated: true, completion: nil)
}
@objc override func end(_ sender: UIBarButtonItem) {
closeHandler()
}
fileprivate override func presentUserViewController(withName name: String) {
let viewController = viewControllersFactory.userViewController(withName: name)
navigationController?.pushViewController(viewController, animated: true)
}
}
class UserNavigationFlowCoordinator: UserFlowCoordinator, NavigationCoordinatorProtocol {
weak var presentingNavigationController: NavigationViewController!
required init(presentingNavigationController: NavigationViewController) {
self.presentingNavigationController = presentingNavigationController
}
override func start(animated: Bool) {
let viewController = viewControllersFactory.usersTableViewController()
viewController.controllerCloseHandler = { [unowned self] in
self.closeHandler()
}
viewController.selectUserHandler = { [unowned self] name in
self.presentUserViewController(withName: name)
}
presentingNavigationController.pushViewController(viewController, animated: animated)
}
override func finish(animated: Bool) {
removeAllChildCoordinators()
let alertController = UIAlertController(title: "Finished!", message: "\(String(describing: self)) did finish", preferredStyle: UIAlertControllerStyle.alert)
let defaultAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)
alertController.addAction(defaultAction)
presentingNavigationController.present(alertController, animated: true, completion: nil)
}
@objc override func end(_ sender: UIBarButtonItem) {
closeHandler()
}
fileprivate override func presentUserViewController(withName name: String) {
let viewController = viewControllersFactory.userViewController(withName: name)
presentingNavigationController?.pushViewController(viewController, animated: true)
}
}
class UserMasterDetailFlowCoordinator: UserFlowCoordinator, MasterDetailCoordinatorProtocol {
weak var splitViewController: UISplitViewController!
required init(splitViewController: UISplitViewController) {
self.splitViewController = splitViewController
}
override func start(animated: Bool) {
let viewController = viewControllersFactory.usersTableViewController()
viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(end(_:)))
viewController.selectUserHandler = { [unowned self] name in
self.presentUserViewController(withName: name)
}
let navVC = viewControllersFactory.navigationController()
navVC.setViewControllers([viewController], animated: false)
splitViewController.viewControllers = [navVC]
}
override func finish(animated: Bool) {
removeAllChildCoordinators()
let alertController = UIAlertController(title: "Finished!", message: "\(String(describing: self)) did finish", preferredStyle: UIAlertControllerStyle.alert)
let defaultAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)
alertController.addAction(defaultAction)
splitViewController.presentingViewController?.present(alertController, animated: true, completion: nil)
}
@objc override func end(_ sender: UIBarButtonItem) {
closeHandler()
}
fileprivate override func presentUserViewController(withName name: String) {
let viewController = viewControllersFactory.userViewController(withName: name)
let navVC = viewControllersFactory.navigationController()
navVC.setViewControllers([viewController], animated: false)
splitViewController.showDetailViewController(navVC, sender: nil)
}
}
class UserPageBasedFlowCoordinator: UserFlowCoordinator, PageBasedCoordinatorProtocol {
weak var pageViewController: PageBasedViewController!
required init(pageViewController: PageBasedViewController) {
self.pageViewController = pageViewController
}
override func start(animated: Bool) {
let viewController = viewControllersFactory.usersTableViewController()
pageViewController.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(end(_:)))
viewController.selectUserHandler = { [unowned self] name in
self.presentUserViewController(withName: name)
}
if var viewControllers = pageViewController.viewControllers {
viewControllers.append(viewController)
pageViewController.setViewControllers(viewControllers)
} else {
pageViewController.setViewControllers([viewController])
}
}
override func finish(animated: Bool) {
removeAllChildCoordinators()
let alertController = UIAlertController(title: "Finished!", message: "\(String(describing: self)) did finish", preferredStyle: UIAlertControllerStyle.alert)
let defaultAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)
alertController.addAction(defaultAction)
pageViewController.presentingViewController?.present(alertController, animated: true, completion: nil)
}
@objc override func end(_ sender: UIBarButtonItem) {
closeHandler()
}
fileprivate override func presentUserViewController(withName name: String) {
let viewController = viewControllersFactory.userViewController(withName: name)
viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(end(_:)))
let viewControllers = pageViewController.viewControllers!
var filteredViewControllers = viewControllers.filter({ (viewController) -> Bool in
return !(viewController is UserViewController)
})
filteredViewControllers.append(viewController)
pageViewController.setViewControllers(filteredViewControllers)
let alertController = UIAlertController(title: "Second page appeared", message: "UserViewController opened in the second page", preferredStyle: UIAlertControllerStyle.alert)
let defaultAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)
alertController.addAction(defaultAction)
pageViewController.present(alertController, animated: true, completion: nil)
}
}
class UserTabbedFlowCoordinator: UserFlowCoordinator, TabbedCoordinatorProtocol {
weak var tabBarController: UITabBarController!
required init(tabBarController: UITabBarController) {
self.tabBarController = tabBarController
}
override func start(animated: Bool) {
let viewController = viewControllersFactory.usersTableViewController()
viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(end(_:)))
viewController.selectUserHandler = { [unowned self] name in
self.presentUserViewController(withName: name)
}
let navVC = viewControllersFactory.navigationController()
navVC.setViewControllers([viewController], animated: false)
if var viewControllers = tabBarController.viewControllers {
viewControllers.append(navVC)
tabBarController.setViewControllers(viewControllers, animated: false)
} else {
tabBarController.setViewControllers([navVC], animated: false)
}
}
override func finish(animated: Bool) {
removeAllChildCoordinators()
let alertController = UIAlertController(title: "Finished!", message: "\(String(describing: self)) did finish", preferredStyle: UIAlertControllerStyle.alert)
let defaultAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)
alertController.addAction(defaultAction)
tabBarController.presentingViewController?.present(alertController, animated: true, completion: nil)
}
@objc override func end(_ sender: UIBarButtonItem) {
closeHandler()
}
fileprivate override func presentUserViewController(withName name: String) {
let viewController = viewControllersFactory.userViewController(withName: name)
viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(end(_:)))
let navVC = viewControllersFactory.navigationController()
navVC.setViewControllers([viewController], animated: false)
let viewControllers = tabBarController.viewControllers!
var filteredViewControllers = viewControllers.filter({ (viewController) -> Bool in
guard let navVC = viewController as? NavigationViewController else { return true }
return !(navVC.viewControllers.first is UserViewController)
})
filteredViewControllers.append(navVC)
tabBarController.setViewControllers(filteredViewControllers, animated: false)
let alertController = UIAlertController(title: "Second tab appeared", message: "UserViewController opened in the second tab", preferredStyle: UIAlertControllerStyle.alert)
let defaultAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)
alertController.addAction(defaultAction)
tabBarController.present(alertController, animated: true, completion: nil)
}
}
class UserContainerFlowCoordinator: UserFlowCoordinator, ModalCoordinatorProtocol {
weak var presentingViewController: UIViewController!
required init(presentingViewController: UIViewController) {
self.presentingViewController = presentingViewController
}
override func start(animated: Bool) {
let viewController = viewControllersFactory.userContainerViewController()
viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(end(_:)))
viewController.usersViewControllerBuilder = { [unowned self, weak viewController] in
let usersTableViewController = self.viewControllersFactory.usersTableViewController()
usersTableViewController.selectUserHandler = { [weak viewController] name in
viewController?.updateUserViewController(name)
}
return usersTableViewController
}
viewController.userViewControllerBuilder = { [unowned self] name in
let userViewController = self.viewControllersFactory.userViewController(withName: name)
return userViewController
}
let navVC = viewControllersFactory.navigationController()
navVC.setViewControllers([viewController], animated: false)
presentingViewController.present(navVC, animated: true, completion: nil)
navigationController = navVC
}
@objc override func end(_ sender: UIBarButtonItem) {
closeHandler()
}
override func finish(animated: Bool) {
removeAllChildCoordinators()
navigationController.dismiss(animated: animated, completion: nil)
let alertController = UIAlertController(title: "Finished!", message: "\(String(describing: self)) did finish", preferredStyle: UIAlertControllerStyle.alert)
let defaultAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)
alertController.addAction(defaultAction)
presentingViewController.present(alertController, animated: true, completion: nil)
}
fileprivate override func presentUserViewController(withName name: String) {
}
}
| true
|
9a5d7fd37be8b014d151b20fe4af09d790904b5b
|
Swift
|
Paste1989/WeatherAppShowcase
|
/WeatherAppShowcase/Services/DataService.swift
|
UTF-8
| 3,036
| 3.1875
| 3
|
[] |
no_license
|
//
// DataService.swift
// WeatherAppShowcase
//
// Created by cobe on 06.09.2021..
//
import Foundation
import CoreLocation
//protocol DataServiceProtocol {
// func didUpdateData(_ weatherManager: DataService, weather: WeatherModel)
// func didFailWithError(error: Error)
//}
class DataService {
var onWeatherUpdateSuccess: ((WeatherModel)->Void)?
var onWeatherUpdateFailure: ((Error)->Void)?
let baseURL = "https://api.openweathermap.org/data/2.5/weather?appid=4dc5e730ec9e6a9cc99b8ebebfab801a&units=metric"
//var delegate: DataServiceProtocol?
func fetchWeatherDataForCity(with cityName: String) {
let urlString = "\(baseURL)&q=\(cityName)"
performRequest(with: urlString)
}
func fetchWeatherDataForLocation(latitude: CLLocationDegrees, longitude: CLLocationDegrees) {
let urlString = "\(baseURL)&lat=\(latitude)&lon=\(longitude)"
performRequest(with: urlString)
}
func performRequest(with urlString: String) {
if let url = URL(string: urlString) {
let session = URLSession(configuration: .default)
let task = session.dataTask(with: url) { (data, response, error) in
if error != nil {
//self.delegate?.didFailWithError(error: error!)
self.onWeatherUpdateFailure?(error!)
return
}
if let safeData = data {
if let weather = self.parseJSON(safeData) {
//self.delegate?.didUpdateData(self, weather: weather)
self.onWeatherUpdateSuccess?(weather)
}
}
}
task.resume()
}
}
func parseJSON(_ weatherData: Data) -> WeatherModel? {
let decoder = JSONDecoder()
do {
let decodedData = try decoder.decode(WeatherData.self, from: weatherData)
print(decodedData.weather)
let id = decodedData.weather[0].id
let name = decodedData.name
let temp = decodedData.main.temp
let minTemp = decodedData.main.temp_min
let maxTemp = decodedData.main.temp_max
let humidity = decodedData.main.humidity
let pressure = decodedData.main.pressure
let windSpeed = decodedData.wind.speed
let weatherData = WeatherModel(conditionId: id, cityName: name, temperature: temp, minTemp: minTemp, maxTemp: maxTemp, humidity: humidity, pressure: pressure, wind: Int(windSpeed))
print("name: \(weatherData.cityName)")
print("temp: \(weatherData.temperatureString)")
print("id: \(weatherData.conditionId)")
return weatherData
} catch {
//delegate?.didFailWithError(error: error)
onWeatherUpdateFailure?(error)
print(error)
return nil
}
}
}
| true
|
490165abe7f65583755f50ed0d6531321de9ad3e
|
Swift
|
Ivorforce/LED-Fan-Client
|
/LLED Client/Server/VideoEndpoint.swift
|
UTF-8
| 1,994
| 2.703125
| 3
|
[] |
no_license
|
//
// Endpoint.swift
// LLED Client
//
// Created by Lukas Tenbrink on 03.06.20.
// Copyright © 2020 Lukas Tenbrink. All rights reserved.
//
import Cocoa
import Network
class VideoConnection: ObservableObject {
let servers: ServerAssembly
let pool: ImagePool
var connections: [Server: NWConnection] = [:]
var fps: Double = 30 {
didSet { _flush() }
}
var isSending: Bool = false {
didSet { _flush() }
}
var observerToken: ResourcePool<NSImage>.ObservationToken?
init(servers: ServerAssembly, pool: ImagePool) {
self.servers = servers
self.pool = pool
}
func _flush() {
objectWillChange.send()
observerToken?.invalidate()
guard isSending else {
connections.values.forEach { $0.cancel() }
connections = [:]
return
}
connections = [:]
for server in servers.available {
guard let connection = ArtnetProvider.connection(host: server.urlString) else {
print("Lost connection to server: \(server)")
continue
}
connection.start(queue: .global())
connections[server] = connection
}
observerToken = pool.observe(delay: .seconds(1 / fps)) { image in
for (server, connection) in self.connections {
guard let screenMode = server.screenMode else {
print("Lost screen mode for server \(server)")
continue
}
let payload = screenMode.pack(image: image)
let packets = server.artnet.pack(payload: payload)
for packet in packets {
connection.send(content: packet, completion: NWConnection.SendCompletion.idempotent)
}
}
}
}
deinit {
isSending = false
_flush()
}
}
| true
|
7b81c5240b20572a28f126942bc3a00575bd6252
|
Swift
|
Blackjacx/Playgrounds
|
/playgrounds/ServiceArea.playground/Contents.swift
|
UTF-8
| 3,377
| 3.171875
| 3
|
[
"MIT"
] |
permissive
|
import Foundation
import CoreLocation
struct EmptyResponse: Decodable {}
struct ServiceArea: Decodable {
enum CodingKeys: String, CodingKey {
case regions = "coordinates"
}
/// These are the holes we cut out from the world polygon. Consider their holes as islands that have to be drawn as
/// separate polygons without holes.
let regions: [Polygon]
}
extension ServiceArea {
static let worldCoordinates = LinearRing(coordinates: [
CLLocationCoordinate2D(latitude: 85, longitude: 90),
CLLocationCoordinate2D(latitude: 85, longitude: 0.1),
CLLocationCoordinate2D(latitude: 85, longitude: -90),
CLLocationCoordinate2D(latitude: 85, longitude: -179.9),
CLLocationCoordinate2D(latitude: 0, longitude: -179.9),
CLLocationCoordinate2D(latitude: -85, longitude: -179.9),
CLLocationCoordinate2D(latitude: -85, longitude: -90),
CLLocationCoordinate2D(latitude: -85, longitude: 0.1),
CLLocationCoordinate2D(latitude: -85, longitude: 90),
CLLocationCoordinate2D(latitude: -85, longitude: 179.9),
CLLocationCoordinate2D(latitude: 0, longitude: 179.9),
CLLocationCoordinate2D(latitude: 85, longitude: 179.9)
])
/// A LinearRing that can contain holes
struct Polygon: Decodable {
let outerRing: LinearRing
let holes: [LinearRing]
init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
var linearRings: [LinearRing] = []
while !container.isAtEnd {
do {
let ring = try container.decode(LinearRing.self)
linearRings.append(ring)
} catch {
_ = try container.decode(EmptyResponse.self) // skip undecodable item
}
}
outerRing = linearRings.first ?? LinearRing()
holes = Array(linearRings.dropFirst())
}
}
/// A simple array of coordinates. It cannot conatin holes like polygons
struct LinearRing: Decodable {
let coordinates: [CLLocationCoordinate2D]
init(coordinates: [CLLocationCoordinate2D] = []) {
self.coordinates = coordinates
}
init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
var coordinates: [[CLLocationDegrees]] = []
while !container.isAtEnd {
do {
let latLngArray = Array(try container.decode([CLLocationDegrees].self))
guard latLngArray.count == 2, let lat = latLngArray.first, let lng = latLngArray.last else { continue }
coordinates.append([lat, lng])
} catch {
_ = try container.decode(EmptyResponse.self) // skip undecodable item
}
}
self.coordinates = Array(coordinates
.map { CLLocationCoordinate2D(latitude: $0[0], longitude: $0[1]) })
}
}
}
let decoder = JSONDecoder()
let geoJsonPath = Bundle.main.path(forResource: "geo_01", ofType: "json")!
let data = FileManager.default.contents(atPath: geoJsonPath)!
let serviceArea = try decoder.decode(ServiceArea.self, from: data)
serviceArea.regions.forEach { print("\($0)\n\n") }
print("Regions: \(serviceArea.regions.count)")
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.