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
53c58e3f613ebfedfe6aa4083e874ba29a3fcfb7
Swift
moj3ve/Hidden-Widgets
/HomeScreenSpaces/Measurements.swift
UTF-8
3,964
2.578125
3
[ "MIT" ]
permissive
// // Measurements.swift // HomeScreenSpaces // // Created by Aryan Chaubal on 8/4/20. // import Foundation class Measurements { // fileprivate static let SIZE_PLACEHOLDER = 200 //// Width and height of the widget static let WIDGET_SIZE: [String: Int] = [ // Standard Dispay Mode "828x1792": 338, // iPhone XR, iPhone 11 "1242x2688": 507, // iPhone XS Max, iPhone 11 Pro Max "1125x2436": 465, // iPhone X, iPhone XS, iPhone 11 Pro "1242x2208": 471, // iPhone 6 Plus, iPhone 6S Plus, iPhone 7 Plus, iPhone 8 Plus "750x1334": 296, // iPhone 6, iPhone 6S, iPhone 7, iPhone 8, iPhone SE 2 "640x1136": 282, // iPhone 5, iPhone 5S, iPhone 5C, iPhone SE, iPod Touch 7 // Zoomed Display Mode "750x1624": 310, // iPhone XR, iPhone 11 "1125x2001": 444, // iPhone 6 Plus, iPhone 6S Plus, iPhone 7 Plus, iPhone 8 Plus ] //// Vertical spacing between top edges of two widgets static let VERTICAL_SPACING: [String: Int] = [ // Standard Dispay Mode "828x1792": 420, // iPhone XR, iPhone 11 "1242x2688": 630, // iPhone XS Max, iPhone 11 Pro Max "1125x2436": 570, // iPhone X, iPhone XS, iPhone 11 Pro "1242x2208": 582, // iPhone 6 Plus, iPhone 6S Plus, iPhone 7 Plus, iPhone 8 Plus "750x1334": 352, // iPhone 6, iPhone 6S, iPhone 7, iPhone 8, iPhone SE 2 "640x1136": 340, // iPhone 5, iPhone 5S, iPhone 5C, iPhone SE, iPod Touch 7 // Zoomed Display Mode "750x1624": 380, // iPhone XR, iPhone 11 "1125x2001": 528, // iPhone 6 Plus, iPhone 6S Plus, iPhone 7 Plus, iPhone 8 Plus ] //// Vertical spacing between right edges of two widgets static let HORIZONTAL_SPACING: [String: Int] = [ // Standard Dispay Mode "828x1792": 382, // iPhone XR, iPhone 11 "1242x2688": 573, // iPhone XS Max, iPhone 11 Pro Max "1125x2436": 522, // iPhone X, iPhone XS, iPhone 11 Pro "1242x2208": 573, // iPhone 6 Plus, iPhone 6S Plus, iPhone 7 Plus, iPhone 8 Plus "750x1334": 346, // iPhone 6, iPhone 6S, iPhone 7, iPhone 8, iPhone SE 2 "640x1136": 302, // iPhone 5, iPhone 5S, iPhone 5C, iPhone SE, iPod Touch 7 // Zoomed Display Mode "750x1624": 348, // iPhone XR, iPhone 11 "1125x2001": 519, // iPhone 6 Plus, iPhone 6S Plus, iPhone 7 Plus, iPhone 8 Plus ] //// Space between top edge of widget and image (screenshot) static let TOP_SPACING: [String: Int] = [ // Standard Dispay Mode "828x1792": 160, // iPhone XR, iPhone 11 "1242x2688": 228, // iPhone XS Max, iPhone 11 Pro Max "1125x2436": 213, // iPhone X, iPhone XS, iPhone 11 Pro "1242x2208": 114, // iPhone 6 Plus, iPhone 6S Plus, iPhone 7 Plus, iPhone 8 Plus "750x1334": 60, // iPhone 6, iPhone 6S, iPhone 7, iPhone 8, iPhone SE 2 "640x1136": 60, // iPhone 5, iPhone 5S, iPhone 5C, iPhone SE, iPod Touch 7 // Zoomed Display Mode "750x1624": 142, // iPhone XR, iPhone 11 "1125x2001": 90, // iPhone 6 Plus, iPhone 6S Plus, iPhone 7 Plus, iPhone 8 Plus ] //// Space between left edge of widget and image (screenshot) static let LEFT_SPACING: [String: Int] = [ // Standard Dispay Mode "828x1792": 54, // iPhone XR, iPhone 11 "1242x2688": 81, // iPhone XS Max, iPhone 11 Pro Max "1125x2436": 69, // iPhone X, iPhone XS, iPhone 11 Pro "1242x2208": 99, // iPhone 6 Plus, iPhone 6S Plus, iPhone 7 Plus, iPhone 8 Plus "750x1334": 54, // iPhone 6, iPhone 6S, iPhone 7, iPhone 8, iPhone SE 2 "640x1136": 28, // iPhone 5, iPhone 5S, iPhone 5C, iPhone SE, iPod Touch 7 // Zoomed Display Mode "750x1624": 46, // iPhone XR, iPhone 11 "1125x2001": 81, // iPhone 6 Plus, iPhone 6S Plus, iPhone 7 Plus, iPhone 8 Plus ] }
true
48ded303febf7199955b62342733e537935ebf47
Swift
VyNguyen0102/MVVM-Practice
/MVVMPractice/ViewsViewModels/CollectionSampleModule/CollectionDetailViewController.swift
UTF-8
1,365
2.640625
3
[]
no_license
// // CollectionDetalViewController.swift // MVVMPractice // // Created by iOS Dev on 8/22/19. // Copyright © 2019 iOS Dev. All rights reserved. // import UIKit import RxSwift class CollectionDetailViewController: UIViewController { @IBOutlet private weak var avatarImageView: UIImageView! @IBOutlet private weak var nameLabel: UILabel! { didSet { nameLabel.style.mediumRegular().black() } } @IBOutlet private weak var emailLabel: UILabel! { didSet { emailLabel.style.mediumRegular().black() } } @IBOutlet private weak var favoriteButton: FavoriteCheckBox! weak var viewModel: CollectionViewModel! private let disposeBag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() setupReactive() } private func setupReactive() { viewModel.selectedUser.asObservable().ignoreNil().subscribe(onNext: { user in self.configure(user: user) }).disposed(by: disposeBag) } private func configure(user: User) { favoriteButton.isChecked = user.isFavorite.value favoriteButton.bind(value: user.isFavorite).disposed(by: disposeBag) avatarImageView.loadAvatarUrlString(urlString: user.avatar) nameLabel.text = user.name emailLabel.text = user.email } }
true
2a5773319a301f8c26216465d8bfd81e28110ec1
Swift
jonathanzw-eb/KhanAcademyBadges
/KhanAcademyBadges/Category.swift
UTF-8
444
2.578125
3
[]
no_license
// // Category.swift // KhanAcademyBadges // // Created by Jonathan Wang on 1/13/17. // Copyright © 2017 JonathanWang. All rights reserved. // import UIKit class Category: NSObject { var name : String var categoryDescription : String var imageUrl : String init (name : String, description : String, url : String) { self.name = name self.categoryDescription = description self.imageUrl = url } }
true
69f74e9b8131794a94d6efacd7f3890a13f47e88
Swift
johannesbjur/movie-diary-app
/MovieDiary/MovieDiary/Movie.swift
UTF-8
1,695
3.3125
3
[]
no_license
// // Movie.swift // MovieDiary // // Created by Johannes Bjurströmer on 2020-01-17. // Copyright © 2020 Johannes Bjurströmer. All rights reserved. // import Foundation import Firebase class Movie { var title: String let comment: String let rating: Int let date: String var fireStoreId: String? init( title: String, comment: String, rating: Int ) { let formatter = DateFormatter() formatter.dateFormat = "yyyy/MM/dd" self.title = title self.comment = comment self.rating = rating self.date = formatter.string( from: Date() ) } // Constructor using item from database // Returns nil if a value is missing init?( snapshot: QueryDocumentSnapshot ) { let snapshotValue = snapshot.data() as [String: Any] guard let title = snapshotValue["title"] as? String else { return nil } guard let comment = snapshotValue["comment"] as? String else { return nil } guard let rating = snapshotValue["rating"] as? Int else { return nil } guard let date = snapshotValue["date"] as? String else { return nil } self.title = title self.comment = comment self.rating = rating self.date = date self.fireStoreId = snapshot.documentID } // Returns movie item as dictionary to save in firebase func toDict() -> [String: Any] { return [ "title": self.title, "comment": self.comment, "rating": self.rating, "date": self.date ] } }
true
512c5ac8dd9fde50fceba6660600d58a31a06c4d
Swift
jcollas/antikythera
/AntikytheraOpenGLPrototype_v3/Classes/ConnectorInfo.swift
UTF-8
459
2.5625
3
[ "MIT" ]
permissive
// // ConnectorInfo.swift // AntikytheraOpenGLPrototype // // Created by Juan J. Collas on 7/6/2020. // import Foundation struct ConnectorInfo: Decodable { enum CodingKeys: String, CodingKey { case name case radius case topGear case bottomGear case connectionType = "connector-type" } var name: String var radius: Float var topGear: String var bottomGear: String var connectionType: String }
true
b69dd52c637d9e4672bac9dac88b16271100b947
Swift
wfltaylor/PopDatePicker
/PopDatePicker/PopDatePicker.swift
UTF-8
2,839
2.5625
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
// // PopDatePicker.swift // PopDatePicker // // Created by Adam Hartford on 4/22/15. // Copyright (c) 2015 Adam Hartford. All rights reserved. // import Cocoa public class PopDatePicker: NSDatePicker { let controller = PopDatePickerController() let popover = NSPopover() var showingPopover = false public var preferredPopoverEdge = NSRectEdge.maxX public var shouldShowPopover = { return true } public override func awakeFromNib() { action = "dateAction" controller.datePicker.action = "popoverDateAction" controller.datePicker.bind(NSBindingName.value, to: self, withKeyPath: "dateValue", options: nil) popover.contentViewController = controller popover.behavior = .semitransient } func popoverDateAction() { if let bindingInfo = infoForBinding(NSBindingName.value) as? NSDictionary { if let keyPath = bindingInfo.value(forKey: NSBindingInfoKey.observedKeyPath.rawValue) as? String { (bindingInfo.value(forKey: NSBindingInfoKey.observedObject.rawValue) as AnyObject).setValue(dateValue, forKeyPath: keyPath) } } } func dateAction() { controller.datePicker.dateValue = dateValue } public override func mouseDown(with theEvent: NSEvent) { becomeFirstResponder() super.mouseDown(with: theEvent) } public override func becomeFirstResponder() -> Bool { if shouldShowPopover() { showingPopover = true controller.datePicker.dateValue = dateValue popover.show(relativeTo: bounds, of: self, preferredEdge: preferredPopoverEdge) showingPopover = false } return super.becomeFirstResponder() } public override func resignFirstResponder() -> Bool { if showingPopover { return false } popover.close() return super.resignFirstResponder() } } class PopDatePickerController: NSViewController { let datePicker: NSDatePicker required init?(coder: NSCoder) { datePicker = NSDatePicker() super.init(coder: coder) } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { datePicker = NSDatePicker(frame: NSMakeRect(22, 17, 139, 148)) super.init(nibName: nil, bundle: nil) let popoverView = NSView(frame: NSMakeRect(0, 0, 180, 180)) datePicker.datePickerStyle = .clockAndCalendar datePicker.drawsBackground = false let cell = datePicker.cell as? NSDatePickerCell cell?.isBezeled = false cell?.sendAction(on: NSEvent.EventTypeMask(rawValue: UInt64(Int(NSEvent.EventType.leftMouseDown.rawValue)))) popoverView.addSubview(datePicker) view = popoverView } }
true
cccda214e99a2cc563cee0bb29598a4a383c92b7
Swift
chenchangqing/learniosanimation
/example02/example02/ProgressView.swift
UTF-8
1,709
3.015625
3
[ "Apache-2.0" ]
permissive
// // ProgressView.swift // example02 // // Created by green on 15/8/12. // Copyright (c) 2015年 green. All rights reserved. // import UIKit class ProgressView: UIView { // 进度条 private var progressLayer : CALayer! // 进度条颜色 var progressColor = UIColor.greenColor().CGColor { willSet { progressLayer.backgroundColor = newValue } } // 进度 var progressValue : Float = 0 { willSet { if newValue <= 0 { progressLayer.frame = CGRectMake(0, 0, 0, CGRectGetHeight(self.bounds)) } else if newValue <= 1 { progressLayer.frame = CGRectMake(0, 0, CGRectGetWidth(self.bounds) * CGFloat(newValue), CGRectGetHeight(self.bounds)) } else { progressLayer.frame = CGRectMake(0, 0, CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds)) } } } override init(frame:CGRect) { super.init(frame: frame) setup() } required init(coder aDecoder: NSCoder) { super.init(coder:aDecoder)! setup() } /** * 设置layer */ private func setup() { self.layer.borderWidth = 1 if progressLayer == nil { progressLayer = CALayer() progressLayer.frame = CGRectMake(0, 0, 50, self.frame.size.height) progressLayer.backgroundColor = progressColor self.layer.addSublayer(progressLayer) } } }
true
7a0ea1b833aceabb8baeef962413e9b650fe2ee9
Swift
kotsuya/RxMemo
/RxMemo/Model/Memo.swift
UTF-8
746
2.9375
3
[]
no_license
// // Memo.swift // RxMemo // // Created by seunghwan.yoo on 2020/01/15. // Copyright © 2020 seunghwan.yoo. All rights reserved. // import Foundation import RxDataSources // RxDataSources // tableView, collectionView binding できる datasourceを提供する // **IdentifiableType 必要 struct Memo: Equatable, IdentifiableType { var content: String var insertDate: Date var identity: String init(content: String, insertDate: Date = Date()) { self.content = content self.insertDate = insertDate self.identity = "\(insertDate.timeIntervalSinceReferenceDate)" } init(original: Memo, updatedContent: String) { self = original self.content = updatedContent } }
true
298c7cd175f4433afe2fa6f1381e39b1201e0cc0
Swift
dchwojko/VirtualTourist
/VirtualTourist/Photo+CoreDataClass.swift
UTF-8
1,111
2.78125
3
[]
no_license
// // Photo+CoreDataClass.swift // VirtualTourist // // Created by DONALD CHWOJKO on 10/24/16. // Copyright © 2016 DONALD CHWOJKO. All rights reserved. // import Foundation import CoreData import UIKit public class Photo: NSManagedObject { var image: UIImage? { get { if let imageData = imageData { return UIImage(data: imageData as Data) } else { return nil } } } static func photosFromArrayOfDictionaries(dictionaries: [[String:AnyObject]], context: NSManagedObjectContext) -> [Photo] { var photos = [Photo]() for photoDictionary in dictionaries { context.performAndWait({ let entity = NSEntityDescription.entity(forEntityName: "Photo", in: context) let photo = NSManagedObject(entity: entity!, insertInto: context) as! Photo photo.imagePath = photoDictionary["url_m"] as? String photos.append(photo) }) } return photos } }
true
90b27b9c71b326b822f06fb75a56572c508739da
Swift
kamakinto/Red-Haki
/Red Haki/StrangerViewController.swift
UTF-8
2,476
2.515625
3
[]
no_license
// // StrangerViewController.swift // Red Haki // // Created by Everett Robinson on 4/8/16. // Copyright © 2016 Everett Robinson. All rights reserved. // import UIKit class StrangerViewController: UIViewController, UIPickerViewDelegate { @IBOutlet weak var quickStatusUILabel: UILabel! @IBOutlet weak var statusPickerUIPicker: UIPickerView! @IBOutlet weak var detailsTextView: UITextView! var statusPicked: String = "" var strangerOptions = ["Followed", "Verbally assaulted", "Physically assaulted"] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int{ return 1 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{ return strangerOptions.count } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?{ return strangerOptions[row] } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { print(strangerOptions[row]) statusPicked = strangerOptions[row] } @IBAction func notifyButton(sender: AnyObject) { let problem = statusPicked let description = detailsTextView.text let longitude = LocationService.sharedInstance.longitude let latitude = LocationService.sharedInstance.latitude if problem == "Followed" { //send info to friends that you are being followed. do NOT upload geolocation to general public. } else{ //configure data to send UserStatus.sharedInstance.updateUserStatus("Stranger", type: problem, desc: description, date: Timestamp, longitude: longitude, latitude: latitude, mediaUrl: "https://") UserData.sharedInstance.status_flag = true let statusUpdate = UserStatus.sharedInstance.toJson() CURRENT_USER_STATUS.setValue(statusUpdate) } // navigate to look around tab tabBarController?.selectedIndex = 1 tabBarController?.tabBar.hidden = false self.navigationController?.popToRootViewControllerAnimated(false) } }
true
78c66590699065548f18a5163accedca510440af
Swift
apple/swift-package-manager
/Sources/PackagePlugin/Errors.swift
UTF-8
2,189
2.546875
3
[ "Apache-2.0", "BSD-3-Clause", "MIT", "LicenseRef-scancode-unknown-license-reference", "Swift-exception" ]
permissive
//===----------------------------------------------------------------------===// // // This source file is part of the Swift open source project // // Copyright (c) 2021-2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// public enum PluginContextError: Error { /// Could not find a tool with the given name. This could be either because /// it doesn't exist, or because the plugin doesn't have a dependency on it. case toolNotFound(name: String) /// Tool is not supported on the target platform case toolNotSupportedOnTargetPlatform(name: String) /// Could not find a target with the given name. case targetNotFound(name: String, package: Package) /// Could not find a product with the given name. case productNotFound(name: String, package: Package) } extension PluginContextError: CustomStringConvertible { public var description: String { switch self { case .toolNotFound(let name): return "Plugin does not have access to a tool named ‘\(name)’" case .toolNotSupportedOnTargetPlatform(let name): return "Tool ‘\(name)’ is not supported on the target platform" case .targetNotFound(let name, let package): return "Package ‘\(package.displayName)’ has no target named ‘\(name)’" case .productNotFound(let name, let package): return "Package ‘\(package.displayName)’ has no product named ‘\(name)’" } } } public enum PluginDeserializationError: Error { /// The input JSON is malformed in some way; the message provides more details. case malformedInputJSON(_ message: String) } extension PluginDeserializationError: CustomStringConvertible { public var description: String { switch self { case .malformedInputJSON(let message): return "Malformed input JSON: \(message)" } } }
true
c33dcd5f52d5de498c3ca2c68f58684066c69b01
Swift
danielctull/Advent-of-Code
/Year2021/Tests/Day07Tests.swift
UTF-8
953
2.796875
3
[ "BSD-3-Clause" ]
permissive
import Advent import Year2021 import Year2019 import XCTest final class Day07Tests: XCTestCase { func testPart1Examples() throws { XCTAssertEqual(try Year2021.Day07.part1(["16,1,2,0,4,2,7,1,2,14"]), 37) } func testPart1Puzzle() throws { let input = try Bundle.module.input(named: "Day07") XCTAssertEqual(try Year2021.Day07.part1(input), 344535) } func testPart2Examples() throws { XCTAssertEqual(try Year2021.Day07.part2(["16,1,2,0,4,2,7,1,2,14"]), 168) } func testPart2Puzzle() throws { let input = try Bundle.module.input(named: "Day07") XCTAssertEqual(try Year2021.Day07.part2(input), 95581659) } func testIntcode() throws { let input = try Bundle.module.input(named: "Day07") var computer = IntcodeComputer(input: input) try computer.run() XCTAssertEqual(computer.ascii.output, "Ceci n'est pas une intcode program\n") } }
true
95e5c6188437bcf3ae3c68d3127eb73c88e19646
Swift
kyunooh/coursera-ios
/ImageProcessor.playground/Sources/BlueFilter.swift
UTF-8
1,552
2.890625
3
[]
no_license
import UIKit public class BlueFilter: RGBAImage { public func blueImage(level: Int) -> UIImage? { let colorSpace = CGColorSpaceCreateDeviceRGB() var bitmapInfo: UInt32 = CGBitmapInfo.ByteOrder32Big.rawValue bitmapInfo |= CGImageAlphaInfo.PremultipliedLast.rawValue & CGBitmapInfo.AlphaInfoMask.rawValue let bytesPerRow = width * 4 let imageDataReference = UnsafeMutablePointer<Pixel>(pixels) for h in 0..<height { for w in 0..<width { let i = h * width + w let green = Float(imageDataReference[i].green) - (Float(level) * 2.55) imageDataReference[i].green = UInt8(max(0, min(255, green))) let blue = Float(imageDataReference[i].blue) + (Float(level) * 2.55) imageDataReference[i].blue = UInt8(max(0, min(255, blue))) let red = Float(imageDataReference[i].red) - (Float(level) * 2.55) imageDataReference[i].red = UInt8(max(0, min(255, red))) } } defer { imageDataReference.destroy() } let imageContext = CGBitmapContextCreateWithData(imageDataReference, width, height, 8, bytesPerRow, colorSpace, bitmapInfo, nil, nil) guard let cgImage = CGBitmapContextCreateImage(imageContext) else {return nil} let image = UIImage(CGImage: cgImage) return image } }
true
393548091c4da0e8cb817baaa63499085f14b0ab
Swift
Humayan-Kabir/EggTimer-iOS13
/EggTimer/Model/EggBoiler.swift
UTF-8
319
2.515625
3
[]
no_license
// // EggBoiler.swift // EggTimer // // Created by SRBD on 2/16/21. // Copyright © 2021 The App Brewery. All rights reserved. // import Foundation class EggBoiler { let boilTime = ["Soft": 8, "Medium": 10, "Hard": 12] var progress: Double? init() { progress = 0.0 } }
true
d5333fc4a9a218473fa8f13cbdb778b16d936a3e
Swift
YannMeur/YMMathLib
/YMMathLib/Classes/old_Matrice.swift
UTF-8
18,420
3.265625
3
[ "MIT" ]
permissive
// // Matrice.swift // MyMathLibPackageDescription // // Created by Yann Meurisse on 29/01/2018. // // Modifié le 06/02/2018 à 16H20 depuis StatNotes // // Ancienne version où les données (data) de la Matrice sont // lues ligne par ligne import Foundation import Accelerate postfix operator ° /*********************************************************/ /// Implémente la notion mathématique de Matrice (de Double) /// avec les principales opérations classiques : /// /// TODO: Lister les opérations /*********************************************************/ public class Matrice: CustomStringConvertible { // Tableau qui contient les composantes du vecteur // ATTENTION : lues ligne par ligne !! var data: [Double] = [] // Dimension du vecteur. var (nbl, nbc) = (0,0) /********************************************************/ /// Initialise la Matrice /// /// - parameters: /// - datas: : Tableau (unidimensionnel) des Doubles, de longueur /// nbl*nbc, rangés implicitement ligne par ligne /// - nbl: : Nombre de lignes /// - nbc: : Nombre de colonnes /*********************************************************/ public init(_ datas: [Double], nbl: Int, nbc: Int) { if datas.count == nbl*nbc { for element in datas { self.data.append(element) } self.nbc = nbc self.nbl = nbl } else { print("Erreur : Nb d'éléments du tableau != nbl*nbc !!") } } /********************************************************/ /// Initialise la Matrice /// /// - parameters: /// - datas: : Tableau (unidimensionnel) des Doubles, de longueur /// nbl*nbc, rangés implicitement ligne par ligne /// - nbl: : Nombre de lignes /// - nbc: : Nombre de colonnes /// - rangement: : si = "c" ou "C" => rangement colonne/colonne /// sinon rangement par défaut (ligne/ligne) /*********************************************************/ public init(_ datas: [Double], nbl: Int, nbc: Int, rangement: String) { if datas.count == nbl*nbc { if rangement == "c" || rangement == "C" { let T = (Matrice(datas, nbl: nbc, nbc: nbl ))° self.data = T.data } else { for element in datas { self.data.append(element) } } self.nbc = nbc self.nbl = nbl } else { print("Erreur : Nb d'éléments du tableau != nbl*nbc !!") } } public init(_ M: Matrice) { self.data = M.data self.nbc = M.nbc self.nbl = M.nbl } public init(nbl: Int, nbc: Int) { self.data = Array(repeating: 0.0, count: nbl*nbc) self.nbc = nbc self.nbl = nbl } public init(nbl: Int) { self.data = Array(repeating: 0.0, count: nbl*nbl) self.nbl = nbl self.nbc = nbl } /*********************************************************/ /// Implémente la conversion en String pour "\\(Matrice)" /*********************************************************/ public var description: String { var result = "" for l in 0...nbl-1 { for c in 0...nbc-1 { let element = data[l*nbc + c] if element == 0.0 { result += "0.0 \t" } else if abs(element) < 1.0e-10 { result += " "+epsilonCar+" \t" } else { //result += "\(round(element*100)/100)\t" result += String(format: "%.3f", element)+"\t" } } result.removeLast() result += "\n" } return result } /*********************************************************/ /// Retourne la dim. de la matrice sous forme de String /*********************************************************/ public func dim() -> String { return "\(self.nbl)X\(self.nbc)" } /********************************************************* Implémente la notion d'indice (subscript) pour "\(Matrice)" *********************************************************/ public subscript(_ x: Int,_ y: Int) -> Double { get { return self.data[x*self.nbc + y] } set { self.data[x*self.nbc + y] = newValue } } /*********************************************************/ /// Implémente la transposition d'une Matrice à l'aide d'un /// opérateur postfixé "°" /// Retourne la transposée de la Matrice /*********************************************************/ public static postfix func °(m: Matrice) -> Matrice { var data: [Double] = [] for i in 0...m.nbc-1 { for j in 0...m.nbl-1 { data.append(m[j,i]) } } return Matrice(data,nbl: m.nbc,nbc: m.nbl) } /********************************************************* Implémente le "*" de 2 Matrices TODO : vérifier compatibilité des dimensions *********************************************************/ public static func *(lhs: Matrice, rhs: Matrice) -> Matrice? { if (lhs.nbc != rhs.nbl) { print("Dimensions incompatibles !") return nil } else { var data: [Double] = [] for i in 0...lhs.nbl-1 { for j in 0...rhs.nbc-1 { data.append((lhs.ligne(i)*rhs.colonne(j))!) } } return Matrice(data,nbl: lhs.nbl,nbc: rhs.nbc) } } /********************************************************* Implémente le "*" d'un scalaire et d'une Matrice *********************************************************/ public static func *(lhs: Double,rhs: Matrice) -> Matrice? { var data: [Double] = [] for elem in rhs.data { data.append(lhs*elem) } return Matrice(data,nbl: rhs.nbl,nbc: rhs.nbc) } /********************************************************* Implémente le "/" d'une Matrice et d'un scalaire (Double) TODO : gérer diviseur = 0.0 (sans doute peux mieux faire avec func generic) *********************************************************/ public static func /(lhs: Matrice, rhs: Double) -> Matrice? { var data: [Double] = [] for elem in lhs.data { data.append(elem/rhs) } return Matrice(data,nbl: lhs.nbl,nbc: lhs.nbc) } /********************************************************* Implémente le "/" d'une Matrice et d'un scalaire (Int) TODO : gérer diviseur = 0.0 (sans doute peux mieux faire avec func generic) *********************************************************/ public static func /(lhs: Matrice, rhs: Int) -> Matrice? { var data: [Double] = [] for elem in lhs.data { data.append(elem/Double(rhs)) } return Matrice(data,nbl: lhs.nbl,nbc: lhs.nbc) } /*********************************************************/ /// Fonction qui retourne une ligne, sous forme d'un Vecteur, /// de la matrice. /// /// TODO: Gérer les erreurs d'indice /// - parameters: /// - ind: : Indice de la ligne à retourner 0 ≤ .. < nbl /*********************************************************/ public func ligne(_ ind: Int) -> Vecteur { return (Vecteur(Array(self.data[ind*self.nbc...(ind+1)*self.nbc - 1]))).transpose() } /*********************************************************/ /// Fonction qui retourne une colonne, sous forme d'un Vecteur, /// de la matrice /// /// TODO: Gérer les erreurs d'indice /// - parameters: /// - ind: : Indice de la ligne à retourner 0 ≤ .. < nbc /*********************************************************/ public func colonne(_ ind: Int) -> Vecteur { var tempArray: [Double] = [] for i in stride(from: ind, to: ind+(self.nbl)*self.nbc, by: self.nbc) { tempArray.append(self.data[i]) } return Vecteur(tempArray) } /*******************************************************************/ /// Retourne une matrice Identité de même dimension /********************************************************************/ public func eye() -> Matrice { let zeros = Array(repeating: 0.0, count: self.nbl*self.nbc) let I = Matrice(zeros,nbl: self.nbl, nbc: self.nbc) for i in 0...self.nbc-1 { I[i,i] = 1.0 } return I } /*******************************************************************/ /// Retourne la matrice "stochastique" associée : /// somme des éléments de chaque lignes (tous≥0) = 1 /********************************************************************/ public func stochastique() -> Matrice? { let result = Matrice(self) for x in 0...self.nbl-1 { let coef = (self.ligne(x)).somme() if coef != 0.0 { for y in 0...self.nbc-1 { result[x,y] /= coef } } /* else { print("Pb : somme d'une ligne = 0") return nil } */ } return result } /*******************************************************************/ /// Fonction qui retourne une Matrice trangulaire sup. "équivalente" /// à la Matrice (carrée) fournie. /// /// Fonction utilisée pour l'inversion par pivot de Gauss /// /// TODO: Gérer les erreurs d'indice /*******************************************************************/ public func triangSup(_ A: Matrice) -> Matrice { let B: Matrice = Matrice(A) let n = A.nbc for j in 0...n-2 { // On trouve i entre j et n-1 tel que |A(i,j)| soit maximal var indTrouve = j var absAijCourant: Double = abs(A[indTrouve,j] ) for i in j+1...n-1 { if abs(A[i,j]) > absAijCourant { indTrouve = i absAijCourant = abs(A[i,j]) } } // On échange Ligne(indTrouve) et Ligne(j) let tempo = B.data[indTrouve*n...(indTrouve+1)*n-1] B.data[indTrouve*n...(indTrouve+1)*n-1] = B.data[j*n...(j+1)*n-1] B.data[j*n...(j+1)*n-1] = tempo // on fait apparaitre les "0" sous la diagonale for i in j+1...n-1 { let ligneTempo = B.ligne(i) - (B[i,j]/B[j,j]) * B.ligne(j) B.data[i*n...(i+1)*n-1] = (ligneTempo?.data[0...n-1])! } } return B } /*******************************************************************/ /// Fonction qui retourne l'inverse d'une Matrice carrée /// /// Pour l'instant : /// /// let A = Matrice([8.0,1,6,3,5,7,4,9,2],nbl: 3,nbc: 3) /// let B = A.inv() /// /// TODO: Gérer les erreurs d'indice /*******************************************************************/ public func inv() -> Matrice { let A: Matrice = self let B: Matrice = Matrice(A) let I: Matrice = A.eye() let n = A.nbc //print("I=\n\(I)") // On triangularise la matrice for j in 0...n-2 { // On trouve i entre j et n-1 tel que |A(i,j)| soit maximal var indTrouve = j var absAijCourant: Double = abs(A[indTrouve,j] ) for i in j+1...n-1 { if abs(A[i,j]) > absAijCourant { indTrouve = i absAijCourant = abs(A[i,j]) } } // On échange Ligne(indTrouve) et Ligne(j) let tempoB = B.data[indTrouve*n...(indTrouve+1)*n-1] B.data[indTrouve*n...(indTrouve+1)*n-1] = B.data[j*n...(j+1)*n-1] B.data[j*n...(j+1)*n-1] = tempoB let tempoI = I.data[indTrouve*n...(indTrouve+1)*n-1] I.data[indTrouve*n...(indTrouve+1)*n-1] = I.data[j*n...(j+1)*n-1] I.data[j*n...(j+1)*n-1] = tempoI // on fait apparaitre les "0" sous la diagonale for i in j+1...n-1 { let coef = B[i,j]/B[j,j] var ligneTempo = B.ligne(i) - coef * B.ligne(j) B.data[i*n...(i+1)*n-1] = (ligneTempo?.data[0...n-1])! ligneTempo = I.ligne(i) - coef * I.ligne(j) I.data[i*n...(i+1)*n-1] = (ligneTempo?.data[0...n-1])! } } //print("I=\n\(I)") // On diagonalise la matrice for jj in 0...n-2 { let j = -jj+n-1 for ii in 0...j-1 { let i = -ii+j-1 let coef = B[i,j]/B[j,j] var ligneTempo = B.ligne(i) - coef * B.ligne(j) B.data[i*n...(i+1)*n-1] = (ligneTempo?.data[0...n-1])! ligneTempo = I.ligne(i) - coef * I.ligne(j) I.data[i*n...(i+1)*n-1] = (ligneTempo?.data[0...n-1])! } } //print("B=\n\(B)") //print("I=\n\(I)") // On fait apparaitre des "1" sur la diagonale de B for i in 0...n-1 { let coef = 1/B[i,i] var ligneTempo = coef*B.ligne(i) B.data[i*n...(i+1)*n-1] = (ligneTempo.data[0...n-1]) ligneTempo = coef*I.ligne(i) I.data[i*n...(i+1)*n-1] = (ligneTempo.data[0...n-1]) } return I } } /*=========================================================================*/ // Fin de la définition de la class Matrice /*=========================================================================*/ /*********************************************************/ /// Retourne une matrice diagonale à partir d'un Vecteur /*********************************************************/ public func diag(v: Vecteur) -> Matrice { let nbElem = max(v.nbl,v.nbc) let result = Matrice(nbl: nbElem, nbc: nbElem) for i in 0...nbElem-1 { result[i,i] = v[i] } return result } /*********************************************************/ /// Retourne une matrice diagonale de "nbl" lignes et /// "nbc" colonnes à partir d'un Vecteur /// à faire : vérifier compatibilité des nombres /*********************************************************/ public func diag(v: Vecteur, nl: Int, nc: Int) -> Matrice { let nbElem = max(v.nbl,v.nbc) let result = Matrice(nbl: nl, nbc: nc) for i in 0...nbElem-1 { result[i,i] = v[i] } return result } /*******************************************************************/ /// Fonction qui retourne l'inverse d'une Matrice carrée /// /// Pour l'instant : /// /// let A = Matrice([8.0,1,6,3,5,7,4,9,2],nbl: 3,nbc: 3) /// let B = inv(A) /// /// TODO: Gérer les erreurs d'indice /*******************************************************************/ public func inv(_ x: Matrice) -> Matrice { return x.inv() } /*******************************************************************/ /// Fonction qui retourne l'inverse d'une Matrice carrée /// ///Utilise Lapack /// /// let A = Matrice([8.0,1,6,3,5,7,4,9,2],nbl: 3,nbc: 3) /// let B = invert(A) /// /// TODO: Gérer les erreurs d'indice /*******************************************************************/ public func invert(_ x: Matrice) -> Matrice { let nbl = x.nbl let nbc = x.nbc var inMatrix: [Double] = x.data var N = __CLPK_integer(sqrt(Double(inMatrix.count))) var pivots = [__CLPK_integer](repeating: 0, count: Int(N)) var workspace = [Double](repeating: 0.0, count: Int(N)) var error : __CLPK_integer = 0 withUnsafeMutablePointer(to: &N) { dgetrf_($0, $0, &inMatrix, $0, &pivots, &error) dgetri_($0, &inMatrix, $0, &pivots, &workspace, $0, &error) } let y = Matrice(inMatrix,nbl: nbl,nbc: nbc) return y } /*******************************************************************/ /// Décomposition en valeurs singulières, /// retourne un tuple /// /// Utilise Lapack /// /// A = U * SIGMA * V^t /// /// let A = Matrice([8.0,1,6,3,5,7,4,9,2],nbl: 3,nbc: 3) /// let Results = svd(A) /// let UU = Results.U /// let D = Results.D /// let VV = Results.V /// /// TODO: Gérer les erreurs d'indice /// /// Rem: Attention avec Lapack les éléments d'une matrice sont lus /// colonne par colonne !! /*******************************************************************/ public func svd(_ x: Matrice) -> (U: Matrice, D: Matrice, V: Matrice) { let nbl = x.nbl let nbc = x.nbc let resU: Matrice let resD: Matrice let resV: Matrice var singleChar = "G" var JOBA = Int8(UInt8(ascii: singleChar.unicodeScalars[singleChar.startIndex])) singleChar = "U" var JOBU = Int8(UInt8(ascii: singleChar.unicodeScalars[singleChar.startIndex])) singleChar = "V" var JOBV = Int8(UInt8(ascii: singleChar.unicodeScalars[singleChar.startIndex])) //let JOBA = "G" //let JOBU = "U" //let JOBV = "V" var M = __CLPK_integer(nbl) var N = __CLPK_integer(nbc) var A: [Double] = (x°).data // Au retour : colonnes orthogonalse de la matrice U var LDA = __CLPK_integer(nbl) var SVA = [Double](repeating: 0.0, count: Int(N)) // Les valeurs singulières de A var MV : __CLPK_integer = 0 //var V: [[Double]] = Array(repeating: Array(repeating: 0.0, count: nbc), count: nbc) var V = [Double](repeating: 0.0, count: Int(N*N)) // Vecteurs singuliers à droite var LDV = __CLPK_integer(nbc) let lwork = max(6,nbl+nbc) var WORK = [Double](repeating: 0.0, count: lwork) var LWORK = __CLPK_integer(lwork) var INFO : __CLPK_integer = 0 dgesvj_(&JOBA,&JOBU,&JOBV,&M,&N,&A,&LDA,&SVA,&MV,&V,&LDV,&WORK,&LWORK,&INFO) print("A : \n\(A)") print("SVA : \n\(SVA)") print("V : \n\(V)") print("nbl = \n\(nbl)") resU = Matrice(A,nbl: nbl,nbc: nbc,rangement: "c") resD = diag(v: Vecteur(SVA)) resV = Matrice(V,nbl: nbc,nbc: nbc,rangement: "c") print("resU.dim() :\n\(resU.dim())") print("resD.dim() :\n\(resD.dim())") print("resV.dim() :\n\(resV.dim())") /* print("resU : \n\(resU)") print("resD : \n\(resD)") print("resV : \n\(resV)") */ return(resU,resD,resV) }
true
6633de2424e01e0685bc5ab68174e71a18b7bc07
Swift
ParkJong-Hun/Swift_Algorithm-Collection
/TriangleSnail.playground/Contents.swift
UTF-8
899
3.59375
4
[]
no_license
import Foundation func triangle(_ n:Int, _ startCount:Int) -> [[Int]] { var arr = [[Int]](repeating: [], count: n) var count = startCount for i in 0..<n { arr[i].append(count) count += 1 } for _ in 0..<n - 1 { arr[n - 1].append(count) count += 1 } for i in stride(from: n - 2, to: 0, by: -1) { arr[i].append(count) count += 1 } if n >= 4 { let returned = triangle(n - 3, count) for i in 0..<returned.count { arr[i + 2].insert(contentsOf: returned[i], at: arr.index(after: arr.startIndex)) } } return arr } func solution(_ n:Int) -> [Int] { let answer:[Int] = triangle(n, 1).flatMap{$0} return answer } solution(4) //[1,2,9,3,10,8,4,5,6,7] solution(5) //[1,2,12,3,13,11,4,14,15,10,5,6,7,8,9] solution(6) //[1,2,15,3,16,14,4,17,21,13,5,18,19,20,12,6,7,8,9,10,11]
true
0f77d02761bb00ca4b8d2b53ad35a4fb9e48f310
Swift
adriantabirta/alar-studios-test
/alar-studios-test/Views/Main/CachebleImageView.swift
UTF-8
1,302
3.0625
3
[]
no_license
// // CachebleImageView.swift // alar-studios-test // // Created by Tabirta Adrian on 26.08.2021. // import UIKit let imageCache = NSCache<NSString, AnyObject>() class CachebleImageView: UIImageView { var imageUrlString: String? func loadImageUsingCache(withUrl urlString : String) { imageUrlString = urlString let url = URL(string: urlString) self.image = nil if let cachedImage = imageCache.object(forKey: urlString as NSString) as? UIImage { self.image = cachedImage return } URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in guard error == nil, let imageData = data, let image = UIImage(data: imageData) else { print("Could not load image for \(String(describing: url?.absoluteString)) because: \(String(describing: error?.localizedDescription))") return } if self.imageUrlString == urlString { DispatchQueue.main.async { self.image = image } } imageCache.setObject(image, forKey: urlString as NSString) }) .resume() } }
true
45dd19ec3354001e720a2b3d93d4cd045b20f408
Swift
uponup/BookBoy
/BookBoy/Service/Book.swift
UTF-8
980
2.890625
3
[]
no_license
// // Book.swift // BookBoy // // Created by 龙格 on 2020/3/19. // Copyright © 2020 Paul Gao. All rights reserved. // import Foundation import SwiftyJSON struct Book { var id: Int = 0 var title: String = "" var coverImg: Data? var coverImgName: String = "" var author: String? var publisher: String? var price: Double? var buyUrl: String? var createDate: Date = Date() var isComplete: Bool = false init() { title = "" coverImg = nil author = nil publisher = nil price = nil buyUrl = nil } init(title: String) { self.title = title coverImg = nil author = nil publisher = nil price = nil buyUrl = nil } static func add() -> Book { var book = Book() book.title = NSLocalizedString("Add a New Book", comment: "") book.coverImgName = "cell_book_mark" return book } }
true
5f7c26536e893b5c783c8d4204abb7c66592f634
Swift
zhentan/adyen-ios
/Adyen/Validators/CountryCodeValidator.swift
UTF-8
549
2.71875
3
[ "MIT" ]
permissive
// // Copyright (c) 2021 Adyen N.V. // // This file is open source and available under the MIT license. See the LICENSE file for more info. // import Foundation /// :nodoc: public struct CountryCodeValidator: Validator { /// :nodoc: public init() { /* Empty initializer */ } /// :nodoc: public func isValid(_ value: String) -> Bool { let allCountryCodes = Locale.isoRegionCodes return allCountryCodes.contains(value) } /// :nodoc: public func maximumLength(for value: String) -> Int { 3 } }
true
3e0c3a0b8ed998c4606793f6927988e7428a78cd
Swift
haideraliahsan/FYP
/ProtypeFYP/Employer/VisibilityViewController.swift
UTF-8
3,266
2.609375
3
[]
no_license
// // VisibilityViewController.swift // RecruitorInterface // // Created by haider ali on 22/01/2019. // Copyright © 2019 haider ali. All rights reserved. // import UIKit class VisibilityViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource { let titl: [String] = ["Mark David From UK","Keily lyn From USA","Briana From Asutrailia","Malik Abdullah From Pakistan"] let skills: [String] = ["Web Designing, PHP developer", "Web Engineering, ASP.NET", "IOS Developer, Swift", "Android Developer", "Python Developer", ""] let array: [String] = ["devtoolspromo", "wall1", "thumb", "thumbNail"] let profileImages: [String] = ["profileImage","profileImage","profileImage","profileImage"] @IBOutlet weak var visibilityCollectionView: UICollectionView! func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return array.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "savedCell", for: indexPath) as! VisibilityCell cell.profileImageView.image = UIImage(named: array[indexPath.row]) cell.title.text = titl[indexPath.row] cell.cvDescription.text = skills[indexPath.row] + ", " + skills[4 - indexPath.row] + " " + skills[indexPath.row] cell.backgroundColor = UIColor.darkGray cell.profileImageView.layer.masksToBounds = false cell.profileImageView.layer.borderColor = UIColor.white.cgColor cell.profileImageView.layer.cornerRadius = 40 cell.profileImageView.clipsToBounds = true cell.backgroundColor = UIColor.white return cell } override func viewDidLoad() { super.viewDidLoad() UINavigationBar.appearance().barTintColor = UIColor.darkGray UINavigationBar.appearance().setBackgroundImage(UIImage(), for: UIBarMetrics.default) UINavigationBar.appearance().shadowImage = UIImage() let topBarHeight = UIApplication.shared.statusBarFrame.size.height + (self.navigationController?.navigationBar.frame.height ?? 0.0) print(topBarHeight) let cellWidth = UIScreen.main.bounds.width let cellHeight = (cellWidth * 9 / 16) + 100 let layout = UICollectionViewFlowLayout() layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) layout.itemSize = CGSize(width: cellWidth, height: cellHeight) layout.scrollDirection = .vertical layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 visibilityCollectionView.backgroundColor = UIColor.darkGray visibilityCollectionView.collectionViewLayout = layout } /* // 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
f80e0c61a1c3ae933d52563bf0568bc2d5b2a0ae
Swift
univalchemist/hipwig-swift
/HipWig/UI/CollectionCells/ExpertDirectionCell/ExpertDirectionCell.swift
UTF-8
1,626
2.921875
3
[]
no_license
// // ExpertDirectionCell.swift // HipWig // // Created by Vladyslav Shepitko on 1/31/19. // Copyright © 2019 HipWig. All rights reserved. // import UIKit import Kingfisher class ExpertDirectionCell: UICollectionViewCell { @IBOutlet private weak var titleLabel: UILabel! @IBOutlet private weak var previewImageView: UIImageView! private let selectedTitleColor = textColor3 private let unselectedTitleColor = UIColor.white override var isSelected: Bool { didSet { self.update(with: isSelected) } } var skill: ExpertSkill! { didSet { self.update(with: skill) } } override func awakeFromNib() { super.awakeFromNib() self.onLoad() } private func onLoad() { self.titleLabel.font = Font.light.of(size: 12) self.previewImageView.tintColor = self.unselectedTitleColor self.adjustConstraints() } private func update(with skill: ExpertSkill) { self.titleLabel.text = skill.title } private func update(with selectedState: Bool) { var skillImage: String = "" if selectedState { self.contentView.backgroundColor = selectedColor self.titleLabel.textColor = self.selectedTitleColor skillImage = self.skill.selectedImage } else { self.contentView.backgroundColor = disabledColor self.titleLabel.textColor = self.unselectedTitleColor skillImage = self.skill.defaultImage } self.previewImageView.setImage(skillImage) } }
true
211db60a4465ac7be7ae7a0287e0c13edfc1f986
Swift
epidemik-dev/ios
/EpidemikWidget/TodayViewController.swift
UTF-8
1,224
2.578125
3
[ "MIT" ]
permissive
// // TodayViewController.swift // EpidemikWidget // // Created by Ryan Bradford on 12/17/17. // Copyright © 2017 RBradford Studios. All rights reserved. // import UIKit import NotificationCenter class TodayViewController: UIViewController, NCWidgetProviding { var trendsView: TrendsWidgetView! override func viewDidLoad() { super.viewDidLoad() initTrendView() // Do any additional setup after loading the view from its nib. } func initTrendView() { trendsView = TrendsWidgetView(frame: self.view.frame) self.view.addSubview(trendsView) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func widgetPerformUpdate(completionHandler: (@escaping (NCUpdateResult) -> ())) { // Perform any setup necessary in order to update the view. // If an error is encountered, use NCUpdateResult.Failed // If there's no update required, use NCUpdateResult.NoData // If there's an update, use NCUpdateResult.NewData if trendsView != nil { trendsView.removeFromSuperview() } initTrendView() completionHandler(NCUpdateResult.newData) } }
true
15b3a2c704a6ac455fd2ecc492574bccbcb38af4
Swift
JonHome/iOSCore
/source/class/ext/Foundation/Dictionary_ext.swift
UTF-8
388
2.640625
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
// // ext_Dictionary.swift // core // // Created by Jon Home on 2020/4/30. // Copyright © 2020 JonHome. All rights reserved. // import Foundation extension Dictionary { public var queryString: String { var output: String = "" for (key,value) in self { output += "\(key)=\(value)&" } output = String(output.dropLast()) return output } }
true
6e4354237291008c029e31fc59d90ac608b20ef9
Swift
fkuhl/ClassicPlayer
/ClassicalMediaLibrary/Anarthrous.swift
UTF-8
1,038
2.953125
3
[]
no_license
// // Anarthrous.swift // ClassicalPlayer // // Created by Frederick Kuhl on 1/14/19. // Copyright © 2019 TyndaleSoft LLC. All rights reserved. // import Foundation extension NSString { func anarthrousCompare(_ string: String) -> ComparisonResult { let meCopy = removeArticle(from: self as String) let stringCopy = removeArticle(from: string) return meCopy.localizedCaseInsensitiveCompare(stringCopy) } } func removeArticle(from: String) -> String { let fromRange = NSRange(from.startIndex..., in: from) let checkingResult = articleExpression.matches(in: from, options: [], range: fromRange) if checkingResult.isEmpty { return from } let range = checkingResult[0].range(at: 0) let startIndex = from.index(from.startIndex, offsetBy: range.location) let endIndex = from.index(startIndex, offsetBy: range.length) return String(from[endIndex...]) } fileprivate let articleExpression = try! NSRegularExpression( pattern: "^(A|An|The)\\s+", options: [.caseInsensitive])
true
43f53762cdacdbabe2e255d9decad1932fc01966
Swift
cephonodes/til
/iOS_App/MyMusic/MyMusic/ViewController.swift
UTF-8
1,625
2.984375
3
[]
no_license
// // ViewController.swift // MyMusic // // Created by Yuki Narita on 2020/02/09. // Copyright © 2020 Swift-Beginners. All rights reserved. // import UIKit import AVFoundation class ViewController: UIViewController { let cymbalPath = Bundle.main.bundleURL.appendingPathComponent("cymbal.mp3") var cymbalPlayer = AVAudioPlayer() let guitarPath = Bundle.main.bundleURL.appendingPathComponent("guitar.mp3") var guitarPlayer = AVAudioPlayer() let backmusicPath = Bundle.main.bundleURL.appendingPathComponent("backmusic.mp3") var backmusicPlayer = AVAudioPlayer() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } fileprivate func playSound(filePath: URL, player: inout AVAudioPlayer, numberOfLoops: Int) { do { player = try AVAudioPlayer(contentsOf: filePath, fileTypeHint: nil) player.numberOfLoops = numberOfLoops player.play() } catch { print("エラーが発生しました") // うーん… } } @IBAction func cymbal(_ sender: Any) { playSound(filePath: cymbalPath, player: &cymbalPlayer, numberOfLoops: 0) } @IBAction func guitar(_ sender: Any) { playSound(filePath: guitarPath, player: &guitarPlayer, numberOfLoops: 0) } @IBAction func play(_ sender: Any) { playSound(filePath: backmusicPath, player: &backmusicPlayer, numberOfLoops: -1) } @IBAction func stop(_ sender: Any) { if backmusicPlayer.isPlaying { backmusicPlayer.stop() } } }
true
da66416de0ead957db6ba511d2f7726fbb032066
Swift
thisischristoph/Van
/Van/Extensions/VanExtension.swift
UTF-8
3,147
2.765625
3
[]
no_license
// // VanExtension.swift // Van // // Created by Christopher Harrison on 18/05/2018. // Copyright © 2018 Christopher Harrison. All rights reserved. // import Foundation extension Van { func toDictionary() -> [String: Any] { var van: [String : Any] = [ VanKeys.uid.rawValue : self.uid, VanKeys.name.rawValue : self.name, VanKeys.profilePicURL.rawValue : self.profilePicURL, VanKeys.category.rawValue : VanCategory.fishChips.rawValue ] let openingTimesMonday: [String : Any] = [ DayKeys.opens.rawValue : self.openingTimes.monday.opens ?? 0, DayKeys.closes.rawValue : self.openingTimes.monday.closes ?? 0, DayKeys.closed.rawValue : self.openingTimes.monday.closed ?? false ] let openingTimesTuesday: [String : Any] = [ DayKeys.opens.rawValue : self.openingTimes.tuesday.opens ?? 0, DayKeys.closes.rawValue : self.openingTimes.tuesday.closes ?? 0, DayKeys.closed.rawValue : self.openingTimes.tuesday.closed ?? false ] let openingTimesWednesday: [String : Any] = [ DayKeys.opens.rawValue : self.openingTimes.wednesday.opens ?? 0, DayKeys.closes.rawValue : self.openingTimes.wednesday.closes ?? 0, DayKeys.closed.rawValue : self.openingTimes.wednesday.closed ?? false ] let openingTimesThursday: [String : Any] = [ DayKeys.opens.rawValue : self.openingTimes.thursday.opens ?? 0, DayKeys.closes.rawValue : self.openingTimes.thursday.closes ?? 0, DayKeys.closed.rawValue : self.openingTimes.thursday.closed ?? false ] let openingTimesFriday: [String : Any] = [ DayKeys.opens.rawValue : self.openingTimes.friday.opens ?? 0, DayKeys.closes.rawValue : self.openingTimes.friday.closes ?? 0, DayKeys.closed.rawValue : self.openingTimes.friday.closed ?? false ] let openingTimesSaturday: [String : Any] = [ DayKeys.opens.rawValue : self.openingTimes.saturday.opens ?? 0, DayKeys.closes.rawValue : self.openingTimes.saturday.closes ?? 0, DayKeys.closed.rawValue : self.openingTimes.saturday.closed ?? false ] let openingTimesSunday: [String : Any] = [ DayKeys.opens.rawValue : self.openingTimes.sunday.opens ?? 0, DayKeys.closes.rawValue : self.openingTimes.sunday.closes ?? 0, DayKeys.closed.rawValue : self.openingTimes.sunday.closed ?? false ] van[VanKeys.openingTimes.rawValue] = [ OpeningTimesKeys.monday.rawValue : openingTimesMonday, OpeningTimesKeys.tuesday.rawValue : openingTimesTuesday, OpeningTimesKeys.wednesday.rawValue : openingTimesWednesday, OpeningTimesKeys.thursday.rawValue : openingTimesThursday, OpeningTimesKeys.friday.rawValue : openingTimesFriday, OpeningTimesKeys.saturday.rawValue : openingTimesSaturday, OpeningTimesKeys.sunday.rawValue : openingTimesSunday ] return van } }
true
e942f106b7b7520a5b2b00f40da99c897e77cd18
Swift
archangelmichael/Swift-IOS-Projects
/ImageScrollAndZoom/ImageScrollAndZoom/ImagesCollectionViewController.swift
UTF-8
6,153
2.71875
3
[]
no_license
// // ImagesCollectionViewController.swift // ImageScrollAndZoom // // Created by Radi on 5/4/16. // Copyright © 2016 archangel. All rights reserved. // import UIKit class ImagesCollectionViewController: UICollectionViewController { var imageUlrs : [String] = [] private let placeholderImage : UIImage = UIImage(named: "download3")! private var downloadedImages : [UIImage] = [] private var currentIndex : Int = 0 override func viewDidLoad() { super.viewDidLoad() self.setupGallery() self.downloadedImages = [UIImage](count: self.imageUlrs.count, repeatedValue: self.placeholderImage) for (index, url) in self.imageUlrs.enumerate() { self.setImageFromUrl(url, index: index) } } func setupGallery() { self.collectionView!.registerNib(UINib(nibName: ImageCollectionViewCell.nibName(), bundle: nil), forCellWithReuseIdentifier: ImageCollectionViewCell.reuseId()) let flowLayout = UICollectionViewFlowLayout() flowLayout.scrollDirection = UICollectionViewScrollDirection.Horizontal let insets = ImageCollectionViewCell.sectionInsets flowLayout.minimumInteritemSpacing = 0.0 flowLayout.minimumLineSpacing = insets.left * 2 self.collectionView!.pagingEnabled = true self.collectionView!.collectionViewLayout = flowLayout } func setImageFromUrl(urlStr: String?, index: Int){ if urlStr != nil { if let url = NSURL(string: urlStr!) { self.getDataFromUrl(url) { (data, response, error) in dispatch_async(dispatch_get_main_queue()) { () -> Void in guard let data = data, let downloadedAvatar = UIImage(data: data) where error == nil else { print("Image download failed.") return } if index < self.downloadedImages.count { self.downloadedImages[index] = downloadedAvatar print("Download complete") self.collectionView!.reloadData() return; } } } } } print("Image download failed.") } func getDataFromUrl(url:NSURL, completion: ((data: NSData?, response: NSURLResponse?, error: NSError? ) -> Void)) { NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) in completion(data: data, response: response, error: error) }.resume() } } // MARK: UICollectionViewDataSource extension ImagesCollectionViewController { override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.imageUlrs.count } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ImageCollectionViewCell.reuseId(), forIndexPath: indexPath) as! ImageCollectionViewCell cell.imagePreview.image = self.downloadedImages[indexPath.row] return cell } } // MARK:UICollectionViewDelegateFlowLayout extension ImagesCollectionViewController : UICollectionViewDelegateFlowLayout { override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { let row = indexPath.row if row < self.downloadedImages.count { let image = self.downloadedImages[row] let zoomImageVC = UIStoryboard(name: "ImageTabs", bundle: nil).instantiateViewControllerWithIdentifier("imageZoomedVC") as! ImageZoomedViewController zoomImageVC.downloadedImage = image self.presentViewController(zoomImageVC, animated: true, completion: nil) } } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { let insets = ImageCollectionViewCell.sectionInsets return CGSize(width: self.collectionView!.frame.size.width - insets.left * 2, height: self.collectionView!.frame.size.height - insets.top * 2) } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets { return ImageCollectionViewCell.sectionInsets } } // MARK: Orientation change delegate extension ImagesCollectionViewController { override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) { if UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad { self.collectionView!.alpha = 0 self.collectionView!.collectionViewLayout.invalidateLayout() let currentOffset = self.collectionView!.contentOffset self.currentIndex = Int(currentOffset.x / self.collectionView!.frame.size.width) } } override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) { if UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad { let indexPath = NSIndexPath(forItem: self.currentIndex, inSection: 0) self.collectionView!.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false) UIView.animateWithDuration(0.125, animations: { self.collectionView!.alpha = 1 }) } } }
true
ad92212ce957103a0e96e7f1adc08fda0f9e748a
Swift
mtrovilho/iOS-Swift-TableView-CoreData-Example
/ListaCoreData/Pessoas.swift
UTF-8
438
2.59375
3
[]
no_license
// // Pessoas.swift // // // Created by Diego Rossini Vieira on 8/26/15. // // import Foundation import CoreData class Pessoas: NSManagedObject { @NSManaged var nome: String class func createInManagedObjectContext(moc: NSManagedObjectContext, nome: String) -> Pessoas { let newItem = NSEntityDescription.insertNewObjectForEntityForName("Pessoas", inManagedObjectContext: moc) as! Pessoas newItem.nome = nome return newItem } }
true
59273b7739e03ad0bced17af3b562a82b5fbb5ca
Swift
JavierSLX/AntologiaLenguajes
/Swift/04-Colecciones.swift
UTF-8
862
3.921875
4
[]
no_license
import UIKit //Arrays var arreglo: Array<String> var array: [Int] = [] var arregloNumeros = [1, 2, 3] let arreggloNumerosInmutable = [3, 2, 1] //Agregando más elementos (al final del array y especificandole en que posicion) arregloNumeros.append(5) arregloNumeros.insert(4, at: 3) //Eliminar valores arregloNumeros.remove(at: 0) arregloNumeros.removeLast() //Accediendo al array print(arregloNumeros) print(arregloNumeros[2]) //Eliminar todo el arreglo arregloNumeros.removeAll() print(arregloNumeros) //Diccionarios var myClassicDictionary = Dictionary<Int, String>() var myModernDictionary = [Int:String]() //Agregando elementos myModernDictionary[003] = "Javier" myModernDictionary = [001:"Juan", 002:"Brais"] //Accediendo al diccionario myModernDictionary[002] //Borrar dato myModernDictionary[002] = nil myModernDictionary.removeValue(forKey: 001)
true
d60f5db15233564775548fd54dc0afe97ada01ed
Swift
SungjiCho/TIL
/BaekJoon/알파벳찾기/알파벳찾기/main.swift
UTF-8
546
3.015625
3
[]
no_license
// // main.swift // 알파벳찾기 // // Created by 조성지 on 2020/06/13. // Copyright © 2020 조성지. All rights reserved. // import Foundation guard let s = readLine()?.trimmingCharacters(in: .whitespaces) else { fatalError("Bad input") } let arr = s.map({ $0.unicodeScalars.first!.value-97 }) var answer = [Int](repeating: -1, count: 26) for (index, item) in arr.enumerated(){ if answer[Int(item)] == -1{ answer[Int(item)] = index } } for n in answer{ print(n, terminator: " ") }
true
13559f16170fca23b6fe45811569eb7877277a99
Swift
YebinKim/iOS-Combine-Study
/Combine-MiniBook.playground/Pages/Time Manipulation Operators.xcplaygroundpage/Contents.swift
UTF-8
7,881
3.46875
3
[]
no_license
//: [Previous](@previous) import Foundation import Combine import SwiftUI import PlaygroundSupport /*: # Time Manipulation Operators - 시간을 처리할 수 있는 Operator *(시간에 따라 값을 변형시키기 위한 Operator)* - 비동기 이벤트 흐름을 모델링할 수 있음 */ private let valuesPerSecond = 1.0 private let delayInSeconds = 1.5 private let collectTimeStride = 4 private let collectMaxCount = 2 private let throttleDelay = 1.0 /*: ## Shifting time - **Publisher의 값 방출을 지연시키는 데 사용함** - *delay(for:scheduler:)* : 지연시키고자 하는 시간(for)과 해당 이벤트를 수행할 스케쥴러(scheduler)를 지정함 */ // delay(for:scheduler:) let delayedSourcePublisher = PassthroughSubject<Date, Never>() let delayedPublisher = delayedSourcePublisher.delay(for: .seconds(delayInSeconds), scheduler: DispatchQueue.main) let delayedSubscription = Timer .publish(every: 1.0 / valuesPerSecond, on: .main, in: .common) .autoconnect() .subscribe(delayedSourcePublisher) let delayedSourceTimeline = TimelineView(title: "Emitted values (\(valuesPerSecond) per sec.):") let delayedTimeline = TimelineView(title: "Delayed values (with a \(delayInSeconds)s delay):") let delayedView = VStack(spacing: 50) { delayedSourceTimeline delayedTimeline } //PlaygroundPage.current.liveView = UIHostingController(rootView: delayedView) // //delayedSourcePublisher.displayEvents(in: delayedSourceTimeline) //delayedPublisher.displayEvents(in: delayedTimeline) /*: ## Collection values - **일정 시간동안 Publisher의 방출 값을 모으는 데 사용함** - *collect(_:Publishers.TimeGroupingStrategy<S>)* : 값을 모을 주기와 해당 이벤트를 수행할 스케쥴러를 지정함 - Publishers.TimeGroupingStrategy<S> 의 종류 - *.byTime(Context, Context.SchedulerTimeType.Stride)* : 주기(Stride)에 따라서만 값을 방출 - *.byTimeOrCount(Context, Context.SchedulerTimeType.Stride, Int)* : 주기(Stride) 또는 최대 개수(Int)에 따라 값을 방출 */ // collect(_:Publishers.TimeGroupingStrategy<S>) let collectedSourcePublisher = PassthroughSubject<Date, Never>() let collectedPublisher = collectedSourcePublisher .collect(.byTime(DispatchQueue.main, .seconds(collectTimeStride))) .flatMap { dates in dates.publisher } let collectedPublisher2 = collectedSourcePublisher .collect(.byTimeOrCount(DispatchQueue.main, .seconds(collectTimeStride), collectMaxCount)) .flatMap { dates in dates.publisher } let collectedSubscription = Timer .publish(every: 1.0 / valuesPerSecond, on: .main, in: .common) .autoconnect() .subscribe(collectedSourcePublisher) let collectedSourceTimeline = TimelineView(title: "Emitted values:") let collectedTimeline = TimelineView(title: "Collected values (every \(collectTimeStride)s):") let collectedTimeline2 = TimelineView(title: "Collected values (at most \(collectMaxCount) every \(collectTimeStride)s):") let collectedView = VStack(spacing: 40) { collectedSourceTimeline collectedTimeline collectedTimeline2 } //PlaygroundPage.current.liveView = UIHostingController(rootView: collectedView) // //collectedSourcePublisher.displayEvents(in: collectedSourceTimeline) //collectedPublisher.displayEvents(in: collectedTimeline) //collectedPublisher2.displayEvents(in: collectedTimeline2) /*: ## Holding off on events - **일정 시간동안 Publisher의 값 방출을 보류하기 위해 사용함** - *debounce(for:scheduler:)* : 지정된 시간(for) 사이에 받는 값을 홀딩시키고 시간마다 값을 방출함 - *throttle(for:scheduler:**latest:**)* : latest 가 false로 설정된 경우 지정된 시간 중 첫 번째 값을 방출하고, true로 설정된 경우 마지막 값을 방출함 */ // debounce(for:scheduler:) let debouncedSubject = PassthroughSubject<String, Never>() let debounced = debouncedSubject .debounce(for: .seconds(1.0), scheduler: DispatchQueue.main) .share() let debouncedSubjectTimeline = TimelineView(title: "Emitted values") let debouncedTimeline = TimelineView(title: "Debounced values") let debouncedView = VStack(spacing: 100) { debouncedSubjectTimeline debouncedTimeline } //PlaygroundPage.current.liveView = UIHostingController(rootView: debouncedView) // //debouncedSubject.displayEvents(in: debouncedSubjectTimeline) //debounced.displayEvents(in: debouncedTimeline) let debouncedSubscription1 = debouncedSubject .sink { string in print("+\(deltaTime)s: Subject emitted: \(string)") } let debouncedSubscription2 = debounced .sink { string in print("+\(deltaTime)s: Debounced emitted: \(string)") } debouncedSubject.feed(with: typingHelloWorld) // throttle(for:scheduler:latest:) let throttledSubject = PassthroughSubject<String, Never>() let throttled = throttledSubject .throttle(for: .seconds(throttleDelay), scheduler: DispatchQueue.main, latest: true) .share() let throttledSubjectTimeline = TimelineView(title: "Emitted values") let throttledTimeline = TimelineView(title: "Throttled values") let throttledView = VStack(spacing: 100) { throttledSubjectTimeline throttledTimeline } //PlaygroundPage.current.liveView = UIHostingController(rootView: throttledView) // //throttledSubject.displayEvents(in: throttledSubjectTimeline) //throttled.displayEvents(in: throttledTimeline) let throttledSubscription1 = throttledSubject .sink { string in print("+\(deltaTime)s: Subject emitted: \(string)") } let throttledSubscription2 = throttled .sink { string in print("+\(deltaTime)s: Throttled emitted: \(string)") } throttledSubject.feed(with: typingHelloWorld) /*: ## Timing out - **일정 시간동안 이벤트를 받지 않으면 시간 초과로 Publisher에 completion 이벤트를 보내는 역할** - *timeout(_:scheduler:)* : 일정 시간동안 이벤트를 받지 않아도 failure completion 이벤트가 발생하지 않음 - *timeout(_:scheduler:**customError:**)* : 일정 시간동안 이벤트를 받지 않으면 failure completion 이벤트를 발생시킴 */ // timeout(_:scheduler:) enum TimeoutError: Error { case timedOut } let subject1 = PassthroughSubject<Void, TimeoutError>() let timedOutSubject = subject1.timeout(.seconds(5), scheduler: DispatchQueue.main, customError: { .timedOut }) let timeline = TimelineView(title: "Button taps") let timedOutView = VStack(spacing: 100) { Button(action: { subject1.send() }) { Text("Press me within 5 seconds") } timeline } //PlaygroundPage.current.liveView = UIHostingController(rootView: timedOutView) // //timedOutSubject.displayEvents(in: timeline) /*: ## Measuring time - **시간을 측정하기 위한 Operator (변형시키는 동작 x)** - *measureInterval(using:)* : Publisher의 방출 값 사이의 시간을 측정하는 데 사용함 */ // measureInterval(using:) let subject2 = PassthroughSubject<String, Never>() let measureSubject = subject2.measureInterval(using: DispatchQueue.main) let measureSubject2 = subject2.measureInterval(using: RunLoop.main) let subjectTimeline = TimelineView(title: "Emitted values") let measureTimeline = TimelineView(title: "Measured values") let view = VStack(spacing: 100) { subjectTimeline measureTimeline } PlaygroundPage.current.liveView = UIHostingController(rootView: view) subject2.displayEvents(in: subjectTimeline) measureSubject.displayEvents(in: measureTimeline) let subscription1 = subject2.sink { print("+\(deltaTime)s: Subject emitted: \($0)") } let subscription2 = measureSubject.sink { print("+\(deltaTime)s: Measure emitted: \(Double($0.magnitude) / 1000000000.0)") } let subscription3 = measureSubject2.sink { print("+\(deltaTime)s: Measure2 emitted: \($0)") } subject2.feed(with: typingHelloWorld) //: [Next](@next)
true
bd1b743d45a5afbd7418d5d7188b9b20fbc38225
Swift
coutar-t/GW2Achievements
/GW2AchievementsBusinessLogic/AchievementDetail/AchievementDetailInteractor.swift
UTF-8
1,390
2.640625
3
[]
no_license
// // AchievementDetailInteractor.swift // GW2AchievementsBusinessLogic // // Created by Thibaut Coutard on 11/08/2019. // Copyright © 2019 Thibaut Coutard. All rights reserved. // import Foundation class AchievementDetailInteractor { weak var output: AchievementDetailInteractorOutput? private let currentRepository: CurrentAchievementRepositoryInput init(currentRepository: CurrentAchievementRepositoryInput) { self.currentRepository = currentRepository } } extension AchievementDetailInteractor: AchievementDetailInteractorInput { func retrieve() { output?.setDefaultValues() currentRepository.get() } } extension AchievementDetailInteractor: CurrentAchievementRepositoryOutput { func didGet(achievement: CurrentAchievementRepositoryResponseProtocol) { output?.notifyAchievement(AchievementDetailItem(name: achievement.name, description: achievement.description, iconUrl: achievement.iconUrl, requirement: achievement.requirement)) } func didHandleError() { // TODO } } private struct AchievementDetailItem: AchievementDetailItemProtocol { var name: String var description: String var iconUrl: String? var requirement: String }
true
ca1eaed93b6da0c17f532a4bdb7a58f129ad7559
Swift
Pointwelve/Bitpal-iOS
/Data/Data/Storage/ConfigurationPlistStorage.swift
UTF-8
4,667
2.828125
3
[ "Apache-2.0" ]
permissive
// // ConfigurationPlistStorage.swift // Data // // Created by Ryne Cheow on 17/4/17. // Copyright © 2017 Pointwelve. All rights reserved. // import Domain import Foundation import RxSwift // swiftlint:disable identifier_name /// Error that is thrown when `Configuration` cannot be read. enum ConfigurationError: Error { /// Particular key is missing from configuration file. case missingKey(ConfigurationKey) } /// Keys that exist in the `Configuration` plists. enum ConfigurationKey: String { /// Root path for all server communication. case apiHost /// Root path for all lambda functions. case functionsHost /// Name of the SSL certificate. case sslCertificateName /// Root path for socket server communication. case socketHost /// Company Name case companyName /// API Key case apiKey /// Terms and Conditions case termsAndConditions } /// The `ConfigurationPlistStorage` represents a configuration storage implementation based on a plist. class ConfigurationPlistStorage: ConfigurationStorage { private let configurationPath: String private let bundle: Bundle /// Initialize `ConfigurationPlistStorage`. /// /// - Parameters: /// - file: Name of file to read. /// - type: Type of file to read. /// - bundle: Bundle the file belongs to. /// - Throws: `ConfigurationError` if `configuration` file is missing. init(file: String = "Configuration", ofType type: String = "plist", inBundle bundle: Bundle) throws { guard let configurationPath = bundle.path(forResource: file, ofType: type) else { throw FileError.missing } self.configurationPath = configurationPath self.bundle = bundle } private func makeConfiguration() throws -> ConfigurationData { guard let configuration = NSDictionary(contentsOfFile: configurationPath) as? [String: Any] else { throw FileError.missing } var certificateData: Data? if let certificateName: String = try? configuration.value(for: .sslCertificateName) { guard let certificatePath = bundle.path(forResource: certificateName, ofType: "p12") else { throw FileError.missing } guard let data = try? Data(contentsOf: URL(fileURLWithPath: certificatePath)), data.isEmpty else { throw FileError.missing } certificateData = data } let host: String = try configuration.value(for: .apiHost) guard !host.isEmpty else { throw FileError.missing } let functionsHost: String = try configuration.value(for: .functionsHost) guard !functionsHost.isEmpty else { throw FileError.missing } let socketHost: String = try configuration.value(for: .socketHost) guard !socketHost.isEmpty else { throw FileError.missing } let companyName: String = try configuration.value(for: .companyName) guard !companyName.isEmpty else { throw FileError.missing } let apiKey: String = try configuration.value(for: .apiKey) guard !apiKey.isEmpty else { throw FileError.missing } let termsAndConditions: String = try configuration.value(for: .termsAndConditions) guard !termsAndConditions.isEmpty else { throw FileError.missing } return ConfigurationData(apiHost: host, functionsHost: functionsHost, socketHost: socketHost, sslCertificateData: certificateData, companyName: companyName, apiKey: apiKey, termsAndConditions: termsAndConditions) } override func get(_ key: String) -> Observable<ConfigurationData> { do { let configuration = try makeConfiguration() return Observable.just(configuration) } catch { return Observable.error(error) } } override func set(_ value: ConfigurationData, for key: String) -> Observable<Void> { // no op return Observable.just(()) } } // MARK: - Helper private extension Dictionary { /// Returns value for a given `ConfigurationKey`. /// /// - Parameter key: `ConfigurationKey` to find in dictionary. /// - Returns: Value for key. /// - Throws: `ConfigurationError` if `key` cannot be read. func value<T>(for key: ConfigurationKey) throws -> T { guard let result = filter({ $0.key.hashValue == key.rawValue.hashValue }).first?.value as? T else { throw ConfigurationError.missingKey(key) } return result } }
true
854547291e7f0e6e11aab9cc4f9d3a9eb6c92763
Swift
ratthakarn/BasicSwift
/VariableAnConstant.playground/Contents.swift
UTF-8
442
2.734375
3
[]
no_license
import UIKit //การประกาศตัวแปรแบบ กำหนดค่าจาก Value var myName = 123 //การประกาศตัวแปรโดยการกำหนดด้วยตัวเอง var mySurname: String = "Rathakarn" mySurname = "AAAAA" //การประกาศค่าคงที่ let country: String = "Thailand" print("Hello World") print("Surname = \(mySurname)")
true
07b0375a6b1a91012981b57b2885b05d74d66ff2
Swift
vivanshinod/Demo-Dapi
/SiteCellView.swift
UTF-8
900
3.203125
3
[]
no_license
// // SiteCellView.swift // Demo Dapi // // Created by Vivan on 21/09/21. // import SwiftUI struct SiteCellView: View { @ObservedObject var site: SiteProduct var body: some View { HStack(alignment: .top) { if let favicon = site.favicon { Image(uiImage: favicon) .resizable() .aspectRatio(contentMode: .fit).frame(width: 40, height: 40) } VStack(alignment: .leading) { Text(site.url).bold() if let contentLength = site.contentLength { Text(contentLength).foregroundColor(.gray) } } } } } struct SiteCellView_Previews: PreviewProvider { static var previews: some View { SiteCellView(site: SiteProduct("apple.com")) } }
true
cd16790711cab63712ac39f15352eee75e9b1784
Swift
cbraunsch-dev/VocabularyApp
/VocabularyApp/GameControllers/GameItemList.swift
UTF-8
1,816
3.1875
3
[]
no_license
// // GameItemList.swift // VocabularyApp // // Created by Chris Braunschweiler on 30.05.21. // Copyright © 2021 braunsch. All rights reserved. // import Foundation protocol GameItemList { func randomItems(nrOfItems: Int) -> [VocabularyPairLocalDataModel] func addItem(item: VocabularyPairLocalDataModel) func obtainItems() -> [VocabularyPairLocalDataModel] func obtainItemsThatMatch(matcher: [VocabularyPairLocalDataModel]) -> [VocabularyPairLocalDataModel] func removeItem(item: VocabularyPairLocalDataModel) } class WordMatchGameItemList: GameItemList { private var items = [VocabularyPairLocalDataModel]() func randomItems(nrOfItems: Int) -> [VocabularyPairLocalDataModel] { guard !items.isEmpty else { return [VocabularyPairLocalDataModel]() } var randomPairs = [VocabularyPairLocalDataModel]() var tempItems = items let nrOfItemsToGet = nrOfItems < items.count ? nrOfItems : items.count for _ in 1...nrOfItemsToGet { let randomIndex = Int.random(in: 0..<tempItems.count) let randomPair = tempItems[randomIndex] randomPairs.append(randomPair) tempItems.remove(at: randomIndex) } return randomPairs } func obtainItems() -> [VocabularyPairLocalDataModel] { return items } func obtainItemsThatMatch(matcher: [VocabularyPairLocalDataModel]) -> [VocabularyPairLocalDataModel] { return items.filter { item in return matcher.contains(item) } } func addItem(item: VocabularyPairLocalDataModel) { self.items.append(item) } func removeItem(item: VocabularyPairLocalDataModel) { self.items.removeAll(where: { it in it == item }) } }
true
39d2ec059b70cff97e400a5fd96bdf7b1baedcb1
Swift
andrewarrow/cactus-ios
/Cactus/Screens/Settings Views/Subscription/PaymentInfoView.swift
UTF-8
3,759
2.671875
3
[]
no_license
// // PaymentInfoView.swift // Cactus // // Created by Neil Poulin on 8/7/20. // Copyright © 2020 Cactus. All rights reserved. // import SwiftUI struct PaymentInfoView: View { var platform: BillingPlatform var manageUrl: URL? var cardBrand: CardBrand? var last4: String? var manageButtonText: String? { switch self.platform { case .APPLE: return "Manage on the App Store" case .GOOGLE: return "Manage on Google Play" case .STRIPE: return nil default: return nil } } var buttonUrl: URL? { if let url = self.manageUrl { return url } if self.platform == .APPLE { return URL(string: "https://apps.apple.com/account/subscriptions") } else if self.platform == .GOOGLE { return URL(string: "https://play.google.com/store/account/subscriptions") } return nil } var brandImage: Image? { return self.platform.cactusImage?.swiftImage } var text: String? { guard platform == .STRIPE else { return nil } if let brand = self.cardBrand, let last4 = self.last4 { return "\(brand.displayName) ending in \(last4)" } return nil } var isHidden: Bool { return self.text == nil && (self.manageButtonText == nil || self.buttonUrl == nil) } var body: some View { HStack { if self.brandImage != nil { self.brandImage!.resizable() .aspectRatio(contentMode: .fit) .ifMatches(self.platform == BillingPlatform.STRIPE) { $0.foregroundColor(NamedColor.Green.color)} .height(25) .width(25) .padding(.trailing, Spacing.small) } if self.text != nil { Text(self.text!) } if self.manageButtonText != nil && self.buttonUrl != nil { Button(action: { NavigationService.shared.openUrl(url: self.buttonUrl!) }) { Text(self.manageButtonText!).foregroundColor(NamedColor.LinkColor.color) } } } .padding(.vertical, Spacing.small) .padding(.horizontal, Spacing.normal) .background(self.isHidden ? Color.clear : NamedColor.PaymentBackground.color) .cornerRadius(CornerRadius.normal) } } struct PaymentInfoView_Previews: PreviewProvider { static var previews: some View { Group { Group { PaymentInfoView(platform: .PROMOTIONAL).previewDisplayName("Promotional (hidden)") PaymentInfoView(platform: .APPLE).previewDisplayName("Apple") PaymentInfoView(platform: .GOOGLE).previewDisplayName("Google") PaymentInfoView(platform: .STRIPE, cardBrand: CardBrand.visa, last4: "0333").previewDisplayName("Stripe Card") } .padding() .background(NamedColor.Background.color) .previewLayout(.sizeThatFits) Group { PaymentInfoView(platform: .APPLE).previewDisplayName("Apple") PaymentInfoView(platform: .GOOGLE, manageUrl: URL(string: "http://google.com")).previewDisplayName("Google") PaymentInfoView(platform: .STRIPE, cardBrand: CardBrand.visa, last4: "0333").previewDisplayName("Stripe Card") } .padding() .background(NamedColor.Background.color) .colorScheme(.dark) .previewLayout(.sizeThatFits) } } }
true
810e9bd5c4d3d88753bd8cea8965e560d405fbf1
Swift
corykim0829/signup-2
/mobile/SignUpApp/SignUpApp/Models/NetworkManager.swift
UTF-8
1,152
2.796875
3
[]
no_license
// // NetworkManager.swift // SignUpApp // // Created by Cory Kim on 2020/03/26. // Copyright © 2020 corykim0829. All rights reserved. // import Foundation class NetworkManager { private let usersURLString = "https://shrouded-tor-36901.herokuapp.com/api/users/" private let duplicatedCode: Int = 200 private let notDuplicatedCode: Int = 204 private let typeOfIdentification = "accountId" func requestIDDuplicationConfirmation(ID value: String, completion: @escaping (Bool) -> Void) { guard let url = URL(string: "\(usersURLString)/signup-check?type=\(typeOfIdentification)&value=\(value)") else { return } let request = URLRequest(url: url) URLSession.shared.dataTask(with: request) { (data, response, err) in if let err = err { print(err) } guard let response = response as? HTTPURLResponse else { return } if response.statusCode == self.duplicatedCode { completion(false) } else if response.statusCode == self.notDuplicatedCode { completion(true) } }.resume() } }
true
ef1fb0cbdecb46487ac2c4e99cfdc91f6d9bee50
Swift
achernoprudov/ACNavigationBar
/ACNavigationBar/ACNavigationBar/StringUtils.swift
UTF-8
526
2.65625
3
[ "Apache-2.0" ]
permissive
// // StringUtils.swift // ACNavigationBar // // Created by Andrey Chernoprudov on 01/12/16. // Copyright © 2016 Little Stars. All rights reserved. // extension String { static func isEmpty(string: String?) -> Bool { return string?.isEmpty ?? true } static func isEmptyTrim(string: String?) -> Bool { return isEmpty(string: string?.trimmingCharacters(in: .whitespacesAndNewlines)) } static func isNotEmpty(string: String?) -> Bool { return !isEmpty(string: string) } }
true
2184db79eb088c18ddf15b8495597ef43d819f88
Swift
grstavares/OpenSource
/Apps/Swift/QRCodeReader/QRCodeReader/ScannerViewController.swift
UTF-8
4,963
2.609375
3
[]
no_license
// // ScannerViewController.swift // SwiftUIScanner // // Created by Tim Owings on 11/3/19. // Copyright 2019 Tim Owings. All rights reserved. // import AVFoundation import UIKit import SwiftUI final class ScannerViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate { var captureSession: AVCaptureSession! var previewLayer: AVCaptureVideoPreviewLayer! var qrCodeFrameView: UIView? override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.blue captureSession = AVCaptureSession() guard let videoCaptureDevice = AVCaptureDevice.default(for: .video) else { return } let videoInput: AVCaptureDeviceInput do { videoInput = try AVCaptureDeviceInput(device: videoCaptureDevice) } catch { return } if (captureSession.canAddInput(videoInput)) { captureSession.addInput(videoInput) } else { failed() return } let metadataOutput = AVCaptureMetadataOutput() if (captureSession.canAddOutput(metadataOutput)) { captureSession.addOutput(metadataOutput) metadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main) metadataOutput.metadataObjectTypes = [.qr, .ean13, .code128] } else { failed() return } previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) //previewLayer.frame = view.layer.bounds previewLayer.frame = view.layer.bounds previewLayer.videoGravity = .resizeAspectFill view.layer.addSublayer(previewLayer) captureSession.startRunning() // Initialize QR Code Frame to highlight the QR code qrCodeFrameView = UIView() if let qrCodeFrameView = qrCodeFrameView { qrCodeFrameView.layer.borderColor = UIColor.green.cgColor qrCodeFrameView.layer.borderWidth = 2 view.addSubview(qrCodeFrameView) view.bringSubviewToFront(qrCodeFrameView) } } func failed() { let ac = UIAlertController(title: "Scanning not supported", message: "Your device does not support scanning a code from an item. Please use a device with a camera.", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "OK", style: .default)) present(ac, animated: true) captureSession = nil } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if (captureSession?.isRunning == false) { captureSession.startRunning() } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) if (captureSession?.isRunning == true) { captureSession.stopRunning() } } func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) { captureSession.stopRunning() // Check if the metadataObjects array is not nil and it contains at least one object. if metadataObjects.count == 0 { qrCodeFrameView?.frame = CGRect.zero print("No QR code is detected") return } if let metadataObject = metadataObjects.first as? AVMetadataMachineReadableCodeObject { print(metadataObject.descriptor ?? "null") print(metadataObject.description) if [AVMetadataObject.ObjectType.qr, AVMetadataObject.ObjectType.ean13].contains(metadataObject.type) { let qrCodeObject = self.previewLayer.transformedMetadataObject(for: metadataObject) qrCodeFrameView?.frame = qrCodeObject!.bounds } guard let stringValue = metadataObject.stringValue else { return } AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate)) found(code: stringValue) } DispatchQueue.main.asyncAfter(deadline: .now() + 1) { self.dismiss(animated: true) } } func found(code: String) { print(code) } override var prefersStatusBarHidden: Bool { return true } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .portrait } } extension ScannerViewController: UIViewControllerRepresentable { public typealias UIViewControllerType = ScannerViewController func makeUIViewController(context: UIViewControllerRepresentableContext<ScannerViewController>) -> ScannerViewController { return ScannerViewController() } func updateUIViewController(_ uiViewController: ScannerViewController, context: UIViewControllerRepresentableContext<ScannerViewController>) { } }
true
f34f4b560743d9ec6f7ed845f61f11cac06dca6f
Swift
xiaocoolnet/meiweini_ios
/MWN_user_2016/BuyListViewController.swift
UTF-8
2,846
2.515625
3
[]
no_license
// // BuyListViewController.swift // MWN_user_2016 // // Created by apple on 16/4/27. // Copyright © 2016年 xiaocool. All rights reserved. // import UIKit class BuyListViewController: UIViewController,UITableViewDelegate,UITableViewDataSource { var buyTable = UITableView() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.view.backgroundColor = RGREY buyTable.frame = self.view.bounds buyTable.backgroundColor = RGREY buyTable.delegate = self buyTable.dataSource = self buyTable.separatorColor = RGREY buyTable.registerClass(BuyListTableViewCell.self, forCellReuseIdentifier: "cell") self.view.addSubview(buyTable) buyTable.rowHeight = 140 // buyTable.scrollEnabled = false } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 2 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)as!BuyListTableViewCell cell.selectionStyle = .None cell.busName.text = "四月是你的谎言" cell.staly.text = "进行中" cell.dateLab.text = "2016-04-28 17:30" cell.price.text = "¥88.88" cell.busNum.text = "已售:12" cell.busImage.image = UIImage(named: "kb4.png") cell.busCommon.text = "和他相遇的瞬间,我的人生就改变了。所见所闻所感,目之所及全都开始变得多姿多彩起来,全世界,都开始发光发亮!" cell.cancel.addTarget(self, action: #selector(BuyListViewController.cancalOrder), forControlEvents: .TouchUpInside) cell.pay.addTarget(self, action: #selector(BuyListViewController.payFor), forControlEvents: .TouchUpInside) return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { print("四月是你的谎言") } func cancalOrder() { print("取消订单") } func payFor() { print("去付款") } 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 prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
true
240e478d32eb30ad8ff8b61fc41594f415b9c31f
Swift
sgonzalez/SwiftCMA
/Sources/Utilities.swift
UTF-8
395
2.640625
3
[ "MIT" ]
permissive
// // Utilities.swift // SwiftCMAES // // Created by Santiago Gonzalez on 4/29/19. // Copyright © 2019 Santiago Gonzalez. All rights reserved. // import Foundation extension Collection { /// Syntactic sugar, equivalent to calling `.enumerated().map`. func indexedMap<T>(_ transform: ((offset: Int, element: Self.Element)) throws -> T) rethrows -> [T] { return try self.enumerated().map(transform) } }
true
419dc2a1c7bd22551fe7086df80d4bc8cdbabeda
Swift
AlaaMetwally/Recipes
/RecipeApi/ViewController.swift
UTF-8
2,135
2.734375
3
[]
no_license
// // ViewController.swift // RecipeApi // // Created by Geek on 10/4/20. // Copyright © 2020 Geek. All rights reserved. // import UIKit import Foundation import Alamofire class ViewController: UIViewController { @IBOutlet var tableView: UITableView! var recipe = [NSDictionary]() override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self tableView.delegate = self getRecipe() } } extension ViewController: UITableViewDelegate{ func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let recipeDetail = recipe[indexPath.row] as! NSDictionary let vc = RecipeDetailViewController(recipeDetail: recipeDetail) vc.recipe = recipeDetail } } extension ViewController: UITableViewDataSource{ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return recipe.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell",for: indexPath ) let recipeDetails = recipe[indexPath.row] as! NSDictionary cell.textLabel?.text = recipeDetails["label"] as! String return cell } func getRecipe() { var recipeArray = [NSDictionary]() let url = URL(string: "https://api.edamam.com/search?q=chicken&app_id=0d3d3583&app_key=3af486c6f67a782f8a2e5b6a1913757e")! Alamofire.request(url, method: .post, encoding: JSONEncoding.default) .responseJSON { response in if let result = response.result.value { let JSON = result as! NSDictionary for jsonHits in JSON["hits"] as! NSArray{ let hits = jsonHits as! NSDictionary recipeArray.append(hits["recipe"] as! NSDictionary) } self.recipe = recipeArray self.tableView.reloadData() } } } }
true
d206e5695cfa5d10a950f7befba9d59d41ffcb46
Swift
spencerHolm/backCountryGNAR
/GNAR/Views/RulesDetail.swift
UTF-8
2,089
3
3
[]
no_license
// // RulesDetail.swift // GNAR // // Created by Spencer Holm on 3/18/21. // import SwiftUI struct RulesDetail: View { @EnvironmentObject var settings: GameSettings var points: Points var body: some View { ZStack{ Color.init(red: 90.0/255.0, green: 205.0/255.0, blue: 255.0/255.0).ignoresSafeArea() VStack{ VStack(alignment: .leading){ Text("Type: \(points.type)") .font(.title2) .foregroundColor(.secondary) HStack{ Text(points.name) Spacer() Text("\(points.points) pts") } .font(.title) Divider() Text("Description:") .font(.title2) .foregroundColor(.secondary) Text(points.description) .navigationTitle(points.name) .navigationBarTitleDisplayMode(.automatic) } Button(action: { settings.score += strToInt(str: points.points) }){ Text("Add") } .buttonStyle(CustomButtonStyle()) Button(action: { settings.score -= strToInt(str: points.points) }){ Text("Remove") } .buttonStyle(RemoveButtonStyle()) Spacer() } .padding() } } } func strToInt(str: String) -> Int { var str = str str.removeAll {$0 == ","} return Int(str) ?? 0 } struct RulesDetail_Previews: PreviewProvider { static var previews: some View { RulesDetail(points: ruleslist[0].rules[0]) } }
true
dd1a1a1b6a41425da8da6643db85a397141329d3
Swift
AnuragMishra/ThrottledChannel
/Playground.playground/Sources/ThrottledChannel.swift
UTF-8
1,291
3.53125
4
[]
no_license
import Foundation /** Provides values sent to the channel to a consumer at a rate throttled based on the processing capabilities of the consumer. */ public class ThrottledChannel<T> { private var value: T? private let source: DispatchSourceUserDataAdd /** Initializes the channel with a reader block that will get values published to the channel. The block is invoked with the latest value published to the channel, and is not guaranteed to receive all values. Should be used for non-essential data where the consumer is interested in knowing the latest value at a rate it is comfortable processing at. - Parameter readLatest: A block that is invoked with the latest available value */ public init(readLatest: @escaping (T) -> ()) { source = DispatchSource.makeUserDataAddSource() source.setEventHandler { [weak self] in if let strongSelf = self, let value = strongSelf.value { readLatest(value) } } source.resume() } /** Publishes a value to the channel - Parameter value: Value to publish */ public func send(_ value: T) { self.value = value source.add(data: 1) } }
true
ee22b1c828c9650e9dc922851694d2303ac6658a
Swift
eajang/iOS-Example-ComplexInputScreens
/ComplexInputScreensDemo/Registration.swift
UTF-8
478
2.734375
3
[ "MIT" ]
permissive
// // Registration.swift // ComplexInputScreensDemo // // Created by Eunae Jang on 17/09/2019. // Copyright © 2019 Eunae Jang. All rights reserved. // import Foundation struct Registration { static let wifiCost = 10 var firstName: String var lastName: String var emailAddress: String var checkInDate: Date var checkOutDate: Date var numberOfAdults: Int var numberOfChildern: Int var roomType: RoomType var wifi: Bool }
true
ed671ef796bb2d6fd9740f92928f32d3c0eb60ce
Swift
RusChr/concurrency-kit
/Tests/ConcurrencyKitTests/AtomicBoolTests.swift
UTF-8
1,132
2.78125
3
[ "MIT" ]
permissive
// // AtomicBoolTests.swift // ConcurrencyKitTests // // Created by Astemir Eleev on 10/03/2019. // Copyright © 2019 Astemir Eleev. All rights reserved. // import XCTest @testable import ConcurrencyKit class AtomicBoolTests: XCTestCase { static var allTests = [ ("testSet", testSet), ("testGet", testGet) ] override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testSet() { let atomic = AtomicBool(true) atomic.set(false) XCTAssertEqual(atomic.value, false) } func testGet() { let atomic = AtomicBool(false) atomic.set(true) let value = atomic.get() XCTAssertEqual(value, true) } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
true
dd010211aef1d6878051f8ab80466565413afc31
Swift
aashishtamsya/Cacher
/Sources/Cache/Protocols/Cache.swift
UTF-8
410
2.84375
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// // Cacheable.swift // Cacher // // Created by Aashish Tamsya on 24/06/19. // Copyright © 2019 Aashish Tamsya. All rights reserved. // import Foundation public protocol Cache { func store<T: Cachable>(_ setting: (to: CacheType, key: String), object: T, _ completion: (() -> Void)?) func retrieve<T: Cachable>(from: CacheType, key: String, _ completion: @escaping (_ object: T?) -> Void) func removeAll() }
true
dd35488a712d78ca3678a09df4fb949e79f041a8
Swift
digime/digime-sdk-ios
/Sources/DigiMeSDK/Files/File.swift
UTF-8
3,101
2.953125
3
[ "Apache-2.0" ]
permissive
// // File.swift // DigiMeSDK // // Created on 24/06/2021. // Copyright © 2021 digi.me Limited. All rights reserved. // import Foundation import UIKit /// Represents a file retrieved from library public struct File: Codable { /// The identifier of the file public let identifier: String /// The file's metadata public let metadata: FileMetadata /// The file's raw data public let data: Data /// The file's raw data public let updatedDate: Date /// The file's MIME type public var mimeType: MimeType { switch metadata { case .mapped: return .applicationOctetStream case .raw(let meta): return meta.mimeType case .none: return .applicationOctetStream } } enum CodingKeys: String, CodingKey { case identifier case metadata case data case updatedDate case mimeType } /// Convenience function to return data as JSON object, if possible /// - Returns: JSON object or nil if deserialization unsuccesful @discardableResult public func toJSON(persistResult: Bool = false) -> Any? { guard mimeType == .applicationJson || mimeType == .applicationOctetStream else { return nil } let result = try? JSONSerialization.jsonObject(with: data, options: []) if persistResult, let result = result as? [[String: Any]] { FilePersistentStorage(with: .documentDirectory).store(object: result, fileName: identifier) } return result } /// Convenience function to return data as UIImage, if possible /// - Returns: UIImage or nil if mime type is not an image type public func toImage() -> UIImage? { let imageMimeTypes: [MimeType] = [.imageBmp, .imageGif, .imagePng, .imageJpeg, .imageTiff] guard imageMimeTypes.contains(mimeType) else { return nil } return UIImage(data: data) } init(fileWithId id: String, rawData: Data, metadata: FileMetadata, updated: Date) { identifier = id data = rawData updatedDate = updated self.metadata = metadata } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) identifier = try container.decode(String.self, forKey: .identifier) metadata = try container.decode(FileMetadata.self, forKey: .metadata) data = try container.decode(Data.self, forKey: .data) updatedDate = try container.decode(Date.self, forKey: .updatedDate) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(identifier, forKey: .identifier) try container.encode(metadata, forKey: .metadata) try container.encode(updatedDate, forKey: .updatedDate) try container.encode(mimeType, forKey: .mimeType) } }
true
69896e6359e9ed1b454d676e6bcf15567a1b1cbd
Swift
zakywisnu/MasakApaHariIni-Swift
/Food Recipes/Core/Utils/Network/ApiCall.swift
UTF-8
1,333
3.15625
3
[]
no_license
// // ApiCall.swift // Food Recipes // // Created by Ahmad Zaky on 20/05/21. // import Foundation struct API { static let baseUrl = "https://masak-apa.tomorisakura.vercel.app" } protocol Endpoint { var url: String {get} } enum Endpoints { enum Gets: Endpoint { case category case recipesCategory(key: String) case recipeDetail(key: String) case article case articleCategory(key: String) case articleDetail(tag: String, key: String) case search(query: String) public var url: String{ switch self { case .category: return "\(API.baseUrl)/api/categorys/recipes" case .recipesCategory(let key): print("network","\(API.baseUrl)/api/categorys/recipes/\(key)") return "\(API.baseUrl)/api/categorys/recipes/\(key)" case .recipeDetail(let key): return "\(API.baseUrl)/api/recipe/\(key)" case .article: return "\(API.baseUrl)/api/categorys/article" case .articleCategory(let key): return "\(API.baseUrl)/api/categorys/article/\(key)" case .articleDetail(let tag, let key): return "\(API.baseUrl)/api/article/\(tag)/\(key)" case .search(let query): return "\(API.baseUrl)/api/search/?q=\(query)" } } } }
true
f0d73545b84704073a0d0a2d88c95fa251f66a0b
Swift
ximhear/metal-filter-camera
/MetalFilterCamera/Filter/GDivideFilter.swift
UTF-8
1,309
2.515625
3
[]
no_license
// // GDivideFilter.swift // MetalImageFilter // // Created by LEE CHUL HYUN on 4/17/19. // Copyright © 2019 LEE CHUL HYUN. All rights reserved. // import Foundation import Metal struct DivideUniforms { var divider: Int32 } class GDivideFilter: GImageFilter { var _divider: Int32 = 1 var divider: Int32 { get { return _divider } set { self.isDirty = true _divider = newValue } } var uniforms: UnsafeMutablePointer<DivideUniforms> override init?(context: GContext, filterType: GImageFilterType) { guard let buffer = context.device.makeBuffer(length: MemoryLayout<PixellationUniforms>.size, options: [MTLResourceOptions.init(rawValue: 0)]) else { return nil } uniforms = UnsafeMutableRawPointer(buffer.contents()).bindMemory(to:DivideUniforms.self, capacity:1) super.init(functionName: "divide", context: context, filterType: filterType) uniformBuffer = buffer } override func configureArgumentTable(commandEncoder: MTLComputeCommandEncoder) { uniforms[0].divider = divider commandEncoder.setBuffer(self.uniformBuffer, offset: 0, index: 0) } override func setValue(_ value: Float) { divider = Int32(value) } }
true
97a07bb20dbe770c66e13adba717654e155accc8
Swift
keitin/Tumbfolio
/Tumbfolio/User.swift
UTF-8
690
2.890625
3
[]
no_license
// // User.swift // Tumbfolio // // Created by 松下慶大 on 2017/04/13. // Copyright © 2017年 matsushita keita. All rights reserved. // import Foundation import Himotoki struct User: Decodable { var name: String var title: String var description: String var posts: [Post] static func decode(_ e: Extractor) throws -> User { return try User( name: e <| ["blog", "name"], title: e <| ["blog", "title"], description: e <| ["blog", "description"], posts: e <|| ["posts"]) } func avatarURL() -> URL { return URL(string: "https://api.tumblr.com/v2/blog/\(name)/avatar/128")! } }
true
73de3c48f4ca8ad5b6a4845b054b4734cbba6977
Swift
AdamDavidsson/MultiDub
/MultiDub/Services/Models/FeedSectionStruct.swift
UTF-8
1,956
2.90625
3
[]
no_license
// // FeedSectionStruct.swift // MultiDub // // Created by iMac on 2/3/17. // Copyright © 2017 MultiDub. All rights reserved. // class FeedSectionStruct: NSObject { var type: FeedType? var arrItems = Array<AnyObject>() func initWithJsonData(array : Array<Dictionary<String, AnyObject>>) -> Void { let item = array[0] type = self.parseItemType(item["__type"] as! String) for item in array { switch type! { case .Dubbed: let newitem = FeedDubbedStruct(dict: item) arrItems.append(newitem) case .Hot: let newitem = FeedHotStruct(dict: item) arrItems.append(newitem) case .HotList: let newitem = FeedHotListStruct() newitem.initWithJson(item) arrItems.append(newitem) case .MultiDubbers: let newitem = FeedMultiDubbersStruct() newitem.initWithJson(item) arrItems.append(newitem) case .Sponsored: let newitem = FeedSponsoredStruct(dict: item) arrItems.append(newitem) default: break } } } func parseItemType(stype:String) -> FeedType { if stype == "Sponsored:#MultiDubWcfServiceApp" { return .Sponsored } else if stype == "Dubbed:#MultiDubWcfServiceApp" { return .Dubbed } else if stype == "Hot:#MultiDubWcfServiceApp" { return .Hot } else if stype == "HotList:#MultiDubWcfServiceApp" { return .HotList } else if stype == "MultiDubbers:#MultiDubWcfServiceApp" { return .MultiDubbers } return .Unknown } }
true
d9bcd615286f60f67422ef91b7e7f4ec4494f840
Swift
RickyAvina/HotDogDetector
/ViewController.swift
UTF-8
2,807
2.546875
3
[]
no_license
// // ViewController.swift // HotDogDetector // // Created by Enrique Aviña on 6/2/20. // Copyright © 2020 Enrique Aviña. All rights reserved. // import UIKit import CoreML import AVKit import Vision import ImageIO class ViewController: UIViewController, AVCaptureVideoDataOutputSampleBufferDelegate { var textLayer = CATextLayer() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let captureSession = AVCaptureSession() captureSession.sessionPreset = .photo guard let captureDevice = AVCaptureDevice.default(for: .video) else { return } guard let input = try? AVCaptureDeviceInput(device: captureDevice) else { return } captureSession.addInput(input) captureSession.startRunning() let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) view.layer.addSublayer(previewLayer) previewLayer.frame = view.frame textLayer.frame = CGRect(x: view.bounds.midX-130, y: view.bounds.maxY-50, width: 400, height: 50) textLayer.fontSize = 32 textLayer.string = "my text" textLayer.foregroundColor = UIColor.red.cgColor textLayer.contentsScale = UIScreen.main.scale view.layer.addSublayer(textLayer) let dataOutput = AVCaptureVideoDataOutput() dataOutput.setSampleBufferDelegate(self, queue: DispatchQueue(label: "videoQueue")) captureSession.addOutput(dataOutput) } func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) { guard let pixelBuffer: CVPixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return } guard let model = try? VNCoreMLModel(for: nicehotdog().model) else { print("Model conversion failed (might not have image input") return } let request = VNCoreMLRequest(model: model) { (finishedRequest, error) in // check error guard let results = finishedRequest.results as? [VNClassificationObservation] else { return } guard let firstObservation = results.first else { return } DispatchQueue.global(qos: .background).async { CATransaction.begin() CATransaction.setDisableActions(true) self.textLayer.string = (firstObservation.identifier == "not_hot_dog" ? "Not hot dog" : "hot dog") + ": " + String(format: "%.2f", Double(firstObservation.confidence)*100) + "%" CATransaction.commit() } } try? VNImageRequestHandler(cvPixelBuffer: pixelBuffer, options: [:]).perform([request]) } }
true
8cee4a0fe8e2bfd2ba86c31908af9b4d6b36113c
Swift
Adilbek12/Oyna
/Oy'na 2/resourse/Colors.swift
UTF-8
597
2.75
3
[]
no_license
import UIKit struct Colors { public static let BORDER_COLOR = getColor(r: 170, g: 208, b: 156) public static let PLACEHOLDER_COLOR = getColor(r: 255, g: 255, b: 255) public static let GRAY = Gradient.init(t: getColor(r: 255, g: 255, b: 255), m: nil, b: getColor(r: 100, g: 100, b: 100)) public static let RED = Gradient.init(t: getColor(r: 255, g: 9, b: 9), m: nil, b: getColor(r: 128, g: 5, b: 5)) public static func getColor(r: CGFloat, g: CGFloat, b: CGFloat) -> UIColor { return UIColor.init(red: r/255, green: g/255, blue: b/255, alpha: 1) } }
true
732165556238d00b36717898b74fd26bfba211b2
Swift
anstjaos/Health-Service-IOS
/health-service/health-service/model/dto/UserInfoDto.swift
UTF-8
570
3
3
[]
no_license
import Foundation class UserInfoDto { private var _userId: String private var _pwd: String private var _email: String init(userId: String, pwd: String, email: String) { self._userId = userId self._pwd = pwd self._email = email } public var userId: String { get { return self._userId } } public var pwd: String { get { return self._pwd } } public var email: String { get { return self._email } } }
true
091f72a7eabc03af0da4fa0ce066a7a765923aae
Swift
akrolayer/Metronome
/Metronome/MetronomeUITests/MetronomeUITests.swift
UTF-8
4,827
2.671875
3
[]
no_license
// // MetronomeUITests.swift // MetronomeUITests // // Created by akrolayer on 2020/07/31. // Copyright © 2020 akrolayer. All rights reserved. // import XCTest class MetronomeUITests: 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 testViewController() throws { // //pickerを二つ並べ、それを下から出しているがそのテスト方法がわかっていない // let app = XCUIApplication() // let bpmTextField = app.textFields["bpmTextBox"] // bpmTextField.tap() // // //XCUIApplication().pickerWheels["picker"].adjust(toPickerWheelValue: "130") // // let firstPredicate = NSPredicate(format: "label BEGINSWITH 'PickerWheel'") // let firstPicker = app.pickerWheels.element(matching: firstPredicate) // firstPicker.adjust(toPickerWheelValue: "123") // let secondPredicate = NSPredicate(format: "label BEGINSWITH 'PickerWheel") // let secondPicker = app.pickerWheels.element(matching: secondPredicate) // secondPicker.adjust(toPickerWheelValue: "16") // // app.buttons["done"].tap() // // XCTAssertEqual(app.staticTexts["changedBPMLabel"].label, "130") } func testNextViewController() throws { // UI tests must launch the application that they test. let app = XCUIApplication() app.launch() // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. //let bpmTextField = app.textFields["bpmTextBox"] //bpmTextField.doubleTap() let silentkeepButton = app.buttons["silentKeepButton"] silentkeepButton.tap() let startButton = app.buttons["startButton1"] let stopButton = app.buttons["stopButton1"] //存在確認 XCTAssert(startButton.exists) XCTAssertTrue(startButton.isEnabled) XCTAssert(stopButton.exists) XCTAssertFalse(stopButton.isEnabled) //Enable,Unableの切り替え startButton.tap() XCTAssertTrue(stopButton.isEnabled) XCTAssertFalse(startButton.isEnabled) stopButton.tap() XCTAssertTrue(startButton.isEnabled) XCTAssertFalse(stopButton.isEnabled) //枠内に入っているか確認 let window = app.windows.element(boundBy: 0) XCTAssert(window.frame.contains(startButton.frame)) XCTAssert(window.frame.contains(stopButton.frame)) startButton.tap() sleep(12) stopButton.tap() XCTAssertEqual(app.staticTexts["resultLabel"].label, "0拍ずれたよ!") } func testNextViewController2() throws { // UI tests must launch the application that they test. let app = XCUIApplication() app.launch() let constantKeepButton = app.buttons["constantKeepButton"] constantKeepButton.tap() let startButton = app.buttons["startButton2"] let stopButton = app.buttons["stopButton2"] //存在確認 XCTAssert(startButton.exists) XCTAssertTrue(startButton.isEnabled) XCTAssert(stopButton.exists) XCTAssertFalse(stopButton.isEnabled) //枠内に入っているか確認 let window = app.windows.element(boundBy: 0) XCTAssert(window.frame.contains(app.buttons["startButton2"].frame)) //画像が変わっているか確認 let image = startButton.images startButton.tap() XCTAssertTrue(app.buttons["stopButton2"].isEnabled) XCTAssertFalse(app.buttons["startButton2"].images == image) XCTAssert(window.frame.contains(app.buttons["stopButton2"].frame)) for _ in 0...11{ startButton.tap() sleep(1) } XCTAssertEqual(app.staticTexts["textView"].label, "0拍ずれたよ!") } func testLaunchPerformance() throws { if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) { // This measures how long it takes to launch your application. measure(metrics: [XCTOSSignpostMetric.applicationLaunch]) { XCUIApplication().launch() } } } }
true
d676c23592a9495f455b967c49e667bb278dcae6
Swift
cutesparrow/Melbourne-Exercise-Client
/MelbourneRun/Model/JoggingPathCardModel.swift
UTF-8
644
2.609375
3
[]
no_license
// // JoggingPathCardModel.swift // MelbExercise // // Created by gaoyu shi on 8/4/21. // import Foundation struct WalkingRouteCard:Codable,Identifiable{ var id:Int var image:String var distance:Double var risk:String var time:String var instructions:[String] var polyline:String } struct CyclingCard:Codable,Identifiable{ var id:Int var path:[Coordinate] var distance:Double var risk:String var time:String var popularStar:Int var distanceToUser:Double var polyline:String } struct Cards:Codable { var customizedCards:[WalkingRouteCard] var popularCards:[CyclingCard] }
true
3ac70a50c6435eaa117fde3ae7c17231d5f1a644
Swift
Robbiekorneta11/NIU-School-Work
/CSCI321/Assignment5/Assignment5/ImageStore.swift
UTF-8
2,772
3.171875
3
[]
no_license
// // imageStore.swift // Assignment5 // // Created by Robbie Korneta on 11/19/20. // Copyright © 2020 Robbie Korneta. All rights reserved. // import Foundation import UIKit class ImageStore { let imageCache = NSCache<NSString, AnyObject>() func downloadImage(with urlString: String, completion: @escaping (_ image: UIImage?) -> Void) { if urlString == "None" { completion(UIImage(named: "default.png")) } else if let cachedImage = imageCache.object(forKey: urlString as NSString) as? UIImage { completion(cachedImage) } else { weak var weakSelf = self if let url = URL(string: urlString) { let task = URLSession.shared.dataTask(with: url) { (data, response, error) in let httpResponse = response as? HTTPURLResponse if httpResponse!.statusCode != 200 { // Perform some error handling // UI updates, like alerts, should be directed to the main thread DispatchQueue.main.async { print("HTTP Error: status code \(httpResponse!.statusCode)") completion(UIImage(named: "default.png")) } } else if (data == nil && error != nil) { // Perform some error handling DispatchQueue.main.async { print("No data downloaded for \(urlString)") completion(UIImage(named: "default.png")) } } else { // Download succeeded if let image = UIImage(data: data!) { DispatchQueue.main.async { weakSelf!.imageCache.setObject(image, forKey: urlString as NSString) completion(image) } } else { DispatchQueue.main.async { print("\(urlString) is not a valid image") completion(UIImage(named: "default.png")) } } } } task.resume() } else { DispatchQueue.main.async { print("\(urlString) is not a valid URL") completion(UIImage(named: "default.png")) } } } } func clearCache() { imageCache.removeAllObjects() } }
true
7fba59c0631cf67020962437be8f881b47dadcb6
Swift
hallomuze/ApiSampleUsingCache
/MoneyRank/APIService.swift
UTF-8
1,186
2.953125
3
[]
no_license
// // APIService.swift // MoneyRank // // Created by eddie kwon on 6/5/17. // Copyright © 2017 hallomuze. All rights reserved. // import UIKit public typealias jsonResultType = (URLResponse? , Data?) -> Void public class APIService: NSObject { static let sharedInstance = APIService() private override init(){ } public func requestHttp(urlString : String , handler:@escaping jsonResultType){ let sessionConfiguration = URLSessionConfiguration.default guard let encodeString = urlString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) else{ return } guard let url = URL(string: encodeString) else { return } var request = URLRequest(url:url) request.httpMethod = "GET" let urlSession = URLSession( configuration:sessionConfiguration, delegate: nil, delegateQueue: nil) let sessionTask = urlSession.dataTask(with:request){ (data,response,error) in handler(response,data) } sessionTask.resume() } }
true
54d836d082f82bbcdc7c21d6d945b8a44511474d
Swift
danilaferents/wagon
/Shared/View/RoundedViews.swift
UTF-8
892
2.8125
3
[]
no_license
// // RoundedVIews.swift // wagon // // Created by Danila Ferents on 16/04/2019. // Copyright © 2019 Danila Ferents. All rights reserved. // import Foundation import UIKit //Classes of a round objects class RoundedButton : UIButton { override func awakeFromNib() { super.awakeFromNib() layer.cornerRadius = 10 //Make corners angled } } class RoundedShadowView: UIView { override func awakeFromNib() { super.awakeFromNib() layer.cornerRadius = 5 //Make corners angled layer.shadowColor = AppColors.Blue.cgColor //Color for corners layer.shadowOpacity = 0.4 //Make View transparent layer.shadowOffset = CGSize.zero //shadow bias layer.shadowRadius = 3 //make shadow bigger } } class RoundedImageView: UIImageView { override func awakeFromNib() { super.awakeFromNib() layer.cornerRadius = 5 } }
true
5ded2a0e64f4bd58fecc85b44e3cb30582ee192c
Swift
yangqingqinglove/OpticalValleyUnite
/OpticalValleyUnite/Classes/UI/WorkOrder/View/YQPartDataCell.swift
UTF-8
2,716
2.734375
3
[]
no_license
// // YQPartDataCell.swift // OpticalValleyUnite // // Created by 杨庆 on 2017/8/31. // Copyright © 2017年 贺思佳. All rights reserved. // import UIKit protocol YQPartDataCellSwitchDelegate : class{ func partDataCellSwitchDelegate(tableView : UITableView,numIndex: Int, model : PartsModel) func partDataCellSwitchDelegateMoveModel( numIndex : Int,model : PartsModel) } class YQPartDataCell: UITableViewCell { // MARK: - 加载的属性 @IBOutlet weak var `switch`: UIButton! @IBOutlet weak var part: UILabel! @IBOutlet weak var partName: UILabel! @IBOutlet weak var numText: UITextField! // 缓存行号 var indexPath : Int = 0 var tableView : UITableView! // 模型的设置是有问题,设置的 var modelcell : PartsModel? { didSet{ self.part.text = modelcell?.position self.partName.text = modelcell?.partsName self.numText.text = modelcell?.partNum } } /// 定义代理 weak var delegate : YQPartDataCellSwitchDelegate? //MARK: - 点击加载方法 @IBAction func switchClick(_ sender: Any) { self.switch.isSelected = !self.switch.isSelected if self.switch.isSelected { self.numText.isUserInteractionEnabled = true // modelcell?.partNum = self.numText.text //调用代理,传递值的 数量的情况 // self.delegate?.partDataCellSwitchDelegate(num: self.numText.text!,numIndex: self.indexPath, model : self.modelcell!) }else{ self.numText.isUserInteractionEnabled = false // self.delegate?.partDataCellSwitchDelegateMoveModel(numIndex: self.indexPath, model: self.modelcell!) } } override func awakeFromNib() { self.numText.delegate = self } } extension YQPartDataCell : UITextFieldDelegate{ func textFieldDidEndEditing(_ textField: UITextField) { self.isEditing = false //合成模型: var dict = [String : Any]() dict["position"] = self.part.text dict["partsName"] = self.partName.text dict["partNum"] = self.numText.text dict["partsId"] = modelcell?.partsId let newModel = PartsModel(dict: dict as [String : AnyObject]) // newModel!.partNum = self.part.text // newModel!.partsName = self.partName.text self.delegate?.partDataCellSwitchDelegate(tableView: tableView, numIndex: self.indexPath, model: newModel) } }
true
f405bbb5711f3020ee7e507f1646543c65ba9da1
Swift
DanielCardonaRojas/SwiftVerify
/Tests/VerifyTests/SampleModels.swift
UTF-8
1,137
3.21875
3
[]
no_license
// // File.swift // // // Created by Daniel Rojas on 18/04/21. // import Foundation struct Pizza { let ingredients: [String] let size: Int } struct UserRegistration { let email: String let password: String let passwordConfirmation: String } enum UserRegistrationError: Error { case invalidEmail, invalidPassword, passwordsDontMatch } struct FormError<FieldType>: Error { enum Reason { case invalidFormat, required, needsMatch } let reason: Reason let field: FieldType static func required(_ field: FieldType) -> FormError { .init(reason: .required, field: field) } static func badFormat(_ field: FieldType) -> FormError { .init(reason: .invalidFormat, field: field) } } typealias LoginFormError = FormError<LoginField> enum LoginField { case email, password, passwordConfirmation } struct FormField<FieldType> { var visited = false let field: FieldType var text = "" } struct LoginForm { typealias Field = FormField<LoginField> var emailField: Field var passwordField: Field var passwordConfirmationField: Field }
true
58f2efa721441117e5255b6faf015f55f3a7e090
Swift
krazzbeluh/VigiClean
/VigiClean/Model/ErrorHandler.swift
UTF-8
1,555
2.78125
3
[]
no_license
// // ErrorHandler.swift // VigiClean // // Created by Paul Leclerc on 21/12/2019. // Copyright © 2019 Paul Leclerc. All rights reserved. // import Foundation import FirebaseAuth import FirebaseStorage import FirebaseFirestore import FirebaseFunctions // Manages errors. Converts firebase errors and contains global Error cases class ErrorHandler { enum Errors: Error { case canNotConvertError } func convertToAuthError(_ error: Error) -> AuthErrorCode! { return AuthErrorCode(rawValue: error._code) } func convertToStorageError(_ error: Error) -> StorageErrorCode! { return StorageErrorCode(rawValue: error._code) } func convertToFirestoreError(_ error: Error) -> FirestoreErrorCode! { return FirestoreErrorCode(rawValue: error._code) } func convertToFunctionsError(_ error: Error) -> FunctionsErrorCode! { return FunctionsErrorCode(rawValue: error._code) } } enum ScannerError: Error { case scanNotSupported, invalidQRCode } enum UserError: Error { case nilInTextField, passwordMismatches, unWantedValues } enum FirebaseInterfaceError: Error { case documentDoesNotExists, unableToDecodeData, unableToDecodeError } enum AlertStrings: String { case ok = "OK" // swiftlint:disable:this identifier_name case error = "Erreur !" case cancel = "Annuler" case copy = "Copier" } extension AuthErrorCode: Error {} extension StorageErrorCode: Error {} extension FunctionsErrorCode: Error {} extension FirestoreErrorCode: Error {}
true
f2b00357028d5d7c8bb1b55f1f9c3d04c0f526b0
Swift
our-spring-day/Demo-iOS
/MannaDemo/Map/Component/InputBar.swift
UTF-8
1,979
2.703125
3
[]
no_license
// // InputBar.swift // MannaDemo // // Created by once on 2020/11/18. // import UIKit import UITextView_Placeholder class InputBar: UIView { let textView = UITextView().then { $0.textColor = .black $0.isEditable = true $0.font = UIFont(name: "NotoSansKR-Regular", size: 15) $0.showsVerticalScrollIndicator = false $0.layer.cornerRadius = 20 $0.layer.borderWidth = 1 $0.layer.borderColor = #colorLiteral(red: 0.8549019608, green: 0.8549019608, blue: 0.8549019608, alpha: 1) $0.backgroundColor = .white $0.placeholder = "메세지 작성" $0.placeholderColor = UIColor.lightGray $0.textContainerInset = UIEdgeInsets(top: 7, left: 7, bottom: 7, right: 7) } let sendButton = UIButton(frame: CGRect(x: 0, y: 0, width: MannaDemo.convertWidth(value: 17), height: MannaDemo.convertHeight(value: 17))) .then { $0.setImage(UIImage(named: "good"), for: .normal) $0.imageView?.contentMode = .scaleAspectFit $0.imageEdgeInsets = UIEdgeInsets(top: 7, left: 7, bottom: 7, right: 7) } override init(frame: CGRect) { super.init(frame: frame) self.addSubview(self.textView) self.addSubview(self.sendButton) self.textView.snp.makeConstraints { $0.top.equalTo(5) $0.leading.equalTo(13) $0.bottom.equalTo(-7) $0.width.equalTo(300) $0.height.equalTo(40) } self.sendButton.snp.makeConstraints { $0.top.equalTo(5) $0.bottom.equalTo(-7) $0.leading.equalTo(textView.snp.trailing).offset(8) $0.trailing.equalTo(-10) } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
true
ff7b44de35ac8ee06d7b151461168c49f92bf346
Swift
guitarguy199/stickershutter
/Meme AR/Views/CategoryCell.swift
UTF-8
1,074
2.8125
3
[]
no_license
// // CategoryCell.swift // Meme AR // // Created by Austin O'Neil on 2/12/21. // import UIKit class CategoryCell: UICollectionViewCell { @IBOutlet weak var categoryImageView: UIImageView! @IBOutlet weak var categoryLabel: UILabel! @IBOutlet weak var bgView: UIView! @IBDesignable class RoundedCornerView: UIView { @IBInspectable var cornerRadius: CGFloat { set { layer.cornerRadius = newValue} get { return layer.cornerRadius} } } override func awakeFromNib() { super.awakeFromNib() bgView.bringSubviewToFront(categoryLabel) bgView.bringSubviewToFront(categoryImageView) bgView.layer.shadowColor = UIColor.black.cgColor bgView.layer.shadowRadius = 2.0 bgView.layer.shadowOffset = .zero bgView.layer.shadowOpacity = 0.5 } func setData(category: String, image: String) { self.categoryLabel.text = category self.categoryImageView.image = UIImage(named: image) } }
true
0181ab1005f290f4c23476a282088b388ff16ed8
Swift
alinahambaryan/MasterDetailinSWIFT
/MasterDetailinSWIFT/DataProvider.swift
UTF-8
2,535
3.25
3
[]
no_license
// // DataProvider.swift // MasterDetailinSWIFT // // Created by Alina Hambaryan on 1/25/16. // Copyright © 2016 Alina Hambaryan. All rights reserved. // import Foundation class DataProvider: NSObject { class func getSampleData() -> [[String: String]] { let userInfo1 = [ "first_name": "John", "last_name" : "Appleased", "job_title" : "dancer", "info" : "American pioneer nurseryman who introduced apple trees to large parts of Pennsylvania, Ontario, Ohio, Indiana, and Illinois, as well as the northern counties of present-day West Virginia. He became an American legend while still alive, due to his kind, generous ways, his leadership in conservation, and the symbolic importance he attributed to apples. He was also a missionary for The New Church (Swedenborgian)[1] and the inspiration for many museums and historical sites such as the Johnny Appleseed Museum[2] in Urbana, Ohio and the Johnny Appleseed Heritage Center[3] in between Lucas, Ohio and Mifflin, Ohio." ]; let userInfo2 = [ "first_name": "Michael", "last_name" : "Jackson", "job_title" : "rockstar", "info" : "Aspects of Michael Jackson's personal life, including his changing appearance, personal relationships, and behavior, generated controversy. In the mid-1990s, he was accused of child sexual abuse, but the civil case was settled out of court for an undisclosed amount and no formal charges were brought.[9] In 2005, he was tried and acquitted of further child sexual abuse allegations and several other charges after the jury found him not guilty on all counts. While preparing for his comeback concert series titled This Is It, Jackson died of acute propofol and benzodiazepine intoxication on June 25, 2009, after suffering from cardiac arrest." ]; let userInfo3 = [ "first_name": "Alina", "last_name" : "Hambaryan", "job_title" : "engineer", "info" : "Languages are living works. They are nudged and challenged and bastardized and mashed-up in a perpetual cycle of undirected and rapid evolution. Technologies evolve, requirements change, corporate stewards and open source community come and go; obscure dialects are vaulted to prominence on the shoulders of exciting new frameworks, and thrust into a surprising new context after a long period of dormancy. ~ NSHipster" ]; return [userInfo1, userInfo2, userInfo3]; } }
true
5333779ac8bb3372703a3882f823f18b8a27588b
Swift
ie-ModelingAndDesign/2015-B
/KyoujuApp/KyoujuApp/ViewController.swift
UTF-8
4,008
2.796875
3
[]
no_license
// // ViewController.swift // KyoujuApp // // Created by 與世山 喬基 on 2015/12/01. // Copyright © 2015年 與世山 喬基. All rights reserved. // import UIKit import RealmSwift class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var addButton: UIButton! // Relamのインスタンスを取得 let realm = try! Realm() // 登録するタスクを格納するリスト(〆切が近い順でソート) let dataArray = try! Realm().objects(Task).sorted("date", ascending: true) override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // 入力画面から戻って来たらテーブルを更新する override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) tableView.reloadData() } // 画面遷移するときのイベント // セルが押されたらタスクを表示 // 追加ボタンが押されたら空のタスク画面を表示 override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){ let inputViewController:InputViewController = segue.destinationViewController as! InputViewController if segue.identifier == "cellSegue" { let indexPath = self.tableView.indexPathForSelectedRow inputViewController.task = dataArray[indexPath!.row] } else { let task = Task() if dataArray.count != 0 { task.id = dataArray.max("id")! + 1 } inputViewController.task = task } } // UITableViewDataSourceプロトコルのメソッド // TableViewの各セクションのセルの数を返す func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataArray.count } // 各セルの内容を返す func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // 再利用可能なcellを得る let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Cell") // cellに値を設定する. let object = dataArray[indexPath.row] // 日付のフォーマットを生成 let dateFormatter: NSDateFormatter = NSDateFormatter() dateFormatter.locale = NSLocale(localeIdentifier:"ja_JP") dateFormatter.dateFormat = "yyyy年MM月dd日(EEE)" // 日付のフォーマットに則って〆切期日を取得 let dateLimit: NSString = dateFormatter.stringFromDate(object.date) // 各セルにレポート名と〆切を表示 cell.textLabel?.text = object.title cell.detailTextLabel?.text = "〆切:\(dateLimit)" return cell } // UITableViewDataSourceプロトコルのメソッド // Deleteボタンが押された時の処理を行う func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == UITableViewCellEditingStyle.Delete { try! realm.write { self.realm.delete(self.dataArray[indexPath.row]) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade) } } } // セルが削除が可能なことを伝える func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath)-> UITableViewCellEditingStyle { return UITableViewCellEditingStyle.Delete; } // 各セルを選択したときに実行される func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { performSegueWithIdentifier("cellSegue",sender: nil) } }
true
a9d4a77b8f3a47449b740d268d6d07151282d4ca
Swift
ooodin/TextureDemoProject
/TestProject/Models/FlightDetailsModel.swift
UTF-8
1,275
3
3
[]
no_license
// // FlightDetailsModel.swift // TestProject // // Created by Artem Semavin on 28/05/2018. // Copyright © 2018 ooodin. All rights reserved. // import Foundation struct FlightDetailsModel { let from: AirportModel let to: AirportModel let departureDate: Date let arrivalDate: Date let price: Double let company: String let options: [String] func departureDateString() -> String { let dateFormater = DateFormatter() dateFormater.dateFormat = "d MMMM YYYY" return "\(dateFormater.string(from: departureDate)) г." } func flightTimeString() -> String { let dateFormater = DateFormatter() dateFormater.dateFormat = "H:mm" return "\(dateFormater.string(from: departureDate)) ⎯⎯ \(dateFormater.string(from: arrivalDate))" } func durationTimeString() -> String { let timeDifference = Calendar.current .dateComponents([.hour, .minute], from: departureDate, to: arrivalDate) let hours = timeDifference.hour == nil ? "" : " \(timeDifference.hour ?? 0) ч" let minutes = timeDifference.minute == nil ? " 00" : " \(timeDifference.minute ?? 0)" return "\(hours)\(minutes) мин" } }
true
d15cbaf30459e99bc44d91112bee257da935c7b6
Swift
oci-pronghorn/SwiftyFog
/SwiftyFog/Sources/SwiftyFog/controllers/MQTTClientAppController.swift
UTF-8
2,562
2.546875
3
[ "MIT" ]
permissive
// // MQTTClientAppController.swift // SwiftyFog // // Created by David Giovannini on 9/4/17. // Copyright © 2017 Object Computing Inc. All rights reserved. // import Foundation // DispatchQueue /* The MQTTClientAppController manages the high level business logic of the application without managing the UI nor being the Cocoa AppDelegate. */ public protocol MQTTClientAppControllerDelegate: class { func on(mqttClient: (MQTTBridge & MQTTControl), log: String) func on(mqttClient: (MQTTBridge & MQTTControl), connected: MQTTConnectedState) } public class MQTTClientAppController { private let clientParams: MQTTClientParams private let network: FogNetworkReachability private let metrics: MQTTMetrics? private var wasStarted: Bool = true public private(set) var client: (MQTTBridge & MQTTControl)? public weak var delegate: MQTTClientAppControllerDelegate? public init(client: MQTTClientParams = MQTTClientParams(), metrics: MQTTMetrics? = nil) { self.clientParams = client self.network = FogNetworkReachability() self.metrics = metrics } public var mqttHost: String = "" { didSet { if mqttHost != oldValue { let newClient = MQTTClient( client: clientParams, host: MQTTHostParams(host: mqttHost, port: .standard), reconnect: MQTTReconnectParams(), metrics: metrics) self.client.assign(newClient) newClient.delegate = self if wasStarted { self.client?.start() } } } } public func goForeground() { // If want to be started, restore it if wasStarted { // Network reachability can detect a disconnected state before the client network.start { [weak self] status in if status != .none { self?.client?.start() } else { self?.client?.stop() } } } } public func goBackground() { // Be a good iOS citizen and shutdown the connection and timers wasStarted = client?.started ?? false client?.stop() network.stop() } } extension MQTTClientAppController: MQTTClientDelegate { public func mqtt(client: MQTTClient, connected: MQTTConnectedState) { DispatchQueue.main.async { self.delegate?.on(mqttClient: client, log: connected.description) self.delegate?.on(mqttClient: client, connected: connected) } } public func mqtt(client: MQTTClient, unhandledMessage: MQTTMessage) { DispatchQueue.main.async { self.delegate?.on(mqttClient: client, log: "Unhandled \(unhandledMessage)") } } public func mqtt(client: MQTTClient, recreatedSubscriptions: [MQTTSubscription]) { DispatchQueue.main.async { } } }
true
658d92cb10262f46b1922cb83082bc46c43e9583
Swift
Crocus7724/mofi
/mofi/view/BorderView.swift
UTF-8
1,013
2.671875
3
[]
no_license
import Foundation import Cocoa class BorderView: NSView { var config: Config! init(config: inout Config) { super.init(frame: NSRect.zero) self.config = config } required init?(coder aDecoder: NSCoder) { fatalError() } override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) NSColor.white.setFill() dirtyRect.fill() // dash customization parameters let dashHeight: CGFloat = 10 let dashLength: CGFloat = 5 let dashColor: NSColor = .clear // setup the context let currentContext = NSGraphicsContext.current!.cgContext currentContext.setLineWidth(dashHeight) currentContext.setLineDash(phase: 0, lengths: [dashLength]) currentContext.setStrokeColor(dashColor.cgColor) // draw the dashed path currentContext.addRect(NSRect(x: bounds.origin.x, y: bounds.origin.y, width: bounds.width, height: 10)) currentContext.strokePath() } }
true
b9e5994a404c42d3e0e497af9f01f86cfffcc12c
Swift
trungnghia2009/Swift_TwitterX
/Twitter/ViewModel/EditProfileViewModel.swift
UTF-8
1,207
3.296875
3
[]
no_license
// // EditProfileViewModel.swift // Twitter // // Created by trungnghia on 5/28/20. // Copyright © 2020 trungnghia. All rights reserved. // import Foundation enum EditProfileOptions: Int, CaseIterable, CustomStringConvertible { case fullname case username case bio var description: String { switch self { case .fullname: return "Name" case .username: return "Username" case .bio: return "Bio" } } } struct EditProfileViewModel { private let user: User let option: EditProfileOptions var titleText: String { return option.description } var optionValue: String? { switch option { case .fullname: return user.fullname case .username: return user.username case .bio: return user.bio } } var shouldHideInfo: Bool { return option == .bio } var shouldHideBio: Bool { return option != .bio } init(user: User, option: EditProfileOptions) { self.user = user self.option = option } }
true
91b2714cd7cee5d4967a553d8d8a0fef207fbe5b
Swift
junteak/omikujiApp
/MaruBatsu/MaruBatsuAddvanced2/MaruBatsu/QueryController.swift
UTF-8
2,027
3.015625
3
[]
no_license
import UIKit class QueryController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } //テキストフィールド @IBOutlet weak var textField: UITextField! //答え設定のBoolがはいる var answer: Bool! // yes, noの切り替え UISegmantをActionde制御はUISegmant // https://majintools.com/2018/10/12/segment/ @IBAction func yesNoButton(_ sender: UISegmentedControl) { switch sender.selectedSegmentIndex { case 0: answer = false case 1: answer = true default: print("エラー") } } //問題とせ正誤が格納される まだわからん var data: [[String: Any]] = [] //保存する @IBAction func saveQButton(_ sender: Any) { if textField.text == "" { showAlert2(message: "問題を追加してください") } else { var ques = textField.text! //配列に入れる data.append(["question": ques, "answer" : answer]) textField.text = "" UserDefaults.standard.set( data, forKey: "qAndA") } } @IBAction func removeQbutton(_ sender: Any) { UserDefaults.standard.removeObject(forKey: "qAndA") showAlert2(message: "すべて削除しました") } //アラート関数を作る-------- func showAlert2(message: String) { let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert) let close = UIAlertAction(title: "閉じる", style: .cancel, handler: nil) alert.addAction(close) present(alert, animated: true, completion: nil) } }
true
ec32e67d441ea336b28d48aae461ef6b36602d43
Swift
lbrndnr/swift-atomics
/Tests/AtomicsTests/RandomPositive.swift
UTF-8
1,325
3.125
3
[ "BSD-3-Clause" ]
permissive
// // RandomPositive.swift // #if !swift(>=4.2) #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) import func Darwin.C.stdlib.arc4random #else // assuming os(Linux) import func Glibc.random #endif #endif #if swift(>=4.0) extension FixedWidthInteger where Self.Magnitude: UnsignedInteger, Self.Stride: SignedInteger { // returns a positive random integer greater than 0 and less-than-or-equal to Self.max/2 static func randomPositive() -> Self { #if swift(>=4.1.50) return Self.random(in: 1...(Self.max>>1)) #else var t = Self() repeat { for _ in 0...((t.bitWidth-1)/32) { #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) t = t<<32 &+ Self(truncatingIfNeeded: arc4random()) #else // probably Linux t = t<<32 &+ Self(truncatingIfNeeded: random()) #endif } } while t == Self() return t & (Self.max>>1) #endif } } #else extension UInt { // returns a positive random integer greater than 0 and less-than-or-equal to UInt32.max/2 // in this variant the least significant bit is always set. static func randomPositive() -> UInt { var t: UInt repeat { #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) t = UInt(arc4random()) #else t = UInt(Glibc.random()) #endif t &= 0x3fff_ffff } while t == 0 return t } } #endif
true
e5a04e70bb3710847d421cc7b1fdc35dfdeaba6e
Swift
eagleera/SegundoParcialWebServices
/SegundoParcialWebServices/TeamMember.swift
UTF-8
367
2.609375
3
[]
no_license
// // TeamMember.swift // SegundoParcialWebServices // // Created by Noel Aguilera Terrazas on 26/03/20. // Copyright © 2020 Daniel Aguilera. All rights reserved. // import Foundation // MARK: - TeamMember struct TeamMember: Codable { var name: String? var imgUrl: String? enum CodingKeys: String, CodingKey { case name case imgUrl = "img_url" } }
true
018f104217f14ed018f986b74a2e9aea0b967f7c
Swift
privacy-inc/sleuth
/Sources/Trackers.swift
UTF-8
773
3.015625
3
[]
no_license
import Foundation public enum Trackers { case attempts, recent func sort(_ blocked: [String: [Date]]) -> [(key: String, value: [Date])] { switch self { case .attempts: return blocked .sorted { $0.1.count == $1.1.count ? $0.0.localizedCaseInsensitiveCompare($1.0) == .orderedAscending : $0.1.count > $1.1.count } case .recent: return blocked .sorted { guard let left = $0.1.last, let right = $1.1.last else { return false } return left > right } } } }
true
d341ee4e557e548d2bc0806d5958cae77e3df26b
Swift
BrisyIOS/CustomAlbum
/CustomAlbum/CustomAlbum/Album/Controller/PhotoListController.swift
UTF-8
5,062
2.515625
3
[ "Apache-2.0" ]
permissive
// // PhotoListController.swift // CustomAlbum // // Created by zhangxu on 2016/12/14. // Copyright © 2016年 zhangxu. All rights reserved. // import UIKit import Photos let ITEM_SIZE = CGSize(width: realValue(value: 93), height: realValue(value: 93)); let IMAGE_SIZE = CGSize(width: realValue(value: 93/2) * scale, height: realValue(value: 93/2) * scale); let MARGIN: CGFloat = realValue(value: 0.55); class PhotoListController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { private let photoCellIdentifier = "photoCellIdentifier"; // collectionView lazy var collectionView: UICollectionView = { let layout = UICollectionViewFlowLayout(); layout.itemSize = ITEM_SIZE; layout.minimumLineSpacing = realValue(value: MARGIN); layout.minimumInteritemSpacing = realValue(value: MARGIN); let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDRH, height: SCREEN_HEIGHT - CGFloat(64)), collectionViewLayout: layout); collectionView.backgroundColor = UIColor.clear; collectionView.dataSource = self; collectionView.delegate = self; collectionView.contentInset = UIEdgeInsets(top: MARGIN, left: MARGIN, bottom: MARGIN, right: MARGIN); return collectionView; }(); /// 带缓存的图片管理对象 private lazy var imageManager:PHCachingImageManager = PHCachingImageManager(); // 单个相册中存储的图片数组 var assets: [PHAsset]?; // 存放image的数据 private lazy var imageArray: [UIImage] = [UIImage](); override func viewDidLoad() { super.viewDidLoad() // 添加collectionView view.addSubview(collectionView); // 注册cell collectionView.register(PhotoCell.self, forCellWithReuseIdentifier: photoCellIdentifier); // 加载assets数组 loadPhotoList(); // Do any additional setup after loading the view. } // 加载assets数组 private func loadPhotoList() -> Void { if assets == nil { assets = [PHAsset](); //则获取所有资源 let allPhotosOptions = PHFetchOptions() //按照创建时间倒序排列 allPhotosOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)] //只获取图片 allPhotosOptions.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.image.rawValue) let assetsFetchResults = PHAsset.fetchAssets(with: PHAssetMediaType.image, options: allPhotosOptions) for i in 0..<assetsFetchResults.count { let asset = assetsFetchResults[i]; assets?.append(asset); } } } // 返回行数 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return assets?.count ?? 0 } // 返回cell func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: photoCellIdentifier, for: indexPath) as? PhotoCell; if let assets = assets { if indexPath.row < assets.count { let asset = assets[indexPath.row]; _ = PhotoHandler.shared.getPhotosWithAsset(asset: asset, targetSize: IMAGE_SIZE, isOriginalImage: false, completion: { (result) in guard let imageData = UIImageJPEGRepresentation(result, 0.3) else { return; } cell?.image = UIImage.init(data: imageData); }) } } return cell!; } // 选中cell , 进入照片详情 func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { collectionView.deselectItem(at: indexPath, animated: false); let photoDetailVc = PhotoDetailController(); if let assets = assets { if indexPath.row < assets.count { photoDetailVc.assets = assets; photoDetailVc.indexPath = indexPath; photoDetailVc.transitioningDelegate = ModalAnimationDelegate.shared; photoDetailVc.modalPresentationStyle = .custom; present(photoDetailVc, animated: true, completion: nil); } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
true
d8c1f1c1bc774ca46d1b8d28b0e50869d801080d
Swift
yungfan/SwiftLecture201807
/LeisureMap/LeisureMap/MasterDetail/DetailViewController.swift
UTF-8
1,479
2.53125
3
[]
no_license
// // DetailViewController.swift // LeisureMap // // Created by stu1 on 2018/7/25. // Copyright © 2018年 YungFan. All rights reserved. // import UIKit class DetailViewController: UIViewController { var selectedStore: Store? //MARK: - UIViewController LifeCircle override func viewDidLoad() { super.viewDidLoad() self.title = selectedStore?.name print(selectedStore!) } //MARK: - Actions //跳转到Map @IBAction func btnMapClicked(_ sender: Any) { self.performSegue(withIdentifier: "moveToMapViewSegue", sender: self) } //跳转到Note @IBAction func btnWebClicked(_ sender: Any) { self.performSegue(withIdentifier: "moveToNoteViewSegue", sender: self) } // 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?) { //通过segue的identifier判断到底是跳转的哪根线 // switch segue.identifier { // // case "moveToMapViewSegue": // // let mapViewController = segue.destination as! MapViewController // // default: // // print("error") // } } deinit { print("DetailViewController deinit") } }
true
f2a001d10ec9b3758cc9e046b067398a26e5f482
Swift
piggest777/AwesomeChuckApp
/AwesomeChuckApp/Services/JokeService.swift
UTF-8
4,958
3.453125
3
[]
no_license
// // JokeService.swift // AwesomeChuckApp // // Created by Denis Rakitin on 2019-05-29. // Copyright © 2019 Denis Rakitin. All rights reserved. // import Foundation import Alamofire import SwiftyJSON //Основной класс, отвечающий за получение информации от API и хранения указанной информации для передачи в дальнейшем другим классам class JokeService { // создание синглтона, поскольку требуется один экземпляр класса static let instance = JokeService() // Переменные которые хранят массив полученных шуток и общее количество имеющихся шуткок var jokes = [Joke]() var totalNumberOFJokes = 0 // функция реализовання на фреймворке Alamofire, котрый отвечает за отправку запроса и обработку вернувшихся резезультатов в виде JSON строки. Назначение этой функции - получение общего количества доступных шуток func getTotalNumberOfJokes (completion: @escaping (_ success: Bool) -> ()){ Alamofire.request("\(JOKES_URL)/count", method: .get, parameters: nil, encoding: JSONEncoding.default, headers: HEADER).responseJSON { (response) in // если в полученном результате отстутвуют ошибки if response.result.error == nil { // попытка полчить данные из запроса guard let data = response.data else {return} do { // попытка обработать данные с помощию do catch блока let json = try JSON(data: data) // обработка полученного значения с помощью фреймворка SwiftyJson, облегчающего обработку результата в формате JSON self.totalNumberOFJokes = json["value"].intValue } catch { debugPrint(error) } // Если обработка прошла успешно, то обработчику выполненному в виде сбегающего замыкание передается BOOL значение true, для реализации последующий действий с полученным результатом completion(true) } else { // если ответ содержит ошибку, дальнейшая обработка результатов функции не производится completion(false) debugPrint(response.result.error as Any) } } } // Функция получения определенного количество шуток, на основании значения введенного пользователем. Используются теже фреймворки и концепции что и в предыдущей функции func getJokes(numberOfJokes: Int, completion: @escaping (_ success: Bool) -> ()) { Alamofire.request("\(JOKES_URL)/random/\(numberOfJokes)", method: .get, parameters: nil, encoding: JSONEncoding.default, headers: HEADER).responseJSON { (response) in if response.result.error == nil { guard let data = response.data else {return} do { let json = try JSON(data: data) let jokesArray = json["value"].arrayValue // поскольку полученный JSON ответ содержит список шутков к виде словаря, то в дальнейшем производится иттерация по полученном словарю с полчуением информации о тексте и идентификационном номере for joke in jokesArray { let jokeId = joke["id"].stringValue let jokeTxt = joke["joke"].stringValue let newJoke = Joke(jokeNum: jokeId, jokeTxt: jokeTxt) self.jokes.append(newJoke) } completion(true) } catch { debugPrint(error) } } else { completion(false) debugPrint(response.result.error as Any) } } } }
true
f4b21a018f7e144be5ddfa7f703f5aea02bb0ab3
Swift
ZJSwift/PredicatePal
/PredicatePal/Const.swift
UTF-8
630
2.953125
3
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
// // Const.swift // PredicatePal // // Created by Glen Low on 7/12/2015. // Copyright © 2015 Glen Low. All rights reserved. // import Foundation /// Constant term. /// - parameter T: The type of the constant. public struct Const<T>: Expression { public typealias ExpressionType = T let value: T /// Create a constant term. /// - parameter value: The constant value. public init(_ value: T) { self.value = value } } /// Build the `NSExpression`. public prefix func*<T>(expression: Const<T>) -> NSExpression { return NSExpression(forConstantValue:expression.value as? AnyObject) }
true
6f433ff92d7399a040ad001f2dc4b8f1a37ffa22
Swift
app-master/ViperTest
/ViperTest/Services/ServerManager.swift
UTF-8
2,547
2.78125
3
[]
no_license
// // ServerManager.swift // ViperTest // // Created by user on 27/07/2019. // Copyright © 2019 Sergey Koshlakov. All rights reserved. // import UIKit class ServerManager: PhotoSearchProtocol, loadImageProtocol { static let manager = ServerManager() private init() {} let apiKey = "4fb7690ff8bda132439e145d616a715d" let baseURL = URL(string: "https://www.flickr.com/services/rest/")! // MARK: - Methods func fetchPhotosForSearchText(_ text: String, page: Int, completion: @escaping ([Photo]?, Int?, NSError?) -> Void) { var components = URLComponents(url: baseURL, resolvingAgainstBaseURL: true) let params = ["api_key" : apiKey, "format" : "json", "nojsoncallback" : "1", "tags" : text, "page" : String(page)] let methodQueryItem = URLQueryItem(name: "method", value: "flickr.photos.getRecent") components?.queryItems = [methodQueryItem] + params.map(){ URLQueryItem(name: $0, value: $1) } guard let finalURL = components?.url else { completion(nil, nil, NSError(domain: "Bad URL", code: 111, userInfo: nil)) return } let session = URLSession.shared session.dataTask(with: finalURL) { (data, _, _) in guard let data = data else { completion(nil, nil, NSError(domain: "Bad Data", code: 112, userInfo: nil)) return } do { let photosResponse = try JSONDecoder().decode(PhotosResponse.self, from: data) let photosInfo = photosResponse.photos let totalPages = photosInfo.total let photos = photosInfo.photo completion(photos, totalPages, nil) return } catch { print(error.localizedDescription) completion(nil, nil, NSError(domain: "Bad Decode", code: 113, userInfo: nil)) return } }.resume() } func fetchImageByURL(_ url: URL, completion: @escaping (UIImage?) -> Void) { URLSession.shared.dataTask(with: url) { (data, _, _) in guard let data = data else { completion(nil) return } let image = UIImage(data: data) completion(image) }.resume() } }
true
e6204b853a7b60b989665e84bfb40b95e4e93713
Swift
SimpleSecond/Swift-Design-Pattern
/19.ChainOfResp/ChainOfResp/Transmitters.swift
UTF-8
2,721
3.25
3
[]
no_license
// // Transmitters.swift // ChainOfResp // // Created by wdy on 2019/10/31. // Copyright © 2019 wdy. All rights reserved. // import Foundation class Transmitter { var nextLink: Transmitter? required init() {} func sendMessage(message: Message, handled: Bool = false) -> Bool { if nextLink != nil { return nextLink!.sendMessage(message: message, handled: handled) } else if !handled { print("End of chain reached, Message not sent") } return handled } class func createChain(localOnly: Bool) -> Transmitter? { let transmitterClasses:[Transmitter.Type] = localOnly ? [PriorityTransmitter.self, LocalTransmitter.self] : [PriorityTransmitter.self, LocalTransmitter.self, RemoteTransmitter.self] var link: Transmitter? for tClass in transmitterClasses.reversed() { let existingLink = link link = tClass.init() link?.nextLink = existingLink } return link } fileprivate class func matchEmailSuffix(message: Message) -> Bool { if let index = message.from.firstIndex(of: "@") { return message.to.hasSuffix(message.from[index...]) } return false } } class LocalTransmitter: Transmitter { override func sendMessage(message: Message, handled: Bool) -> Bool { var handled = handled if !handled && Transmitter.matchEmailSuffix(message: message) { print("Message to \(message.to) sent locally") handled = true } return super.sendMessage(message: message, handled: handled) } } class RemoteTransmitter: Transmitter { override func sendMessage(message: Message, handled: Bool) -> Bool { var handled = handled if !handled && !Transmitter.matchEmailSuffix(message: message) { print("Message to \(message.to) sent remotely") handled = true } return super.sendMessage(message: message, handled: handled) } } class PriorityTransmitter: Transmitter { var totalMessages = 0 var handledMessages = 0 override func sendMessage(message: Message, handled: Bool) -> Bool { var handled = handled totalMessages = totalMessages + 1 if !handled && message.subject.hasPrefix("Priority") { handledMessages = handledMessages + 1 print("Message to \(message.to) sent as priority") print("Status: Handled \(handledMessages) of \(totalMessages)") handled = true } return super.sendMessage(message: message, handled: handled) } }
true
c99e5906dde8905e30d5e07f625c5ef054533af2
Swift
udacity/ios-nd-robot-maze-2
/Robot-Maze-2-Part-1/Maze/MazeCellView.swift
UTF-8
2,434
2.8125
3
[ "MIT" ]
permissive
// // MazeCell.swift // Maze // // Created by Jarrod Parkes on 8/14/15. // Copyright © 2015 Udacity, Inc. All rights reserved. // import UIKit // MARK: - MazeCellView class MazeCellView : UIView { // MARK: Properties var wallColor: UIColor = UIColor.orange var cellModel: MazeCellModel? var wallWidth: CGFloat = 1 // MARK: UIView override func draw(_ rect: CGRect) { super.draw(rect) if let cellModel = cellModel { // Set the wallColor wallColor.set() let width = bounds.width let height = bounds.height let path = CGMutablePath() // Half wallWidth let hw = wallWidth / CGFloat(2) if cellModel.top { path.move(to: CGPoint(x: 0 - hw, y: 0)) path.addLine(to: CGPoint(x: width + hw, y: 0)) } if cellModel.right { path.move(to: CGPoint(x: width, y: 0)) path.addLine(to: CGPoint(x: width, y: height)) } if cellModel.bottom { path.move(to: CGPoint(x: width + hw, y: height)) path.addLine(to: CGPoint(x: 0 - hw, y: height)) } if cellModel.left { path.move(to: CGPoint(x: 0, y: height)) path.addLine(to: CGPoint(x: 0, y: 0)) } let bezierPath = UIBezierPath(cgPath: path) bezierPath.lineWidth = wallWidth; bezierPath.stroke() // Rounded corners let context = UIGraphicsGetCurrentContext() context?.saveGState() let nearCornerValue = -0.5 * wallWidth let farCornerValue = width + nearCornerValue context?.fillEllipse(in: CGRect(x: nearCornerValue, y: nearCornerValue, width: wallWidth, height: wallWidth)) context?.fillEllipse(in: CGRect(x: farCornerValue, y: farCornerValue, width: wallWidth, height: wallWidth)) context?.fillEllipse(in: CGRect(x: farCornerValue, y: nearCornerValue, width: wallWidth, height: wallWidth)) context?.fillEllipse(in: CGRect(x: nearCornerValue, y: farCornerValue, width: wallWidth, height: wallWidth)) context?.restoreGState() } } }
true
1a5e3e50d54e3e7b0bcc6cb20d8024236da079d6
Swift
redjohnzarra/ios-testapp
/ios-testapp/ios-testapp/Model/Restaurant.swift
UTF-8
740
3.203125
3
[]
no_license
// // Restaurant.swift // ios-testapp // // Created by Reden John Zarra on 06/12/2018. // Copyright © 2018 Reden John Zarra. All rights reserved. // import Foundation struct Restaurant { private(set) public var name: String private(set) public var address: String private(set) public var imageURL: String private(set) public var latitude: Double private(set) public var longitude: Double private(set) public var likes: Int init(name: String, address: String, imageURL: String, latitude: Double, longitude: Double, likes: Int) { self.name = name self.address = address self.imageURL = imageURL self.latitude = latitude self.longitude = longitude self.likes = likes } }
true
e18eae8296d1ea6fef38ca28f31a069295ed441b
Swift
johnnyrainbow/iMeasureU-ios-assesment
/IMeasureUapp/Util/CSVUtil.swift
UTF-8
1,146
3.078125
3
[]
no_license
// // CSVReader.swift // IMeasureUapp // // Created by Gabriel Kennedy on 29/03/19. // Copyright © 2019 Gabriel Kennedy. All rights reserved. // import Foundation import CSV class CSVUtil { //Static Util class static var headerRow = [String]() static func readCSV() -> CSVReader { //Get the path of the csv file let file_url = Bundle.main.path(forResource: "players_sample", ofType: "csv") //Create a readable stream for the file let stream = InputStream(fileAtPath: file_url!)! //Pass into CSVReader let csv = try! CSVReader(stream: stream,hasHeaderRow: true) return csv } static func populatePlayerData(csv: CSVReader) { //First row is headers headerRow = csv.headerRow! while let row = csv.next() { //We define a generic system that takes a row header and creates a key for a player by that value. let p = Player() //Declare a new player //Iterate header keys headerRow.forEach { key in Parser.parse(player: p, key:key,csv:csv) } } } }
true
89b9055fb848949af29e8d6902ecac270e206320
Swift
azureplus/SwiftCharDet
/Sources/SwiftCharDet/ISOLatin1Encoding.swift
UTF-8
1,553
2.59375
3
[]
no_license
/* MIT License Copyright (c) 2017 Andy Best Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation struct ISOLatin1Detector: StringEncodingDetector { static func encodingConfidence(forData sampleData: Data) -> (Double, String.Encoding) { var confidence = 0 for byte in sampleData { if (byte > 0x1f && byte < 0x7F) || (byte > 0xA0) { confidence += 1 } } return (Double(confidence) / Double(sampleData.count), String.Encoding.isoLatin1) } }
true
31659bf18145fd91e3384b4a9067e885850675dd
Swift
buraktuncdev/ios-swift-mvvm-unittest
/iOS_TheMovieDB/View Controllers/Cells/MoviePlayingCell.swift
UTF-8
1,083
2.546875
3
[]
no_license
// // MoviePlayingCell.swift // iOS_TheMovieDB // // Created by Phuc Bui on 6/30/21. // Copyright © 2021 PhucBui. All rights reserved. // import UIKit // // MARK: - Movie Playing Now Cell // class MoviePlayingCell: UITableViewCell { // // MARK: - Constants // static let identifier = "MoviePlayingCell" /// /// Configure add custom collection image view /// func configure(customView: UIView) { contentView.addSubview(customView) //Autolayout customView.translatesAutoresizingMaskIntoConstraints = false let constraints = [ customView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 0), customView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 0), customView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: 0), customView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: 0) ] NSLayoutConstraint.activate(constraints) } }
true
3cd12c9aa2e05a9730f0207de77cb544d025a279
Swift
bilaldurnagol/News
/News/Resources/DatabaseManager.swift
UTF-8
10,889
2.953125
3
[ "MIT" ]
permissive
// // DatabaseManager.swift // News // // Created by Bilal Durnagöl on 2.11.2020. // import Foundation class DatabaseManager { static let shared = DatabaseManager() let localhost: String = "host" //MARK:- Account funcs // User login function public func login(email: String, password: String, completion: @escaping (Result<User, Error>) -> ()) { let params = [ "email": email, "password": password ] let data = try? JSONSerialization.data(withJSONObject: params, options: .init()) guard let url = URL(string: "\(localhost)/login") else {return} var urlRequest = URLRequest(url: url) urlRequest.httpBody = data urlRequest.httpMethod = "POST" urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type") URLSession.shared.dataTask(with: urlRequest, completionHandler: { [self]data, response, error in guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else { let message = try? JSONDecoder().decode(DatabaseMessage.self, from: data!) guard let error = message?.message else {return} completion(.failure(DatabaseManagerError.failedToLogin(error: error))) return } getUserInfo(email: email, completion: {result in switch result { case .failure(_): completion(.failure(DatabaseManagerError.failedToGetUserInfo)) case .success(let user): completion(.success(user)) } }) }).resume() } //Get user info public func getUserInfo(email: String, completion: @escaping (Result<User, Error>) -> ()) { guard let url = URL(string: "\(localhost)/user_info/\(email)") else {return} URLSession.shared.dataTask(with: url, completionHandler: {data, response, error in guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else { completion(.failure(DatabaseManagerError.failedToGetUserInfo)) return } guard let userInfo = try? JSONDecoder().decode(User.self, from: data!) else {return} completion(.success(userInfo)) }).resume() } //Create user func public func createNewUser(user: User, completion: @escaping (Result<User, Error>) -> ()) { let params = [ "user_name": user.user_name, "user_email": user.user_email, "user_password": user.user_password, "user_location": user.user_location ] let data = try? JSONSerialization.data(withJSONObject: params, options: .init()) guard let url = URL(string: "\(localhost)/register") else {return} var urlRequest = URLRequest(url: url) urlRequest.httpBody = data urlRequest.httpMethod = "POST" urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") URLSession.shared.dataTask(with: urlRequest, completionHandler: {data, response, _ in guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else { let message = try? JSONDecoder().decode(DatabaseMessage.self, from: data!) guard let error = message?.message else {return} completion(.failure(DatabaseManagerError.failedToCreateNewUser(error: error))) return } let user = try? JSONDecoder().decode(User.self, from: data!) completion(.success(user!)) }).resume() } //MARK:- Topic Funcs //add topics public func addTopic(email: String, chooseTopicsArray: [String], completion: @escaping (Result<String,Error>) -> ()) { var params = [ "topics": [] ] for topic in chooseTopicsArray { let topicArray = ["topic_name": topic] var topicsArray = params ["topics"] topicsArray!.append(topicArray) params["topics"] = topicsArray } print(params) let data = try? JSONSerialization.data(withJSONObject: params, options: .init()) guard let url = URL(string: "\(localhost)/add_topics/\(email)") else {return} var urlRequest = URLRequest(url: url) urlRequest.httpBody = data urlRequest.httpMethod = "POST" urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type") URLSession.shared.dataTask(with: urlRequest, completionHandler: {data, response, _ in guard let urlResponse = response as? HTTPURLResponse, urlResponse.statusCode == 200 else { completion(.failure(DatabaseManagerError.failedToAddTopic)) return } let message = try? JSONDecoder().decode(DatabaseMessage.self, from: data!) guard let safeMessage = message?.message else {return} completion(.success(safeMessage)) }).resume() } //MARK:- Articles Funcs //Get all articles public func getArticles(url: String, completion: @escaping (Result<[Article]?, Error>) -> ()) { guard let url = URL(string: url) else {return} URLSession.shared.dataTask(with: url, completionHandler: {data, response, error in guard let data = data, error == nil else { completion(.failure(DatabaseManagerError.failedToFetchArticles)) return } let articles = try? JSONDecoder().decode(ArticleList.self, from: data) completion(.success(articles?.articles)) }).resume() } //Get featured articles public func getFeaturedArticle(url: String, completion: @escaping (Result<[Article]?, Error>) -> ()) { guard let url = URL(string: url) else {return} URLSession.shared.dataTask(with: url, completionHandler: {data, response, error in guard let data = data, error == nil else { completion(.failure(DatabaseManagerError.failedToFetchFeaturedArticles)) return } let articles = try? JSONDecoder().decode(ArticleList.self, from: data) completion(.success(articles?.articles)) }).resume() } //MARK:- Setting Funcs //Edit profile public func editProfile(userID: Int, userName: String, userEmail: String, userPassword: String, completion: @escaping (Bool)->()) { let params = [ "name": userName, "email": userEmail, "password": userPassword ] let data = try? JSONSerialization.data(withJSONObject: params, options: .init()) guard let url = URL(string: "\(localhost)/user_info_update/\(userID)") else {return} var urlRequest = URLRequest(url: url) urlRequest.httpBody = data urlRequest.httpMethod = "PUT" urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type") URLSession.shared.dataTask(with: urlRequest, completionHandler: {_, response, _ in guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else { completion(false) return } completion(true) }).resume() } //Update topics public func updateTopics(topics: [String], userID: Int, completion: @escaping (Bool) -> ()) { var params = [ "topics": [] ] as [String: Any] for topic in topics { let topicArray: [String: Any] = ["topic_name" : topic] var topicsArray = params["topics"] as? [[String: Any]] ?? [[String: Any]]() topicsArray.append(topicArray) params["topics"] = topicsArray } let data = try? JSONSerialization.data(withJSONObject: params, options: .init()) guard let url = URL(string: "\(localhost)/update_topic/\(userID)") else {return} var urlRequest = URLRequest(url: url) urlRequest.httpBody = data urlRequest.httpMethod = "POST" urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type") URLSession.shared.dataTask(with: urlRequest, completionHandler: {data, response, _ in guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else { completion(false) return } completion(true) }).resume() } //Update Location public func updateLocation(user: User?, completion: @escaping (Bool) -> ()) { guard let location = user?.user_location, let id = user?.user_id else {return} let params = [ "location": location ] let data = try? JSONSerialization.data(withJSONObject: params, options: .init()) guard let url = URL(string: "\(localhost)/update_location/\(id)") else {return} var urlRequest = URLRequest(url: url) urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type") urlRequest.httpBody = data urlRequest.httpMethod = "PUT" URLSession.shared.dataTask(with: urlRequest, completionHandler: {data, response, error in guard let urlResponse = response as? HTTPURLResponse, urlResponse.statusCode == 200 else { completion(false) return } completion(true) }).resume() } } //MARK:- Database Errors extension DatabaseManager { enum DatabaseManagerError: Error { case failedToLogin(error: String) case failedToGetUserInfo case failedToCreateNewUser(error: String) case failedToAddTopic case failedToFetchArticles case failedToFetchFeaturedArticles } } extension DatabaseManager.DatabaseManagerError: LocalizedError { public var errorDescription: String? { switch self { case .failedToLogin(error: let error): return NSLocalizedString("\(error)", comment: "Error") case .failedToGetUserInfo: return NSLocalizedString("Failed to get user info.", comment: "Error") case .failedToCreateNewUser(error: let error): return NSLocalizedString("\(error)", comment: "Error") case .failedToAddTopic: return NSLocalizedString("Failed add user's choose topics.", comment: "Error") case .failedToFetchArticles: return NSLocalizedString("Failed to get news.", comment: "Error") case .failedToFetchFeaturedArticles: return NSLocalizedString("Failed to get featured news.", comment: "Error") } } }
true
c1927d039efc56dfe5216ea14bd74bb1b3a86ece
Swift
beetee17/WordBomb
/Word Bomb/Utils/Enums.swift
UTF-8
1,093
2.96875
3
[]
no_license
// // Enums.swift // Word Bomb // // Created by Brandon Thio on 17/7/21. // import Foundation struct GameMode: Identifiable { var modeName: String var instruction: String? var words: [String]? var variants: [String:[String]]? var queries: [(String, Int)]? var gameType: GameType var id = UUID() } enum InputStatus: String, Codable { case Correct case Wrong case Used func outputText(_ input: String) -> String { switch self { case .Correct: return "\(input) is Correct" case .Wrong: return "\(input) is Wrong" case .Used: return "Already used \(input)" } } } enum GameType: String, CaseIterable, Codable { case Classic = "Classic" case Exact = "Exact" case Reverse = "Reverse" } enum GameState: String, Codable { case initial, playerInput, playerTimedOut, gameOver, paused, playing } enum ViewToShow: String, Codable { case main, gameTypeSelect, modeSelect, game, pauseMenu, multipeer, peersView, GKMain, GKLogin }
true
76b7d3171b3210a3ba7ffbebe2ab16d5b6d6d901
Swift
wenjiehe/BlurEffectDemo
/BlurEffectDemo/ViewController.swift
UTF-8
1,696
2.796875
3
[]
no_license
// // ViewController.swift // BlurEffectDemo // // Created by 贺文杰 on 2019/7/15. // Copyright © 2019 贺文杰. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet var baseView: UIView! ///创建模糊效果 var blurEffect = UIBlurEffect.init(style: .regular) var visualEffectView = UIVisualEffectView() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.view.setNeedsLayout() self.view.layoutIfNeeded() /// 承载模糊效果的视图 visualEffectView = UIVisualEffectView.init(effect: blurEffect) visualEffectView.frame = baseView.frame /// UIVibrancyEffect作用是放大和调整UIVisualEffectView内容视图的内容的颜色 let vibrancyView = UIVisualEffectView.init(effect: UIVibrancyEffect.init(blurEffect: blurEffect)) vibrancyView.frame = baseView.frame visualEffectView.contentView.addSubview(vibrancyView) let whiteView = UIView.init(frame: CGRect.init(x: 20, y: 20, width: baseView.frame.width - 40, height: 150)) whiteView.backgroundColor = .white let label = UILabel.init(frame: CGRect.init(x: 0, y: 0, width: whiteView.frame.width, height: whiteView.frame.height)) label.text = "HelveticaNeue-Bold" label.font = UIFont.init(name: "HelveticaNeue-Bold", size: 30) label.textAlignment = .center whiteView.addSubview(label) vibrancyView.contentView.addSubview(label) self.view.addSubview(visualEffectView) } }
true
a5c28c2491b86ce84f3a4b741f64b0c93b69aa83
Swift
epeschard/BSWInterfaceKit
/Source/Protocols/ViewModel.swift
UTF-8
1,493
2.65625
3
[ "MIT" ]
permissive
// // Created by Pierluigi Cifani on 03/05/16. // Copyright © 2016 Blurred Software SL. All rights reserved. // import UIKit import BSWFoundation import Deferred //MARK:- Protocols public protocol ViewModelConfigurable { associatedtype VM func configureFor(viewModel viewModel: VM) -> Void } public protocol ViewModelReusable: ViewModelConfigurable { static var reuseType: ReuseType { get } static var reuseIdentifier: String { get } } public protocol AsyncViewModelPresenter: ViewModelConfigurable { var dataProvider: Future<Result<VM>>! { get set } } extension AsyncViewModelPresenter where Self: UIViewController { public init(dataProvider: Future<Result<VM>>) { self.init(nibName: nil, bundle: nil) self.dataProvider = dataProvider dataProvider.uponMainQueue { result in switch result { case .Failure(let error): self.showErrorMessage("WTF", error: error) case .Success(let viewModel): self.configureFor(viewModel: viewModel) } } } } //MARK:- Extensions extension ViewModelReusable where Self: UICollectionViewCell { public static var reuseIdentifier: String { return NSStringFromClass(self).componentsSeparatedByString(".").last! } public static var reuseType: ReuseType { return .ClassReference(Self) } } //MARK:- Types public enum ReuseType { case NIB(UINib) case ClassReference(AnyClass) }
true
eee8677dd5f5bb3e7dc352c7962ce057ab249ebf
Swift
okryl/ITunes-Search
/YS-ITunes/Classes/Service/ITunesSearchAPI.swift
UTF-8
2,665
2.796875
3
[]
no_license
// // ITunesSearchAPI.swift // YS-ITunes // // Created by Omer Karayel on 31/12/16. // Copyright © 2016 Omer Karayel. All rights reserved. // import Foundation typealias successBlock = (_ response: [String: AnyObject]) ->Void typealias failureBlock = (_ error: String) -> Void /* Service cagrilari singleton bir method uzerinden cagrilmistir */ final class ITunesSearchApi: NSObject { private let baseURL = "https://itunes.apple.com/search?term=" private static var instance : ITunesSearchApi? static func sharedInstance() -> ITunesSearchApi { if instance == nil { instance = ITunesSearchApi() } return instance! } //MARK: - Public Search Request func search(withText text: String, offType media: Media, success:@escaping successBlock, failure: @escaping failureBlock) { LoadingManager.sharedInstance().startIndicator() guard let url = buildUrl(searchText: text, mediaType: media) else {fatalError("URL ERROR")} let task = startTask(withURL: url, success: success, failure: failure) task.resume() } //MARK: - Start Task private func startTask(withURL url: URL,success:@escaping successBlock, failure: @escaping failureBlock) -> URLSessionTask{ return URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in LoadingManager.sharedInstance().stopIndicator() guard let httpResponse = response as? HTTPURLResponse else { self.mainThread { failure("HTTP RESPONSE ERROR") } return } guard httpResponse.statusCode == 200 else { self.mainThread { failure("HTTP RESPONSE STATUS CODE ERROR") } return } guard let data = data, let json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String: AnyObject] else { self.mainThread { failure("JSON ERROR") } return } self.mainThread { success(json) } }) } //MARL: - Build Request URL private func buildUrl(searchText: String!, mediaType: Media!) -> URL? { let text = searchText.replacingOccurrences(of: " ", with: "+") return URL(string: baseURL + text + "&media=" + mediaType.url) } }
true
d9fe86d9857886ed3e7030bcbe2462d818611105
Swift
thanhsieunhan/Calculator
/NumberButton.swift
UTF-8
754
2.953125
3
[]
no_license
// // NumberButton.swift // Calculator // // Created by le ha thanh on 7/14/16. // Copyright © 2016 le ha thanh. All rights reserved. // import UIKit class NumberButton: UIButton { required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) numberButton() } func numberButton() -> Void { backgroundColor = UIColor(red: 255/255, green: 255/255, blue: 255/255, alpha: 1.0) // Shadow and Radius layer.shadowColor = UIColor(red: 255/355, green: 255/255, blue: 255/255, alpha: 0.25).CGColor layer.shadowOffset = CGSizeMake(0.0, 2.0) layer.shadowOpacity = 1.0 layer.shadowRadius = 0.0 layer.masksToBounds = false layer.cornerRadius = 4.0 } }
true
d440ade44470e435351f0a747bd27fe92643c3f8
Swift
gausam/yoti-face-capture-ios
/Samples/CocoaPods/Sample/Sources/Sample/Extensions/UIViewController+AlertExtension.swift
UTF-8
574
2.5625
3
[ "MIT" ]
permissive
// // Copyright © 2021 Yoti Ltd. All rights reserved. // import UIKit extension UIViewController { func showAlert(title: String, message: String, buttons: [UIAlertAction]) { let alertVC = UIAlertController(title: title, message: message, preferredStyle: .alert) for button in buttons { alertVC.addAction(button) } present(alertVC, animated: true, completion: nil) } }
true
f30317343e964f8eaef182eb4c58c6d5db91531c
Swift
JavteshGBC/parking-app
/ParkingApp/Models/Parking.swift
UTF-8
5,034
3.109375
3
[]
no_license
// Group: Project Groups 12 // Name: Mohit Sharma // Student ID: 101342267 // Group Member: Javtesh Singh Bhullar // Member ID: 101348129 // // Parking.swift // ParkingApp // // Created by Mohit Sharma on 22/05/21. // import Foundation import MapKit import FirebaseFirestore import FirebaseFirestoreSwift struct Parking : Codable { private let db = Firestore.firestore() @DocumentID var id:String? var buildingCode:String var parkingHours:Double var carPlateNumber:String var suitNumber:String var streetAddress:String var coordinate:CLLocationCoordinate2D var dateTime:Timestamp init() { self.buildingCode = "" self.parkingHours = 0.0 self.carPlateNumber = "" self.suitNumber = "" self.streetAddress = "" self.coordinate = CLLocationCoordinate2D() self.dateTime = Timestamp() } enum CodingKeys : String, CodingKey { case id = "id" case buildingCode = "building_code" case parkingHours = "parking_hours" case carPlateNumber = "car_plate_number" case suitNumber = "suit_number" case streetAddress = "street_address" case coordinate = "coordinate" case dateTime = "date_time" } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(self.buildingCode, forKey: .buildingCode) try container.encode(self.parkingHours, forKey: .parkingHours) try container.encode(self.carPlateNumber, forKey: .carPlateNumber) try container.encode(self.suitNumber, forKey: .suitNumber) try container.encode(self.streetAddress, forKey: .streetAddress) try container.encode(GeoPoint.init(latitude: self.coordinate.latitude, longitude: self.coordinate.longitude), forKey: .coordinate) try container.encode(self.dateTime, forKey: .dateTime) } init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) self._id = try values.decode(DocumentID<String>.self, forKey: .id) self.buildingCode = try values.decode(String.self, forKey: .buildingCode) self.parkingHours = try values.decode(Double.self, forKey: .parkingHours) self.carPlateNumber = try values.decode(String.self, forKey: .carPlateNumber) self.suitNumber = try values.decode(String.self, forKey: .suitNumber) self.streetAddress = try values.decode(String.self, forKey: .streetAddress) let geoPoint = try values.decode(GeoPoint.self, forKey: .coordinate) self.coordinate = CLLocationCoordinate2D(latitude: geoPoint.latitude, longitude: geoPoint.longitude) self.dateTime = try values.decode(Timestamp.self, forKey: .dateTime) } func addParking(userID:String, parking:Parking, completion: @escaping (String?) -> Void ){ do { try self.db.collection("users/\(userID)/parkings").addDocument(from : parking){ (error) in if let error = error { completion("Unable to add parking. Please Try again. Error: \(error)") } else { completion(nil) } } } catch { print(error) } } func getParkingByDocumentID(_ documentID:String, completion: @escaping (Parking) -> Void) { self.db.collection("parkings").document(documentID).getDocument{ (queryResult, error) in if let error = error { print("Error occured when fetching parking from firestore. Error: \(error)") return } else { do { if let parking = try queryResult?.data(as : Parking.self) { completion(parking) } else { print("No parking found") } } catch { print(error) } } } } func getUserParkings(userID:String, completion: @escaping ([Parking]?, String?) -> Void) { self.db.collection("users/\(userID)/parkings").order(by: "date_time", descending: true).getDocuments(){ (queryResults, error) in if error != nil { completion(nil,"An internal error occured") } else if queryResults!.documents.count == 0 { completion(nil, "No parkings added") } else { do { var parkingList:[Parking] = [Parking]() for result in queryResults!.documents { if let parking = try result.data(as : Parking.self) { parkingList.append(parking) } } completion(parkingList, nil) } catch { print(error) } } } } }
true
d180013e4e94cfcd94464dbc871982419ba3720f
Swift
madhav0108/MinTXT
/MINTXT/ChatSViewController.swift
UTF-8
1,901
3.046875
3
[]
no_license
// // ChatSViewController.swift // MINTXT // // Created by madhav sharma on 10/19/20. // import UIKit import MessageKit struct Message: MessageType { var sender: SenderType var messageId: String var sentDate: Date var kind: MessageKind } struct Sender: SenderType { var senderId: String var displayName: String } class ChatSViewController: MessagesViewController { private var messages = [Message]() private let ballerMach = Sender(senderId: "333", displayName: "Baller Mach") private let sarahParker = Sender(senderId: "666", displayName: "Sarah Parker") override func viewDidLoad() { super.viewDidLoad() messages.append(Message(sender: ballerMach, messageId: "3", sentDate: Date(), kind: .text("Hey Sarah!"))) messages.append(Message(sender: sarahParker, messageId: "6", sentDate: Date(), kind: .text("Hey Baller!"))) messagesCollectionView.messagesDataSource = self messagesCollectionView.messagesLayoutDelegate = self messagesCollectionView.messagesDisplayDelegate = self // Do any additional setup after loading the view. } } extension ChatSViewController: MessagesDataSource, MessagesLayoutDelegate, MessagesDisplayDelegate { func currentSender() -> SenderType { return ballerMach } func messageForItem(at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> MessageType { return messages[indexPath.section] } func numberOfSections(in messagesCollectionView: MessagesCollectionView) -> Int { return messages.count } }
true
e3cf2282462adc25e5629bf3022cd752558c3a0f
Swift
danielmu/HotWeatherApp
/DanMuana_HotWeatherApp/DanMuana_HotWeatherApp/ServiceModel.swift
UTF-8
3,556
3.03125
3
[]
no_license
// // ServiceModel.swift // DanMuana_HotWeatherApp // // Created by Dan Muana on 11/3/21. // import Foundation class ServiceModel { static let shared = ServiceModel() // MARK: - Network variables let URL_BASE = "https://api.openweathermap.org/data/2.5/weather?" let URL_API_KEY = "65d00499677e59496ca2f318eb68c049" //keepsafe let URL_FOR_CITY = "q=" let URL_FOR_ZIP = "zip=" let US_STATES = ["AL":"Alabama","AK":"Alaska","AZ":"Arizona","AR":"Arkansas","CA":"California","CO":"Colorado","CT":"Connecticut","DE":"Delaware","FL":"Florida","GA":"Georgia","HI":"Hawaii","ID":"Idaho","IL":"Illinois","IN":"Indiana","IA":"Iowa","KS":"Kansas","KY":"Kentucky","LA":"Louisiana","ME":"Maine","MD":"Maryland","MA":"Massachusetts","MI":"Michigan","MN":"Minnesota","MS":"Mississippi","MO":"Missouri","MT":"Montana","NE":"Nebraska","NV":"Nevada","NH":"New Hampshire","NJ":"New Jersey","NM":"New Mexico","NY":"New York","NC":"North Carolina","ND":"North Dakota","OH":"Ohio","OK":"Oklahoma","OR":"Oregon","PA":"Pennsylvania","RI":"Rhode Island","SC":"South Carolina","SD":"South Dakota","TN":"Tennessee","TX":"Texas","UT":"Utah","VT":"Vermont","VA":"Virginia","WA":"Washington","WV":"West Virginia","WI":"Wisconsin","WY":"Wyoming"] var URL_BUILT = "" var URL_LOOKUP_INPUT = "Phoenix" // "85050" var URL_LOOKUP_TYPE = "q=" // "zip=" // MARK: - Network Service Setup let session = URLSession(configuration: .default) func setLookUpInput(_ lookupInput: String) { //check for state abbriviations URL_LOOKUP_INPUT = lookupInput.count == 2 ? US_STATES[lookupInput.uppercased()] ?? lookupInput : lookupInput //check for ZIP or NAME URL_LOOKUP_TYPE = Int(lookupInput) != nil ? URL_FOR_ZIP : URL_FOR_CITY } func buildURL() -> String { URL_BUILT = URL_BASE + URL_LOOKUP_TYPE + URL_LOOKUP_INPUT + "&units=imperial&appid=" + URL_API_KEY return URL_BUILT.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? URL_BUILT } // MARK: - Network Service Calls func lookupWeather(onSuccess: @escaping (LookUp) -> Void, onError: @escaping (String) -> Void) { guard let url = URL(string: buildURL()) else { onError("Failed to build URL") return } let task = session.dataTask(with: url) { (data, response, error) in DispatchQueue.main.async { if let error = error { onError(error.localizedDescription) return } guard let data = data, let response = response as? HTTPURLResponse else { onError("Invalid data or response") return } do { if response.statusCode == 200 { let items = try JSONDecoder().decode(LookUp.self, from: data) onSuccess(items) } else if response.statusCode == 401 { onError("Invalid API Key") } else if response.statusCode == 404 { onError("City not found! Check Spelling") } else { onError("ERROR Response: \(response.statusCode)") } } catch { onError(error.localizedDescription) } } } task.resume() } }
true
9f3041fe0fd7141efbb36b5b5e2122e5eae5c7ab
Swift
Chiagoziem/BeyondBirth
/BeyondBirth/MenuViewController.swift
UTF-8
7,899
2.578125
3
[]
no_license
// // MenuController.swift // team7 // // Created by Chiagoziem on 11/7/18. // Copyright © 2018 Admin. All rights reserved. // import UIKit import Firebase class MenuViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // check if the user is logged in before allowing the user to see/use the other capabilities checkIfUserIsLoggedIn() // design views setupViews() } func setupViews() { navigationItem.title = "Menu" navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Logout", style: .plain, target: self, action: #selector(handleLogout)) view.backgroundColor = .white // view.addSubview(journalButton) view.addSubview(breathingButton) view.addSubview(appointmentButton) view.addSubview(timerButton) view.addSubview(emotionButton) // setupjournal() setupbreathing() setupappointment() setuptimer() setupemotion() } // checks if the current user is logged in func checkIfUserIsLoggedIn() { // if uid is nil, the user is not logged in if Auth.auth().currentUser?.uid == nil { // show login view perform(#selector(handleLogin), with: nil, afterDelay: 0) } // else, the user is logged in } // MARK: - button actions // presents login view @objc func handleLogin() { present(LoginViewController(), animated: true, completion: nil) } // log out the current user @objc func handleLogout() { do { try Auth.auth().signOut() } catch let logoutError { print(logoutError) } // present login view present(LoginViewController(), animated: true, completion: nil) } // @objc func journal() { // self.navigationController?.pushViewController(JournalViewController(), animated: true) // } // creates the BreathingExercisesController for breathing exercises @objc func breathing() { let flowLayout = UICollectionViewFlowLayout() let customCollectionViewController = BreathingExercisesViewController(collectionViewLayout: flowLayout) self.navigationController?.pushViewController(customCollectionViewController, animated: true) } @objc func appointments() { self.navigationController?.pushViewController(AppointmentViewController(), animated: true) } @objc func timer() { self.navigationController?.pushViewController(TimerViewController(), animated: true) } @objc func emotion() { self.navigationController?.pushViewController(EmotionsMainViewController(), animated: true) } // MARK: - views // let journalButton: UIButton = { // let button = UIButton(type: .system) // button.backgroundColor = UIColor(r: 8, g: 28, b: 255) // button.setTitle("Journal", for: .normal ) // button.setTitleColor(UIColor.white, for: .normal) // button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 20) // button.translatesAutoresizingMaskIntoConstraints = false // button.addTarget(self, action: #selector(journal), for: .touchUpInside) // return button // }() let breathingButton: UIButton = { let button = UIButton(type: .system) button.backgroundColor = UIColor(r: 8, g: 28, b: 255) button.setTitle("Breathing Exercises", for: .normal ) button.setTitleColor(UIColor.white, for: .normal) button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 20) button.translatesAutoresizingMaskIntoConstraints = false button.addTarget(self, action: #selector(breathing), for: .touchUpInside) return button }() let appointmentButton: UIButton = { let button = UIButton(type: .system) button.backgroundColor = UIColor(r: 8, g: 28, b: 255) button.setTitle("Appointments", for: .normal ) button.setTitleColor(UIColor.white, for: .normal) button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 20) button.translatesAutoresizingMaskIntoConstraints = false button.addTarget(self, action: #selector(appointments), for: .touchUpInside) return button }() let timerButton: UIButton = { let button = UIButton(type: .system) button.backgroundColor = UIColor(r: 8, g: 28, b: 255) button.setTitle("Timer", for: .normal ) button.setTitleColor(UIColor.white, for: .normal) button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 20) button.translatesAutoresizingMaskIntoConstraints = false button.addTarget(self, action: #selector(timer), for: .touchUpInside) return button }() let emotionButton: UIButton = { let button = UIButton(type: .system) button.backgroundColor = UIColor(r: 8, g: 28, b: 255) button.setTitle("Emotions", for: .normal ) button.setTitleColor(UIColor.white, for: .normal) button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 20) button.translatesAutoresizingMaskIntoConstraints = false button.addTarget(self, action: #selector(emotion), for: .touchUpInside) return button }() // MARK: - constraints // func setupjournal() { // journalButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true // journalButton.bottomAnchor.constraint(equalTo: breathingButton.topAnchor, constant: -12).isActive = true // journalButton.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -24).isActive = true // journalButton.heightAnchor.constraint(equalToConstant: 40).isActive = true // } func setupbreathing() { breathingButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true breathingButton.bottomAnchor.constraint(equalTo: appointmentButton.topAnchor, constant: -12).isActive = true breathingButton.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -24).isActive = true breathingButton.heightAnchor.constraint(equalToConstant: 40).isActive = true } func setupappointment() { appointmentButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true appointmentButton.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true appointmentButton.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -24).isActive = true appointmentButton.heightAnchor.constraint(equalToConstant: 40).isActive = true } func setuptimer() { timerButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true timerButton.topAnchor.constraint(equalTo: appointmentButton.bottomAnchor, constant: 12).isActive = true timerButton.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -24).isActive = true timerButton.heightAnchor.constraint(equalToConstant: 40).isActive = true } func setupemotion() { emotionButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true emotionButton.topAnchor.constraint(equalTo: timerButton.bottomAnchor, constant: 12).isActive = true emotionButton.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -24).isActive = true emotionButton.heightAnchor.constraint(equalToConstant: 40).isActive = true } func preferredStatusBarStyle() -> UIStatusBarStyle { return .lightContent } } // so i dont have to type color: num/255 every time extension UIColor { convenience init(r: CGFloat, g: CGFloat, b: CGFloat){ self.init(red: r/255, green: g/255, blue: b/255, alpha: 1) } }
true
338dc868e218053531bba4fa875bfe3657068045
Swift
alanyangcn/leetcode-swift
/1672_Richest_Customer_Wealth/1672_Richest_Customer_Wealth.playground/Contents.swift
UTF-8
1,414
3.625
4
[ "MIT" ]
permissive
import Foundation /* * problem url: https://leetcode.com/problems/richest-customer-wealth */ /* You are given an m x n integer grid accounts where accounts[i][j] is the amount of money the i​​​​​​​​​​​th​​​​ customer has in the j​​​​​​​​​​​th​​​​ bank. Return the wealth that the richest customer has. A customer's wealth is the amount of money they have in all their bank accounts. The richest customer is the customer that has the maximum wealth.   Example 1: Input: accounts = [[1,2,3],[3,2,1]] Output: 6 Explanation: 1st customer has wealth = 1 + 2 + 3 = 6 2nd customer has wealth = 3 + 2 + 1 = 6 Both customers are considered the richest with a wealth of 6 each, so return 6. Example 2: Input: accounts = [[1,5],[7,3],[3,5]] Output: 10 Explanation: 1st customer has wealth = 6 2nd customer has wealth = 10 3rd customer has wealth = 8 The 2nd customer is the richest with a wealth of 10. Example 3: Input: accounts = [[2,8,7],[7,1,3],[1,9,5]] Output: 17   Constraints: m == accounts.length n == accounts[i].length 1 <= m, n <= 50 1 <= accounts[i][j] <= 100 */ class Solution { func maximumWealth(_ accounts: [[Int]]) -> Int { let result = accounts.map({$0.reduce(0, +)}).max() ?? 0 return result } } let input = [[1,2,3],[3,2,1]] print(Solution().maximumWealth(input))
true
7eb99c32b8eedb5ecabc982413c9dda6b1cae28e
Swift
pointfreeco/pointfreeco
/Sources/Transcripts/BlogPosts/BlogPost0048_2020CyberMondaySale.swift
UTF-8
2,740
3.015625
3
[ "MIT", "CC-BY-NC-4.0", "LicenseRef-scancode-other-copyleft", "LicenseRef-scancode-unknown-license-reference", "CC-BY-NC-SA-4.0", "LicenseRef-scancode-proprietary-license", "CC-BY-4.0" ]
permissive
import Foundation public let post0048_CyberMondaySale = BlogPost( author: .pointfree, blurb: """ For the next 24 hours, we're offering personal Point-Free subscriptions for 30% off the first year! """, contentBlocks: [ Episode.TranscriptBlock( content: #""" We’re happy to announce a [rare Point-Free sale](/discounts/cyber-monday-2020) this Cyber Monday by offering 30% off the first year of your subscription! Once subscribed you'll get instant access to all 127 episodes (and growing) of Point-Free, including popular collections that have grown this past year: - [Composable Architecture](/collections/composable-architecture): We started developing the Composable Architecture from first principles after breaking down the problems app architecture should solve, all the way back in July 2019. We continued to refine things over _17 hours_ (so far) in this collection of episodes, while covering aspects of SwiftUI, Combine, and more general concepts like testing and dependencies! We finally bundled things up into [an open source library](https://github.com/pointfreeco/swift-composable-architecture) so that you can immediately put these concepts to use in your applications! - [Parsing](/collections/parsing): When we define "parsing" as transforming some kind of unstructured data into something more structured, it turns out that parsing is quite a ubiquitous problem that shows up in a lot of the everyday code we write! It also turns out that functional programming has a lot to say about parsing. We first started covering the topic last year, but many viewers have requested more content, and we have recently picked things up again. Now's the perfect time to jump in! In addition to these topics, we covered: - [SwiftUI bindings](/episodes/ep107-composable-swiftui-bindings-the-problem) and how they compose - [SwiftUI's new `redacted` API](/episodes/ep115-redacted-swiftui-the-problem) - [Combine's Scheduler API](/episodes/ep104-combine-schedulers-testing-time) and how to test Combine code - [How to design your app's dependencies](/episodes/ep110-designing-dependencies-the-problem) - And what do you get when you design a Swift key path for enums? [Case paths!](https://www.pointfree.co/episodes/ep87-the-case-for-case-paths-introduction) [Click here](/discounts/cyber-monday-2020) to redeem the coupon code now. The offer will only remain valid through November 30, 2020. """#, timestamp: nil, type: .paragraph ) ], coverImage: nil, hidden: true, id: 48, publishedAt: Date(timeIntervalSince1970: 1_606_690_440), title: "Cyber Monday Sale: 30% Off Point-Free" )
true