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
3f825468272781b13e7461871836a6dfbf304fec
Swift
KiraLayo/Algorithm
/409. 最长回文串/main.swift
UTF-8
1,194
3.46875
3
[]
no_license
// // main.swift // 409. 最长回文串 // // Created by YP-21031 on 2022/2/23. // Copyright © 2022 KiraLayo. All rights reserved. // //409. 最长回文串 //给定一个包含大写字母和小写字母的字符串 s ,返回 通过这些字母构造成的 最长的回文串 。 // //在构造过程中,请注意 区分大小写 。比如 "Aa" 不能当做一个回文字符串。 // // // //示例 1: // //输入:s = "abccccdd" //输出:7 //解释: //我们可以构造的最长的回文串是"dccaccd", 它的长度是 7。 //示例 2: // //输入:s = "a" //输入:1 //示例 3: // //输入:s = "bb" //输入: 2 // // //提示: // //1 <= s.length <= 2000 //s 只能由小写和/或大写英文字母组成 import Foundation class Solution { func longestPalindrome(_ s: String) -> Int { var countMap: [Character:Int] = [:] for c in s { countMap[c, default: 0] += 1; } var res = 0; for item in countMap { if item.value % 2 == 0 { res += item.value; } else if res % 2 == 0, item.value % 2 != 0 { res += 1 } } return res } }
true
159abb3246223a91b46c30d652788ad47779937b
Swift
adam-fowler/aws-signer-v4
/Sources/AWSCrypto/MD5.swift
UTF-8
1,384
2.578125
3
[ "Apache-2.0" ]
permissive
// Replicating the CryptoKit framework interface for < macOS 10.15 // written by AdamFowler 2020/01/30 #if !os(Linux) import CommonCrypto public extension Insecure { struct MD5Digest : ByteDigest { public static var byteCount: Int { return Int(CC_MD5_DIGEST_LENGTH) } public var bytes: [UInt8] } struct MD5: CCHashFunction { public typealias Digest = MD5Digest public static var algorithm: CCHmacAlgorithm { return CCHmacAlgorithm(kCCHmacAlgMD5) } var context: CC_MD5_CTX public static func hash(bufferPointer: UnsafeRawBufferPointer) -> Self.Digest { var digest: [UInt8] = .init(repeating: 0, count: Digest.byteCount) CC_MD5(bufferPointer.baseAddress, CC_LONG(bufferPointer.count), &digest) return .init(bytes: digest) } public init() { context = CC_MD5_CTX() CC_MD5_Init(&context) } public mutating func update(bufferPointer: UnsafeRawBufferPointer) { CC_MD5_Update(&context, bufferPointer.baseAddress, CC_LONG(bufferPointer.count)) } public mutating func finalize() -> Self.Digest { var digest: [UInt8] = .init(repeating: 0, count: Digest.byteCount) CC_MD5_Final(&digest, &context) return .init(bytes: digest) } } } #endif
true
5a26854c9be9678f6221b27c07af47e3a63c95e6
Swift
Keanyuan/SwiftContact
/SwiftContent/SwiftContent/Classes/ContentView/shaixuan/FiltrateView.swift
UTF-8
2,188
2.53125
3
[ "MIT" ]
permissive
// // FiltrateView.swift // SwiftContent // // Created by Kean on 2017/6/25. // Copyright © 2017年 祁志远. All rights reserved. // import UIKit /// 动画时长 private let kAnimationDuration = 0.25 class FiltrateView: UIView { class func show(){ let filtrateView = FiltrateView() filtrateView.frame = UIScreen.main.bounds filtrateView.backgroundColor = UIColor(red: 0/255.0, green: 0/255.0, blue: 0/255.0, alpha: 0.6) let window = UIApplication.shared.keyWindow window?.addSubview(filtrateView) } func randomFloat(min: Float, max: Float) -> Float { return (Float(arc4random()) / 0xFFFFFFFF) * (max - min) + min } override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() UIView.animate(withDuration: kAnimationDuration) { self.bgView.x = SCREENW - self.bgView.width } } fileprivate func setupUI(){ addSubview(bgView) bgView.addSubview(filtrateView) filtrateView.snp.makeConstraints { (make) in make.top.right.bottom.equalTo(bgView) make.width.equalTo(bgView).multipliedBy(0.8) } } private lazy var bgView:UIView = { let bgView = UIView() bgView.frame = CGRect(x: SCREENW, y: 0, width: SCREENW, height: SCREENH) return bgView }() private lazy var filtrateView:UIView = { let filtrateView = UIView() filtrateView.backgroundColor = UIColor.white filtrateView.isUserInteractionEnabled = true return filtrateView }() override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { cancleBtnClick() } func cancleBtnClick(){ UIView.animate(withDuration: kAnimationDuration, animations: { self.bgView.x = SCREENW }) { (_) in self.removeFromSuperview() } } }
true
3fed2703dfcfa37394263d5aec5e7f7e43a00efc
Swift
valen90/jwt-keychain
/Sources/JWTKeychain/Controllers/API/UserControllerType.swift
UTF-8
1,958
2.734375
3
[ "MIT" ]
permissive
import Vapor import HTTP /// Defines basic authorization functionality. public protocol UserControllerType { /// Initializes the UsersController with a JWT configuration. /// /// - Parameters: /// configuration : the JWT configuration to be used to generate user tokens. /// drop : the Droplet instance init(configuration: ConfigurationType, drop: Droplet, mailer: MailerType) /// Registers a user on the DB. /// /// - Parameter request: current request. /// - Returns: JSON response with User data. /// - Throws: on invalid data or if unable to store data on the DB. func register(request: Request) throws -> ResponseRepresentable /// Logins the user on the system, giving the token back. /// /// - Parameter request: current request. /// - Returns: JSON response with User data. /// - Throws: on invalid data or wrong credentials. func login(request: Request) throws -> ResponseRepresentable /// Logs the user out of the system. /// /// - Parameter request: current request. /// - Returns: JSON success response. /// - Throws: if not able to find token. func logout(request: Request) throws -> ResponseRepresentable /// Generates a new token for the user. /// /// - Parameter request: current request. /// - Returns: JSON with token. /// - Throws: if not able to generate token. func regenerate(request: Request) throws -> ResponseRepresentable /// Returns the authenticated user data. /// /// - Parameter request: current request. /// - Returns: JSON response with User data. /// - Throws: on no user found. func me(request: Request) throws -> ResponseRepresentable /// Requests a reset of password for the given email. /// /// - Parameter request: current request. /// - Returns: success or failure message func resetPasswordEmail(request: Request) throws -> ResponseRepresentable }
true
48f07d8472d0f0a6f5247f4ab843c6522265c33a
Swift
Leandro97/orama-sample-app
/OramaSampleApp/Common/Repository/Local/FundLocalDataSourceImpl.swift
UTF-8
514
2.71875
3
[]
no_license
// // FundLocalDataSourceImpl.swift // OramaSampleApp // // Created by Leandro Martins de Freitas on 18/04/21. // import Foundation import RealmSwift class FundLocalDataSourceImpl: FundLocalDataSource { func saveBuy(fund: Fund) { let realm = try! Realm() try! realm.write() { realm.add(fund) } } func getBoughtFunds() -> [Fund] { let realm = try! Realm() let results = Array(realm.objects(Fund.self)) return results } }
true
a104da0d716669d9c8504b630307d61dc55a6226
Swift
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Swift/towers-of-hanoi-1.swift
UTF-8
207
2.90625
3
[]
no_license
func hanoi(n:Int, a:String, b:String, c:String) { if (n > 0) { hanoi(n - 1, a, c, b) println("Move disk from \(a) to \(c)") hanoi(n - 1, b, a, c) } } hanoi(4, "A", "B", "C")
true
a7ab99f08626c597f643f6af41ca433e271a835b
Swift
hassan-rafique/CAMTest
/CAMTest/Service/ServerClient.swift
UTF-8
1,138
2.609375
3
[]
no_license
// // ServerClient.swift // CAMTest // // Created by Hassan Rafique Awan on 06/05/2020. // Copyright © 2020 Hassan Rafique Awan. All rights reserved. // import Foundation import RxSwift class ServerClient { func getStates() -> Observable<[State]> { return Observable.create { observer -> Disposable in let url = URL(string: "https://raw.githubusercontent.com/vega/vega/master/docs/data/us-state-capitals.json")! URLSession.shared.dataTask(with: url) { (data, response, error) in guard let data = data else { if let error = error { observer.onError(error) } else { observer.onNext([]) } return } do { let states = try JSONDecoder().decode([State].self, from: data) observer.onNext(states) } catch { observer.onError(error) } }.resume() return Disposables.create() } } }
true
a6d19ce2cbfb3c85e9f3eb03e6eedd779d087596
Swift
teakun/SekigaeKun
/SekigaeKun/Sekigae/Seat.swift
UTF-8
1,392
3.78125
4
[]
no_license
import Foundation enum SeatType: String { case pair = "ペア" case solo = "ソロ" } class Seat { let type: SeatType var member1: Member? = nil var member2: Member? = nil var hasAmari: Bool { return (member1 == nil) || (member2 == nil) } var emptySeatCount: Int { var count = 2 if member1 == nil { count -= 1 } if member2 == nil { count -= 1 } return count } init(type: SeatType) { self.type = type } func swap(target: Member, new: Member) { if (member1 === target && member2 === new) || (member1 === new && member2 === target) { let tmp = member1 member1 = member2 member2 = tmp } else if member1 === target { member1 = new } else if member2 === target { member2 = new } else if member1 === new { member1 = target } else if member2 === new { member2 = target } } @discardableResult func setMember(member: Member) -> Bool { if member1 == nil { member1 = member return true } else if member2 == nil { member2 = member return true } else { return false } } func reset() { member1 = nil member2 = nil } }
true
1eda2fb862aa7d834638b2e4901738a52f7b3f83
Swift
TJSartain/CasualTournament
/Tournament/Core Data/Tournament+CoreDataProperties.swift
UTF-8
2,912
2.671875
3
[]
no_license
// // Tournament+CoreDataProperties.swift // Casual Tournament // // Created by TJ Sartain on 9/14/18. // Copyright © 2018 iTrinity, Inc. All rights reserved. // // import Foundation import CoreData extension Tournament { @nonobjc public class func fetchRequest() -> NSFetchRequest<Tournament> { return NSFetchRequest<Tournament>(entityName: "Tournament") } @NSManaged public var date: NSDate? @NSManaged public var location: String? @NSManaged public var name: String? @NSManaged public var games: NSOrderedSet? @NSManaged public var teams: NSOrderedSet? @NSManaged public var winner: Team? @NSManaged public var second: Team? @NSManaged public var third: Team? } // MARK: Generated accessors for games extension Tournament { @objc(insertObject:inGamesAtIndex:) @NSManaged public func insertIntoGames(_ value: Game, at idx: Int) @objc(removeObjectFromGamesAtIndex:) @NSManaged public func removeFromGames(at idx: Int) @objc(insertGames:atIndexes:) @NSManaged public func insertIntoGames(_ values: [Game], at indexes: NSIndexSet) @objc(removeGamesAtIndexes:) @NSManaged public func removeFromGames(at indexes: NSIndexSet) @objc(replaceObjectInGamesAtIndex:withObject:) @NSManaged public func replaceGames(at idx: Int, with value: Game) @objc(replaceGamesAtIndexes:withGames:) @NSManaged public func replaceGames(at indexes: NSIndexSet, with values: [Game]) @objc(addGamesObject:) @NSManaged public func addToGames(_ value: Game) @objc(removeGamesObject:) @NSManaged public func removeFromGames(_ value: Game) @objc(addGames:) @NSManaged public func addToGames(_ values: NSOrderedSet) @objc(removeGames:) @NSManaged public func removeFromGames(_ values: NSOrderedSet) } // MARK: Generated accessors for teams extension Tournament { @objc(insertObject:inTeamsAtIndex:) @NSManaged public func insertIntoTeams(_ value: Team, at idx: Int) @objc(removeObjectFromTeamsAtIndex:) @NSManaged public func removeFromTeams(at idx: Int) @objc(insertTeams:atIndexes:) @NSManaged public func insertIntoTeams(_ values: [Team], at indexes: NSIndexSet) @objc(removeTeamsAtIndexes:) @NSManaged public func removeFromTeams(at indexes: NSIndexSet) @objc(replaceObjectInTeamsAtIndex:withObject:) @NSManaged public func replaceTeams(at idx: Int, with value: Team) @objc(replaceTeamsAtIndexes:withTeams:) @NSManaged public func replaceTeams(at indexes: NSIndexSet, with values: [Team]) @objc(addTeamsObject:) @NSManaged public func addToTeams(_ value: Team) @objc(removeTeamsObject:) @NSManaged public func removeFromTeams(_ value: Team) @objc(addTeams:) @NSManaged public func addToTeams(_ values: NSOrderedSet) @objc(removeTeams:) @NSManaged public func removeFromTeams(_ values: NSOrderedSet) }
true
5bd3a9ecf3870ea5c5b53368ddc657a76e3eec19
Swift
suhaiboon/MiReconnect2019
/MiReconnect2019/Agenda/AgendaTableViewCell.swift
UTF-8
8,899
2.609375
3
[]
no_license
// // AgendaTableViewCell.swift // AgendaPage // // Created by Suhaib AlMutawakel on 7/30/19. // Copyright © 2019 Suhaib AlMutawakel. All rights reserved. // import UIKit import Foundation import UserNotifications protocol agendaDelegate { func reminderPressed() } class AgendaTableViewCell: UITableViewCell { // @IBOutlet weak var ImageBackground: UIImageView! // I do not know why are you using this var delegate: agendaDelegate? var userDefault = UserDefaults.standard @IBOutlet weak var speakerImage: UIImageView! @IBOutlet weak var sessionTitle: UILabel! @IBOutlet weak var speakerName: UILabel! @IBOutlet weak var startTime: UILabel! @IBOutlet weak var duration: UILabel! @IBOutlet weak var remindBtn: UIButton! // It's not a very good idea to add `!` to a variable here, but I'm going with the flow :) private var agenda: Agenda! //Setting up the agenda cell based on the info received from tableview func setAgenda(agenda: Agenda){ self.agenda = agenda speakerImage.image = UIImage(named: agenda.speakerImage) //speakerImage.image = agenda.speakerImage sessionTitle.text = agenda.sessionTitle //startTime.text = "\(agenda.startTimeHours) : \(agenda.startTimeMinutes)" if agenda.startTimeMinutes == 0{ startTime.text = String(agenda.startTimeHours) + ":" + "00" } else{ startTime.text = String(agenda.startTimeHours) + ":" + String(agenda.startTimeMinutes) } duration.text = agenda.duration speakerName.text = agenda.speakerName //Setting the button tag equal to index so we keep track of buttons created // remindBtn.tag = myIndex // // remindBtn.setImage(agenda.isSelected ? UIImage(named: "bellOn") : UIImage(named: "bellOff"), for: .normal) configureReminderImaage() } //Function that handles once the remind button is pressed @IBAction func btnPressed(_ sender: Any) { agenda.hasReminder = !agenda.hasReminder configureReminderImaage() //When the button is pressed for the first time it is set to on if agenda.hasReminder { let id : String = String(remindBtn!.tag) setNotification(id: id) // saveReminderSetting() } else { let id : String = String(remindBtn!.tag) removeNotificaiton(id: id) } } func configureReminderImaage() { let reminderImageName = agenda.hasReminder ? "bellOn" : "bellOff" remindBtn.setImage(UIImage(named: reminderImageName), for: .normal) } // func saveReminderSetting () { // userDefault.set(remindBtn.tag, forKey: "bellOn") // } // func checkReminderSettings () { // let hasReminderSetting = userDefault.bool(forKey: "bellOn") // // if hasReminderSetting { // agenda.hasReminder = true // } // } //trying to fix the repeated button reminder // override func prepareForReuse() { // super.prepareForReuse() // remindBtn.setImage(UIImage(named: "bellOff"), for: .normal) // } // func setNotification (id : String) { let center = UNUserNotificationCenter.current() let reminderTime: Int = 15 let content = UNMutableNotificationContent() let lectureTitle = agendas[remindBtn.tag].sessionTitle content.title = lectureTitle content.body = " \(lectureTitle) with \(agendas[remindBtn.tag].speakerName) is about to start in 15 minutes. Head to main hall." content.categoryIdentifier = "alarm" content.userInfo = ["btnID": id] content.sound = UNNotificationSound.default var dateComponents = DateComponents() dateComponents.month = 9 dateComponents.day = 12 dateComponents.hour = agendas[remindBtn.tag].startTimeHours dateComponents.minute = agendas[remindBtn.tag].startTimeMinutes //dateComponents.day = 10 //dateComponents.hour = agendaItems[remindBtn.tag].startTimeHours if agendas[remindBtn.tag].startTimeMinutes < reminderTime { dateComponents.hour = agendas[remindBtn.tag].startHoursMilitary - 1 dateComponents.minute = 60 - reminderTime }else { dateComponents.hour = agendas[remindBtn.tag].startHoursMilitary dateComponents.minute = agendas[remindBtn.tag].startTimeMinutes - reminderTime } // dateComponents.hour = 18 // dateComponents.minute = 14 //dateComponents.minute = agendaItems[remindBtn.tag].startTimeMinutes let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true) // Repeating the reminder/notification instead of set time // let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false) //let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger) let request = UNNotificationRequest(identifier: id, content: content, trigger: trigger) center.add(request) } func removeNotificaiton(id : String){ let center = UNUserNotificationCenter.current() center.getPendingNotificationRequests { (notifications) in //print("Count: \(notifications.count)") for item in notifications { //let userInfo = item.content.userInfo // let userInfo:Dictionary<AnyHashable,Any?> = item.content.userInfo // let infoDict : Dictionary = userInfo as! Dictionary<String,String?> // let notifcationObjectId : String = infoDict["btnID"]!! //var dict : Dictionary = Dictionary<AnyHashable,Any>() //let yourData = userInfo["btnId"] //print(notifcationObjectId) let notifcationObjectId = item.identifier if id == notifcationObjectId { center.removePendingNotificationRequests(withIdentifiers: [id]) //center.removeDeliveredNotifications(withIdentifiers: ["btnID"]) print("done") print(id, notifcationObjectId) } } } } // //@IBAction func remindPressed(_ sender: Any) { // delegate?.reminderPressed() // // remindBtn.setImage(UIImage(named: "belllicon"), for: .normal) // // // let center = UNUserNotificationCenter.current() // // let content = UNMutableNotificationContent() // let lectureTitle = agendaItems[remindBtn.tag].sessionTitle // content.title = lectureTitle // content.body = "Lecture: \(lectureTitle) is about to start in 5 minutes. Head to main hall." // content.categoryIdentifier = "alarm" // content.userInfo = ["customData": "fizzbuzz"] // content.sound = UNNotificationSound.default // // var dateComponents = DateComponents() // dateComponents.month = 8 // dateComponents.day = 29 // dateComponents.hour = agendaItems[remindBtn.tag].startTimeHours // dateComponents.minute = agendaItems[remindBtn.tag].startTimeMinutes // let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true) // // //Repeating the reminder/notification instead of set time // //let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false) // // let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger) // center.add(request) // } // // var agenda: Agenda! { // didSet{ // updateUI() // } // } // // func updateUI() { // //ImageBackground.image = UIImage(named: agenda.placeholder) //// ImageBackground.layer.shadowOpacity = 0.2 // opacity, 20% //// ImageBackground.layer.shadowColor = UIColor.init(red:0.20, green:0.52, blue:0.90, alpha:1.0).cgColor //// ImageBackground.layer.shadowRadius = 5 // HALF of blur //// ImageBackground.layer.shadowOffset = CGSize(width: 0, height: 2) // Spread x, y //// ImageBackground.layer.masksToBounds = false // // } // }
true
defbca64f70a2e1e8caf7c6af00d09125addb13e
Swift
28th-BE-SOPT-iOS-Part/LimKyungJin
/Week1HW/Week1HW/ProfileViewController.swift
UTF-8
1,180
2.890625
3
[]
no_license
// // ProfileViewController.swift // Week1HW // // Created by kyoungjin on 2021/04/23. // import UIKit class ProfileViewController: UIViewController { @IBOutlet weak var profileName: UILabel! @IBOutlet weak var profilePicture: UIImageView! var name : String? var image : String? override func viewDidLoad() { super.viewDidLoad() setProfile() // Do any additional setup after loading the view. } func setProfile() { if let myName = self.name { profileName.text = myName } if let myPicture = self.image { profilePicture.image = UIImage(named: myPicture) } } @IBAction func dismissClicked(_ sender: Any) { self.dismiss(animated: true, completion: nil) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
true
36a34db259b8d2f419d83197f944102c452f068e
Swift
cryptoapi-project/cryptoapi-swift
/CryptoAPI/Models/Rates/RatesResponseModel.swift
UTF-8
932
2.609375
3
[ "MIT" ]
permissive
// // RatesResponseModel.swift // CryptoAPI // // Created by Alexander Eskin on 4/3/20. // Copyright © 2020 PixelPlex. All rights reserved. // import Foundation public struct RatesResponseModel: Codable { public let symbol: String public let rate: CoinRateResponseModel } public struct CoinRateResponseModel { public let usd: String public let eur: String public let krw: String public let cny: String public let jpy: String public let aud: String public let rub: String public let cad: String public let chf: String public let gbp: String } extension CoinRateResponseModel: Codable { enum CodingKeys: String, CodingKey { case usd = "USD" case eur = "EUR" case krw = "KRW" case cny = "CNY" case jpy = "JPY" case aud = "AUD" case rub = "RUB" case cad = "CAD" case chf = "CHF" case gbp = "GBP" } }
true
96bbf4c6cf5bbfec67a9c2d738a4976b3f9a35e1
Swift
trevorschoeny/Budget-App-Part-2
/Budget App Part 2/Views/Budget Views/NewPeriodView.swift
UTF-8
4,998
3.03125
3
[]
no_license
// // NewPeriodView.swift // Budget App Part 2 // // Created by Trevor Schoeny on 6/6/21. // import SwiftUI struct NewPeriodView: View { @EnvironmentObject var budgetModel:BudgetModel @State var extraFunds = ExtraFunds() @State var inputBudget: BudgetEntity? @State var inputFunds: Double = 0 @Environment(\.presentationMode) var isPresented var body: some View { NavigationView { VStack { List { VStack(alignment: .leading) { HStack(spacing: 0) { Text("You have ") if inputFunds == 0 { if extraFunds.total - extraFunds.fundNumArr.reduce(0, +) >= 0 { Text("$" + String(extraFunds.total - extraFunds.fundNumArr.reduce(0, +))) .font(.title3) .foregroundColor(.green) } else { Text("$" + String(extraFunds.total - extraFunds.fundNumArr.reduce(0, +))) .font(.title3) .foregroundColor(.red) } } else { if inputFunds - extraFunds.fundNumArr.reduce(0, +) >= 0 { Text("$" + String(inputFunds - extraFunds.fundNumArr.reduce(0, +))) .font(.title3) .foregroundColor(.green) } else { Text("$" + String(inputFunds - extraFunds.fundNumArr.reduce(0, +))) .font(.title3) .foregroundColor(.red) } } Text(" remaining funds.") } Text("Allocate them for the next period, or continue.") .font(.footnote) .foregroundColor(.gray) } ForEach (0..<budgetModel.savedEntities.count) { i in HStack { Text(budgetModel.savedEntities[i].name! + ": ") Spacer() Text("$") TextField("0.00", text: $extraFunds.fundArr[i]) .keyboardType(.decimalPad) .onChange(of: extraFunds.fundArr[i]) { _ in extraFunds.fundNumArr[i] = Double(extraFunds.fundArr[i]) ?? 0.0 } } } } // MARK: Start New Period VStack { Button(action: { if inputFunds == 0 { for i in 0..<budgetModel.savedEntities.count { budgetModel.savedEntities[i].extraAmount = Double(extraFunds.fundArr[i]) ?? 0.0 budgetModel.savedEntities[i].balance = budgetModel.savedEntities[i].budgetAmount + budgetModel.savedEntities[i].extraAmount budgetModel.saveData() } } else { for i in 0..<budgetModel.savedEntities.count { if budgetModel.savedEntities[i].name == inputBudget?.name { print("HERE 1") print(budgetModel.savedEntities[i].extraAmount) print(Double(extraFunds.fundArr[i]) ?? 0.0) budgetModel.savedEntities[i].extraAmount = Double(extraFunds.fundArr[i]) ?? 0.0 budgetModel.savedEntities[i].balance = budgetModel.savedEntities[i].budgetAmount + budgetModel.savedEntities[i].extraAmount } else { print("HERE 2") budgetModel.savedEntities[i].extraAmount += Double(extraFunds.fundArr[i]) ?? 0.0 budgetModel.savedEntities[i].balance += Double(extraFunds.fundArr[i]) ?? 0.0 } } budgetModel.saveData() } self.isPresented.wrappedValue.dismiss() }, label: { ZStack { Rectangle() .font(.headline) .foregroundColor(Color(#colorLiteral(red: 0, green: 0.5603182912, blue: 0, alpha: 1))) .frame(height: 55) .cornerRadius(10) .padding(.horizontal) Text("Start New Period") .font(.headline) .foregroundColor(.white) } }) .padding(.bottom, 10) } } .navigationTitle("New Period") } } } //struct NewPeriodView_Previews: PreviewProvider { // static var previews: some View { // NewPeriodView() // } //}
true
2d4fb263edade000dbfad6c8c917f41ae5819773
Swift
renaudjenny/SwiftClockUI
/Sources/SwiftClockUI/Elements/Steampunk/SteampunkHourArm.swift
UTF-8
3,095
3.09375
3
[ "MIT" ]
permissive
import SwiftUI struct SteampunkHourArm: Shape { func path(in rect: CGRect) -> Path { let thickness = rect.radius * 1/30 let middleHoleCenter = CGPoint(x: rect.midX, y: rect.midY - rect.radius * 1/4 - thickness) var path = Path() addBottomHole(to: &path, rect: rect) addMiddleHole(to: &path, rect: rect) addRectangle(to: &path, rect: rect) addArrow(to: &path, rect: rect) path.addVerticalMirror(in: rect) path.addCircle(CGRect.circle(center: rect.center, radius: rect.radius * 1/15)) path.addCircle(CGRect.circle(center: middleHoleCenter, radius: rect.radius * 1/30)) return path } private func addBottomHole(to path: inout Path, rect: CGRect) { let thickness = rect.radius * 1/30 let endPoint = CGPoint(x: rect.midX + thickness/2, y: rect.midY - rect.radius * 1/15 - thickness) path.addArc( center: rect.center, radius: rect.radius * 1/15 + thickness, startAngle: .fullRound * 1/4, endAngle: .inCircle(for: endPoint, circleCenter: rect.center), clockwise: true ) } private func addMiddleHole(to path: inout Path, rect: CGRect) { let thickness = rect.radius * 1/30 let circle = CGRect.circle( center: CGPoint(x: rect.midX, y: rect.midY - rect.radius * 1/4 - thickness), radius: rect.radius * 1/30 + thickness ) let startPoint = CGPoint(x: rect.midX + thickness/2, y: circle.maxY) let endPoint = CGPoint(x: rect.midX + thickness/2, y: circle.minY) path.addArc( center: circle.center, radius: circle.radius, startAngle: .inCircle(for: startPoint, circleCenter: circle.center), endAngle: .inCircle(for: endPoint, circleCenter: circle.center), clockwise: true ) } func addRectangle(to path: inout Path, rect: CGRect) { let thickness = rect.radius * 1/30 let y = rect.midY - rect.radius * 4/9 path.addLine(to: CGPoint(x: rect.midX + thickness/2, y: y)) path.addLine(to: CGPoint(x: rect.midX + thickness * 2, y: y)) path.addLine(to: CGPoint(x: rect.midX + thickness * 2, y: y - thickness)) path.addLine(to: CGPoint(x: rect.midX + thickness/2, y: y - thickness)) } func addArrow(to path: inout Path, rect: CGRect) { let thickness = rect.radius * 1/30 let bottomY = rect.midY - rect.radius * 49/90 let middleY = rect.midY - rect.radius * 41/72 let topY = rect.midY - rect.radius * 25/36 path.addLine(to: CGPoint(x: rect.midX + thickness/2, y: bottomY)) path.addLine(to: CGPoint(x: rect.midX + thickness * 2, y: middleY)) path.addLine(to: CGPoint(x: rect.midX, y: topY)) } } struct SteampunkHourArm_Previews: PreviewProvider { static var previews: some View { ZStack { Circle().stroke() SteampunkHourArm().fill(style: .init(eoFill: true, antialiased: true)) } .padding() } }
true
84eee26ba69d1c0d89345577f9d98bec2f339a49
Swift
velyan/Comment-Spell-Checker
/Comment Spell Checker/Model.swift
UTF-8
549
2.765625
3
[ "MIT" ]
permissive
// // Model.swift // SpellChecker // // Created by Velislava Yanchina on 17/11/18. // Copyright © 2018 Velislava Yanchina. All rights reserved. // import Foundation typealias ResourceTuple = (name: String, extension: String) struct Content { var title: String var description: String var resource: ResourceTuple } protocol NavigationItemProtocol { var title: String {get set} } struct NavigationItem: NavigationItemProtocol{ internal var title: String } struct HeaderNavigationItem : NavigationItemProtocol { internal var title: String }
true
b4f9149ffe24b0d9a320be32c3cf858005fb1fbf
Swift
Dmitry770/TestTask
/TestTask/Base/Models/Content.swift
UTF-8
389
2.6875
3
[]
no_license
// // Content.swift // TestTask // // Created by Macintosh on 20/12/2019. // Copyright © 2019 Macintosh. All rights reserved. // import Foundation import Alamofire struct Content: Codable { let id: Int let name: String init(dictionary: Dictionary<String, Any>) { id = dictionary["id"] as? Int ?? 0 name = dictionary["name"] as? String ?? "" } }
true
9e8a4d03ee7250fe3f9565dd009c4bf5d3ff2234
Swift
chetanrathore/iOSDemo
/HotelApp/HotelApp/ImageCachingVC.swift
UTF-8
3,532
2.546875
3
[]
no_license
// // ImageCachingVC.swift // HotelApp // // Created by LaNet on 2/21/17. // Copyright © 2017 developer93. All rights reserved. // import UIKit class ImageCachingVC: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet var tblData: UITableView! var refresh: UIRefreshControl! var arrData:[AnyObject]! var task: URLSessionDownloadTask! var session:URLSession! var cache:NSCache<AnyObject, AnyObject>! override func viewDidLoad() { super.viewDidLoad() tblData.dataSource = self tblData.delegate = self session = URLSession.shared task = URLSessionDownloadTask() self.arrData = [] self.cache = NSCache() refresh = UIRefreshControl() refresh.addTarget(self, action: #selector(self.getData), for: .valueChanged) getData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func getData() { let url: URL! = URL(string: "https://itunes.apple.com/search?term=flappy&entity=software") self.task = session.downloadTask(with: url, completionHandler: { (resUrl, response, err) in if resUrl != nil{ let data: Data = try! Data(contentsOf: resUrl!) do{ let dic = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves) as AnyObject self.arrData = dic.value(forKey: "results") as? [AnyObject] DispatchQueue.main.async { self.tblData.reloadData() self.refresh.endRefreshing() } }catch{ print("Fail to get data") } } }) task.resume() } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return arrData.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "cell") let data = arrData[indexPath.row] as! [String:AnyObject] cell.textLabel?.text = data["trackName"] as? String cell.imageView?.image = #imageLiteral(resourceName: "location.png") if self.cache.object(forKey: indexPath.row as AnyObject) != nil{ cell.imageView?.image = self.cache.object(forKey: indexPath.row as AnyObject) as? UIImage }else{ let strUrl = data["artworkUrl100"] as! String let imagUrl: URL = URL(string: strUrl)! task = session.downloadTask(with: imagUrl, completionHandler:{ (resUrl, response, err) in do{ let data: Data = try! Data(contentsOf: resUrl!) DispatchQueue.main.async { let img = UIImage(data: data) let cell = self.tblData.cellForRow(at: indexPath) cell?.imageView?.image = img self.cache.setObject(img!, forKey: indexPath.row as AnyObject) } }catch{ print("fail to download image") } }) task.resume() } return cell } }
true
e4402fe36c010416493e4b1921f4b71d367940f7
Swift
pg8wood/discord-swift
/Swiftcord/DiscordAPI/REST/DiscordAPI.swift
UTF-8
1,344
2.890625
3
[]
no_license
// // DiscordAPI.swift // DiscordVoice // // Created by Patrick Gatewood on 11/24/20. // import UIKit import Combine class DiscordAPI: APIClient { let session: URLSessionProtocol private let myUserID = "275833464618614784" init(session: URLSessionProtocol) { self.session = session } func get<T: APIRequest>(_ request: T) -> AnyPublisher<T.Response, APIError> { // all url construction should be in the request type let url = request.baseURL.appendingPathComponent(request.path) var urlRequest = URLRequest(url: url) request.headers.forEach { urlRequest.setValue($0.value, forHTTPHeaderField: $0.key) } return session.apiResponse(for: urlRequest) .map(\.data) .tryMap(request.decodeResponse) .mapError { error -> APIError in switch error { case is DecodingError: return .decodingFailed case let urlError as URLError: return .sessionFailed(urlError) default: return .unknown(error) } } .eraseToAnyPublisher() } func getMyUser() -> AnyPublisher<User, APIError> { get(GetUserRequest(userID: myUserID)) } }
true
1b00066486626b9daabfccd425d84a79c25911db
Swift
nokiotto80/LearningRecapApp
/LearningRecapApp/Operations.swift
UTF-8
4,993
2.703125
3
[]
no_license
// Operations.swift // ExercisesVincentJan2018 // // Created by Vincenzo Pugliese on 08/01/2018. // Copyright © 2018 Vincenzo Pugliese. All rights reserved. // import UIKit class Operationsr: UIViewController,UIPickerViewDelegate, UIPickerViewDataSource { func numberOfComponents(in pickerView: UIPickerView) -> Int { return 2 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return numbers100.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return String(numbers100[row]) } var numbers100 : [Int] = [] // inizializzazione func alert() { let alertController = UIAlertController(title: "Touches began,Alert", message: "Questa è una alert,SWIPE riuscito!!", preferredStyle: UIAlertControllerStyle.alert) alertController.addAction(UIAlertAction(title: "close", style: UIAlertActionStyle.default,handler: nil)) // self.present(alertController, animated: true, completion: nil) } //tap gesture recognizer,funzione in ObjectiveC @objc func handleGesture(gesture: UISwipeGestureRecognizer) -> Void { if gesture.direction == UISwipeGestureRecognizerDirection.right { print("Swipe Right") imageViewRight.isHidden = false // sleep(4) performSegue(withIdentifier: "SegueTableViewController",sender: self) alert() } else if gesture.direction == UISwipeGestureRecognizerDirection.left { print("Swipe Left") imageViewLeft.isHidden = false // sleep(2) sleep(4) alert() } else if gesture.direction == UISwipeGestureRecognizerDirection.up { print("Swipe Up") imageViewUp.isHidden = false // sleep(4) alert() imageViewUp.isHidden = true } else if gesture.direction == UISwipeGestureRecognizerDirection.down { print("Swipe Down") imageViewDown.isHidden = false // sleep(4) alert() } // sleep(100) // imageViewUp.isHidden = true // imageViewDown.isHidden = true // imageViewRight.isHidden = true // imageViewLeft.isHidden = true } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. for i in 1...100 { numbers100.append(i) //assafaMaronn,arriva fino a 100 } //populate the array print(numbers100) let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(handleGesture)) swipeLeft.direction = .left self.view.addGestureRecognizer(swipeLeft) let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(handleGesture)) swipeRight.direction = .right self.view.addGestureRecognizer(swipeRight) let swipeUp = UISwipeGestureRecognizer(target: self, action: #selector(handleGesture)) swipeUp.direction = .up self.view.addGestureRecognizer(swipeUp) let swipeDown = UISwipeGestureRecognizer(target: self, action: #selector(handleGesture)) swipeDown.direction = .down self.view.addGestureRecognizer(swipeDown) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBOutlet weak var labelOperations: UILabel! @IBOutlet weak var imageViewUp: UIImageView! @IBOutlet weak var imageViewDown: UIImageView! @IBOutlet weak var imageViewRight: UIImageView! @IBOutlet weak var imageViewLeft: UIImageView! @IBOutlet weak var txtView: UITextView! @IBOutlet weak var picker1: UIPickerView! @IBOutlet weak var btnCheck: UIButton! @IBOutlet weak var lblValue: UILabel! @IBAction func btnCheck(_ sender: UIButton) { // print the selected value of picker var selectedValue = picker1.selectedRow(inComponent: 0) print(selectedValue+1) var selectedValue1 = picker1.selectedRow(inComponent: 1) print(selectedValue1+1) if selectedValue >= selectedValue1 { txtView.text = "il valore selezionato del primo picker \(selectedValue+1) è maggiore (o uguale) del valore \(selectedValue1+1) del secondo picker" } else { txtView.text = "il valore selezionato del primo picker \(selectedValue+1) è minore del valore \(selectedValue1+1) del secondo picker" } } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { // Chamamos a view para forçar que a edição pare self.view.endEditing(true) } }
true
ce6f89b5f3c7b6d48eb4bb30d59a17f93f2c3331
Swift
shantaramk/Data-Structure-And-Algorithm-In-Swift
/Data-Structure-And-Algorithm-In-Swift/Sliding Window/maximum_Sum_Subarray.swift
UTF-8
1,077
3.890625
4
[]
no_license
//: [Previous](@previous) import Foundation /// Max Sum Subarray of size K ///https://practice.geeksforgeeks.org/problems/max-sum-subarray-of-size-k5313/1 func maximumSumSubarray(for array: [Int], windowSize: Int) -> Int { var i = 0 var j = 0 let n = array.count var maxSum = 0 while j<n { var temp = 0 let currentWindow = j-i+1; let element = array[j] if currentWindow < windowSize { maxSum += element j+=1 } else if currentWindow == windowSize { if i-1>=0 { let old_element = array[i-1] temp = maxSum - old_element temp += element if temp > maxSum { maxSum = temp } } else { maxSum += element } i+=1 j+=1 } } return maxSum } print(maximumSumSubarray(for: [100, 200, 300, 400], windowSize: 2)) print(maximumSumSubarray(for: [100, 200, 300, 400], windowSize: 4))
true
786dffa78523aba0fd14ab50ee726171245a585a
Swift
CesarSGA/ProyectoFinal
/OnBoarding/Controllers/Top/TopViewController.swift
UTF-8
5,850
2.65625
3
[]
no_license
// // TopViewController.swift // OnBoarding // // import UIKit import WebKit import SafariServices class TopViewController: UIViewController { @IBOutlet weak var categoryCollectionView: UICollectionView! @IBOutlet weak var popularCollectionView: UICollectionView! @IBOutlet weak var artistCollectionView: UICollectionView! var categories = [Tag]() var albums = [Album]() var artists = [Artist]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. getCategories() topAlbums() topArtists() registerCells() } private func registerCells(){ categoryCollectionView.register(UINib(nibName: CategoryCollectionViewCell.identifier, bundle: nil), forCellWithReuseIdentifier: CategoryCollectionViewCell.identifier) popularCollectionView.register(UINib(nibName: CaratulaPortraitCollectionViewCell.identifier, bundle: nil), forCellWithReuseIdentifier: CaratulaPortraitCollectionViewCell.identifier) artistCollectionView.register(UINib(nibName: CaratulaLandscapeCollectionViewCell.identifier, bundle: nil), forCellWithReuseIdentifier: CaratulaLandscapeCollectionViewCell.identifier) } // MARK: Funciones para obtener los datos de la API func getCategories() { let apiKey = "85b04280e810869b7e663889c4dd2d81" let urlString = "https://ws.audioscrobbler.com/2.0/?method=chart.gettoptags&tag=disco&limit=10&api_key=\(apiKey)&format=json" if let url = URL(string: urlString) { if let data = try? Data(contentsOf: url) { parse(json: data) } } func parse(json: Data) { let decoder = JSONDecoder() if let jsonPeticion = try? decoder.decode(TagsCategory.self, from: json) { categories = jsonPeticion.tags.tag } } } func topAlbums(){ let apiKey = "85b04280e810869b7e663889c4dd2d81" let urlString = "https://ws.audioscrobbler.com/2.0/?method=tag.gettopalbums&tag=disco&limit=10&api_key=\(apiKey)&format=json" if let url = URL(string: urlString) { if let data = try? Data(contentsOf: url) { parse(json: data) } } func parse(json: Data) { let decoder = JSONDecoder() if let jsonPeticion = try? decoder.decode(TopAlbums.self, from: json) { albums = jsonPeticion.albums.album } } } func topArtists(){ let apiKey = "85b04280e810869b7e663889c4dd2d81" let urlString = "https://ws.audioscrobbler.com/2.0/?method=chart.gettopartists&limit=10&api_key=\(apiKey)&format=json" if let url = URL(string: urlString) { if let data = try? Data(contentsOf: url) { parse(json: data) } } func parse(json: Data) { let decoder = JSONDecoder() if let jsonPeticion = try? decoder.decode(TopArtist.self, from: json) { artists = jsonPeticion.artists.artist } } } } // MARK: Metodos del CollectionView extension TopViewController: UICollectionViewDelegate, UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { switch collectionView { case categoryCollectionView: return categories.count case popularCollectionView: return albums.count case artistCollectionView: return artists.count default: return 0 } } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { switch collectionView { case categoryCollectionView: let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CategoryCollectionViewCell.identifier, for: indexPath) as! CategoryCollectionViewCell cell.setup(category: categories[indexPath.row]) return cell case popularCollectionView: let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CaratulaPortraitCollectionViewCell.identifier, for: indexPath) as! CaratulaPortraitCollectionViewCell cell.setup(album: albums[indexPath.row]) return cell case artistCollectionView: let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CaratulaLandscapeCollectionViewCell.identifier, for: indexPath) as! CaratulaLandscapeCollectionViewCell cell.setup(artist: artists[indexPath.row]) return cell default: return UICollectionViewCell() } } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { switch collectionView { case categoryCollectionView: let controller = ListTopViewController.instantiate() controller.category = categories[indexPath.row] navigationController?.pushViewController(controller, animated: true) case popularCollectionView: let urlDirection = albums[indexPath.row].url let safariVC = SFSafariViewController(url: URL(string: urlDirection)!) present(safariVC, animated: true) case artistCollectionView: let urlDirection = artists[indexPath.row].url let safariVC = SFSafariViewController(url: URL(string: urlDirection)!) present(safariVC, animated: true) default: let urlDirection = "https://www.last.fm/home" let safariVC = SFSafariViewController(url: URL(string: urlDirection)!) present(safariVC, animated: true) } } }
true
b2b1a4efbf506ae1942c9b78eaade1b821e8a68e
Swift
TianTeng6661/algorithm014-algorithm014
/Week_08/141. 环形链表.swift
UTF-8
541
3.21875
3
[]
no_license
import UIKit //单向链表 public class ListNode { public var val: Int public var next: ListNode? public init(_ val: Int) { self.val = val self.next = nil } } func hasCycle(_ head: ListNode?) -> Bool { guard head != nil else { return false } var low = head?.next var quick = head?.next?.next while quick != nil { if(quick === low){ return true } quick = quick?.next?.next low = low?.next } return false }
true
f7126b7fdf994002d54629460de8b6d7f6e4a1e0
Swift
ApplikeySolutions/PandoraPlayer
/Player/Classes/Extensions/CommonExtensions.swift
UTF-8
2,196
2.75
3
[ "MIT" ]
permissive
// // CommonExtensions.swift // Player // // Created by user on 6/7/17. // Copyright © 2017 Applikey Solutions. All rights reserved. // import Foundation import UIKit fileprivate let defaultDuration = 0.3 extension UIImageView { func changeImageWithExpandingAnimation(_ image: UIImage, duration: TimeInterval = defaultDuration) { guard image != self.image, let container = superview else { return } let topImageView = UIImageView(image: image) topImageView.frame = frame topImageView.contentMode = .scaleAspectFill container.insertSubview(topImageView, aboveSubview: self) self.image = image UIView.animate(withDuration: duration, animations: { topImageView.transform = topImageView.transform.scaledBy(x: 1.5, y: 1.5) topImageView.alpha = 0 }) { (completed) in topImageView.removeFromSuperview() } } } extension UIImage { func resize(to size: CGSize) -> UIImage? { UIGraphicsBeginImageContext(size) let rect = CGRect(origin: CGPoint.zero, size: size) draw(in: rect) let resized = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return resized } } extension UILabel { func changeAnimated(_ text: String, color: UIColor, duration: TimeInterval = defaultDuration) { let animation = "TextAnimation" if layer.animation(forKey: animation) == nil { let transition = CATransition() transition.duration = duration transition.type = kCATransitionFade transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) layer.add(transition, forKey: animation) } self.text = text self.textColor = color } } extension CATransition { static func fading(_ duration: TimeInterval) -> CATransition { let transition = CATransition() transition.duration = duration transition.type = kCATransitionFade transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) return transition } }
true
8999552ae867d12cdca267a74509c8dd5712c14a
Swift
arvindravi/CreditScore
/CreditScoreTests/Mocks/MockHomePresenterView.swift
UTF-8
997
2.609375
3
[ "MIT" ]
permissive
// // MockHomePresenterView.swift // CreditScoreTests // // Created by Arvind Ravi on 07/07/2021. // import CreditKit @testable import CreditScore final class MockHomePresenterView: HomePresenterView { // MARK: - Custom Type - enum Event: Equatable { case didSuccessfullyFetchCreditInformation(withScore: Int) case didFailToFetchCreditInformationWith(error: String) } // MARK: - Properties - private(set) var capturedEvents = [Event]() // MARK: - Protocol Conformances - func homePresenter(_ presenter: HomePresenter, didSuccessfullyFetchCreditInformation information: CreditInformationRawResponse) { capturedEvents.append(.didSuccessfullyFetchCreditInformation(withScore: information.creditReportInfo.score)) } func homePresenter(_ presenter: HomePresenter, didFailToFetchCreditInformationWith error: String) { capturedEvents.append(.didFailToFetchCreditInformationWith(error: error)) } }
true
917fb187a052e6608532fb404edf2b20ea026938
Swift
LuAndreCast/iOS_WatchProjects
/watchOS2/PrimeNumbers/PrimeNumbers WatchKit Extension/InterfaceController.swift
UTF-8
2,188
2.984375
3
[ "MIT" ]
permissive
// // InterfaceController.swift // PrimeNumbers WatchKit Extension // // Created by Luis Castillo on 1/6/16. // Copyright © 2016 Luis Castillo. All rights reserved. // import WatchKit import Foundation class InterfaceController: WKInterfaceController { @IBOutlet var numberSlider: WKInterfaceSlider! @IBOutlet var primeQLabel: WKInterfaceLabel! @IBOutlet var Updatebutton: WKInterfaceButton! @IBOutlet var resultLabel: WKInterfaceLabel! var number:Int = 50 override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) numberSlider.setValue( Float(number) ) primeQLabel.setText("is \(number) prime?") resultLabel.setText("") }//eom override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() }//eom override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() }//eom @IBAction func sliderValueChanged(value: Float) { number = Int(value) //setting up new question primeQLabel.setText("is \(number) Prime?") //clearing results since its a new Question resultLabel.setText("") }//eo-a @IBAction func findOut() { //checking if prime var isPrime:Bool = true if number == 1 || number == 0 { isPrime = false } if number != 2 && number != 1 { for (var iter = 2; iter < number ;iter++) { if number % iter == 0 { isPrime = false } }//eofl } //print("is prime? \(isPrime)")//testing //update result if isPrime { resultLabel.setText("\(number) is Prime") } else { resultLabel.setText("\(number) is NOT Prime") } }//eo-a }
true
ad801b390141be48406db03005102a25f1db8b17
Swift
OliveiraAlbertCoelho/Pursuit-Core-iOS-Images-Lab
/imagesHandlingLab/imagesHandlingLab/detailViewController/UserDetailViewController.swift
UTF-8
1,315
3.109375
3
[]
no_license
// // UserDetailViewController.swift // imagesHandlingLab // // Created by albert coelho oliveira on 9/6/19. // Copyright © 2019 albert coelho oliveira. All rights reserved. // import UIKit class UserDetailViewController: UIViewController { var user: User? @IBOutlet weak var age: UILabel! @IBOutlet weak var image: UIImageView! @IBOutlet weak var name: UILabel! @IBOutlet weak var address: UILabel! @IBOutlet weak var email: UILabel! override func viewDidLoad() { super.viewDidLoad() setImageUp() loadUp() } func setImageUp(){ ImageHelper.shared.fetchImage(urlString: (user?.picture.large)!) { (result) in DispatchQueue.main.async { switch result { case .failure(let error): print(error) case .success(let image): self.image.image = image } } } image.layer.borderWidth = 1 image.layer.masksToBounds = false image.layer.cornerRadius = image.frame.height/2 image.clipsToBounds = true } func loadUp() { name.text = user?.name.FullName address.text = user?.location.address email.text = user?.phone age.text = user?.dob.age.description } }
true
56b4581d1820b633d5b0e5c3e7cff551513b8a41
Swift
matthewfortier/BurlingtonTour
/Burlington Tour/Models/Favorite.swift
UTF-8
652
3.03125
3
[]
no_license
// // Favorite.swift // Burlington Tour // // Created by Matthew Fortier on 3/29/18. // Copyright © 2018 Matthew Fortier. All rights reserved. // import Foundation class Favorite: NSObject, NSCoding { var id: String var type: String init(id: String, type: String) { self.id = id self.type = type } func encode(with aCoder: NSCoder) { aCoder.encode(id, forKey: "id") aCoder.encode(type, forKey: "type") } required init?(coder aDecoder: NSCoder) { self.id = aDecoder.decodeObject(forKey: "id") as! String self.type = aDecoder.decodeObject(forKey: "type") as! String } }
true
c4ca6538cbc920a8d80b6f25db0c095f2d7f59ca
Swift
imranTalukder/Swift-programming-in-Hackerrank
/Separate-the-Numbers.swift
UTF-8
978
3.40625
3
[]
no_license
import Foundation class notEasyProblem { var mainStr: String var mainLen: Int init(mainStr: String, mainLen: Int) { self.mainStr = mainStr self.mainLen = mainLen } func permutationF(inStr: String) -> Int { var str = inStr var Len = str.count var incValue = Int(str)! + 1 while Len < mainLen { str = str + String(incValue) incValue += 1 Len = str.count } if Len == mainLen && str == mainStr { return 1 } return 0 } func show() { for i in 1...mainLen / 2 { let inStr = mainStr.dropLast(mainLen - i) let chk = permutationF(inStr: String(inStr)) if chk == 1 { print("YES \(inStr)") return } } print("NO") } } let q = Int(readLine()!)! for _ in 1...q { let originalString = readLine()! let originLeng = originalString.count if originLeng == 1 { print("NO") } else { let obj = notEasyProblem(mainStr: originalString, mainLen: originLeng) obj.show() } }
true
f2c270f9caefb73edc240a55c6e67be8edbdf295
Swift
MichalSousedik/master-thesis
/App/milacci/Milacci/Module/Invoices/ViewModel/InvoiceViewModel.swift
UTF-8
2,855
2.609375
3
[]
no_license
// // InvoiceCellViewModel.swift // Milacci // // Created by Michal Sousedik on 09/09/2020. // Copyright © 2020 Michal Sousedik. All rights reserved. // import RxDataSources typealias InvoiceItemsSection = AnimatableSectionModel<Int, InvoiceViewModel> protocol InvoiceViewPresentable: IdentifiableType, Equatable { var title: String { get } var state: String { get } var canDownloadFile: Bool { get } var canUploadFile: Bool { get } var value: String { get } var invoice: Invoice { get } var infoMessage: String? { get } } class InvoiceViewModel: InvoiceViewPresentable{ static func == (lhs: InvoiceViewModel, rhs: InvoiceViewModel) -> Bool { return lhs.title == rhs.title && lhs.state == rhs.state && lhs.invoice.id == rhs.invoice.id && lhs.value == rhs.value && lhs.infoMessage == rhs.infoMessage && lhs.canUploadFile == rhs.canUploadFile && lhs.canDownloadFile == rhs.canDownloadFile } typealias Identity = Int var title: String var state: String var value: String var invoice: Invoice var canDownloadFile: Bool var canUploadFile: Bool var infoMessage: String? init(withInvoice invoice: Invoice){ self.invoice = invoice self.title = "" self.state = invoice.state.description self.canDownloadFile = invoice.filename != nil && invoice.filename != "" self.canUploadFile = false if invoice.filename == nil || invoice.filename == "" { if invoice.userWorkType == WorkType.agreement { self.infoMessage = L10n.userWorkTypeIsAgreement } if (invoice.state == InvoiceState.approved) { self.infoMessage = L10n.invoiceIsAlreadyApproved } if (invoice.state == InvoiceState.paid) { self.infoMessage = L10n.invoiceIsAlreadyPaid } } self.value = "" if let doubleValue = invoice.value, let value = Double(doubleValue)?.toCzechCrowns { self.value = value } } var identity: Int { return invoice.id } } class EmployeeInvoiceViewModel: InvoiceViewModel { override init(withInvoice invoice: Invoice){ super.init(withInvoice: invoice) var title = "-" if let user = invoice.user { title = "\(user.name ?? "-") \(user.surname ?? "-")" } self.title = title } } class MyInvoiceViewModel: InvoiceViewModel { override init(withInvoice invoice: Invoice){ super.init(withInvoice: invoice) self.title = invoice.overviewPeriodOfIssue self.canUploadFile = (invoice.filename == nil || invoice.filename == "") && invoice.userWorkType != WorkType.agreement && (invoice.state == InvoiceState.notIssued || invoice.state == InvoiceState.waiting) } }
true
2bfdbea49978f6984b6fe49be82137f9afb52a27
Swift
chriseidhof/adaptive-swift
/Adaptive/main.swift
UTF-8
1,914
3.125
3
[]
no_license
// Implementation of Adaptive Functional Programming // https://sites.google.com/site/umutacar/publications/popl2002.pdf?attredirects=1 import Cocoa struct Person: Equatable { var name: String static func ==(lhs: Person, rhs: Person) -> Bool { return lhs.name == rhs.name } } //final class TableViewApp { // // private let adaptive = Adaptive() // private let people: Node<AdaptiveArray<Person>> // private let changePeople: (Array<Person>.Change) -> () // // init() { // let (p1, cp) = adaptive.array(initial: Array<Person>()) // people = p1 // changePeople = cp // // } // // enum Message { // case append(Person) // } // // func send(message: Message) { // switch message { // case .append(let person): // changePeople(.append(person)) // } // } //} // func test() { let adaptive = Adaptive() let (l, last) = adaptive.fromSequence([4,3,2]) let l2 = adaptive.map(l, { (value: Int) -> Int in print("incrementing \(value)") return value + 1 }) let sum = adaptive.reduce(l2, initial: 0, +) sum.read { print("current sum: \($0)") } adaptive.propagate() last.write(AList<Int>.cons(7, adaptive.new(value: .empty))) adaptive.propagate() let (arr, change) = adaptive.array(initial: [1,2,3,4,5]) arr.read { result in print("changes: \(result.changes)") } change(.insert(element: 0, at: 1)) adaptive.propagate() // let result = changed.map() { arr in // adaptive.reduce2(compare: ==, list: arr.changes, initial: arr.initial, transform: { (i: [Int], change: Array<Int>.Change) -> [Int] in // var x = i // x.apply(change: change) // print("applying: \(change)") // return i // }) // } // result.read { r in // print("array: \(r)") // } } // //test()
true
eaf038b41ea0943b8ab3006104a41c12629e0d26
Swift
igoriols/clappr-ios
/Tests/Extensions/UIImageViewTests.swift
UTF-8
3,029
2.578125
3
[ "BSD-3-Clause" ]
permissive
import Quick import Nimble import OHHTTPStubs @testable import Clappr class UIImageViewTests: QuickSpec { override func spec() { describe(".UIImageViewTests") { describe("get image from url") { beforeEach { OHHTTPStubs.removeAllStubs() } context("when the response is 200") { beforeEach { stub(condition: isExtension("png") && isHost("test200")) { _ in let image = UIImage(named: "poster", in: Bundle(for: UIImageViewTests.self), compatibleWith: nil)! let data = image.pngData() return OHHTTPStubsResponse(data: data!, statusCode: 200, headers: ["Content-Type":"image/png"]) } } it("sets image") { let url = URL(string: "https://test200/poster.png") let imageView = UIImageView() imageView.setImage(from: url!) expect(imageView.image).toEventuallyNot(beNil()) } } context("when the response is different of 200") { beforeEach { stub(condition: isExtension("png") && isHost("test400")) { _ in return OHHTTPStubsResponse(data: Data(), statusCode: 400, headers: [:]) } } it("doesn't set image") { let url = URL(string: "https://test400/poster.png") let imageView = UIImageView() imageView.setImage(from: url!) expect(imageView.image).toEventually(beNil()) } } context("when repeat the same request") { var requestCount: Int! beforeEach { requestCount = 0 stub(condition: isExtension("png") && isHost("test.io")) { _ in requestCount += 1 let image = UIImage(named: "poster", in: Bundle(for: UIImageViewTests.self), compatibleWith: nil)! let data = image.pngData() return OHHTTPStubsResponse(data: data!, statusCode: 200, headers: ["Content-Type":"image/png"]) } } it("uses image from cache") { let url = URL(string: "https://test.io/poster.png") let imageView = UIImageView() imageView.setImage(from: url!) expect(imageView.image).toEventuallyNot(beNil()) imageView.setImage(from: url!) expect(requestCount).to(equal(1)) } } } } } }
true
201463276b675e6fd07533244a4792fb06c235a9
Swift
ahspadafora/TripTracker
/TripTracker/Managers/LocationManager.swift
UTF-8
5,003
3.015625
3
[]
no_license
// // LocationService.swift // TripTracker // // Created by Amber Spadafora on 1/30/21. // Copyright © 2021 Amber Spadafora. All rights reserved. // import Foundation import CoreLocation typealias TripStartedCompletionBlock = (TripTracker) -> Void typealias TripEndedCompletionBlock = (TripTracker) -> Void typealias SpeedUpdateCompletionBlock = (TripTracker) -> Void typealias ErrorHandlingCompletionBlock = (TripTracker, Error) -> Void typealias AuthStatusChangedCompletionBlock = (LocationManagerAuthStatus?) -> Void enum LocationManagerAuthStatus { case notDetermined case restricted case denied case authorizedAlways case authorizedWhenInUse } // responsible for requesting authorization & users location class LocationManager: NSObject { static let shared = LocationManager() let tripTracker: TripTracker = TripTracker() var authStatus: LocationManagerAuthStatus? var error: Error? private lazy var coreLocationManager: CLLocationManager = { let locationManager = CLLocationManager() locationManager.delegate = self locationManager.activityType = .fitness locationManager.desiredAccuracy = .greatestFiniteMagnitude return locationManager }() func requestAlwaysAuthIfNeeded(callback: AuthStatusChangedCompletionBlock) { // get coreLocation authorization status let clauthStatus = CLLocationManager.authorizationStatus() // convert to our LocationManagerAuthStatus if clauthStatus == .notDetermined { self.authStatus = .notDetermined self.coreLocationManager.requestAlwaysAuthorization() callback(self.authStatus) return } if clauthStatus == .authorizedWhenInUse { self.authStatus = .authorizedWhenInUse callback(self.authStatus) return } if clauthStatus == .authorizedAlways { self.authStatus = .authorizedAlways callback(self.authStatus) return } self.authStatus = .denied callback(self.authStatus) } var tripStartedCompletionBlock: TripStartedCompletionBlock? var speedUpdateCompletionBlock: SpeedUpdateCompletionBlock? var errorHandlingCompletionBlock: ErrorHandlingCompletionBlock? var authStatusChangedCompletionBlock: AuthStatusChangedCompletionBlock? // starts location updating, sends back info to update UI using completion handlers func startTrip(startCompletion: @escaping TripStartedCompletionBlock, speedUpdateCompletion: @escaping SpeedUpdateCompletionBlock, errorCompletion: @escaping ErrorHandlingCompletionBlock) { coreLocationManager.startUpdatingLocation() self.tripStartedCompletionBlock = startCompletion self.speedUpdateCompletionBlock = speedUpdateCompletion self.errorHandlingCompletionBlock = errorCompletion } // ends location updating func endTrip(completion: @escaping TripEndedCompletionBlock) { coreLocationManager.stopUpdatingLocation() completion(self.tripTracker) self.tripTracker.clearData() } } extension LocationManager: CLLocationManagerDelegate { // if not authorized, TODO: handle func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { print("auth status changed") switch status { case .authorizedWhenInUse: self.authStatus = .authorizedWhenInUse self.authStatusChangedCompletionBlock?(.authorizedWhenInUse) case .authorizedAlways: self.authStatus = .authorizedAlways self.authStatusChangedCompletionBlock?(.authorizedAlways) default: self.authStatus = .denied self.authStatusChangedCompletionBlock?(.denied) // TO DO: add callback that updates UI to present notice to user } } // called when location manager fails at retrieving users location func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { self.error = error self.errorHandlingCompletionBlock?(self.tripTracker, error) } // called each time the location manager gets a location update func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { guard let location = locations.first else { return } print("location updated") tripTracker.addPoint(location: Location(CLLocation: location)) let tripIsJustStarting = self.tripTracker.pointCount == 1 if tripIsJustStarting { // sends a callback to update UI for time started label self.tripStartedCompletionBlock?(self.tripTracker) } // sends update to UI for current speed label self.speedUpdateCompletionBlock?(self.tripTracker) } }
true
8aa6561e1bb2109769f3a7efcf7a30b498c060ed
Swift
danielylee/calculator
/Calculator3/CalculatorModel.swift
UTF-8
3,776
3.234375
3
[]
no_license
// // CalculatorModel.swift // Calculator3 // // Created by Daniel Lee on 12/21/17. // Copyright © 2017 Daniel Lee. All rights reserved. // import Foundation struct CalculatorModel { var numberFormatter = NumberFormatter() var result: Double? { return accumulator } var resultIsPending: Bool { return pendingBinaryOperation != nil } var description: String { var outputString = "" for element in descriptions { outputString += element } return outputString } mutating func setOperand(_ operand: Double) { if !resultIsPending { clear() } accumulator = operand descriptions.append(formattedAccumulator!) } mutating func clear() { accumulator = nil pendingBinaryOperation = nil descriptions = [] } mutating func performOperation(_ symbol: String) { if let operation = operations[symbol] { switch operation { case .constant(let value): accumulator = value descriptions.append(symbol) case .unaryOperation(let function, let descriptionFunction): if accumulator != nil { accumulator = function(accumulator!) descriptions = [descriptionFunction(description)] } case .binaryOperation(let function): if resultIsPending { performPendingBinaryOperation() } if accumulator != nil { pendingBinaryOperation = PendingBinaryOperation(firstOperand: accumulator!, function: function) descriptions.append(symbol) // accumulator needs to be reset for next part of operation accumulator = nil } case .equals: performPendingBinaryOperation() } } } private var descriptions = [String]() private var accumulator: Double? private var formattedAccumulator: String? { if let number = accumulator { return numberFormatter.string(from: number as NSNumber) ?? String(number) } else { return nil } } private enum Operation { case constant(Double) case unaryOperation(((Double) -> Double), (String) -> String) case binaryOperation((Double, Double) -> Double) case equals } private var operations: Dictionary<String, Operation> = [ "π": Operation.constant(Double.pi), "√": Operation.unaryOperation(sqrt, { "√(\($0))" }), "±": Operation.unaryOperation({ -$0 }, { "-(\($0))" }), "x²": Operation.unaryOperation({ $0 * $0 }, { "(\($0))²"}), "x⁻¹": Operation.unaryOperation({ 1 / $0 }, {"(\($0))⁻¹"}), "+": Operation.binaryOperation(+), "-": Operation.binaryOperation(-), "×": Operation.binaryOperation(*), "÷": Operation.binaryOperation(/), "=": Operation.equals ] private struct PendingBinaryOperation { let firstOperand: Double let function: (Double, Double) -> Double func perform(with secondOperand: Double) -> Double { return function(firstOperand, secondOperand) } } private var pendingBinaryOperation: PendingBinaryOperation? private mutating func performPendingBinaryOperation() { guard resultIsPending && accumulator != nil else { return } accumulator = pendingBinaryOperation!.perform(with: accumulator!) pendingBinaryOperation = nil } }
true
40815d3c70cbd4f1a11eaa2390df6f14ee8706ed
Swift
CoderEllis/webo
/wobo/wobo/Classes/Home/PhotoBrowser/PhotoBrowserAnimator.swift
UTF-8
4,662
2.953125
3
[ "Apache-2.0" ]
permissive
// // PhotoBrowserAnimator.swift // wobo // // Created by Soul Ai on 6/1/2019. // Copyright © 2019 Soul Ai. All rights reserved. // import UIKit // 面向协议开发 protocol AnimatorPresentedDelegate: NSObjectProtocol { func startRect(_ indexPath: IndexPath) -> CGRect func endRect(_ indexPath: IndexPath) -> CGRect func imageView(_ indexPath: IndexPath) -> UIImageView } protocol AnimatorDismissDelegate: NSObjectProtocol { func indexPathForDimissView() -> IndexPath func imageViewForDimissView() -> UIImageView } class PhotoBrowserAnimator: NSObject { var isPresented : Bool = false weak var presentedDelegate : AnimatorPresentedDelegate? var indexPath : IndexPath? weak var dismissDelegate : AnimatorDismissDelegate? deinit { print("PhotoBrowserAnimator----销毁") } private weak var presentCtrl: PhotoBrowserPresentationController? public var maskAlpha: CGFloat { set { presentCtrl?.alph = newValue } get { return presentCtrl?.alph ?? 0 } } } extension PhotoBrowserAnimator: UIViewControllerTransitioningDelegate { func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {//弹出 isPresented = true return self } func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { //消失 isPresented = false return self } func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? { let ctrl = PhotoBrowserPresentationController(presentedViewController: presented, presenting: presenting) presentCtrl = ctrl return ctrl } } extension PhotoBrowserAnimator: UIViewControllerAnimatedTransitioning { func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.3 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { isPresented ? animationForPresentedView(transitionContext) : animationForDismissView(transitionContext) } ///自定义弹出动画 func animationForPresentedView(_ transitionContext: UIViewControllerContextTransitioning) { // 0.nil值校验 guard let presentedDelegate = presentedDelegate, let indexPath = indexPath else { return } //1.取出弹出的View let presentedView = transitionContext.view(forKey: .to)! // 2.将prensentedView添加到containerView中 transitionContext.containerView.addSubview(presentedView) // 3.获取执行动画的imageView let startRect = presentedDelegate.startRect(indexPath) let imageView = presentedDelegate.imageView(indexPath) transitionContext.containerView.addSubview(imageView) imageView.frame = startRect // 4.执行动画 presentedView.alpha = 0.0 transitionContext.containerView.backgroundColor = UIColor.black UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: { imageView.frame = presentedDelegate.endRect(indexPath) }) { (_) in imageView.removeFromSuperview() presentedView.alpha = 1.0 transitionContext.containerView.backgroundColor = UIColor.clear transitionContext.completeTransition(true) //告诉上下文完成动画 } } ///自定义消失动画 func animationForDismissView(_ transitionContext: UIViewControllerContextTransitioning) { guard let dismissDelegate = dismissDelegate,let presentedDelegate = presentedDelegate else { return } let dismissView = transitionContext.view(forKey: .from) dismissView?.removeFromSuperview() // 2.获取执行动画的ImageView let imageView = dismissDelegate.imageViewForDimissView() transitionContext.containerView.addSubview(imageView) let indexPath = dismissDelegate.indexPathForDimissView() UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: { imageView.frame = presentedDelegate.startRect(indexPath) }) { (_) in // dismissView?.removeFromSuperview() transitionContext.completeTransition(true) } } }
true
a22c28e45c6329bfebdf12f1bddd286bba2883bc
Swift
RockyAo/AVFoundationVideoDemo
/AVFoundationVideoDemo/AVFoundationVideoDemo/RACameraTool/RAAuthorizationCheck.swift
UTF-8
3,234
2.59375
3
[]
no_license
// // AuthorizationCheck.swift // AVFoundationVideoDemo // // Created by ZCBL on 16/8/10. // Copyright © 2016年 RA. All rights reserved. // import UIKit import AVFoundation import Photos enum mediaType:Int { case video = 0 case audio = 1 } class RAAuthorizationCheck: NSObject { } // MARK: - 权限检查 extension RAAuthorizationCheck { /// 检测是否有摄像头使用权限 /// /// - parameter Type: 类型,默认为视频 可选audio /// /// - returns: true / false class internal func checkCameraAuthorization(Type:mediaType = .video) -> Bool { var authorizationStatus:AVAuthorizationStatus if Type == .video { authorizationStatus = AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeVideo) }else{ authorizationStatus = AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeAudio) } if authorizationStatus == .Authorized{ return true }else{ return false } } /// 是否拥有相册使用权限(如没没有权限,或未请求权限会弹出权限请求,8.0以上可用该方法) /// /// - returns: true/false @available(iOS 8.0, *) class internal func checkPhotoAlbumAuthorization() -> Bool{ let authorization = PHPhotoLibrary.authorizationStatus() if authorization != .Authorized{ PHPhotoLibrary.requestAuthorization({ (PHAuthorizationStatus) in print(PHAuthorizationStatus) }) } if PHPhotoLibrary.authorizationStatus() == .Authorized { return true }else{ return false } } } // MARK: - 设备可用性检查 extension RAAuthorizationCheck { /// 检查相机硬件是否存在 /// /// - returns: true / false class internal func checkCameraDeviceAvilable() -> Bool { return UIImagePickerController.isSourceTypeAvailable(.Camera) } /// 检查是否支持图库 /// /// - returns: true / false class internal func checkPhotoLibraryAvilable() -> Bool{ return UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary) } /// 检测是否支持相册 /// /// - returns: true / false class internal func checkPhotoAlbum() -> Bool { return UIImagePickerController.isSourceTypeAvailable(.SavedPhotosAlbum) } /// 检测是否有闪光灯硬件 /// /// - returns: true / false class internal func checkHasFlash() -> Bool { let captureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeMuxed) return captureDevice.hasFlash } /// 检测是否支持手电筒 /// /// - returns:true / false class internal func checkHasTorch() -> Bool { let captureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeMuxed) return captureDevice.hasTorch } }
true
cb108291232a86d0e5e3eaae4ab42c9c68cce7e1
Swift
adam-leitgeb/ALKit
/Sources/ALKit/Extensions/Foundation/String+Utilities.swift
UTF-8
1,006
3
3
[]
no_license
// // String+Utilities.swift // // // Created by Adam Leitgeb on 22/02/2020. // import Foundation public extension String { var isPhoneNumber: Bool { do { let checkingType: NSTextCheckingResult.CheckingType = .phoneNumber let detector = try NSDataDetector(types: checkingType.rawValue) let matches = detector.matches(in: self, options: [], range: NSMakeRange(0, count)) guard let result = matches.first else { return false } if result.resultType != .phoneNumber && result.range.location != 0 && result.range.length != self.count { return false } return true } catch { return false } } var isEmail: Bool { let argumentsList = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}" let emailPredicate = NSPredicate(format: "SELF MATCHES %@", argumentsList) return emailPredicate.evaluate(with: self) } }
true
90bdd8e1f27633515569e7f4f640161554b67e60
Swift
vishalkalola1/Practicals
/ZattooPractical/ZattooPractical/ViewControllers/LoginVIewController/LoginViewController.swift
UTF-8
1,874
2.65625
3
[]
no_license
// // LoginViewController.swift // ZattooPractical // // Created by Vishal on 7/2/21. import UIKit final class LoginViewController: UIViewController { var loginViewModel : LoginViewModelType? @IBOutlet weak var txtUsername: UITextField! @IBOutlet weak var txtPassword: UITextField! @IBAction func actionLogin(_ sender: UIButton) { if txtUsername.text == "" { print("Please enter username") } else if txtPassword.text == "" { print("Please enter password") } else { startSession() } } private func login() { let credentials = ["login":self.txtUsername.text!, "password":self.txtPassword.text!] self.loginViewModel?.authentication(credentials){ error in if let error = error { print("🤬🤬🤬", error) } else { self.watch() } } } private func startSession() { let session = [ "app_tid" : "8a302808-6433-4960-967c-920192a835be", "uuid" : "\(UUID())", "lang":"en", "format":"json" ] loginViewModel?.startSession(session) { error in if let error = error { print("🤬🤬🤬", error) } else { DispatchQueue.main.async { self.login() } } } } private func watch(){ loginViewModel?.startWatch { error in if let error = error { print("🤬🤬🤬", error) }else{ print("📶📶📶 Streaming Watch Start 📶📶📶") DispatchQueue.main.async { self.loginViewModel?.startVideo() } } } } }
true
95cba3555db213a7995c2a58eaf4d6d52050ca31
Swift
chinmaysukhadia/aboutMe360
/AboutMe360/Extensions/DictionaryExtensions.swift
UTF-8
415
2.734375
3
[]
no_license
// // DictionaryExtensions.swift // AboutMe360 // // Created by Himanshu Pal on 9/22/19. // Copyright © 2019 Appy. All rights reserved. // import Foundation extension Dictionary { var queryString: String { var output: String = "" for (key,value) in self { output += "\(key)=\(value)&" } //output = String(output.characters.dropLast()) return output } }
true
97eeaffbd682beb355d0770b13d59e67cf1d302e
Swift
iarata/DSP-Playground
/DSP Playground/View/Graph/TimeDomain.swift
UTF-8
1,078
2.78125
3
[ "BSD-3-Clause", "MIT" ]
permissive
// // TimeDomain.swift // DSP Playground // // Created by Alireza Hajebrahimi on 2021/07/18. // import SwiftUI //import SwiftUICharts import Combine struct TimeDomain: View { @Binding var manager: AVManager @State var pub = DSPNotification().publisherPath() @State var amps = [Double]() var body: some View { AmplitudeVisualizer(amplitudes: amps) .onReceive(pub) { (output) in self.amps = manager.amplitudes } .onAppear { self.amps = manager.amplitudes } } // var body: some View { // HStack(spacing: 0.0){ // ForEach(0..<self.amplitudes.count, id: \.self) { number in // VerticalBar(amplitude: self.$amplitudes[number]) // } // .drawingGroup() // } // .onReceive(pub) { (output) in // self.amps = manager.amplitudes // } // .onAppear { // self.amps = manager.amplitudes // } // MetalView() // } }
true
94329389122b7c5e7c7e3977e8fd35505f14697d
Swift
Atinder1989/BMS_Assignment
/BookMyShowAssignment/BookMyShowAssignment/Service/Service.swift
UTF-8
611
3
3
[]
no_license
// // Service.swift // BookMyShowAssignment // // Created by Atinder on 13/04/21. // import Foundation enum WebserviceHTTPMethod: String { case GET = "GET" case POST = "POST" } struct Service { var url: String! var httpMethod : WebserviceHTTPMethod var params : [String: Any] var headers : [String: Any] init(httpMethod :WebserviceHTTPMethod) { self.httpMethod = httpMethod self.params = [String: Any]() self.headers = [HTTPHeaderKey.HTTPHeaderKeyContenttype.rawValue:HTTPHeaderValue.HTTPHeaderValueApplicationJSON.rawValue] } }
true
a3efc316ec47ff7e1a92fbf263d09f567b4bc181
Swift
mshibanami/GitHubTrendingRSS
/Sources/GitHubTrendingRSSKit/Managers/FeedFileCreator.swift
UTF-8
2,121
2.703125
3
[ "MIT" ]
permissive
// Copyright (c) 2018 Manabu Nakazawa. Licensed under the MIT license. See LICENSE in the project root for license information. import Foundation public class FeedFileCreator { public let siteGenerator: SiteSourceMaker public let rootOutputDirectory: URL public init(outputDirectory: URL, siteGenerator: SiteSourceMaker) { self.siteGenerator = siteGenerator self.rootOutputDirectory = outputDirectory } public func createRSSFile(repositories: [Repository], languageTrendingLink: LanguageTrendingLink, period: Period, supportedEmojis: [GitHubEmoji]) throws -> URL { let fileManager = FileManager.default let feedHTML = try siteGenerator.makeRSS( from: languageTrendingLink, period: period, repositories: repositories, supportedEmojis: supportedEmojis) let outputDirectory = rootOutputDirectory.appendingPathComponent(period.rawValue) try fileManager.createDirectory( at: outputDirectory, withIntermediateDirectories: true, attributes: nil) let fileName = "\(languageTrendingLink.name).xml" let fileURL = outputDirectory.appendingPathComponent(fileName) guard fileManager.createFile( atPath: fileURL.path, contents: feedHTML.data(using: .utf8), attributes: nil) else { throw NSError() } return fileURL } public func createRSSListFile(languageLinks: [LanguageTrendingLink]) throws -> URL { let fileManager = FileManager.default try fileManager.createDirectory( at: rootOutputDirectory, withIntermediateDirectories: true, attributes: nil) let html = try siteGenerator.makeHomeHTML(from: languageLinks) let fileURL = rootOutputDirectory.appendingPathComponent("index.html") guard fileManager.createFile( atPath: fileURL.path, contents: html.data(using: .utf8), attributes: nil) else { throw NSError() } return fileURL } }
true
4b61f8068a6e3c4d6a7a5962c417b2f0445d6d5d
Swift
apphud/Apphud-App
/Apphud/Views/AppItemView.swift
UTF-8
1,357
2.5625
3
[]
no_license
// // AppItemView.swift // Apphud // // Created by Alexander Selivanov on 02.10.2020. // import SwiftUI import struct Kingfisher.KFImage struct AppItemView: View { @EnvironmentObject var session: SessionStore var app: AHApp var body: some View { HStack { Group { if let url = app.iconURL { KFImage(url).resizable() .background(Color(hex: "F5F5F5")) .aspectRatio(contentMode: .fit) .clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous)) } else { Image("app_icon_placeholder").resizable() .aspectRatio(contentMode: .fit) .cornerRadius(8) .clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous)) } }.frame(width: 44, height: 44) Text(app.name).frame(maxWidth: .infinity, alignment: .leading) if app.id == session.currentApp?.id { Image("select_app_image") } } } } struct AppItemView_Previews: PreviewProvider { static var previews: some View { AppItemView(app: AHApp(id: "", name: "Diff", bundleId: "com", packageName: nil, iconUrl: "http://placehold.it/199")) } }
true
261d9bb9b36f97897eefadcb822ddafec6dbca6b
Swift
madhurmohta/NYT
/NYT/Modules/ArticleList/Data Provider/ArticleDataProvider.swift
UTF-8
1,074
2.734375
3
[ "MIT" ]
permissive
// // ArticleDataProvider.swift // NYT // // Created by Madhur Mohta on 10/12/2017. // import UIKit struct ArticleDataProvider { static func fetchArticles(_ completion:@escaping (Base?)->()) { DispatchQueue.global(qos: DispatchQoS.QoSClass.background).async { () -> Void in NYTServiceManager.fetchArticlesList { (responseData) in if let data = responseData { guard let baseModel = self.getParsedModel(responseData: data) else { completion(nil) ; return } if baseModel.status == "OK" { completion(baseModel) } } else { completion(nil) } } } } static func getParsedModel(responseData: Data) -> Base? { var baseModel: Base? do { baseModel = try JSONDecoder().decode(Base.self, from: responseData) } catch { print("Error") } return baseModel } }
true
7311dfbec629f446d8d9ea2decdbfa8f2104f555
Swift
square/Blueprint
/BlueprintUI/Tests/ConstrainedSizeTests.swift
UTF-8
11,277
2.734375
3
[ "Apache-2.0" ]
permissive
import BlueprintUI import XCTest class ConstrainedSizeTests: XCTestCase { func test_in_unconstrained() { let constraint = SizeConstraint(width: .unconstrained, height: .unconstrained) // Unconstrained do { let fixed = ConstrainedSize(wrapping: FixedElement()) let flexible = ConstrainedSize(wrapping: FlexibleElement()) XCTAssertEqual( CGSize(width: 100, height: 110), fixed.content.measure(in: constraint) ) XCTAssertEqual( CGSize(width: 100, height: 110), flexible.content.measure(in: constraint) ) } // atMost - width only do { let fixed = ConstrainedSize(width: .atMost(75), wrapping: FixedElement()) let flexible = ConstrainedSize(width: .atMost(75), wrapping: FlexibleElement()) XCTAssertEqual( CGSize(width: 75, height: 110), fixed.content.measure(in: constraint) ) XCTAssertEqual( CGSize(width: 75, height: 147), flexible.content.measure(in: constraint) ) } // atMost do { let fixed = ConstrainedSize(width: .atMost(75), height: .atMost(85), wrapping: FixedElement()) let flexible = ConstrainedSize(width: .atMost(75), height: .atMost(85), wrapping: FlexibleElement()) XCTAssertEqual( CGSize(width: 75, height: 85), fixed.content.measure(in: constraint) ) XCTAssertEqual( CGSize(width: 75, height: 85), flexible.content.measure(in: constraint) ) } // atLeast - width only do { let fixed = ConstrainedSize(width: .atLeast(175), wrapping: FixedElement()) let flexible = ConstrainedSize(width: .atLeast(175), wrapping: FlexibleElement()) XCTAssertEqual( CGSize(width: 175, height: 110), fixed.content.measure(in: constraint) ) XCTAssertEqual( CGSize(width: 175, height: 110), flexible.content.measure(in: constraint) ) } // atLeast do { let fixed = ConstrainedSize(width: .atLeast(175), height: .atLeast(150), wrapping: FixedElement()) let flexible = ConstrainedSize(width: .atLeast(175), height: .atLeast(150), wrapping: FlexibleElement()) XCTAssertEqual( CGSize(width: 175, height: 150), fixed.content.measure(in: constraint) ) XCTAssertEqual( CGSize(width: 175, height: 150), flexible.content.measure(in: constraint) ) } // withinRange - width only do { let fixed = ConstrainedSize(width: .within(110...120), wrapping: FixedElement()) let flexible = ConstrainedSize(width: .within(110...120), wrapping: FlexibleElement()) XCTAssertEqual( CGSize(width: 110, height: 110), fixed.content.measure(in: constraint) ) XCTAssertEqual( CGSize(width: 120, height: 92), flexible.content.measure(in: constraint) ) } // withinRange do { let fixed = ConstrainedSize(width: .within(110...120), height: .within(120...130), wrapping: FixedElement()) let flexible = ConstrainedSize( width: .within(110...120), height: .within(120...130), wrapping: FlexibleElement() ) XCTAssertEqual( CGSize(width: 110, height: 120), fixed.content.measure(in: constraint) ) XCTAssertEqual( CGSize(width: 120, height: 120), flexible.content.measure(in: constraint) ) } // absolute - width only do { let fixed = ConstrainedSize(width: .absolute(125), wrapping: FixedElement()) let flexible = ConstrainedSize(width: .absolute(125), wrapping: FlexibleElement()) XCTAssertEqual( CGSize(width: 125, height: 110), fixed.content.measure(in: constraint) ) XCTAssertEqual( CGSize(width: 125, height: 88), flexible.content.measure(in: constraint) ) } // absolute do { let fixed = ConstrainedSize(width: .absolute(125), height: .absolute(135), wrapping: FixedElement()) let flexible = ConstrainedSize(width: .absolute(125), height: .absolute(135), wrapping: FlexibleElement()) XCTAssertEqual( CGSize(width: 125, height: 135), fixed.content.measure(in: constraint) ) XCTAssertEqual( CGSize(width: 125, height: 135), flexible.content.measure(in: constraint) ) } } func test_in_atMost() { let constraint = SizeConstraint(width: .atMost(75.0), height: .atMost(300.0)) // Unconstrained do { let fixed = ConstrainedSize(wrapping: FixedElement()) let flexible = ConstrainedSize(wrapping: FlexibleElement()) XCTAssertEqual( CGSize(width: 100, height: 110), fixed.content.measure(in: constraint) ) XCTAssertEqual( CGSize(width: 75, height: 147), flexible.content.measure(in: constraint) ) } // atMost - width only do { let fixed = ConstrainedSize(width: .atMost(85), wrapping: FixedElement()) let flexible = ConstrainedSize(width: .atMost(85), wrapping: FlexibleElement()) XCTAssertEqual( CGSize(width: 85, height: 110), fixed.content.measure(in: constraint) ) XCTAssertEqual( CGSize(width: 75, height: 147), flexible.content.measure(in: constraint) ) } // atMost do { let fixed = ConstrainedSize(width: .atMost(85), height: .atMost(85), wrapping: FixedElement()) let flexible = ConstrainedSize(width: .atMost(85), height: .atMost(85), wrapping: FlexibleElement()) XCTAssertEqual( CGSize(width: 85, height: 85), fixed.content.measure(in: constraint) ) XCTAssertEqual( CGSize(width: 75, height: 85), flexible.content.measure(in: constraint) ) } // atLeast - width only do { let fixed = ConstrainedSize(width: .atLeast(175), wrapping: FixedElement()) let flexible = ConstrainedSize(width: .atLeast(175), wrapping: FlexibleElement()) XCTAssertEqual( CGSize(width: 175, height: 110), fixed.content.measure(in: constraint) ) XCTAssertEqual( CGSize(width: 175, height: 63), flexible.content.measure(in: constraint) ) } // atLeast do { let fixed = ConstrainedSize(width: .atLeast(175), height: .atLeast(150), wrapping: FixedElement()) let flexible = ConstrainedSize(width: .atLeast(175), height: .atLeast(150), wrapping: FlexibleElement()) XCTAssertEqual( CGSize(width: 175, height: 150), fixed.content.measure(in: constraint) ) XCTAssertEqual( CGSize(width: 175, height: 150), flexible.content.measure(in: constraint) ) } // withinRange - width only do { let fixed = ConstrainedSize(width: .within(110...120), wrapping: FixedElement()) let flexible = ConstrainedSize(width: .within(110...120), wrapping: FlexibleElement()) XCTAssertEqual( CGSize(width: 110, height: 110), fixed.content.measure(in: constraint) ) XCTAssertEqual( CGSize(width: 110, height: 100), flexible.content.measure(in: constraint) ) } // withinRange do { let fixed = ConstrainedSize(width: .within(110...120), height: .within(120...130), wrapping: FixedElement()) let flexible = ConstrainedSize( width: .within(110...120), height: .within(120...130), wrapping: FlexibleElement() ) XCTAssertEqual( CGSize(width: 110, height: 120), fixed.content.measure(in: constraint) ) XCTAssertEqual( CGSize(width: 110, height: 120), flexible.content.measure(in: constraint) ) } // absolute - width only do { let fixed = ConstrainedSize(width: .absolute(125), wrapping: FixedElement()) let flexible = ConstrainedSize(width: .absolute(125), wrapping: FlexibleElement()) XCTAssertEqual( CGSize(width: 125, height: 110), fixed.content.measure(in: constraint) ) XCTAssertEqual( CGSize(width: 125, height: 88), flexible.content.measure(in: constraint) ) } // absolute do { let fixed = ConstrainedSize(width: .absolute(125), height: .absolute(135), wrapping: FixedElement()) let flexible = ConstrainedSize(width: .absolute(125), height: .absolute(135), wrapping: FlexibleElement()) XCTAssertEqual( CGSize(width: 125, height: 135), fixed.content.measure(in: constraint) ) XCTAssertEqual( CGSize(width: 125, height: 135), flexible.content.measure(in: constraint) ) } } } fileprivate struct FixedElement: Element { var content: ElementContent { ElementContent { constraint -> CGSize in // Using different sizes for width and height in case // any internal calculations mix up x and y; we'll catch that. CGSize(width: 100, height: 110) } } func backingViewDescription(with context: ViewDescriptionContext) -> ViewDescription? { nil } } fileprivate struct FlexibleElement: Element { var content: ElementContent { ElementContent { constraint -> CGSize in let totalArea: CGFloat = 100 * 110 let width: CGFloat switch constraint.width { case .atMost(let max): width = max case .unconstrained: width = 100 } return CGSize(width: width, height: round(totalArea / width)) } } func backingViewDescription(with context: ViewDescriptionContext) -> ViewDescription? { nil } }
true
570c7444e46c6a12318a5495b61bd8518092a51d
Swift
cdeerinck/SpaceShooter
/SpaceShooter/Asteroid Stuff/contemplateAsteroid.swift
UTF-8
527
2.78125
3
[]
no_license
// // contemplateAsteroid.swift // Space Shooter // // Created by Chuck Deerinck on 7/18/19. // Copyright © 2019 Chuck Deerinck. All rights reserved. // import Foundation import SpriteKit func contemplateAsteroid(scene: GameScene) { if Int.random(in: 0...42) != 42 { return } //Why 42? Why not. if let candidate = scene.asteroids.randomElement() { _ = makeAsteroid(from: candidate, in: scene, at:CGPoint(x: CGFloat(Float.random(in: Float(scene.frame.minX)...Float(scene.frame.maxX))), y:scene.frame.maxY+100)) } }
true
cc64a2124d2645d71bda486b90b84ca6bfeb1433
Swift
getsentry/sentry-cocoa
/SentryTestUtils/TestCurrentDateProvider.swift
UTF-8
1,632
2.765625
3
[ "MIT" ]
permissive
import Foundation @objc public class TestCurrentDateProvider: CurrentDateProvider { public static let defaultStartingDate = Date(timeIntervalSinceReferenceDate: 0) private var internalDate = defaultStartingDate private var internalSystemTime: UInt64 = 0 public var driftTimeForEveryRead = false public override func date() -> Date { defer { if driftTimeForEveryRead { internalDate = internalDate.addingTimeInterval(0.1) } } return internalDate } /// Reset the date provider to its default starting date. public func reset() { setDate(date: TestCurrentDateProvider.defaultStartingDate) internalSystemTime = 0 } public func setDate(date: Date) { internalDate = date } /// Advance the current date by the specified number of seconds. public func advance(by seconds: TimeInterval) { setDate(date: date().addingTimeInterval(seconds)) internalSystemTime += seconds.toNanoSeconds() } public func advanceBy(nanoseconds: UInt64) { setDate(date: date().addingTimeInterval(TimeInterval(nanoseconds) / 1e9)) internalSystemTime += nanoseconds } public var internalDispatchNow = DispatchTime.now() public override func dispatchTimeNow() -> dispatch_time_t { return internalDispatchNow.rawValue } public var timezoneOffsetValue = 0 public override func timezoneOffset() -> Int { return timezoneOffsetValue } public override func systemTime() -> UInt64 { return internalSystemTime } }
true
0aff3f27bf907eebcc4165018b6eb4e5e700430e
Swift
kangyoungkyun/DailyBibleThinkShare2
/ChurchCommunity/TodayFrontPage/TodayCollectionVC.swift
UTF-8
6,298
2.5625
3
[]
no_license
// // TodayCollectionVC.swift // ChurchCommunity // // Created by MacBookPro on 2018. 3. 27.. // Copyright © 2018년 MacBookPro. All rights reserved. // import UIKit import Firebase private let reuseIdentifier = "Cell" class TodayCollectionVC: UICollectionViewController, UICollectionViewDelegateFlowLayout,CollectionViewCellDelegate { var logout = false func showAllPosts() { let appDelegate = UIApplication.shared.delegate as! AppDelegate let tabBarController = appDelegate.tabBarController //인디케이터 종료 self.present(tabBarController!, animated: true, completion: nil) } func writeAction() { let writeView = WriteViewController() //글쓰기 화면을 rootView로 만들어 주기 let navController = UINavigationController(rootViewController: writeView) self.present(navController, animated: true, completion: nil) } var pages = [Page]() //페이지 컨트롤러 lazy var pageControl: UIPageControl = { let pc = UIPageControl() pc.translatesAutoresizingMaskIntoConstraints = false pc.currentPage = 0 pc.numberOfPages = pages.count pc.currentPageIndicatorTintColor = UIColor(red:0.20, green:0.20, blue:0.20, alpha:1.0) pc.pageIndicatorTintColor = UIColor.white return pc }() //오른쪽으로 스크롤 했을 때 - 위치로 현재 페이지 구해주기 override func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { let x = targetContentOffset.pointee.x pageControl.currentPage = Int(x / view.frame.width) } //창이 사라질때 값 1 더해주기 override func viewWillDisappear(_ animated: Bool) { howMany += 1 } //즉 묵상 탭 안으로 들어갔다가 뒤로 눌렀을때 2가 되어 있다. 즉, var index = IndexPath(item: 0, section: 0) override func viewWillAppear(_ animated: Bool) { if(howMany > 1){ self.collectionView?.selectItem(at: index, animated: true, scrollPosition: .left) } //페이지 안에서 로그아웃 버튼을 눌렀을 때 한번더 로그아웃 해주기 let firebaseAuth = Auth.auth().currentUser?.uid if (firebaseAuth == nil){ //print("로그아웃된것이 확인되었습니다.") dismiss(animated: true, completion: nil) } } var howMany = 0 override func viewDidLoad() { super.viewDidLoad() setupBottomControls() howMany = 1 //SwipingController 객체를 생성하고 최상위 뷰로 설정 //배경색을 흰색 collectionView?.backgroundColor = UIColor(red:0.97, green:0.97, blue:0.97, alpha:1.0) collectionView?.showsHorizontalScrollIndicator = false collectionView?.showsVerticalScrollIndicator = false //collectionView에 cell을 등록해주는 작업, 여기서는 직접 만든 cell을 넣어주었고, 아이디를 설정해 주었다. collectionView?.register(PageCell.self, forCellWithReuseIdentifier: "cellId") //페이징기능 허용 collectionView?.isPagingEnabled = true getSingle() setData() } var todateCheck = "" var todate = "" //현재 날짜 한글 func getSingle(){ let date = Date() let calendar = Calendar.current //켈린더 객체 생성 let year = calendar.component(.year, from: date) //년 let month = calendar.component(.month, from: date) //월 let day = calendar.component(.day, from: date) //일 todate = "\(year)년 \(month)월 \(day)일," todateCheck = "\(year)\(month)\(day)" } func setData(){ let ref = Database.database().reference() //print("check date ===" , todateCheck) ref.child("front").child(todateCheck).observe(.value) { (snapshot) in for child in snapshot.children{ let childSnapshot = child as! DataSnapshot //자식 DataSnapshot 가져오기 let childValue = childSnapshot.value as! [String:Any] //자식의 value 값 가져오기 var pasge = Page(headerText: "", bodyText: "") //print("childvalue: ",childValue) if let a = childValue["a"]{ //print("a : ", a) pasge = Page(headerText: a as! String, bodyText: "") }else if let b = childValue["b"]{ pasge = Page(headerText: "" , bodyText: b as! String) } self.pages.insert(pasge, at: 0) } self.collectionView?.reloadData() } ref.removeAllObservers() } override func viewDidLayoutSubviews() { self.setupBottomControls() } //스택뷰 객세 생성과 위치 설정 함수 fileprivate func setupBottomControls() { //uistackview 객체 만들기 배열 타입으로 view 객체들이 들어간다 let bottomControlsStackView = UIStackView(arrangedSubviews: [ pageControl]) //오토레이아웃 설정 허용해주기 bottomControlsStackView.translatesAutoresizingMaskIntoConstraints = false //객체들이 하나하나 보이게 설정 bottomControlsStackView.distribution = .fillEqually //bottomControlsStackView.axis = .vertical //전체 뷰에 위에서 만든 stackView를 넣어준다. view.addSubview(bottomControlsStackView) //스택뷰 위치 지정해주기 NSLayoutConstraint.activate([ bottomControlsStackView.bottomAnchor.constraint(equalTo: view.bottomAnchor), bottomControlsStackView.leadingAnchor.constraint(equalTo: view.leadingAnchor), bottomControlsStackView.trailingAnchor.constraint(equalTo: view.trailingAnchor), bottomControlsStackView.heightAnchor.constraint(equalToConstant: 50) ]) } }
true
d647c08747e1f6a8db719e9b7d55fcd6dffcf218
Swift
NawafSwe/EJADAH-APP
/Ejadah/Utilites/Views/Buttons/MoreButtonView.swift
UTF-8
592
2.765625
3
[]
no_license
// // MoreButtonView.swift // ios-AccessibilityApp // // Created by Nawaf B Al sharqi on 01/03/2021. // import SwiftUI struct MoreButtonView: View { var body: some View { Image(IconsCollection.more) .resizable() .aspectRatio(contentMode: .fit) .frame(width: UIScreen.width / 5 * 0.3, height: UIScreen.height / 5 * 0.05, alignment: .center) .padding() .accessibility(label: Text("التعديل")) } } struct MoreButtonView_Previews: PreviewProvider { static var previews: some View { MoreButtonView() } }
true
546f0ff84c0ff8bbd307faa4d9206935c275af15
Swift
lcs-jsacalcohen/PortfolioDevTask-SectionB-Variables-Constants-Data-Types-Operators-Control-Flow
/Portfolio Development Task.playground/Pages/Question 4.xcplaygroundpage/Contents.swift
UTF-8
3,284
4.28125
4
[]
no_license
/*: # Question 4 Bored over the holiday, wishing you could just be back in Gordon's Computer Science class, you and your friend invent a game called "YouTube Mashup". You each choose a video on YouTube. You play 10 seconds of your video, then your friend plays 10 seconds of their video. On the next turn, your friend plays their 10 seconds of video first, then you play your 10 seconds of a different video. The goal of the game is to guess what kind of video your friend will play first, and pick something for the final 10 seconds that will be a ridiculous and funny mashup. For example: ![cat-in-the-hat-mad-max](cat-in-the-hat-mad-max.png "Cat in the Hat vs. Mad Max") To make things more interesting, each time your friend smiles, giggles, or laughs, an amount of money changes hands. Create a variable called `totalMoneyIHaveEarned` with an appropriate data type. The game of YouTube Mashup begins: 1. You play a 10 second clip from *Grey's Anatomy* and your friend follows this up with a clip from *Mythbusters*. Not a great mashup, and you barely smile, so you only have to pay your friend $0.10. Use a *compound assignment operator* to update `totalMoneyIHaveEarned`. 2. You know your friend loves old romance movies, and you're prepared when they play a 10-second clip from *Ghost*, the 1990 movie starring Patrick Swayze and Demi Moore. You follow that up with a 10-second clip from *SpongeBob SquarePants*, and the resulting mashup is both borderline inappropriate and terribly funny. Your friend giggles a lot. They must pay up, and your total money earned increases by $6.75. Use a *compound assignment operator* to update `totalMoneyIHaveEarned`. 3. You play a clip from *Star Wars Episode XII: The Force Awakens*, and your friend is embarrassed when she follows this up with a clip from *Star Trek V: The Final Frontier*. Two sci-fi movies that just don't go that well together. No one laughs at all, but to smooth over the awkward moment you generously agree to share half your current earnings your friend. Update `totalMoneyIHaveEarned` using a *compound assignment operator*. 4. Finally, your friend plays a clip from *Sesame Street* and you follow this with a clip from *The Fast and The Furious*. Big Bird mashed up with Dwayne "The Rock" Johnson... you bring down the house. No need to share the details of this mashup here, but your friend agrees that you've struck pure gold. Your total earnings are tripled. Update `totalMoneyIHaveEarned` using a *compound assignment operator*. */ // Answer question 4 below var totalMoneyIHaveEarned = 0.0 // Must be a Double since you can earn part of a dollar. totalMoneyIHaveEarned -= 0.1 // Part 1 totalMoneyIHaveEarned += 6.75 // Part 2 totalMoneyIHaveEarned /= 2 // Part 3 totalMoneyIHaveEarned *= 3 // Part 4 /*: ## Now share your understanding 1. Commit your response on this page (Option-Command-C). 2. [Add a link][al] to your Computer Science portfolio. [al]: https://www.youtube.com/watch?v=Wa3Wl3T25jo&list=PLTGGOQnktyWs9TlNJ30pgYgypvIGrt3Lx&index=1 ### Learning Goals - Programming * Goal 4 * *Knowledge* * I know how to use assignment statements, including compound assignment operators, when appropriate. [Next](@next) */
true
9b10e4232d5cfa35abffb95565c812d98754b679
Swift
drekka/Rxy
/Rxy/Nimble/Completable+Nimble.swift
UTF-8
1,187
2.828125
3
[ "MIT" ]
permissive
// Copyright © 2018 Derek Clarkson. All rights reserved. import RxBlocking import RxSwift import Nimble /// This extension provides wrappers for asynchronous observables which convert them to synchronous and generate Nimble errors /// if the result is not the expected one. public extension PrimitiveSequence where Trait == CompletableTrait, Element == Never { /** Waits for a Completable to complete. */ public func waitForCompletion(file: FileString = #file, line: UInt = #line) { if case let .failed(elements: _, error: error) = result { fail("Expected successful completion, got a \(error.typeDescription) instead", file: file, line: line) } } /** Waits for an error to be produced. If the Completable completes without an error, is produced a Nimble failure is generated and a nil returned. */ @discardableResult public func waitForError(file: FileString = #file, line: UInt = #line) -> Error? { if case let .failed(elements: _, error: error) = result { return error } fail("Expected an error, but completed instead", file: file, line: line) return nil } }
true
9495886a4e09042482f5fdc97137ab78c21b7c35
Swift
DjivaCanessane/InstagridTutorial
/InstagridTutorial/Views/Main View/MainView+ImageMethods.swift
UTF-8
2,807
2.984375
3
[]
no_license
// // MainView+ImageMethods.swift // InstagridTutorial // // Created by Djiveradjane Canessane on 17/02/2021. // import SwiftUI // Extension for checking presence of image in the gridLayout extension MainView { // Vérification pour la première configuration private var isFirstLayoutButtonSelected: Bool { return layoutViewModel.showBottomRightButton && !layoutViewModel.showTopLeftButton } private var isContainingImageForFirstLayoutButton: Bool { return imagePickerViewModel.selectedImageTopRight != nil || imagePickerViewModel.selectedImageBottomRight != nil || imagePickerViewModel.selectedImageBottomLeft != nil } // Vérification pour la seconde configuration private var isSecondLayoutButtonSelected: Bool { return !layoutViewModel.showBottomRightButton && layoutViewModel.showTopLeftButton } private var isContainingImageForSecondLayoutButton: Bool { return imagePickerViewModel.selectedImageTopRight != nil || imagePickerViewModel.selectedImageTopLeft != nil || imagePickerViewModel.selectedImageBottomLeft != nil } // Vérification pour la troisième configuration private var isThirdLayoutButtonSelected: Bool { return layoutViewModel.showBottomRightButton && layoutViewModel.showTopLeftButton } private var isContainingImageForThirdLayoutButton: Bool { return imagePickerViewModel.selectedImageTopRight != nil || imagePickerViewModel.selectedImageTopLeft != nil || imagePickerViewModel.selectedImageBottomRight != nil || imagePickerViewModel.selectedImageBottomLeft != nil } func isShowingAtLeastOneImage() -> Bool { var isShowing: Bool = false // Check presence of image for the first LayoutButton configuration if isFirstLayoutButtonSelected { if isContainingImageForFirstLayoutButton { isShowing = true } } // Check presence of image for the second LayoutButton configuration else if isSecondLayoutButtonSelected { if isContainingImageForSecondLayoutButton { isShowing = true } } // Check presence of image for the third LayoutButton configuration else if isThirdLayoutButtonSelected { if isContainingImageForThirdLayoutButton { isShowing = true } } return isShowing } } // Permet de convertir une view en UIView extension UIView { func asImage(rect: CGRect) -> UIImage { let renderer = UIGraphicsImageRenderer(bounds: rect) return renderer.image { rendererContext in layer.render(in: rendererContext.cgContext) } } }
true
423c52ca324e2a86125d508e9a4fccbf4c6557d9
Swift
mike011/TableViewWithREST
/TableViewWithREST/Gist/PullRouter.swift
UTF-8
2,038
2.734375
3
[]
no_license
// // PullRouter.swift // TableViewWithREST // // Created by Michael Charland on 2019-08-23. // Copyright © 2019 charland. All rights reserved. // import Alamofire import Foundation enum PullRouter: URLRequestConvertible { static let baseURLString = "https://api.github.com/" case pull(owner: String, repo: String, number: Int) case pulls(owner: String, repo: String) case merge(owner: String, repo: String, number: Int) func asURLRequest() throws -> URLRequest { var method: HTTPMethod { switch self { case .merge: return .put case .pull: return .get case .pulls: return .get } } let url: URL = { switch self { case let .merge(owner, repo, number): let relativePath = "repos/\(owner))/\(repo)/pulls/\(number)/merge" var url = URL(string: PullRouter.baseURLString)! url.appendPathComponent(relativePath) return url case let .pull(owner, repo, number): // GET /repos/:owner/:repo/pulls let relativePath = "repos/\(owner))/\(repo)/pulls/\(number)" var url = URL(string: PullRouter.baseURLString)! url.appendPathComponent(relativePath) return url case let .pulls(owner, repo): // GET /repos/:owner/:repo/pulls let relativePath = "repos/\(owner))/\(repo)/pulls" var url = URL(string: PullRouter.baseURLString)! url.appendPathComponent(relativePath) return url } }() var urlRequest = URLRequest(url: url) urlRequest.httpMethod = method.rawValue // Set OAuth token if we have one if let token = GitHubAPIManager.shared.OAuthToken { urlRequest.setValue("token \(token)", forHTTPHeaderField: "Authorization") } return urlRequest } }
true
eb3ebade322f2c45093d0a09dd4d3128533ff097
Swift
GonzaloiOS/OpenLibray_TableView
/BuscadorLibroTabla/BuscadorLibroTabla/DetailViewController.swift
UTF-8
3,908
2.609375
3
[]
no_license
// // DetailViewController.swift // BuscadorLibroTabla // // Created by Gonzalo on 27/03/16. // Copyright © 2016 G. All rights reserved. // import UIKit protocol DetailProtocolDelegate { func bookSearchedAndAddedToArray(book:Book) } class DetailViewController: UIViewController,UITextFieldDelegate,SystemClassDelegate { let communication = SystemClass() @IBOutlet weak var coverBookImageVIew: UIImageView! @IBOutlet weak var titleBookTextView: UITextView! @IBOutlet weak var authorTextView: UITextView! @IBOutlet weak var searchTextField: UITextField! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! var currentDictionary:[String:Book] = [:] var delegate:DetailProtocolDelegate? var onlyShowBookInfo:Book? override func viewDidLoad() { super.viewDidLoad() self.titleBookTextView.text = "" self.authorTextView.text = "" if((self.onlyShowBookInfo) != nil){ self.searchTextField.hidden = true; self.titleBookTextView.text = self.onlyShowBookInfo!.title! self.authorTextView.text = self.onlyShowBookInfo!.author! self.coverBookImageVIew.image = self.onlyShowBookInfo!.image }else{ self.searchTextField.hidden = false; self.searchTextField.delegate = self self.communication.delegate = self } self.activityIndicator.hidesWhenStopped = true self.activityIndicator.stopAnimating() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func textFieldShouldReturn(textField: UITextField) -> Bool { let temporalDictionary = self.currentDictionary[textField.text!] print(self.currentDictionary) if ((temporalDictionary) != nil) { self.bookFetched(self.currentDictionary[textField.text!]!) }else{ print(textField.text!) communication.getDataFromText(textField.text!) self.activityIndicator.startAnimating() } self.searchTextField.resignFirstResponder() return true } func bookFetched(book: Book) { self.titleBookTextView.text = book.title! self.authorTextView.text = book.author! self.coverBookImageVIew.image = book.image! self.delegate?.bookSearchedAndAddedToArray(book) self.currentDictionary[book.identifierSBNF] = book self.activityIndicator.stopAnimating() } func searchBookError(errorString: String) { self.activityIndicator.stopAnimating() let actionSheetController: UIAlertController = UIAlertController(title: "Error", message: errorString, preferredStyle: .Alert) //Create and add the Cancel action let cancelAction: UIAlertAction = UIAlertAction(title: "OK", style: .Cancel) { action -> Void in //Just dismiss the action sheet } actionSheetController.addAction(cancelAction) //Present the AlertController self.presentViewController(actionSheetController, animated: true, completion: nil) } /* // 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
1e47190f2ef8947de08b8c1fc2f7216c4626a488
Swift
Nachobear/IT2100KRoberts
/Lab03KRoberts.playground/Contents.swift
UTF-8
2,305
4.34375
4
[]
no_license
//: Playground - noun: a place where people can play import UIKit var Pi0: Int = 22/7 var Pi1: Float = 22/7 var Pi2: Double = 22/7 /* Each of the three variables above were assigned the value of 22/7 (approximately Pi) but all hold different values. The first Pi Variable was declared as an integer, which can only be a whole number, which is why everything to the right of the ones place was omitted. The second Pi variable was declared as a Float, which can hold fractional numbers but only up to a small number of decimal places, which is why only six of the decimal places were shown and the rest were omitted. The third Pi variable was declared as a Double, which allows for a ridiculous number of decimal places, which is why that version of 22/7 did not have to be rounded. */ class Counter { var count = 0 func increment() { count += 1 } func decrement() { count -= 1 } func increment(by amount: Int) { count += amount } func decrement(by amount: Int) { count -= amount } func reset() { count = 0 } func getCount() -> Int { return count } func display() { print(getCount()) } } var counter1 = Counter() counter1.increment(by:7) counter1.decrement() counter1.decrement(by:3) counter1.increment() counter1.display() func concatAll(names: [String], separator: String) -> String { var namesConcat = String() for name in names { namesConcat = namesConcat + name + separator } return namesConcat } var names = ["billy", "randy", "joe"] //print(concatAll(names: names, separator: "xxx")) var separator = "xxx" var fullString = concatAll(names: names, separator: separator) print (fullString) for i in 0..<separator.characters.count { fullString.characters.dropLast() } print(fullString) /* I could't get rid of the separator at the end of the string. I tried the following code but I don't know why it didn't work: for var i = 0 ; i < separator.characters.count ; i = i + 1 { namesConcat = (namesConcat.characters.dropLast()) } I put it in right above "return namesConcat" in the "concatAll" func. I think it didn't work because the syntax has changed since the book was written. I'm not sure how to find the current versions. */
true
fb83d17ff22fc025be21bf631fabc7e3783ee95b
Swift
Karim-W/SwiftUI-Calculator
/App/App/ContentView.swift
UTF-8
7,515
3.109375
3
[]
no_license
// // ContentView.swift // App // // Created by Karim Wael on 6/24/20. // Copyright © 2020 Karim Wael. All rights reserved. // import SwiftUI enum keys:String{ case Zero,One,Two,Three,Four,Five,Six,Seven,Eight,Nine,dec case Plus,Minus,Multiply,Divide,Equal case AC,PC,PM var title:String { switch self { case .dec:return "." case .Equal : return "=" case .Zero:return "0" case .One: return "1" case .Two: return "2" case .Three: return "3" case .Four: return "4" case .Five: return "5" case .Six: return "6" case .Seven: return "7" case .Eight: return "8" case .Nine: return "9" case .Plus: return "+" case .Minus: return "-" case .Multiply: return "x" case .Divide: return "÷"//÷ case .AC: return "AC"//AC case .PC: return "%" case .PM: return "+/-" } } var backgroundColor:Color{ switch self{ case .Plus: return Color.orange case .Equal : return Color.orange case .Zero,.One,.Two,.Three,.Four,.Five,.Six,.Seven,.Eight,.Nine,.dec: return Color.init(UIColor.darkGray) case .Minus: return Color.orange case .Multiply: return Color.orange case .Divide: return Color.orange case .AC: return Color.gray case .PC: return Color.gray case .PM: return Color.gray } } } class GlobalEnviroment: ObservableObject{ @Published var Display = "" @Published var Satement = "" @Published var eq = false @Published var dFlag = false @Published var left = "" @Published var OP = Character("z") } struct Queues { var list = [Character]() public mutating func enqueue( element: Character) { list.append(element) } public mutating func dequeue() -> Character{ let t = list.remove(at: 0) return t } } struct ContentView: View { @EnvironmentObject var env: GlobalEnviroment let buttons:[[keys]] = [ [.AC,.PM,.PC,.Divide], [.Seven,.Eight,.Nine,.Multiply], [.Four,.Five,.Six,.Minus], [.One,.Two,.Three,.Plus], [.Zero,.dec,.Equal]] var Disp:String = "" let col = Color.gray let itemw = (UIScreen.main.bounds.width-40)/4 var body: some View { ZStack (alignment: .bottom ){ Color.black.edgesIgnoringSafeArea(.all) VStack (spacing: 12){ HStack{ Spacer() Text(env.Display).foregroundColor(.white).font(.system(size: 72))}.padding() ForEach(buttons,id: \.self) { row in HStack{ ForEach(row,id: \.self) { button in Button(action: { if (self.env.eq == true) {self.env.Display = ""; self.env.eq = false} if(button == .AC){ self.env.Display = "" self.env.left = "" self.env.dFlag = false }else if (button == .PC){ self.env.dFlag = true let t: Float = ( self.env.Display as NSString).floatValue self.env.Display = String(t/100) }else if (button == .PM){ self.env.dFlag = true let t: Float = ( self.env.Display as NSString).floatValue self.env.Display = String(t * -1) }else if(button.title == "+" || button.title == "-" || button.title == "x" || button.title == "÷"){ self.env.left = self.env.Display self.env.Display = "" self.env.OP = Character(button.title) }else if (button == .Equal){ self.env.eq = true self.env.Display = self.Domath(l: self.env.left, o: self.env.OP, r: self.env.Display) }else{ self.env.Display = self.env.Display + button.title} }) { Text(button.title).font(.system(size: 32)).frame(width: self.getW(but: button), height: self.itemw, alignment: .center).foregroundColor(.white).background(button.backgroundColor).cornerRadius(self.getW(but: button)/2) } } } } }.padding(.bottom) } } func calc(dis:String) -> String{ var que = Queues() var left = String() var right = String() var op = Character("z") //var res = Float() let state = dis.unicodeScalars.map{ Character($0) } //let char = charSequence[index] for i in 0...state.count-1 { if( state[i] == "+" || state[i] == "-" || state[i] == "x" || state[i] == "÷") { op = state[i] }else if (op == "z") { left.append(state[i]) }else { right.append(state[i]) } } return Domath(l:left, o:op, r:right) } func Domath(l:String,o:Character,r:String)->String{ var res = Float() var nres = Int() switch o{ case "+": if (env.dFlag == false){ nres = (Int(l)! + Int(r)!) return String(nres) }else{ res = ((l as NSString).floatValue + (r as NSString).floatValue) return String(res) } case"-": if (env.dFlag == false){ nres = (Int(l)! - Int(r)!) return String(nres) }else{ res = ((l as NSString).floatValue - (r as NSString).floatValue) return String(res) } case"x": if (env.dFlag == false){ nres = (Int(l)! * Int(r)!) return String(nres) }else{ res = ((l as NSString).floatValue * (r as NSString).floatValue) return String(res) } case "÷": res = ((l as NSString).floatValue / (r as NSString).floatValue) return String(res) default: return "ERR" } } func getW(but:keys) -> CGFloat{ if (but == .Zero){ return itemw * 2 }else{ return itemw } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView().environmentObject(GlobalEnviroment()) } }
true
3ff3a42880373f25d654087971c6af08c3e0db51
Swift
JothiRamaswamy/Myliever
/Myliever/Myliever/ViewController.swift
UTF-8
5,165
2.609375
3
[]
no_license
// // ViewController.swift // Myliever // // Created by Jothi Ramaswamy on 3/12/18. // Copyright © 2018 Jothi Ramaswamy. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var label1: UILabel! //1st q answer label @IBOutlet weak var slider1: UISlider! //1st q answer slider @IBAction func Pressed1(_ sender: Any) { //extracting answer value let value = Int(slider1.value) self.label1.text = "\(value)" if slider1.value == 110 { self.label1.text = "\(value)+" } } @IBOutlet weak var label2: UILabel! //2nd q answer label @IBOutlet weak var slider2: UISlider! //2nd q answer slider @IBAction func Pressed2(_ sender: Any) { //extracting answer value let value = Int(slider2.value) self.label2.text = "\(value)" if slider2.value == 300 { self.label2.text = "\(value)+" } } @IBOutlet weak var label3: UILabel! //3rd q answer label @IBOutlet weak var slider3: UISlider! //3rd q answer slider @IBAction func Pressed3(_ sender: Any) { //extracting answer value let value = Int(slider3.value) self.label3.text = "\(value)" if slider3.value == 10 { self.label3.text = "\(value)+" } } @IBOutlet weak var label4: UILabel! //4th q answer label @IBOutlet weak var slider4: UISlider! //4th q answer slider @IBAction func Pressed4(_ sender: Any) { //extracting answer value let value = Int(slider4.value) self.label4.text = "\(value)" if slider4.value == 10 { self.label4.text = "\(value)+" } } @IBOutlet weak var label5: UILabel! //5th q answer label @IBOutlet weak var slider5: UISlider! //5th q answer slider @IBAction func Pressed5(_ sender: Any) { //extracting answer value let value = Int(slider5.value) self.label5.text = "\(value)" if slider5.value == 10 { self.label5.text = "\(value)+" } } @IBOutlet weak var label6: UILabel! //6th q answer label @IBOutlet weak var slider6: UISlider! //6th q answer slider @IBAction func Pressed6(_ sender: Any) { //extracting answer value let value = Int(slider6.value) self.label6.text = "\(value)" if slider6.value == 20 { self.label6.text = "\(value)+" } } @IBOutlet weak var button7: UISegmentedControl! //7th q- yes/no question @IBOutlet weak var label8: UILabel! //8th q answer label @IBOutlet weak var slider8: UISlider! //8th q answer slider @IBAction func Pressed8(_ sender: Any) { //extracting answer value let value = Int(slider8.value) self.label8.text = "\(value)" } @IBOutlet weak var label9: UILabel! //9th q answer label @IBOutlet weak var slider9: UISlider! //9th q answer slider @IBAction func Pressed9(_ sender: Any) { //extracting answer value let value = Int(slider9.value) self.label9.text = "\(value)" } var percentRisk = 49 @IBAction func infoSent(_ sender: Any) { //computing risk let one = Int((slider1.value - 70) / 4) let two = Int((abs(slider2.value - 150)) / 15) let three = Int(slider3.value * 2) let four = Int(slider4.value) let five = Int(slider5.value) let six = Int(slider6.value / 2) var seven = 0 if (button7.selectedSegmentIndex == 0) { seven = 20 } let eight = Int(slider8.value * 2) let nine = Int(slider9.value) var total = one + two + three + four + five total = total + six + seven + eight + nine percentRisk = Int(5 * total / 6) UserDefaults().set(percentRisk, forKey: "percentRisk") performSegue(withIdentifier: "resultScrn", sender: self) } let gradientLayer = CAGradientLayer() override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.clear // 2 gradientLayer.frame = self.view.bounds // 3 let color4 = UIColor(red:0.80, green:0.90, blue:1.00, alpha:0.6).cgColor as CGColor let color3 = UIColor(red:0.80, green:0.90, blue:1.00, alpha:0.85).cgColor as CGColor let color2 = UIColor(red:0.80, green:0.90, blue:1.00, alpha:1.0).cgColor as CGColor //let color1 = UIColor(red:0.60, green:0.68, blue:0.75, alpha:1.0).cgColor as CGColor gradientLayer.colors = [color4, color3, color2] // 4 gradientLayer.locations = [0.25, 0.4, 0.8] // 5 self.view.layer.insertSublayer(gradientLayer, at: 0) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
true
a0eab0693061f192da94b93c85c210e18408f511
Swift
guoshengboy/LearnSwift
/基础部分/基础部分/Enum&StructViewController.swift
UTF-8
1,835
3.765625
4
[]
no_license
// // Enum&StructViewController.swift // 基础部分 // // Created by cgs on 2017/5/15. // Copyright © 2017年 cgs. All rights reserved. // import UIKit class Enum_StructViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.view.backgroundColor = UIColor.white; //enum 最基本的枚举 和OC不一样 没有默认0 1 2 字符串就是字符串 enum Direction{ case East case South case West case North } let dir = Direction.East print(dir); //给枚举赋值 Direction1.East.rawValue 取枚举的值 East=10 后面的依次增加1 enum Direction1: Double{ case East = 10 case South case West case North } let dir1 = Direction1.East if dir1 == Direction1.East { print(Direction1.North.rawValue) } print(dir1); //Struct 来创建一个结构体。结构体和类有很多相同的地方,比如方法和构造器。它们之间最大的一个区别就 是结构体是传值,类是传引用。 struct car{ var dir: Direction1 func getCarName() -> String { return "宝骏" } } let oneStruct = car.init(dir: Direction1.East) let carName = oneStruct.getCarName() print(carName) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
true
3f5276e82ad2dbaa0cae205f125dad260fe5bf74
Swift
ogawa0147/excamera-ios
/Camera/Extensions/UITableView+Nib.swift
UTF-8
1,108
2.796875
3
[ "MIT" ]
permissive
import UIKit public protocol UITableViewCellNibRegistrable: class { static var reuseIdentifier: String { get } static var nib: UINib { get } } public extension UITableViewCellNibRegistrable { static var reuseIdentifier: String { return String(describing: self) } static var nib: UINib { let nibName = String(describing: self) return UINib(nibName: nibName, bundle: Bundle(for: self)) } } public extension UITableView { func register<T: UITableViewCellNibRegistrable>(_ registrableType: T.Type, forCellReuseIdentifier reuseIdentifier: String) where T: UITableViewCell { register(registrableType.nib, forCellReuseIdentifier: reuseIdentifier) } } public extension UITableView { func dequeueReusableCell<T: UITableViewCellNibRegistrable>(withIdentifier identifier: String, for indexPath: IndexPath) -> T where T: UITableViewCell { guard let cell = dequeueReusableCell(withIdentifier: identifier, for: indexPath) as? T else { fatalError("Could not dequeue cell with type \(T.self)") } return cell } }
true
2d235a60e8fc3030309a2b3b7ae3ddc78dd1a871
Swift
Krisloveless/daily-coding-challenges
/swift/Problem 100/Problem 100/Solution.swift
UTF-8
751
3.5
4
[ "MIT" ]
permissive
// // Solution.swift // Problem 100 // // Created by sebastien FOCK CHOW THO on 2019-09-02. // Copyright © 2019 sebastien FOCK CHOW THO. All rights reserved. // import Foundation typealias Point = (row: Int, column: Int) func distanceBetween(a: Point, b: Point) -> Int { let width = abs(b.column - a.column) let height = abs(b.row - a.row) return max(width, height) } extension Array where Element == Point { func minimumSteps() -> Int { var result = 0 var copy = self var current = copy.removeFirst() while !copy.isEmpty { let next = copy.removeFirst() result += distanceBetween(a: current, b: next) current = next } return result } }
true
1cc8c5f3f7933dc5b7f6bf60a745604067ab85d6
Swift
wanqingrongruo/AnyImageKit
/Sources/AnyImageKit/Picker/View/Cell/PreviewCell.swift
UTF-8
12,087
2.5625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// // PreviewCell.swift // AnyImageKit // // Created by 蒋惠 on 2019/9/27. // Copyright © 2019-2022 AnyImageKit.org. All rights reserved. // import UIKit protocol PreviewCellDelegate: AnyObject { /// 开始拖动 func previewCellDidBeginPan(_ cell: PreviewCell) /// 拖动时回调。scale:缩放比率 func previewCell(_ cell: PreviewCell, didPanScale scale: CGFloat) /// 结束拖动 func previewCell(_ cell: PreviewCell, didEndPanWithExit isExit: Bool) /// 单击时回调 func previewCellDidSingleTap(_ cell: PreviewCell) /// 获取工具栏的显示状态 func previewCellGetToolBarHiddenState() -> Bool } class PreviewCell: UICollectionViewCell { weak var delegate: PreviewCellDelegate? var asset: Asset! var manager: PickerManager! { didSet { if oldValue == nil { update(options: manager.options) } } } var isDownloaded: Bool = false /// 内嵌容器 /// 本类不能继承 UIScrollView,因为实测 UIScrollView 遵循了 UIGestureRecognizerDelegate 协议,而本类也需要遵循此协议 /// 若继承 UIScrollView 则会覆盖 UIScrollView 的协议实现,故只内嵌而不继承 private(set) lazy var scrollView: UIScrollView = { let view = UIScrollView() view.showsVerticalScrollIndicator = false view.showsHorizontalScrollIndicator = false if #available(iOS 11.0, *) { view.contentInsetAdjustmentBehavior = .never } return view }() /// 显示图像 lazy var imageView: UIImageView = { let view = UIImageView(frame: .zero) view.clipsToBounds = true return view }() /// 下载进度 private(set) lazy var iCloudView: LoadingiCloudView = { let view = LoadingiCloudView(frame: .zero) view.isHidden = true return view }() /// 单击手势 private(set) lazy var singleTap: UITapGestureRecognizer = { return UITapGestureRecognizer(target: self, action: #selector(onSingleTap)) }() /// 拖动手势 private(set) lazy var pan: UIPanGestureRecognizer = { let pan = UIPanGestureRecognizer(target: self, action: #selector(onPan(_:))) pan.delegate = self return pan }() /// 计算contentSize应处于的中心位置 var centerOfContentSize: CGPoint { let deltaWidth = bounds.width - scrollView.contentSize.width let offsetX = deltaWidth > 0 ? deltaWidth * 0.5 : 0 let deltaHeight = bounds.height - scrollView.contentSize.height let offsetY = deltaHeight > 0 ? deltaHeight * 0.5 : 0 return CGPoint(x: scrollView.contentSize.width * 0.5 + offsetX, y: scrollView.contentSize.height * 0.5 + offsetY) } /// 取图片适屏size var fitSize: CGSize { guard let image = imageView.image else { return CGSize.zero } let screenSize = ScreenHelper.mainBounds.size let scale = image.size.height / image.size.width var size = CGSize(width: screenSize.width, height: scale * screenSize.width) if size.width > size.height { size.width = size.width * screenSize.height / size.height size.height = screenSize.height } return size } /// 取图片适屏frame var fitFrame: CGRect { let size = fitSize let y = (scrollView.bounds.height - size.height) > 0 ? (scrollView.bounds.height - size.height) * 0.5 : 0 return CGRect(x: 0, y: y, width: size.width, height: size.height) } /// 记录pan手势开始时imageView的位置 private var beganFrame = CGRect.zero /// 记录pan手势开始时,手势位置 private var beganTouch = CGPoint.zero override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor.clear setupView() isAccessibilityElement = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func prepareForReuse() { super.prepareForReuse() iCloudView.reset() } // MARK: - Function /// 设置图片 func setImage(_ image: UIImage?) { imageView.image = image if image != nil { layout() } } override func layoutSubviews() { super.layoutSubviews() if UIDevice.current.userInterfaceIdiom == .pad { // Optimize performance, fit size classes layout() } } /// 重新布局 internal func layout() { scrollView.frame = contentView.bounds scrollView.setZoomScale(1.0, animated: false) imageView.frame = fitFrame let minZoomScale = getDefaultScale() let maxZoomScale = getMaxZoomScale(with: minZoomScale) scrollView.minimumZoomScale = minZoomScale scrollView.maximumZoomScale = maxZoomScale scrollView.setZoomScale(minZoomScale, animated: false) } /// 设置 iCloud 下载进度 internal func setDownloadingProgress(_ progress: Double) { isDownloaded = progress == 1 iCloudView.isHidden = progress == 1 iCloudView.setProgress(progress) if progress == 1 { NotificationCenter.default.post(name: .previewCellDidDownloadResource, object: asset) } } // MARK: - Override func reset() { } func singleTapped() { delegate?.previewCellDidSingleTap(self) } func panBegin() { delegate?.previewCellDidBeginPan(self) } func panScale(_ scale: CGFloat) { delegate?.previewCell(self, didPanScale: scale) } func panEnded(_ exit: Bool) { delegate?.previewCell(self, didEndPanWithExit: exit) } /// 通知子类更新配置 /// 由于 update options 方法来自协议,无法在子类重载,所以需要这个方法通知子类 func optionsDidUpdate(options: PickerOptionsInfo) { } } // MARK: - PickerOptionsConfigurable extension PreviewCell: PickerOptionsConfigurable { func update(options: PickerOptionsInfo) { optionsDidUpdate(options: options) updateChildrenConfigurable(options: options) } } // MARK: - Private function extension PreviewCell { private func setupView() { contentView.addSubview(scrollView) scrollView.addSubview(imageView) contentView.addSubview(iCloudView) iCloudView.snp.makeConstraints { maker in maker.top.equalToSuperview().offset(100) maker.left.equalToSuperview().offset(10) maker.height.equalTo(25) } // 添加手势 contentView.addGestureRecognizer(singleTap) // 必须加在scrollView上。不能加在contentView上,否则长图下拉不能触发 scrollView.addGestureRecognizer(pan) } /// 获取缩放比例 private func getDefaultScale() -> CGFloat { guard let image = imageView.image else { return 1.0 } let width = scrollView.bounds.width let scale = image.size.height / image.size.width let size = CGSize(width: width, height: scale * width) let screenSize = ScreenHelper.mainBounds.size if size.width > size.height { return size.height / screenSize.height } if UIDevice.current.userInterfaceIdiom == .pad { let height = scrollView.bounds.height let scale = image.size.width / image.size.height let size = CGSize(width: height * scale, height: height) if size.height > size.width { return size.width / screenSize.width } } return 1.0 } private func getMaxZoomScale(with minZoomScale: CGFloat) -> CGFloat { guard let image = imageView.image else { return 1.0 } var maxZoomScale = (image.size.width / ScreenHelper.mainBounds.width) * 2 maxZoomScale = maxZoomScale / (1.0 / minZoomScale) return maxZoomScale < 1.0 ? 1.0 : maxZoomScale } } // MARK: - Target extension PreviewCell { /// 响应单击 @objc private func onSingleTap() { singleTapped() } /// 响应拖动 @objc private func onPan(_ pan: UIPanGestureRecognizer) { guard imageView.image != nil else { return } switch pan.state { case .began: beganFrame = imageView.frame beganTouch = pan.location(in: scrollView) panBegin() case .changed: let result = panResult(pan) imageView.frame = result.0 // 通知代理,发生了缩放。代理可依scale值改变背景蒙板alpha值 panScale(result.1) case .ended, .cancelled: imageView.frame = panResult(pan).0 if pan.velocity(in: self).y > 0 { // dismiss panEnded(true) } else { // 取消dismiss endPan() } default: endPan() } } private func panResult(_ pan: UIPanGestureRecognizer) -> (CGRect, CGFloat) { // 拖动偏移量 let translation = pan.translation(in: scrollView) let currentTouch = pan.location(in: scrollView) // 由下拉的偏移值决定缩放比例,越往下偏移,缩得越小。scale值区间[0.3, 1.0] let scale = min(1.0, max(0.3, 1 - translation.y / bounds.height)) let width = beganFrame.size.width * scale let height = beganFrame.size.height * scale // 计算x和y。保持手指在图片上的相对位置不变。 // 即如果手势开始时,手指在图片X轴三分之一处,那么在移动图片时,保持手指始终位于图片X轴的三分之一处 let xRate = (beganTouch.x - beganFrame.origin.x) / beganFrame.size.width let currentTouchDeltaX = xRate * width let x = currentTouch.x - currentTouchDeltaX let yRate = (beganTouch.y - beganFrame.origin.y) / beganFrame.size.height let currentTouchDeltaY = yRate * height let y = currentTouch.y - currentTouchDeltaY return (CGRect(x: x.isNaN ? 0 : x, y: y.isNaN ? 0 : y, width: width, height: height), scale) } private func endPan() { panScale(1.0) panEnded(false) // 如果图片当前显示的size小于原size,则重置为原size let size = fitSize let needResetSize = imageView.bounds.size.width < size.width || imageView.bounds.size.height < size.height UIView.animate(withDuration: 0.25) { self.imageView.center = self.centerOfContentSize if needResetSize { self.imageView.bounds.size = size } } } } // MARK: - UIGestureRecognizerDelegate extension PreviewCell: UIGestureRecognizerDelegate { override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { // 只响应pan手势 guard let pan = gestureRecognizer as? UIPanGestureRecognizer else { return true } let velocity = pan.velocity(in: self) // 向上滑动时,不响应手势 if velocity.y < 0 { return false } // 横向滑动时,不响应pan手势 if abs(Int(velocity.x)) > Int(velocity.y) { return false } // 向下滑动,如果图片顶部超出可视区域,不响应手势 if scrollView.contentOffset.y > 0 { return false } // 响应允许范围内的下滑手势 return true } } extension Notification.Name { static let previewCellDidDownloadResource = Notification.Name("org.AnyImageKit.Notification.Name.Picker.PreviewCellDidDownloadResource") }
true
c4cd3876ec171870b459f3d0c224f3182811f6d0
Swift
st4n667/iTunesApiSearchSave
/iTunesSearchSave2019/Screens/SearchScreen/Views/SongSearchResultCell.swift
UTF-8
2,454
2.703125
3
[ "MIT" ]
permissive
// // SongCell.swift // iTunesSearchSave2019 // // Created by Staszek on 19/12/2019. // Copyright © 2019 st4n. All rights reserved. // import UIKit class SongSearchResultCell: UITableViewCell { static let reuseIdentifier = "SongCell" override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } required init?(coder: NSCoder) { fatalError() } deinit { print(String(describing: type(of: self)), #function) } override func prepareForReuse() { super.prepareForReuse() titleLabel.text = nil artistLabel.text = nil albumLabel.text = nil coverImageView.image = nil coverImageView.cancelImageLoad() } override func layoutSubviews() { let labelsStack = UIStackView(arrangedSubviews: [titleLabel, artistLabel, albumLabel]) labelsStack.axis = .vertical labelsStack.spacing = 4 let overallStack = UIStackView(arrangedSubviews: [coverImageView, labelsStack]) overallStack.alignment = .center overallStack.distribution = .fill overallStack.spacing = 12 coverImageView.constrainHeight(80) coverImageView.constrainWidth(80) addSubview(overallStack) overallStack.anchor(top: topAnchor, leading: leadingAnchor, bottom: bottomAnchor, trailing: trailingAnchor, padding: .init(top: 4, left: 8, bottom: 4, right: 8) ) addSubview(separatorView) separatorView.anchor(top: overallStack.bottomAnchor, leading: leadingAnchor, bottom: nil, trailing: trailingAnchor, padding: .init(top: 0, left: 64, bottom: 0, right: 0)) } // MARK: - UI Elements lazy var separatorView: UIView = { let v = UIView(frame: .zero) v.backgroundColor = UIColor(white: 0.9, alpha: 0.9) v.constrainHeight(0.5) return v }() lazy var titleLabel = CustomLabel(numberOfLines: 2, style: .header) lazy var artistLabel = CustomLabel(numberOfLines: 1, style: .regular) lazy var albumLabel = CustomLabel(numberOfLines: 1, style: .bolded) lazy var coverImageView: UIImageView = { let iv = UIImageView(frame: .zero) iv.contentMode = .scaleAspectFill iv.layer.cornerRadius = 8 iv.clipsToBounds = true return iv }() }
true
e0ac6708128288bb84497b298586ee552b518ec7
Swift
modelist61/Rock-Paper-Scissors
/Rock Paper Scissors/ContentView.swift
UTF-8
3,146
3.125
3
[]
no_license
// // ContentView2.swift // Rock Paper Scissors // // Created by Dmitry Tokarev on 10.10.2021. // import SwiftUI struct ContentView: View { @State private var gameMode: GameMode = .single @State private var showSelector = true var body: some View { ZStack { switch gameMode { case .single: SinglePlayerView() .blur(radius: showSelector ? 5 : 0) case .double: TwoPlayerView() } RoundedRectangle(cornerRadius: 30) .frame(width: 250, height: 350) .foregroundColor(Color("Purple3")) .opacity(0.9) .overlay( SelectorLable(gameMode: $gameMode, showSelector: $showSelector) ) .opacity(showSelector ? 1.0 : 0.0) .animation(.easeInOut(duration: 0.5)) } } } struct ContentView2_Previews: PreviewProvider { static var previews: some View { ContentView() } } struct SelectorLable: View { @Binding var gameMode: GameMode @Binding var showSelector: Bool @State private var showShadow = 0 var body: some View { VStack { Text("Game Mode") .foregroundColor(.white) .font(.system(size: 35)) .fontWeight(.heavy) Spacer() Button { gameMode = .single showSelector.toggle() } label: { ZStack { Text("vs") .font(.system(size: 35)) .fontWeight(.bold) HStack { Image(systemName: "person.fill") .resizable() .aspectRatio(contentMode: .fit) Spacer() Image(systemName: "iphone") .resizable() .aspectRatio(contentMode: .fit) .offset(x: -12) } }.foregroundColor(.white) .frame(width: 170, height: 60) }.padding(.bottom, 40) Button { gameMode = .double showSelector.toggle() } label: { ZStack { Text("vs") .font(.system(size: 35)) .fontWeight(.bold) HStack { Image(systemName: "person.fill") .resizable() .aspectRatio(contentMode: .fit) Spacer() Image(systemName: "person.fill") .resizable() .aspectRatio(contentMode: .fit) } }.foregroundColor(.white) .frame(width: 170, height: 60) } Spacer() }.padding() } }
true
5970bb259e4e2a5997141afd8a817016f181eeca
Swift
jboteros/eBirdIosApp
/eBirdApp/eBirdApp/View/CatalogContainer/CatalogTableViewCell.swift
UTF-8
1,777
2.765625
3
[]
no_license
// // CatalogTableViewCell.swift // eBirdApp // // Created by Johnatan Botero on 10/28/17. // Copyright © 2017 Johnatan Botero. All rights reserved. // import UIKit class CatalogTableViewCell: UITableViewCell { @IBOutlet weak var birdsContainer: UIImageView! @IBOutlet weak var lblName: UILabel! @IBOutlet weak var lblNameScientific: UILabel! @IBOutlet weak var lblCountry: UILabel! override func awakeFromNib() { circleImg(birdsContainer) super.awakeFromNib() // Initialization code } func LoadData(i: Int){ birdsContainer.imageFromServerURL(urlString: AppController.birdsContainer[i]["image"] as! String) lblName.text = AppController.birdsContainer[i]["name"] as? String lblNameScientific.text = AppController.birdsContainer[i]["nameScientific"] as? String lblCountry.text = ("\(String(describing: AppController.birdsContainer[i]["country"]! as! String))-\(String(describing: AppController.birdsContainer[i]["zone"]! as! String))") } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } } extension UIImageView { public func imageFromServerURL(urlString: String) { URLSession.shared.dataTask(with: NSURL(string: urlString)! as URL, completionHandler: { (data, response, error) -> Void in if error != nil { print(error!) return } DispatchQueue.main.async(execute: { () -> Void in let image = UIImage(data: data!) self.image = image }) }).resume() }}
true
ed6d167a4ceb8b92c0cda8f9831364f2f2ad0009
Swift
priom/AnimalAge
/AnimalAge/ViewController.swift
UTF-8
812
2.625
3
[]
no_license
// // ViewController.swift // AnimalAge // // Created by Priom on 2015-08-26. // Copyright © 2015 Priom.net. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet var prntAge: UILabel! @IBOutlet var inAge: UITextField! @IBAction func calcAge(sender: AnyObject) { var age = Int(inAge.text!)! age = age * 12 prntAge.text = "Your dog is \(age) years old in human years." // prntAge.text = "Please enter a value" } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
true
c8019008938866a945433a2a964fe78fafa0123a
Swift
skrulcik/PhotoFinder
/Photo Finder/ImageResult.swift
UTF-8
4,107
3.203125
3
[]
no_license
// // ImageResult.swift // Photo Finder // // Created by Scott Krulcik on 10/4/15. // Copyright © 2015 Scott Krulcik. All rights reserved. // import Foundation import UIKit /** ## Image Result Wrapper class for Encapsulates a single JSON from the Google Image Search API "results" array, allowing object-like access from other files. [API-Defined Fields](https://developers.google.com/image-search/v1/jsondevguide#results_guaranteed) */ class ImageResult: NSObject { let imageTitle: String let snippet: String let link: String let width: Int let height: Int let thumbnailLink: String var imageDescription: String { return "\(link)\n\(snippet)" } class func fromList(jsonList: [[String : AnyObject]]) -> [ImageResult] { var results = [ImageResult]() for rawJSON in jsonList { if let concreteObject = ImageResult(json: rawJSON) { results.append(concreteObject) } } return results } /** Attempts to create `ImageResult` object out of JSON Dictionary. Guarantees proper object creation if all required keys are present. If any required keys are missing, initialization fails. */ init?(json: [String : AnyObject]) { if let imageTitle = json["title"] as? String, let snippet = json["snippet"] as? String, let link = json["link"] as? String, let rawImageData = json["image"] as? [String : AnyObject], let width = rawImageData["width"] as? Int, let height = rawImageData["height"] as? Int, let thumbnailLink = rawImageData["thumbnailLink"] as? String { self.imageTitle = imageTitle self.snippet = snippet self.link = link self.width = width self.height = height self.thumbnailLink = thumbnailLink super.init() } else { return nil } } } /** Slight breach of MVC here, but this allows the model, which has access to both the thumbnail and regular URL, populate images with increasing resolution. Because theses methods are here, it is achieved without any other classes poking around the JSON, which is the point of this class. */ extension ImageResult { /** Downloads full image (if necessary) and populates the given UIImageView Completion handler is only called on success */ func populateViewWithImage(imageView: UIImageView, completion: (Void -> Void)? = nil) { populateViewFromURL(imageView, linkString: link, completion: completion) } /** Downloads thumbnail (if necessary) and populates the given UIImageView Completion handler is only called on success */ func populateViewWithImageThumbnail(imageView: UIImageView, completion: (Void -> Void)? = nil) { populateViewFromURL(imageView, linkString: thumbnailLink, completion: completion) } private func populateViewFromURL(imageView: UIImageView, linkString: String, completion: (Void -> Void)? = nil) { if let imageURL = NSURL(string: linkString) { let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration() let session = NSURLSession(configuration: sessionConfig) let imageDownload = session.downloadTaskWithURL(imageURL, completionHandler: { (imageLocation: NSURL?, response: NSURLResponse?, error: NSError?) in if let imageLocation = imageLocation, let imageData = NSData(contentsOfURL: imageLocation), let image = UIImage(data: imageData) { dispatch_async(dispatch_get_main_queue(), { imageView.image = image completion?() }) } else { NSLog("result/configure-cell/download/error Image Coulndn't be created") } }) imageDownload.resume() } else { NSLog("result/configure-cell/error URL Creation Failed") } } }
true
39bf01f834e6171c012cb1141d2e7ecb37c2c187
Swift
adya/TSKit
/Sources/TSKit.Core/Synchronizers/BaseQueueSynchronizer.swift
UTF-8
1,679
2.65625
3
[]
no_license
// - Since: 01/05/2022 // - Author: Arkadii Hlushchevskyi // - Copyright: © 2022. Arkadii Hlushchevskyi. // - Seealso: https://github.com/adya/TSKit.Core/blob/master/LICENSE.md import Dispatch /// Base synchronizer that other `DispatchQueue`-based synchronizer inherit. /// /// Default behavior is `NonReentrantSerialQueueSynchronizer`. public class QueueSynchronizer: AnySynchronizer { private(set) var queue: DispatchQueue! private(set) var flags: DispatchWorkItemFlags private let reentranceDetector: AnyReentranceDetector init(qos: DispatchQoS, attributes: DispatchQueue.Attributes = [], reentranceDetector: AnyReentranceDetector = NonReentrantDetector()) { self.flags = attributes.contains(.concurrent) ? .barrier : [] self.reentranceDetector = reentranceDetector self.queue = .init(label: "\(self)", qos: qos, attributes: attributes) if let detector = reentranceDetector as? AnyDispatchQueueAttachable { detector.attach(queue) } } public func read<Result>(_ block: () throws -> Result) rethrows -> Result { guard reentranceDetector.enter() else { return try block() } defer { reentranceDetector.leave() } return try queue.sync(execute: block) } @discardableResult public func syncWrite<Result>(_ block: () throws -> Result) rethrows -> Result { guard reentranceDetector.enter() else { return try block() } defer { reentranceDetector.leave() } return try queue.sync(flags: flags, execute: block) } public func write(_ block: @escaping () -> Void) { queue.async(flags: flags, execute: block) } }
true
6eb27d99f534a345ba7a2877b2ef26eed2db117a
Swift
ZacharyKhan/Top-iTunes-Albums
/Top Albums/View/AlbumTableViewCell.swift
UTF-8
3,163
2.84375
3
[]
no_license
// // AlbumTableViewCell.swift // Top Albums // // Created by Zachary Khan on 11/25/19. // Copyright © 2019 Zachary Khan. All rights reserved. // import UIKit class AlbumTableViewCell: UITableViewCell { var album : Album? { didSet { parseAlbumData(album: self.album) } } let titleLabel : UILabel = { let label = UILabel() label.text = "TITLE" label.font = .boldSystemFont(ofSize: 16) label.textColor = .black label.translatesAutoresizingMaskIntoConstraints = false return label }() let artistLabel : UILabel = { let label = UILabel() label.text = "ARTIST" label.font = .systemFont(ofSize: 14) label.textColor = .darkGray label.translatesAutoresizingMaskIntoConstraints = false return label }() let albumImageView : UIImageView = { let imageView = UIImageView() imageView.translatesAutoresizingMaskIntoConstraints = false imageView.backgroundColor = .purple imageView.layer.cornerRadius = 5 imageView.clipsToBounds = true return imageView }() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupCell() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } fileprivate func setupCell() { backgroundColor = .white addSubview(albumImageView) albumImageView.topAnchor.constraint(equalTo: topAnchor, constant: 16).isActive = true albumImageView.leftAnchor.constraint(equalTo: leftAnchor, constant: 16).isActive = true albumImageView.widthAnchor.constraint(equalTo: heightAnchor, constant: -32).isActive = true albumImageView.heightAnchor.constraint(equalTo: heightAnchor, constant: -32).isActive = true addSubview(titleLabel) titleLabel.topAnchor.constraint(equalTo: topAnchor, constant: 16).isActive = true titleLabel.leftAnchor.constraint(equalTo: albumImageView.rightAnchor, constant: 16).isActive = true titleLabel.rightAnchor.constraint(equalTo: rightAnchor, constant: -16).isActive = true titleLabel.bottomAnchor.constraint(equalTo: centerYAnchor, constant: -2).isActive = true addSubview(artistLabel) artistLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 4).isActive = true artistLabel.leftAnchor.constraint(equalTo: albumImageView.rightAnchor, constant: 16).isActive = true artistLabel.rightAnchor.constraint(equalTo: rightAnchor, constant: -16).isActive = true artistLabel.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -16).isActive = true } fileprivate func parseAlbumData(album: Album?) { guard let album = album else { return } DispatchQueue.main.async { self.titleLabel.text = album.name self.artistLabel.text = album.artist self.albumImageView.loadImage(fromUrl: album.artworkURL) } } }
true
3f1d355ff751efcf21ba501f304a5355edb70b4c
Swift
CosmosSwift/swift-cosmos
/Sources/Cosmos/Types/Invariant.swift
UTF-8
769
3.125
3
[ "Apache-2.0" ]
permissive
// An Invariant is a function which tests a particular invariant. // The invariant returns a descriptive message about what happened // and a boolean indicating whether the invariant has been broken. // The simulator will then halt and print the logs. public typealias Invariant = (_ request: Request) -> (String, Bool) // Invariants defines a group of invariants typealias Invariants = [Invariant] // expected interface for registering invariants public protocol InvariantRegistry { func registerRoute(moduleName: String, route: String, invariant: Invariant) } // FormatInvariant returns a standardized invariant message. public func formatInvariant(module: String, name: String, message: String) -> String { "\(module): \(name) invariant\n\(message)\n" }
true
f8931f2ce6b2c863be2f42fa79b2a64047c39db6
Swift
anissa-agahchen/InvasivesBC-iOS
/InvasivesBC/Form Framework/Core/Models/Validator.swift
UTF-8
1,180
3.34375
3
[ "Apache-2.0" ]
permissive
// // Validator.swift // InvasivesBC // // Created by Pushan on 2020-04-13. // Copyright © 2020 Amir Shayegh. All rights reserved. // import Foundation // Validation Result Tuple typealias ValidationResult = (success: Bool, message: String) // Validator // Validate any data with type T protocol Validator { associatedtype T func validate(data: T?) -> ValidationResult } // Generic Base Validator class BaseValidator<T>: Validator { func validate(data: T?) -> ValidationResult { return (true, "") } } // PasswordValidator: Validate password string class PasswordValidator: BaseValidator<String> { let message = "Please enter a valid password" override func validate(data: String?) -> ValidationResult { guard let value = data else { return (false, message)} return (value.count > 4, message) } } // EmailValidator: Validate email string class EmailValidator: BaseValidator<String> { let message = "Invalid email" override func validate(data: String?) -> ValidationResult { guard let value: String = data else { return (false, message) } return (value.isEmail, message) } }
true
5d65f6db7486f22923a2bde55dee5427a4628fd3
Swift
andreykuzin70/FoodDrop
/FoodDropApp/FoodDropApp/Views/LogInView.swift
UTF-8
4,209
3.015625
3
[]
no_license
// // SignInView.swift // FoodDropApp // // Created by Natnael Mekonnen on 3/17/21. // import SwiftUI struct LogInView: View { @State var username: String = "" @State var password: String = "" @Binding var goToCreateAccount: Bool @Binding var goToLogIn: Bool @Binding var goToNavMenu: Bool var body: some View { ZStack { BackgroundView() VStack { HeaderView() Spacer() Text("Log In") .font(/*@START_MENU_TOKEN@*/.title/*@END_MENU_TOKEN@*/) .bold() .padding(.bottom, 20) LogInFormView(goToCreateAccount: $goToCreateAccount, goToLogIn: $goToLogIn, goToNavMenu: $goToNavMenu).environmentObject(LogInVM()) Spacer() } } } } struct SignInView_Previews: PreviewProvider { static var previews: some View { LogInView(goToCreateAccount: .constant(false), goToLogIn: .constant(true), goToNavMenu:.constant(false)).environmentObject(LogInVM()) } } struct LogInFormView: View { @State var email: String = "" @State var password: String = "" @Binding var goToCreateAccount: Bool @Binding var goToLogIn: Bool @Binding var goToNavMenu: Bool @State var showAlert = false @EnvironmentObject var session: LogInVM // a method that listens to any change that happend the user signing func getUser () { session.listen() } //https://benmcmahen.com/authentication-with-swiftui-and-firebase/ /// // This method takes care of user signing in. if there is an error it changes the state of the alert otherwise changes the state of the view to which it next go to. This is used in the action of the login button func logIn () { session.signIn(email: email, password: password) { (result, error) in if error != nil { self.showAlert = true } else { print("Log in success") self.goToNavMenu = true self.goToLogIn = false self.goToCreateAccount = false } } } var body: some View { VStack { TextField("Email", text: $email) .padding() .background(Color.white) .cornerRadius(5.0) .padding(.bottom, 20) .frame(width: 300) .autocapitalization(/*@START_MENU_TOKEN@*/.none/*@END_MENU_TOKEN@*/) .disableAutocorrection(true) SecureField("Password", text: $password) .padding() .background(Color.white) .cornerRadius(5.0) .padding(.bottom, 20) .frame(width: 300) Button( action: { self.logIn() }, label: { Text("LOGIN") .font(.headline) .foregroundColor(.white) .padding() .frame(width: 200) .background(Color.blue) .cornerRadius(15.0) } ).alert(isPresented: $showAlert) { Alert(title: Text("Log in Error"), message: Text("Account not found or password/username not mactched "), dismissButton: .default(Text("OK"))) } Divider().frame(width:200) Button( action: { self.goToCreateAccount = true self.goToLogIn = false }, label: { Text("Create Account") .font(.headline) .foregroundColor(.white) .padding() .frame(width: 200) .background(Color.red) .cornerRadius(15.0) } ) }.onAppear(perform: getUser) } }
true
fcbf301fa7078e674a4733bb06953513213f31bf
Swift
n913239/LearnIOS
/Section20/RSSReader/RSSReader/ViewController.swift
UTF-8
4,119
2.625
3
[]
no_license
// // ViewController.swift // RSSReader // // Created by mikewang on 2017/9/18. // Copyright © 2017年 mike. All rights reserved. // import UIKit class ViewController: UIViewController { var objects = [NewsItem]() var reachability = Reachability(hostName: "www.apple.com") lazy var session = { return URLSession(configuration: .default) } () func internetOK() -> Bool { if reachability?.currentReachabilityStatus().rawValue == 0 { return false } else { return true } } func downloadXML(webAddress:String) { if internetOK() == true { // start download if let url = URL(string: webAddress) { let task = session.dataTask(with: url, completionHandler: { (data, response, error) in if error != nil { DispatchQueue.main.async { self.popAlert(withTitle: "Error", andMessage: error!.localizedDescription) } return } if let okData = data { //let x = NSString(data: okData, encoding: String.Encoding.utf8.rawValue) let parser = XMLParser(data: okData) let rssParserDelegate = RSSParserDelegate() parser.delegate = rssParserDelegate if parser.parse() == true { self.objects = rssParserDelegate.getResult() DispatchQueue.main.async { self.myTableView.reloadData() } } else { print("parser fail") } } }) task.resume() } } else { popAlert(withTitle: "No internet", andMessage: "Please try again later!") } } func popAlert(withTitle title:String, andMessage message:String) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) present(alert, animated: true, completion: nil) } @IBOutlet weak var myTableView: UITableView! override func viewDidLoad() { super.viewDidLoad() myTableView.dataSource = self myTableView.delegate = self let news1 = NewsItem(title: "first news", link: "https://www.apple.com") let news2 = NewsItem(title: "second news", link: "https://www.nike.com") let news3 = NewsItem(title: "third news", link: "https://www.udemy.com") objects.append(news1) objects.append(news2) objects.append(news3) downloadXML(webAddress: "https://www.cnet.com/rss/iphone-update/") } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "moreInfo" { if let dvc = segue.destination as? WebViewController { if let selectedRow = myTableView.indexPathForSelectedRow?.row { dvc.webAddressFromViewOne = objects[selectedRow].link } } } } } extension ViewController: UITableViewDataSource, UITableViewDelegate { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return objects.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) cell.textLabel?.text = objects[indexPath.row].title return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) } }
true
83a338165bf09db6b1be9266bb1bd0bfd8431f97
Swift
MacVit/TermostatControl
/TermostatControl/Controllers/TermostatVC.swift
UTF-8
1,719
2.671875
3
[]
no_license
// // ViewController.swift // TermostatControl // // Created by Vitalii Maksymliuk on 1/25/19. // Copyright © 2019 Vitalii Maksymliuk. All rights reserved. // import UIKit class TermostatVC: UIViewController { // MARK: - Outlets @IBOutlet weak private var weatherControlView: WeatherControlView! @IBOutlet weak private var powerSliderView: PowerSlideView! @IBOutlet weak var arcWheel: ArcView! @IBOutlet weak var temperatureView: TemperatureView! @IBOutlet weak private var weatherControlViewHeight: NSLayoutConstraint! // MARK: - Properties var temperatureAngle: CGFloat = 0 { didSet { temperatureView.lbTemperature.text = temperatureAngle.description } } // MARK: - Methods override func viewDidLoad() { super.viewDidLoad() weatherControlView.selectedButtonHanlder = { (selectedIndex) in print("Did select at \(selectedIndex)") } // let rotation = Int(UserDefaults.standard.rotation / 5) // print("Last Rotation \(rotation)") // temperatureView.lbTemperature.text = "\(-rotation)" arcWheel.changeAngleHanlder = { angle in // let range = -40...40 let modifiedAngle = (-angle.rounded() * 0.8) self.temperatureView.temperature = Int(modifiedAngle.rounded()) print(self.temperatureView.temperature) } // temperatureView.lbTemperature.text = "\(Int(UserDefaults.standard.rotation) / 3)" } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } }
true
1cb41540ed343571d169f895944c2206883ff4d3
Swift
ShahzaibSE/Learn-Swift
/mix_practice_1_switch_array_dictnry.playground/Contents.swift
UTF-8
1,188
3.796875
4
[]
no_license
//: Playground - noun: a place where people can play import Cocoa //var str = "Hello, playground" var studentList = Array<Dictionary<String, String>>() // Creating an array which contains a list of data associated with each student. var superheroInfo: Dictionary<String,String> = ["name":"Batman", "secretIndentity":"Bruce Wayne", "age":"28"] studentList = [["name": "Shahzaib", "age": "23", "country" : "Saudia Arabia"], ["name" : "Shaheen", "age" :"25", "country": "Egypt"], ["name" : "Shaheen", "age" :"30", "country": "Egypt"]] for student in studentList { for (key, value) in student { print("\(key) : \(value)") } print(); } // some more switch snippet. var hero: Dictionary<String,String> = ["name": "Batman", "real_name" : "Bruce Wayne", "alias" : "Gotham City"] print("Get your superhero") switch hero["alias"]{ case "Batman", "The Cape Crusader", "Gotham City" : print("The Dark Knight") fallthrough case "The Cape Crusader": print("Gotham's guardian") case "Gotham City": print("The Batman") //case 1...10: // This throws error // print("The Trinity") default: print("Superhero not found") } var arr: [Any] = ["34",1]
true
0236d1f632f8caac10f0c2efa882ae4b38ef50b4
Swift
ChungMai/DesignPatterns
/FlyweightPattern/FlyweightPatternTests/FlyweightRectFactory.swift
UTF-8
1,506
3.0625
3
[]
no_license
// // FlyweightRectFactory.swift // FlyweightPattern // // Created by Home on 9/17/16. // Copyright © 2016 Home. All rights reserved. // import Foundation import SpriteKit class FlyweightRectFactory{ internal static var rectsMap = Dictionary<SKColor,FlyweightRect>() internal static var rectsMapNS = NSMutableDictionary() internal static var rectsMapNSC = NSCache() static func getFlyweightRect(color:SKColor) -> FlyweightRect{ if let result = rectsMap[color]{ return result } else{ let result = FlyweightRect(color:color) rectsMap[color] = result return result } } static func getFlyweightRectWithNS(color:SKColor) -> FlyweightRect{ let result = rectsMapNS[color.description] if result == nil{ let flyweight = FlyweightRect(color:color) rectsMapNS.setValue(flyweight, forKeyPath: color.description) return flyweight as FlyweightRect }else { return result as! FlyweightRect } } static func getFlyweightRectWithNSc(color: SKColor) -> FlyweightRect{ let result = rectsMapNSC.objectForKey(color.description) if result == nil { let flyweight = FlyweightRect(color: color) rectsMapNSC.setObject(flyweight, forKey:color.description) return flyweight as FlyweightRect }else { return result as! FlyweightRect } } }
true
14490411dbe13f32a88091911165b003d9aaf4e0
Swift
tache/MondoPlayerView
/MondoPlayerTest/ViewController.swift
UTF-8
1,187
2.578125
3
[ "MIT" ]
permissive
// // ViewController.swift // MondoPlayerTest // // Created by Christopher Graham on 7/25/15. // Copyright (c) 2015 MoltenViper. All rights reserved. // import UIKit import MondoPlayerView class ViewController: UIViewController { @IBOutlet weak var mondoPlayer: MondoPlayer! override func viewDidLoad() { super.viewDidLoad() setupStationPlayer(); } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidAppear(_ animated: Bool) { // start playing a stream mondoPlayer.play() } func setupStationPlayer() { mondoPlayer.delegate = self mondoPlayer.URL = URL(string:"https://yp.shoutcast.com/sbin/tunein-station.m3u?id=1516098") } } extension ViewController: MondoPlayerDelegate { func mondoPlayer(_ mondoPlayer: MondoPlayer, changedState: MondoPlayerState) { print("player changed state: \(changedState)") } func mondoPlayer(_ mondoPlayer: MondoPlayer, encounteredError: NSError) { print("player error: " + encounteredError.localizedDescription) } }
true
d04e6c769b91657fabf628c04a81e18ba1bb8fe1
Swift
shandysulen/UINotificationsDependencyProject
/CocoaPodProject/NotificationViewController.swift
UTF-8
1,491
2.921875
3
[]
no_license
// // NotificationViewController.swift // CocoaPodProject // // Created by Shandy Sulen on 7/20/17. // Copyright © 2017 Shandy Sulen. All rights reserved. // import UIKit import UINotifications class NotificationView: UINotificationView { enum CustomNotificationStyle: UINotificationStyle { case success case failure var font: UIFont { switch self { case .success: return UIFont.systemFont(ofSize: 20, weight: UIFontWeightSemibold) case .failure: return UIFont.systemFont(ofSize: 13, weight: UIFontWeightRegular) } } var backgroundColor: UIColor { switch self { case .success: return UIColor.blue case .failure: return UIColor.red } } var textColor: UIColor { return UIColor.white } /// The height of the notification which applies on the notification view. var height: UINotificationHeight { switch self { case .success: return UINotificationHeight.custom(height: CGFloat(100)) case .failure: return UINotificationHeight.statusBar } } /// When `true`, the notification is swipeable and tappable. var interactive: Bool { return true } } }
true
a3c377b3cb82ca17e04dd7d6d4568c135220e695
Swift
loveq369/reform-swift
/ReformMath/ReformMath/Relations.swift
UTF-8
411
2.90625
3
[ "LicenseRef-scancode-warranty-disclaimer", "MIT" ]
permissive
// // Relations.swift // ReformMath // // Created by Laszlo Korte on 15.08.15. // Copyright © 2015 Laszlo Korte. All rights reserved. // func sign(_ p: Vec2d, a: Vec2d, b: Vec2d) -> Double { return (p.x - b.x) * (a.y - b.y) - (a.x - b.x) * (p.y - b.y) } public func leftOf(_ point: Vec2d, line: Line2d, epsilon: Double = 0) -> Bool { return sign(point, a:line.from, b:line.from + line.direction) < epsilon }
true
a871350094f76f5542b23af58e36a2a69a2eaa22
Swift
cstuart08/Zo
/ZoApp/ZoApp/Models/Response.swift
UTF-8
4,794
2.703125
3
[ "MIT" ]
permissive
// // Response.swift // ZōApp // // Created by The Zō Team on 10/2/19. // Copyright © 2019 Zō App. All rights reserved. // import AVKit import CloudKit struct ResponseConstants { static let responseKey = "response" static let usernameKey = "username" static let bodyTextKey = "bodyText" static let imageAssetKey = "imageAsset" static let linkKey = "link" static let timestampKey = "timestamp" static let isFavoriteKey = "isFavorite" static let responseTagsKey = "responseTags" static let responseRecordIDKey = "responseRecordID" static let requestReferenceKey = "requestReference" } class Response { var username: String var bodyText: String? var link: String? var timestamp: Double var isFavorite = false var responseTags: [String] var responseRecordID: CKRecord.ID var requestReference: CKRecord.Reference var imageData: Data? var image: UIImage? { get { guard let imageData = self.imageData else { return nil } return UIImage(data: imageData) } set { self.imageData = newValue?.jpegData(compressionQuality: 0.5) } } var imageCkAsset: CKAsset? { get { let tempDirectory = NSTemporaryDirectory() let tempDirectoryURL = URL(fileURLWithPath: tempDirectory) let fileURL = tempDirectoryURL.appendingPathComponent(UUID().uuidString).appendingPathExtension("jpg") do { try imageData?.write(to: fileURL) } catch { print("Error in \(#function) : \(error.localizedDescription) \n---\n \(error)") } return CKAsset(fileURL: fileURL) } } init(username: String, bodyText: String?, image: UIImage?, link: String?, timestamp: Double = Date().timeIntervalSince1970, responseTags: [String], responseRecordID: CKRecord.ID = CKRecord.ID(recordName: UUID().uuidString), requestReference: CKRecord.Reference) { self.username = username self.bodyText = bodyText self.link = link self.timestamp = timestamp self.responseTags = responseTags self.responseRecordID = responseRecordID self.requestReference = requestReference self.image = image } // Pulling from CloudKit init?(ckRecord: CKRecord) { guard let username = ckRecord[ResponseConstants.usernameKey] as? String, let bodyText = ckRecord[ResponseConstants.bodyTextKey] as String?, let link = ckRecord[ResponseConstants.linkKey] as? String?, let timestamp = ckRecord[ResponseConstants.timestampKey] as? Double, let isFavorite = ckRecord[ResponseConstants.isFavoriteKey] as? Bool, let responseTags = ckRecord[ResponseConstants.responseTagsKey] as? [String], let requestReference = ckRecord[ResponseConstants.requestReferenceKey] as? CKRecord.Reference else { return nil } let imageCkAsset = ckRecord[ResponseConstants.imageAssetKey] as? CKAsset self.username = username self.bodyText = bodyText self.link = link self.timestamp = timestamp self.isFavorite = isFavorite self.responseTags = responseTags self.responseRecordID = ckRecord.recordID self.requestReference = requestReference //guard let url = imageCkAsset.fileURL else { return } if let url = imageCkAsset?.fileURL { do { self.imageData = try Data(contentsOf: url) } catch { print("Error in \(#function) : \(error.localizedDescription) \n---\n \(error)") } } } } // Pushing to CloudKit extension CKRecord { convenience init(response: Response) { self.init(recordType: ResponseConstants.responseKey, recordID: response.responseRecordID) self.setValue(response.username, forKey: ResponseConstants.usernameKey) self.setValue(response.bodyText, forKey: ResponseConstants.bodyTextKey) if response.image != nil { self.setValue(response.imageCkAsset, forKey: ResponseConstants.imageAssetKey) } self.setValue(response.link, forKey: ResponseConstants.linkKey) self.setValue(response.timestamp, forKey: ResponseConstants.timestampKey) self.setValue(response.isFavorite, forKey: ResponseConstants.isFavoriteKey) self.setValue(response.responseTags, forKey: ResponseConstants.responseTagsKey) self.setValue(response.requestReference, forKey: ResponseConstants.requestReferenceKey) } } extension Response: Equatable { static func == (lhs: Response, rhs: Response) -> Bool { return lhs.username == rhs.username } }
true
fa8a922f632715dde2359dd04fd65637412727ef
Swift
Gc0066/introToSwift
/listMaker/Lister.swift
UTF-8
2,506
3.609375
4
[]
no_license
// // Lister.swift // listMaker // // Created by George Coleman on 18/10/2018. // Copyright © 2018 George Coleman. All rights reserved. // import Foundation enum ListError: Error { case emptyString case duplicateItem case outOfRange(invalidIndex: Int) } /** Class to maintain shopping lists. - Author: George Coleman - Copyright: Coventry University 2018 - Requires: iOS 10 */ public class Lister { var items: [String] var increment: Int //turns the lister class into a singleton. /** The first time this is accessed it instantiates an instance of the Lister class. On subsequent access it returns a pointer to the same object. */ public static let sharedInstance = Lister() private init() { self.items = [] self.increment = 0 } /* init() { self.items = [] self.increment = 0 }*/ public func add(item: String) { self.items.append(item) } public func getItem(index: Int) throws -> String { if (index < 0 || index > (self.count-1)) { throw ListError.outOfRange(invalidIndex: index) } return self.items[index] } public var count:Int { get { return self.items.count } } public var counter:Int { get { return self.increment } set(check) { self.increment = check } } /** Clears the list of all items within it. ``` let lister = Lister() let item = lister.clearList() ``` */ public func clearList() { self.items.removeAll() } /** inserts a new item at a specific element within the list of items. ``` let lister = Lister() let item = lister.insert(newElement: "Bread", at: 2) ``` - Parameter newElement: the new item to insert. - Parameter at: The index to insert the item into. */ public func insert(newElement: String, at:Int) { } public func remove(at: Int) throws { } public func moveItem(fromindex: Int, toIndex: Int) { } public func printTemp() { let temperature = 70 switch temperature { case 65...75: print("The temperature is just right") case Int.min...64: print("temperature too cold") default: print("the temperature is too hot") } } }
true
31d7bb65aba61a5f50f10bf3a4238fbb7eceaea9
Swift
billymeltdown/cocoafob
/swift/CocoaFob/CocoaFobLicVerifier.swift
UTF-8
3,760
2.53125
3
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
// // CocoaFobLicVerifier.swift // CocoaFob // // Created by Gleb Dolgich on 12/07/2015. // Copyright © 2015 PixelEspresso. All rights reserved. // import Foundation /** Verifies CocoaFob registration keys */ public struct CocoaFobLicVerifier { var pubKey: SecKeyRef // MARK: - Initialization /** Initializes key verifier with a public key in PEM format - parameter publicKeyPEM: String containing PEM representation of the public key */ public init?(publicKeyPEM: String) { let emptyString = "" as NSString let password = Unmanaged.passUnretained(emptyString as AnyObject) var params = SecItemImportExportKeyParameters( version: UInt32(bitPattern: SEC_KEY_IMPORT_EXPORT_PARAMS_VERSION), flags: SecKeyImportExportFlags.ImportOnlyOne, passphrase: password, alertTitle: Unmanaged.passUnretained(emptyString), alertPrompt: Unmanaged.passUnretained(emptyString), accessRef: nil, keyUsage: nil, keyAttributes: nil) var keyFormat = SecExternalFormat.FormatPEMSequence var keyType = SecExternalItemType.ItemTypePublicKey if let keyData = publicKeyPEM.dataUsingEncoding(NSUTF8StringEncoding) { let keyBytes = unsafeBitCast(keyData.bytes, UnsafePointer<UInt8>.self) let keyDataCF = CFDataCreate(nil, keyBytes, keyData.length)! var importArray: CFArray? = nil let osStatus = withUnsafeMutablePointers(&keyFormat, &keyType) { (pKeyFormat, pKeyType) -> OSStatus in SecItemImport(keyDataCF, nil, pKeyFormat, pKeyType, SecItemImportExportFlags(rawValue: 0), &params, nil, &importArray) } if osStatus != errSecSuccess || importArray == nil { return nil } let items = importArray! as NSArray if items.count >= 1 { self.pubKey = items[0] as! SecKeyRef } else { return nil } } else { return nil } } /** Verifies registration key against registered name. Doesn't throw since you are most likely not interested in the reason registration verification failed. - parameter regKey: Registration key string - parameter name: Registered name string - returns: `true` if the registration key is valid for the given name, `false` if not */ public func verify(regKey: String, forName name: String) -> Bool { do { if let keyData = regKey.cocoaFobFromReadableKey().dataUsingEncoding(NSUTF8StringEncoding), nameData = name.dataUsingEncoding(NSUTF8StringEncoding) { let decoder = try getDecoder(keyData) let signature = try cfTry(.Error) { SecTransformExecute(decoder, $0) } let verifier = try getVerifier(self.pubKey, signature: signature as! NSData, nameData: nameData) let result = try cfTry(.Error) { SecTransformExecute(verifier, $0) } let boolResult = result as! CFBooleanRef return Bool(boolResult) } else { return false } } catch { return false } } // MARK: - Helper functions private func getDecoder(keyData: NSData) throws -> SecTransform { let decoder = try cfTry(.Error) { return SecDecodeTransformCreate(kSecBase32Encoding, $0) } try cfTry(.Error) { return SecTransformSetAttribute(decoder, kSecTransformInputAttributeName, keyData, $0) } return decoder } private func getVerifier(publicKey: SecKeyRef, signature: NSData, nameData: NSData) throws -> SecTransform { let verifier = try cfTry(.Error) { return SecVerifyTransformCreate(publicKey, signature, $0) } try cfTry(.Error) { return SecTransformSetAttribute(verifier, kSecTransformInputAttributeName, nameData, $0) } try cfTry(.Error) { return SecTransformSetAttribute(verifier, kSecDigestTypeAttribute, kSecDigestSHA1, $0) } return verifier } }
true
c89836f4cef291cca4505a97a2067d0f1be668b4
Swift
justMaku/tejlor
/Sources/Gateway.swift
UTF-8
1,477
3.34375
3
[]
no_license
// // Gateway.swift // Taylor // // Created by Michał Kałużny on 10/04/2017. // // import Foundation protocol Server {} struct User { let UUID: String } struct Channel { let UUID: String } enum Context { case channel(channel: Channel) case user(user: User) var uuid: String { switch self { case .channel(let channel): return channel.UUID case .user(let user): return user.UUID } } } protocol GatewayDelegate { func gateway(_ gateway: Gateway, joinedServer server: Server) func gateway(_ gateway: Gateway, leftServer server: Server) func gateway(_ gateway: Gateway, joinedChannel channel: Channel) func gateway(_ gateway: Gateway, leftChannel channel: Channel) func gateway(_ gateway: Gateway, receivedMessage message: String, context: Context) } enum GatewayState { case disconnected case connecting case connected } protocol Gateway { var state: GatewayState { get } var delegate: GatewayDelegate? { get set } func connect() throws func disconnect() func join(_ channel: Channel) func send(_ message: String, to context: Context) } extension Gateway { var connected: Bool { return state == .connected } func send(_ message: String, to channel: Channel) { send(message, to: .channel(channel: channel)) } func send(_ message: String, to user: User) { send(message, to: .user(user: user)) } }
true
8b8bc98918e00198e2ed9f33850d6bad9873da7e
Swift
astannard/LemonadeStand
/LemonadeStand/Customer.swift
UTF-8
559
2.96875
3
[]
no_license
// // Customer.swift // LemonadeStand // // Created by Andy on 15/01/2015. // Copyright (c) 2015 Andy Stannard. All rights reserved. // import Foundation class Customer{ init(){ var random = arc4random_uniform(10) taste = Double(random) / 10.0 } var taste:Double = 0.0 func preference() -> String { if(taste <= 0.4){ return "acidic" } else if(taste <= 0.6) { return "neutral" } else { return "weak" } } }
true
4e87b198f749eb14335c3f7feafdb7d2854580cc
Swift
net-a-porter-mobile/XCTest-Gherkin
/Example/XCTest-Gherkin_ExampleUITests/StepDefinitions/UITestStepDefinitions.swift
UTF-8
2,318
2.671875
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// // UITestStepDefinitions.swift // XCTest-Gherkin // // Created by Sam Dean on 6/3/16. // Copyright © 2016 CocoaPods. All rights reserved. // import Foundation import XCTest import XCTest_Gherkin final class UIStepDefiner: StepDefiner { override func defineSteps() { step("I have launched the app") { XCUIApplication().launch() } step("I tap the (.*) button") { (matches: [String]) in XCTAssert(matches.count > 0, "Should have been a match") let identifier = matches.first! XCUIApplication().buttons[identifier].firstMatch.tap() } } } final class InitialScreenStepDefiner: StepDefiner { override func defineSteps() { step("I press Push Me button") { InitialScreenPageObject().pressPushMe() } } } final class InitialScreenPageObject: PageObject { private let app = XCUIApplication() class override var name: String { return "Initial Screen" } override func isPresented() -> Bool { return tryWaitFor(element: app.buttons["PushMe"].firstMatch, withState: .exists) } func pressPushMe() { app.buttons["PushMe"].firstMatch.tap() } } final class ModalScreenStepDefiner: StepDefiner { override func defineSteps() { step("I press Close Me button") { ModalScreen().pressCloseMe() } } } final class ModalScreen: PageObject { private let app = XCUIApplication() override func isPresented() -> Bool { return tryWaitFor(element: app.buttons["CloseMe"].firstMatch, withState: .exists) } func pressCloseMe() { app.buttons["CloseMe"].firstMatch.tap() } } extension PageObject { func tryWaitFor(element: XCUIElement, withState state: String, waiting timeout: TimeInterval = 5.0) -> Bool { let predicate = NSPredicate(format: state) guard predicate.evaluate(with: element) == false else { return true } let expectation = XCTNSPredicateExpectation(predicate: predicate, object: element) let result = XCTWaiter().wait(for: [expectation], timeout: timeout) == .completed return result } } extension String { fileprivate static let exists = "exists == true" }
true
55ca344f958069eaf25c9ad76d6779aac3a3b943
Swift
roblkenn/Time2Budget-iOS
/Time to Budget/Time to Budget/TaskEditorTimePickerViewController.swift
UTF-8
5,057
2.671875
3
[ "MIT" ]
permissive
// // TaskEditorTimePickerViewController.swift // Time to Budget // // Created by Robert Kennedy on 3/1/15. // Copyright (c) 2015 Arrken Games, LLC. All rights reserved. // import UIKit class TaskEditorTimePickerViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate { // ========== View Properties ========== var timePicked: Time = Time() var taskEditorVC: TaskEditorViewController! @IBOutlet weak var doneButton: UIButton! @IBOutlet weak var colonLabel: UILabel! // ========== Time Picker Properties ========== @IBOutlet weak var timePicker: UIPickerView! var timeHourPickerData: [Int] = Factory.prepareTimeHourPickerData() var timeMinutePickerData: [Int] = Factory.prepareTimeMinutePickerData() // ==================== View Controller Methods ==================== override func viewDidLoad() { super.viewDidLoad() // Apply the Time to Budget theme to this view. Style.viewController(self) Style.button(self.doneButton) Style.label(colonLabel) // Apply previous time if any to the UIPicker. if let unwrappedTime = taskEditorVC.taskTime { timePicked = Time(newTime: unwrappedTime) } else { timePicked.hours = 0 timePicked.minutes = 0 } // Update UIPicker to reflect above changes. timePicker.selectRow(getHourIndex(), inComponent: 0, animated: true) timePicker.selectRow(getMinIndex(), inComponent: 1, animated: true) } override func viewDidLayoutSubviews() { labelForHours() labelForMinutes() } // ==================== UIPickerDataSource Methods ==================== func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 2 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { if component == 0 { return timeHourPickerData.count } else { return timeMinutePickerData.count } } //==================== UIPickerDelegate Methods ==================== func pickerView(pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? { if component == 0 { return Style.picker(timeHourPickerData[row]) } else { return Style.picker(timeMinutePickerData[row]) } } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { if component == 0 { timePicked.hours = timeHourPickerData[row] } else { timePicked.minutes = timeMinutePickerData[row] } } //==================== IBAction Methods ==================== @IBAction func doneButtonPressed(sender: UIButton) { taskEditorVC.taskTime = self.timePicked.toDouble() self.navigationController?.popViewControllerAnimated(true) } //==================== Helper Methods ==================== /** Returns the integer index for the currently selected hour based on the self.timePicked.hours property. - Parameter None: - returns: Int index for the currently selected hour. */ func getHourIndex() -> Int { return timePicked.hours } /** Returns the integer index for the currently selected minutes based on the seld.timePicked.minutes property. - Parameter None: - returns: Int index for the currently selected minutes. */ func getMinIndex() -> Int { if timePicked.minutes == 15 { return 1 } else if timePicked.minutes == 30 { return 2 } else if timePicked.minutes == 45 { return 3 } else { return 0 } } func labelForHours() { let lblText = "Hours" let lblWidth = self.timePicker.frame.size.width / CGFloat(self.timePicker.numberOfComponents) let lblXPos = self.timePicker.frame.origin.x let lblYPos = self.timePicker.frame.origin.y let hrsLabel = UILabel() hrsLabel.frame = CGRect(x: lblXPos, y: lblYPos, width: lblWidth, height: 20) hrsLabel.text = lblText hrsLabel.textAlignment = NSTextAlignment.Center Style.label(hrsLabel) self.view.addSubview(hrsLabel) } func labelForMinutes() { let lblText = "Minutes" let lblWidth = self.timePicker.frame.size.width / CGFloat(self.timePicker.numberOfComponents) let lblXPos = self.timePicker.frame.origin.x + lblWidth let lblYPos = self.timePicker.frame.origin.y let minsLabel = UILabel(frame: CGRect(x: lblXPos, y: lblYPos, width: lblWidth, height: 20)) minsLabel.text = lblText minsLabel.textAlignment = NSTextAlignment.Center Style.label(minsLabel) self.view.addSubview(minsLabel) } }
true
6dd25338cf6d375f64e9cd6c8c421fe4ea4f5ab4
Swift
andresfguzman/connectFourApp
/ConnectFourApp/Core/Entities/Player.swift
UTF-8
483
2.78125
3
[]
no_license
// // Player.swift // ConnectFourApp // // Created by Andrés Guzmán on 2/12/19. // Copyright © 2019 Andres Felipe Guzman Lopez. All rights reserved. // import Foundation import UIKit protocol Player { var id: Int {get set} var name: String {get set} var color: UIColor {get set} var moves: Int {get set} var didWin: Bool {get set} } struct RawPlayer: Player { var moves: Int var id: Int var name: String var color: UIColor var didWin: Bool }
true
95d21f2f9daf3ff2cea281a3e5844bfe676ed389
Swift
CourtlandBueno/SwiftSoupFork
/Sources/SwiftSoup/Selector.swift
UTF-8
11,163
3.609375
4
[ "MIT" ]
permissive
// // Selector.swift // SwiftSoup // // Created by Nabil Chatbi on 21/10/16. // Copyright © 2016 Nabil Chatbi.. All rights reserved. // import Foundation /** CSS-like element selector, that finds elements matching a query. # Selector syntax A selector is a chain of simple selectors, separated by combinators. Selectors are **case insensitive** (including against elements, attributes, and attribute values). The universal selector (*) is implicit when no element selector is supplied (i.e. {@code *.header} and {@code .header} is equivalent). # Pattern - ## Matches - ### Example - `*` - any element - `*` - `tag` - elements with the given tag name - `div` - `*|E` - elements of type E in any namespace *ns* - `*|name` finds `<fb:name>` elements - `ns|E` - elements of type E in the namespace *ns* - `fb|name` finds `<fb:name>` elements - `#id` - elements with attribute ID of "id" - `div#wrap`, `#logo` - `.class` - elements with a class name of "class" - `div.left`, `.result` - `[attr]` - elements with an attribute named "attr" (with any value) - `a[href]`, `[title]` - `[^attrPrefix]` - elements with an attribute name starting with "attrPrefix". Use to find elements with HTML5 datasets - `[^data-]`, `div[^data-]` - `[attr=val]` - elements with an attribute named "attr", and value equal to "val" - `img[width=500]`, `a[rel=nofollow]` - `[attr="val"]` - elements with an attribute named "attr", and value equal to "val" - `span[hello="Cleveland"][goodbye="Columbus"]`, `a[rel="nofollow"]` - `[attr^=valPrefix]` - elements with an attribute named "attr", and value starting with "valPrefix" - `a[href^=http:]` - `[attr$=valSuffix]` - elements with an attribute named "attr", and value ending with "valSuffix" - `img[src$=.png]` - `[attr*=valContaining]` - elements with an attribute named "attr", and value containing "valContaining" - `a[href*=/search/]` - `[attr~=regex]` - elements with an attribute named "attr", and value matching the regular expression - `img[src~=(?i)\\.(png|jpe?g)]` - - The above may be combined in any order - `div.header[title]` ## Combinators - `E F` - an F element descended from an E element - `div a`, `.logo h1` - `E {@literal >} F` - an F direct child of E - `ol {@literal >} li` - `E + F` - an F element immediately preceded by sibling E - `li + li`, `div.head + div` - `E ~ F` - an F element preceded by sibling E - `h1 ~ p` - `E, F, G` - all matching elements E, F, or G - `a[href], div, h3` ## Pseudo selectors - `:lt(n)` - elements whose sibling index is less than n - `td:lt(3)` finds the first 3 cells of each row - `:gt(n)` - elements whose sibling index is greater than n - `td:gt(1)` finds cells after skipping the first two - `:eq(n)` - elements whose sibling index is equal to n - `td:eq(0)` finds the first cell of each row - `:has(selector)` - elements that contains at least one element matching the selector - `div:has(p)` finds divs that contain p elements - `:not(selector)` - elements that do not match the selector. See also {@link Elements#not(String)} - `div:not(.logo)` finds all divs that do not have the "logo" class.`div:not(:has(div))` finds divs that do not contain divs. - `:contains(text)` - elements that contains the specified text. The search is case insensitive. The text may appear in the found element, or any of its descendants. - `p:contains(jsoup)` finds p elements containing the text "jsoup". - `:matches(regex)` - elements whose text matches the specified regular expression. The text may appear in the found element, or any of its descendants. - `td:matches(\\d+)` finds table cells containing digits. `div:matches((?i)login)` finds divs containing the text, case insensitively. - `:containsOwn(text)` - elements that directly contain the specified text. The search is case insensitive. The text must appear in the found element, not any of its descendants. - `p:containsOwn(jsoup)` finds p elements with own text "jsoup". - `:matchesOwn(regex)` - elements whose own text matches the specified regular expression. The text must appear in the found element, not any of its descendants. - `td:matchesOwn(\\d+)` finds table cells directly containing digits. `div:matchesOwn((?i)login)` finds divs containing the text, case insensitively. - - The above may be combined in any order and with other selectors - `.light:contains(name):eq(0)` ## Structural pseudo selectors - `:root` - The element that is the root of the document. In HTML, this is the `html` element - `:root` - `:nth-child(an+b)` - elements that have `an+b-1` siblings **before** it in the document tree, for any positive integer or zero value of `n`, and has a parent element. For values of `a` and `b` greater than zero, this effectively divides the element's children into groups of a elements (the last group taking the remainder), and selecting the bth element of each group. For example, this allows the selectors to address every other row in a table, and could be used to alternate the color of paragraph text in a cycle of four. The `a` and `b` values must be integers (positive, negative, or zero). The index of the first child of an element is 1. In addition to this, `:nth-child()` can take `odd` and `even` as arguments instead. `odd` has the same signification as `2n+1`, and `even` has the same signification as `2n`. - `tr:nth-child(2n+1)` finds every odd row of a table. `:nth-child(10n-1)` the 9th, 19th, 29th, etc, element. `li:nth-child(5)` the 5h li - `:nth-last-child(an+b)` - elements that have `an+b-1` siblings **after** it in the document tree. Otherwise like `:nth-child()` - `tr:nth-last-child(-n+2)` the last two rows of a table - `:nth-of-type(an+b)` - pseudo-class notation represents an element that has `an+b-1` siblings with the same expanded element name before it in the document tree, for any zero or positive integer value of n, and has a parent element - `img:nth-of-type(2n+1)` - `:nth-last-of-type(an+b)` - pseudo-class notation represents an element that has `an+b-1` siblings with the same expanded element name after it in the document tree, for any zero or positive integer value of n, and has a parent element - `img:nth-last-of-type(2n+1)` - `:first-child` - elements that are the first child of some other element. - `div {@literal >} p:first-child` - `:last-child` - elements that are the last child of some other element. - `ol {@literal >} li:last-child` - `:first-of-type` - elements that are the first sibling of its type in the list of children of its parent element - `dl dt:first-of-type` - `:last-of-type` - elements that are the last sibling of its type in the list of children of its parent element - `tr {@literal >} td:last-of-type` - `:only-child` - elements that have a parent element and whose parent element hasve no other element children - `:only-of-type` - an element that has a parent element and whose parent element has no other element children with the same expanded element name - `:empty` - elements that have no children at all */ open class Selector { private let evaluator: Evaluator private let root: Element private init(_ query: String, _ root: Element)throws { let query = query.trim() try Validate.notEmpty(string: query) self.evaluator = try QueryParser.parse(query) self.root = root } private init(_ evaluator: Evaluator, _ root: Element) { self.evaluator = evaluator self.root = root } static func initResult(_ query: String, _ root: Element) -> Result<Selector, Swift.Error> { return .init { try Selector.init(query, root) } } /** * Find elements matching selector. * * - Parameter query: CSS selector * - Parameter root: root element to descend into * - Returns: matching elements, empty if none * @throws Selector.SelectorParseException (unchecked) on an invalid CSS query. */ public static func select(_ query: String, _ root: Element)throws->Elements { return try Selector(query, root).select() } public static func selectResult(_ query: String, _ root: Element) -> Result<Elements,Swift.Error> { let _initResult = initResult(query, root) return _initResult.flatMap { (selector) in return .init(catching: {try selector.select()}) } } /** * Find elements matching selector. * * - Parameter evaluator: CSS selector * - Parameter root: root element to descend into * - Returns: matching elements, empty if none */ public static func select(_ evaluator: Evaluator, _ root: Element)throws->Elements { return try Selector(evaluator, root).select() } public static func selectResult(_ evaluator: Evaluator, _ root: Element) -> Result<Elements, Swift.Error> { return .init(catching: {try Selector(evaluator, root).select() }) } /** * Find elements matching selector. * * - Parameter query: CSS selector * - Parameter roots: root elements to descend into * - Returns: matching elements, empty if none */ public static func select(_ query: String, _ roots: Array<Element>)throws->Elements { try Validate.notEmpty(string: query) let evaluator: Evaluator = try QueryParser.parse(query) var elements: Array<Element> = Array<Element>() var seenElements: Array<Element> = Array<Element>() // dedupe elements by identity, not equality for root: Element in roots { let found: Elements = try select(evaluator, root) for el: Element in found.array() { if (!seenElements.contains(el)) { elements.append(el) seenElements.append(el) } } } return Elements(elements) } private func select()throws->Elements { return try Collector.collect(evaluator, root) } private var selectResult: Result<Elements,Swift.Error> { return .init(catching: Selector.select(self)) } // exclude set. package open so that Elements can implement .not() selector. static func filterOut(_ elements: Array<Element>, _ outs: Array<Element>) -> Elements { let output: Elements = Elements() for el: Element in elements { var found: Bool = false for out: Element in outs { if (el.equals(out)) { found = true break } } if (!found) { output.add(el) } } return output } }
true
3458d0d87cae0c4c2d2eea551a4b83fb59b2be28
Swift
adityashri16/TascDemoShoppingApp
/TASCShopping/ViewController/ReceiptViewController.swift
UTF-8
2,246
2.90625
3
[]
no_license
// // ReceiptViewController.swift // TASCShopping // // Created by impadmin on 12/7/18. // Copyright © 2018 impadmin. All rights reserved. // import UIKit //This is a simple controller class to display the receipt calculated from the cart class ReceiptViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var receiptTable: UITableView! var receipt:Receipt? // MARK: -View methods override func viewDidLoad() { super.viewDidLoad() self.title = "Receipt" self.receipt = ReceiptService().calculateReceipt() self.receiptTable.register(UITableViewCell.self, forCellReuseIdentifier: "cellIdentifier") self.receiptTable.reloadData() } // MARK: -Table View func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard let items = self.receipt?.items else { return 0 } return items.count + 2 // adding two more rows to show total amount and total tax } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = self.receiptTable.dequeueReusableCell(withIdentifier: "cellIdentifier")else { return UITableViewCell(style: .default, reuseIdentifier: "cellIdentifier") } if let receiptObj = self.receipt{ if let items = receiptObj.items{ if(indexPath.row == items.count + 1){ // show total amount at last row cell.textLabel?.text = "Total: " + receiptObj.grandTotal.toPriceDisplayString() } else if (indexPath.row == items.count){ // show total sales tax for 2nd last row cell.textLabel?.text = "Sales Tax: " + receiptObj.totalTaxes.toPriceDisplayString() } else{ //show receipt item cell.textLabel?.numberOfLines = 3 cell.textLabel?.lineBreakMode = .byWordWrapping cell.textLabel?.text = items[indexPath.row].itemName } } } return cell } }
true
14e20c11ec60442b633f5ee18c96a73867360fca
Swift
cpabbathi/CodingChallenges
/Cracking the Coding Interview/5.1 Insertion.playground/Contents.swift
UTF-8
462
3.09375
3
[]
no_license
import Foundation func insertMintoN(n: Int, m: Int, i: Int, j: Int) -> Int { var mask = -1 mask <<= (j + 1) let rightMask = (1 << i) - 1 mask |= rightMask let n = n & mask let m = m << i return m | n } String(insertMintoN(n: Int("10000000000", radix: 2)!, m: Int("10011", radix: 2)!, i: 2, j: 6), radix: 2) String(insertMintoN(n: Int("11111111111", radix: 2)!, m: Int("10011", radix: 2)!, i: 2, j: 6), radix: 2)
true
198d5e56013095f61b0294b485108490346e22fd
Swift
jackiethind/DojoAssignments
/iOS/TTT/TTT/ViewController.swift
UTF-8
2,651
2.734375
3
[]
no_license
// // ViewController.swift // TTT // // Created by Jackie Thind on 3/8/17. // Copyright © 2017 Jackie Thind. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var blockOne: UIButton! @IBOutlet weak var blockTwo: UIButton! @IBOutlet weak var blockThree: UIButton! @IBOutlet weak var blockFour: UIButton! @IBOutlet weak var blockFive: UIButton! @IBOutlet weak var blockSix: UIButton! @IBOutlet weak var blockSeven: UIButton! @IBOutlet weak var blockEight: UIButton! @IBOutlet weak var blockNine: UIButton! @IBOutlet weak var winLabel: UILabel! var activePlayer = 1 // red var gameState = [0,0,0,0,0,0,0,0,0] var redPlayer: [Int] = [] var bluePlayer: [Int] = [] let winningCombinations = [[1,2,3], [4,5,6], [7,8,9], [3,6,9], [2,5,8], [1,4,7], [7,5,3], [1,5,9]] // let winningCombo1 = [1,2,3] // let winningCombo2 = [4,5,6] // let winningCombo3 = [7,8,9] // let winningCombo4 = [3,6,9] // let winningCombo5 = [2,5,8] // let winningCombo6 = [1,4,7] // let winningCombo7 = [7,5,3] // let winningCombo8 = [1,5,9] // @IBAction func buttonPressed(_ sender: UIButton) { if gameState[sender.tag-1] == 0 { gameState[sender.tag-1] = activePlayer if (activePlayer == 1) { sender.backgroundColor = UIColor.red redPlayer.append(sender.tag) print("Red player chose \(redPlayer)") activePlayer = 2 } else { sender.backgroundColor = UIColor.blue bluePlayer.append(sender.tag) print("Blue player chose \(bluePlayer)") activePlayer = 1 } } print(winningCombinations[0][0]) } @IBAction func resetButton(_ sender: UIButton) { blockOne.backgroundColor = UIColor.gray blockTwo.backgroundColor = UIColor.gray blockThree.backgroundColor = UIColor.gray blockFour.backgroundColor = UIColor.gray blockFive.backgroundColor = UIColor.gray blockSix.backgroundColor = UIColor.gray blockSeven.backgroundColor = UIColor.gray blockEight.backgroundColor = UIColor.gray blockNine.backgroundColor = UIColor.gray } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
true
cfb541877b2cef97726d351d8cc42f8767a4a91b
Swift
sxxjaeho/iOS-Primer
/contents/arithmetic/code/最长递增子序列.playground/Contents.swift
UTF-8
1,550
3.578125
4
[]
no_license
import UIKit /* 题目: 给定数组arr,设长度为n,输出arr的最长递增子序列。(如果有多个答案,请输出其中字典序最小的) 示例: 输入:[2,1,5,3,6,4,8,9,7] 输出:[1,3,4,8,9] 时间复杂度:O(nlogn) 空间复杂度:O(n) */ func LIS ( _ arr: [Int]) -> [Int] { let n = arr.count; var sub = Array(repeating: 0, count: n+1) var dp = Array(repeating: 0, count: n) var len = 1; sub[1] = arr[0]; dp[0] = 1; // [2, 1, 5, 3, 6, 4, 8, 9, 7] // sub = [0, 2, 0, 0, 0, 0, 0, 0, 0, 0] for i in 1..<n { if (sub[len] < arr[i]) { len += 1 sub[len] = arr[i]; dp[i] = len; } else { // [0, 1, 5, 0, 0, 0, 0, 0, 0, 0] // l = 0, r = 2, mid = 1 // sub[mid] = 1, arr[i] = 3 // l = 2, r = 2, mid = 2 // sub[mid] = 5, arr[i] = 3 // l = 2, r = 1 var l = 0; var r = len; while (l <= r) { let mid = l + (r - l) / 2; if (sub[mid] >= arr[i]) { r = mid - 1; } else { l = mid + 1; } } sub[l] = arr[i]; dp[i] = l; } } var res = Array(repeating: 0, count: len); for i in (0..<n).reversed() { if dp[i] == len { len -= 1 res[len] = arr[i]; } } return res; } print(LIS([2, 1, 5, 3, 6, 4, 8, 9, 7]))
true
c9859a7864dde43646dd996b42a5d27e50429086
Swift
ekmixon/Lucid
/Lucid/Core/ManagerResult.swift
UTF-8
1,428
2.890625
3
[ "MIT" ]
permissive
// // ManagerResult.swift // Lucid // // Created by Théophane Rupin on 9/6/19. // Copyright © 2019 Scribd. All rights reserved. // public enum ManagerResult<E> where E: Entity { case groups(DualHashDictionary<EntityIndexValue<E.RelationshipIdentifier, E.Subtype>, [E]>) case entities([E]) public var entities: [E] { switch self { case .groups(let groups): return groups.values.flatMap { $0 } case .entities(let entities): return entities } } public var entity: E? { return entities.first } public var isEmpty: Bool { return entities.isEmpty } } public extension ManagerResult { static func entity(_ entity: E?) -> ManagerResult { return .entities([entity].compactMap { $0 }) } static var empty: ManagerResult { return .entities([]) } } // MARK: - Sequence extension ManagerResult: Sequence { public __consuming func makeIterator() -> Array<E>.Iterator { return entities.makeIterator() } } // MARK: - Conversions public extension QueryResult { var managerResult: ManagerResult<E> { switch data { case .groups(let groups): return .groups(groups) case .entitiesSequence(let entities): return .entities(entities.array) case .entitiesArray(let entities): return .entities(entities) } } }
true
782eec11ddfa40862373c34731eb25bb55de888a
Swift
CodersHigh/x-common
/exercism-answers.playground/Sources/Luhn.swift
UTF-8
710
3.1875
3
[ "MIT" ]
permissive
class Luhn{ var numbers : [Int] = [] var addends : [Int] = [] var checksum : Int var isValid : Bool init(_ cardNumber : Int) { for i in String(cardNumber).characters{ numbers.insert(Int(String(i))!,at : 0) } for i in 0..<numbers.count{ addends.insert(i % 2 == 0 ? numbers[i] : numbers[i] * 2 > 9 ? numbers[i] * 2 - 9 : numbers[i] * 2, at: 0) } self.checksum = addends.reduce(0, {$0 + $1}) self.isValid = checksum % 10 == 0 } class func create(_ n : Int) -> Int{ let a = Luhn(n * 10) let b = (10 - a.checksum % 10) % 10 return n * 10 + b } }
true
adbe932ac4321e27c776c90a57f4b6d02321c474
Swift
PacktPublishing/Hands-On-Full-Stack-Development-with-Swift
/Chapter01/simple-server.swift
UTF-8
1,280
2.71875
3
[ "MIT" ]
permissive
import Darwin.C let zero = Int8(0) let transportLayerType = SOCK_STREAM // TCP let internetLayerProtocol = AF_INET // IPv4 let sock = socket(internetLayerProtocol, Int32(transportLayerType), 0) let portNumber = UInt16(4000) let socklen = UInt8(socklen_t(MemoryLayout<sockaddr_in>.size)) var serveraddr = sockaddr_in() serveraddr.sin_family = sa_family_t(AF_INET) serveraddr.sin_port = in_port_t((portNumber << 8) + (portNumber >> 8)) serveraddr.sin_addr = in_addr(s_addr: in_addr_t(0)) serveraddr.sin_zero = (zero, zero, zero, zero, zero, zero, zero, zero) withUnsafePointer(to: &serveraddr) { sockaddrInPtr in let sockaddrPtr = UnsafeRawPointer(sockaddrInPtr).assumingMemoryBound(to: sockaddr.self) bind(sock, sockaddrPtr, socklen_t(socklen)) } listen(sock, 5) print("Server listening on port \(portNumber)") repeat { let client = accept(sock, nil, nil) let html = "<!DOCTYPE html><html><body style='text-align:center;'><h1>Hello from <a href='https://swift.org'>Swift</a> Web Server.</h1></body></html>" let httpResponse: String = """ HTTP/1.1 200 OK server: simple-swift-server content-length: \(html.count) \(html) """ httpResponse.withCString { bytes in send(client, bytes, Int(strlen(bytes)), 0) close(client) } } while sock > -1
true
b3f157f49b9755ee056f0d89012c00ab9d69479e
Swift
eshwartm/TicTacToe-Swift
/Tic/SomePlayground.playground/section-1.swift
UTF-8
561
3.34375
3
[]
no_license
// Playground - noun: a place where people can play import Cocoa var str = "Hello, playground" var numColumns = 3 var numRows = 3 var boardArr = Dictionary<Int, String>() boardArr = [0:" ", 1:" ", 2:" ", 3:" ", 4:" ", 5:" ", 6:" ", 7:" ", 8:" "] //for row in 0..numColumns { // for col in 0..numRows { // println(\(boardArr[row][col])) // } //} boardArr.count boardArr[0] boardArr var someVar = false var a:String = (someVar ? "X" : "O") a
true
0b636b431bb63978d9f6efedf9f407a217a8fba9
Swift
manikandan-bangaru/MyWeatherApp
/MyWeatherApp/NetWork/WeatherRequestParams.swift
UTF-8
4,697
2.90625
3
[ "MIT" ]
permissive
// // WeatherRequestParams.swift // MyWeatherApp // // Created by manikandan bangaru on 07/06/21. // import Foundation public class APIRequestParams { var host : String var path : String public init(apiPath : String) { self.path = apiPath self.host = WeatherRequestParamConstants.Host } public class APIRequestParamsBuilder { var apiPath: String init(apiPath: String) { self.apiPath = apiPath } } } public class WeatherRequestParams: APIRequestParams { var cityName : String? var cityID : String? var zipCode : String? var countryCode : String? var latitude : String? var longitude : String? init(apiPath : String , builder : SearchCityParamBuilder) { self.cityName = builder.cityName super.init(apiPath: apiPath) } init(apiPath : String , builder : WeatherSearchParamBuilder) { self.cityName = builder.cityName self.cityID = builder.cityID self.zipCode = builder.zipCode self.countryCode = builder.countryCode self.latitude = builder.latitude self.longitude = builder.longitude super.init(apiPath: apiPath) } public func getRequestURL() -> URL?{ var params = [String : AnyObject]() var cityInfo = String() if let ci = cityID{ params[WeatherRequestParamConstants.Params.cityID] = ci as AnyObject } if let zc = zipCode{ cityInfo = zc if let cc = countryCode { cityInfo += cc } }else { if let cn = cityName { cityInfo = cn } } if cityInfo.isEmpty == false { params[WeatherRequestParamConstants.Params.CityInfo] = cityInfo as AnyObject } if let lat = self.latitude { params[WeatherRequestParamConstants.Params.Latitude] = lat as AnyObject } if let lon = self.longitude { params[WeatherRequestParamConstants.Params.Longitude] = lon as AnyObject } var urlComponents = URLComponents(string: self.host) urlComponents?.path = self.path urlComponents?.queryItems = [URLQueryItem]() for (key, value) in params{ let queryItem = URLQueryItem(name: key, value: "\(value)") urlComponents?.queryItems?.append(queryItem) } //Adding Metrics for degree celcius let unitsQuery = URLQueryItem(name: WeatherRequestParamConstants.Units, value: "\(WeatherRequestParamConstants.UnitValues.Metric)") urlComponents?.queryItems?.append(unitsQuery) //Adding API Key let apiKey = URLQueryItem(name: WeatherRequestParamConstants.Params.APIKey, value: "\(WeatherRequestParamConstants.API_Key_value)") urlComponents?.queryItems?.append(apiKey) return urlComponents?.url } public class SearchCityParamBuilder: APIRequestParams.APIRequestParamsBuilder { var cityName : String? init() { super.init(apiPath: WeatherRequestParamConstants.SearchCityPath) } public func set(cityName : String)->SearchCityParamBuilder{ self.cityName = cityName return self } public func build() -> WeatherRequestParams{ return WeatherRequestParams(apiPath: self.apiPath, builder: self) } } public class WeatherSearchParamBuilder: APIRequestParams.APIRequestParamsBuilder { var cityName : String? var cityID : String? var zipCode : String? var countryCode : String? var latitude : String? var longitude : String? init() { super.init(apiPath: WeatherRequestParamConstants.WeatherSearchPath) } func set(cityName : String) -> WeatherSearchParamBuilder { self.cityName = cityName return self } func set(latitude : String , longitude : String) -> WeatherSearchParamBuilder{ self.latitude = latitude self.longitude = longitude return self } func set(cityID : String) -> WeatherSearchParamBuilder { self.cityID = cityID return self } func set(zipCode : String , countryCode :String) -> WeatherSearchParamBuilder{ self.zipCode = zipCode self.countryCode = countryCode return self } func build() -> WeatherRequestParams{ return WeatherRequestParams(apiPath: self.apiPath, builder: self) } } }
true
e60264c01caf00f54f807bf8bb92d8e378e8d5e2
Swift
equweiyu/leetcode-swift
/leetcode.playground/Pages/41. First Missing Positive .xcplaygroundpage/Contents.swift
UTF-8
464
2.78125
3
[]
no_license
class Solution { func firstMissingPositive(_ nums: [Int]) -> Int { // // if nums.count == 0 { // return 1 // } // if nums.count == 1 { // if nums[0] == 1 { // return 2 // }else { // return 1 // } // } var r = 1 while nums.contains(r) { r += 1 } return r } } Solution.init().firstMissingPositive([1,2,3,5])
true
dad468f4f4868083b176b903182d6adcc43b9e3e
Swift
Nirajpaul2/contacts-cleanswiftvip-sqlite-ios
/Contacts/Scenes/Base/StatusBarToggleable.swift
UTF-8
694
2.703125
3
[]
no_license
// // StatusBarToggleable.swift // Contacts // // Created by Glenn Posadas on 3/26/21. // Copyright © 2021 Outliant. All rights reserved. // import UIKit protocol StatusBarToggleable: class { var statusBarShouldBeHidden: Bool { get set } var statusBarAnimationStyle: UIStatusBarAnimation { get set } var statusBarStyle: UIStatusBarStyle { get set } } extension StatusBarToggleable where Self: UIViewController { func updateStatusBarAppearance( withDuration duration: Double = 0.3, completion: ((Bool) -> Void)? = nil) { UIView.animate(withDuration: duration, animations: { [weak self] in self?.setNeedsStatusBarAppearanceUpdate() }, completion: completion) } }
true
179324edc89fb276e82b9f06d06032e893eaf090
Swift
minsOne/Dodi
/Projects/DodiRepository/Sources/Todo/TodoCachedRepositoryImpl.swift
UTF-8
1,493
2.890625
3
[]
no_license
// // TodoCachedRepositoryImpl.swift // DodiRepository // // Created by Geektree0101 on 2021/08/13. // import Foundation import DodiCore struct TodoCachedRepositoryImpl: TodoCachedRepository { private enum Const { static let todosKey: String = "TodoCachedRepository.todos" } private let userDefaults: UserDefaults init(userDefaults: UserDefaults) { self.userDefaults = userDefaults } func todo(id: Int) -> Todo? { let todos = self.cachedTodos() return todos.first(where: { $0.id == id }) } func appendTodo(_ todo: Todo) { var todos = self.cachedTodos() todos.append(todo) self.save(todos) } func insertTodo(_ todo: Todo, at index: Int) { var todos = self.cachedTodos() todos.insert(todo, at: index) self.save(todos) } func save(_ todos: [Todo]) { guard let jsonString = try? PropertyListEncoder().encode(todos) else { return } self.userDefaults.setValue(jsonString, forKey: Const.todosKey) } func allTodos() -> [Todo] { return self.cachedTodos() } func update(_ todo: Todo) { var todos = self.cachedTodos() guard let index = todos.firstIndex(where: { $0.id == todo.id }) else { return } todos[index] = todo self.save(todos) } private func cachedTodos() -> [Todo] { guard let data = self.userDefaults.value(forKey: Const.todosKey) as? Data, let todos = try? PropertyListDecoder().decode([Todo].self, from: data) else { return [] } return todos } }
true
db09fed7e15237a6b99197e409641fdebd07fe6e
Swift
srpunjabi/espresso
/Espresso/Espresso/ShopDetailsController.swift
UTF-8
5,458
2.65625
3
[]
no_license
// // TableViewController.swift // Espresso // // Created by Sumit Punjabi on 6/4/16. // Copyright © 2016 wakeupsumo. All rights reserved. // import UIKit import MapKit class ShopDetailsController: UITableViewController { @IBOutlet weak var mapView: MKMapView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var addressLabel: UILabel! @IBOutlet weak var hoursLabel: UILabel! @IBOutlet weak var phoneNumberLabel: UILabel! @IBOutlet weak var webSiteLabel: UILabel! @IBOutlet weak var distanceLabel: UILabel! var coffeeShop:CoffeeShop? let addressSection = 0 let addressRow = 0 let infoSection = 1 let directionCellRow = 1 let phoneCellRow = 2 let webCellRow = 3 override func viewDidLoad() { super.viewDidLoad() mapView.delegate = self setup() } //MARK: - Setup func setup() { if let coffeeShop = coffeeShop { nameLabel.text = coffeeShop.name setupAddressLabel(coffeeShop) setUpPhoneLabel(coffeeShop) setUpWebsiteLabel(coffeeShop) setUpDistance(coffeeShop) showPin(coffeeShop) } } //MARK: - Setup Helpers func setupAddressLabel(shop:CoffeeShop) { guard let street = shop.street else { return } guard let city = shop.city else { return } addressLabel.text = "\(street)\n" + "\(city)" } func setUpWebsiteLabel(shop:CoffeeShop) { guard let url = shop.url else { webSiteLabel.text = "No" return } webSiteLabel.text = url } func setUpDistance(shop:CoffeeShop) { guard let distance = shop.distance else { distanceLabel.text = "0.0" return } var distanceInMiles = distance * 0.000621371192 distanceInMiles = Double(round(distanceInMiles * 100)/100) distanceLabel.text = "\(distanceInMiles) mi" } func setUpPhoneLabel(shop:CoffeeShop) { guard let phone = shop.phone else { phoneNumberLabel.text = "No" return } phoneNumberLabel.text = phone } //MARK: - UITableView Delegate Methods override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { switch indexPath.row { case webCellRow where indexPath.section == infoSection: //open webpage openWebURL() case phoneCellRow where indexPath.section == infoSection: //make a call openPhoneURL() case directionCellRow where indexPath.section == infoSection: //open maps openMapURL() case addressRow where indexPath.section == addressSection: openMapURL() default: break } } //MARK: - URL Helpers func openWebURL() { guard let sURL = coffeeShop?.url else { return } guard let url = NSURL(string: sURL) else { return } UIApplication.sharedApplication().openURL(url) } func openPhoneURL() { guard let phone = coffeeShop?.phoneBasic else { return } guard let url = NSURL(string: "tel:+1\(phone)") else { return } UIApplication.sharedApplication().openURL(url) } func openMapURL() { guard let street = coffeeShop?.street?.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet()) else { return } guard let city = coffeeShop?.city?.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet()) else { return } guard let url = NSURL(string: "http://maps.apple.com/?daddr=\(street)\(city)") else { return } UIApplication.sharedApplication().openURL(url) } //MARK: - Location Helpers func centerMapOnLocation(coord: CLLocationCoordinate2D) { let regionRadius: CLLocationDistance = 100 let coordinateRegion = MKCoordinateRegionMakeWithDistance(coord, regionRadius * 2.0, regionRadius * 2.0) mapView.setRegion(coordinateRegion, animated: true) } func showPin(coffeeShop:CoffeeShop) { guard let lat = coffeeShop.latitude else { return } guard let lng = coffeeShop.longitude else { return } let coord = CLLocationCoordinate2D(latitude: lat, longitude: lng) let annotation = CoffeeShopAnnotation(title: coffeeShop.name, coordinate: coord,type: .CoffeeShop, id: coffeeShop.identifier) mapView.addAnnotation(annotation) centerMapOnLocation(coord) } } extension ShopDetailsController: MKMapViewDelegate { func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? { guard let annotation = annotation as? CoffeeShopAnnotation else { return nil } let reuseId = "coffeePin" var view:MKAnnotationView if let dequedView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) as MKAnnotationView? { view = dequedView view.annotation = annotation } else { view = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId) view.image = UIImage(named: annotation.imageName) } return view } }
true
9a3ac957feb832c70c351a61568d1fbaa4653418
Swift
neha275/ThemeControl
/ThemeControl/View/ViewController.swift
UTF-8
1,701
2.59375
3
[]
no_license
// // ViewController.swift // ThemeControl // // Created by Neha Gupta on 29/06/18. // Copyright © 2018 Neha Gupta. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var tblList:UITableView! let cityName:[String] = ["New Delhi", "Mumbai","Pune"] override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = Theme.currentTheme.background } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewDidAppear(_ animated: Bool) { } override func viewWillAppear(_ animated: Bool) { view.backgroundColor = Theme.currentTheme.background tblList.reloadData() } } extension ViewController: UITableViewDataSource, UITableViewDelegate { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return cityName.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "InfoTableViewCell", for: indexPath) as! InfoTableViewCell cell.titleLabel.text = cityName[indexPath.row] cell.cardView.layer.cornerRadius = 4 cell.cardView.layer.masksToBounds = true cell.cardView.backgroundColor = Theme.currentTheme.accent cell.titleLabel.textColor = Theme.currentTheme.title return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 150 } }
true