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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
46824453a7346da86d74646e66e04faaf2becb13
|
Swift
|
bhumesh/SimpleMVVM1
|
/JarusAssigment/DataFetcher/DataFetcher.swift
|
UTF-8
| 2,154
| 3.078125
| 3
|
[] |
no_license
|
//
// DataFetcher.swift
// JarusAssigment
//
// Created by BhumeshwerKatre on 11/04/21.
//
import Foundation
protocol DataFetcherProtocol {
func getDataForRequest<T: Codable>(_ request: String, completion: @escaping(Result<T, APIError>) -> Void)
}
class DataFetcher: DataFetcherProtocol {
private lazy var operationQueue: OperationQueue = {
var queue = OperationQueue()
queue.name = "Data_Fetcher_Queue"
queue.maxConcurrentOperationCount = 1
return queue
}()
func getDataForRequest<T: Codable>(_ request: String, completion: @escaping (Result<T, APIError>) -> Void) {
let operation = DataFetcherOperation<T>(request)
operation.completionBlock = {
if operation.isCancelled {
completion(.failure(.requestCancelled))
return
}
if let result = operation.result {
completion(result)
} else {
completion(.failure(.noData))
}
}
self.operationQueue.addOperation(operation)
}
}
enum Result<T, U> where U: Error {
case success(T)
case failure(U)
}
enum APIError: Error {
case requestCancelled
case jsonParsingFailure
case requestFailed(Error?, [String: Any]? = nil)
case noData
}
class DataFetcherOperation<T: Codable>: Operation {
let request: String
var result: Result<T, APIError>?
init(_ request: String) {
self.request = request
}
override func main() {
if isCancelled {
return
}
if let path = Bundle.main.path(forResource: "assignment", ofType: "json") {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
let jsonDecoder = JSONDecoder()
if let response = try jsonDecoder.decode(T?.self, from: data) {
self.result = .success(response)
} else {
self.result = .failure(.noData)
}
} catch {
self.result = .failure(.jsonParsingFailure)
}
}
}
}
| true
|
a4200121108007f917d9367907513d3eaf02df02
|
Swift
|
silence0201/LeetCodePractice
|
/LeetCodePractice/Practice/0024SwapPairs.swift
|
UTF-8
| 593
| 2.921875
| 3
|
[
"MIT"
] |
permissive
|
//
// 0024SwapPairs.swift
// Practice
//
// Created by Silence on 2022/3/1.
//
import Foundation
class Solution24 {
func swapPairs(_ head: ListNode?) -> ListNode? {
let dummyHead = ListNode(-1, head)
var cur: ListNode? = dummyHead
while (cur?.next != nil && cur?.next?.next != nil) {
let first = cur?.next
let second = cur?.next?.next
cur?.next = second
first?.next = second?.next
second?.next = first
cur = first
}
return dummyHead.next
}
}
| true
|
eb80a59abc3da0d00c73931ba8385c7efea7dcf0
|
Swift
|
mikkoholler/daily-scale
|
/Daily Scale/HeiaHandler.swift
|
UTF-8
| 6,791
| 2.75
| 3
|
[] |
no_license
|
//
// HeiaHandler.swift
// Daily Scale
//
// Created by Michael Holler on 10/05/16.
// Copyright © 2016 Holler. All rights reserved.
//
import Foundation
class HeiaHandler {
static let instance = HeiaHandler()
let defaults = NSUserDefaults.standardUserDefaults()
func saveToken(new:String) {
defaults.setObject(new, forKey: "Token")
print("Token saved.")
}
func getToken() -> String {
var token = ""
if let fetched = defaults.objectForKey("Token") as? String {
token = fetched
print("Got token.")
}
return token
}
func deleteToken() {
defaults.removeObjectForKey("Token")
print("Token deleted.")
}
func loginWith(user:String, passwd:String, completion: (Bool) -> ()) {
var success = false
let secret = Secret()
let params = "grant_type=password&username=\(user)&password=\(passwd)&client_id=\(secret.clientid)&client_secret=\(secret.secret)"
let request = NSMutableURLRequest()
request.HTTPMethod = "POST"
request.HTTPBody = params.dataUsingEncoding(NSUTF8StringEncoding)
request.URL = NSURL(string: "https://api.heiaheia.com/oauth/token")
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) in
do {
let statuscode = (response as! NSHTTPURLResponse).statusCode
if (statuscode == 200) {
if let jsonObject = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String:AnyObject] {
if let token = jsonObject["access_token"] as? String {
self.saveToken(token)
success = true
}
}
}
} catch {
print("Could not tokenize")
}
NSOperationQueue.mainQueue().addOperationWithBlock {
completion(success)
}
}
task.resume()
}
func login(completion: (String, Int?) -> ()) {
let token = getToken()
if (!token.isEmpty) {
completion(token, 200)
} else {
let secret = Secret()
let params = "grant_type=password&username=\(secret.username)&password=\(secret.passwd)&client_id=\(secret.clientid)&client_secret=\(secret.secret)"
let request = NSMutableURLRequest()
request.HTTPMethod = "POST"
request.HTTPBody = params.dataUsingEncoding(NSUTF8StringEncoding)
request.URL = NSURL(string: "https://api.heiaheia.com/oauth/token")
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) in
do {
if (error != nil) {
completion("", error?.code)
} else {
// TODO: crashes with no internets
if let jsonObject = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String:AnyObject] {
if let token = jsonObject["access_token"] as? String {
NSOperationQueue.mainQueue().addOperationWithBlock {
self.saveToken(token)
completion(token, 200)
}
}
}
}
} catch {
print("Could not tokenize")
}
}
task.resume()
}
}
func getWeights(completion: ([Weight], Int?) -> ()) {
var feed = [Weight]()
var statuscode = 400
let request = NSMutableURLRequest()
let params = "year=2016&page=1&per_page=100&access_token=\(getToken())"
let components = NSURLComponents(string: "https://api.heiaheia.com/v2/items")
components?.query = params
request.HTTPMethod = "GET"
request.URL = components?.URL
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) in
do {
if let r = response as? NSHTTPURLResponse {
statuscode = r.statusCode
if (statuscode == 200) {
if let jsonObject = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? Array<[String:AnyObject]> {
feed = jsonObject
.filter { $0["kind"] as! String == "Weight" }
.map { (let item) -> Weight in
return self.parse(item)
}
}
}
} else {
statuscode = 400
}
} catch let e {
print("Cannot \(e)")
statuscode = 400
}
NSOperationQueue.mainQueue().addOperationWithBlock {
completion(feed, statuscode)
}
}
task.resume()
}
func parse(item: [String:AnyObject]) -> Weight {
var weight = Weight()
if let entry = item["entry"] as? [String:AnyObject] {
if let date = entry["date"] as? String {
weight.date = dateFromString(date)
}
if let value = entry["value"] as? Double {
weight.kg = value
}
}
return weight
}
func saveWeight(date:NSDate, weight:Double) {
login() { (token) in
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let datestr = dateFormatter.stringFromDate(date)
let weightstr = String(format: "%.1f", weight)
let params = "access_token=\(token)&date=\(datestr)&value=\(weightstr)¬es=&private=true"
let request = NSMutableURLRequest()
request.HTTPMethod = "POST"
request.HTTPBody = params.dataUsingEncoding(NSUTF8StringEncoding)
request.URL = NSURL(string: "https://api.heiaheia.com/v2/weights")
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) in
}
task.resume()
}
}
func dateFromString(date: String) -> NSDate {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let dateInFormat = dateFormatter.dateFromString(date)
return dateInFormat!
}
}
| true
|
ec555ceadd9b4b8bd00a16a11e9e5896b44a27db
|
Swift
|
MagicalMike/message-broker
|
/Message Broker/Receiver/Receiver/Controllers/MessagingVC.swift
|
UTF-8
| 5,866
| 2.546875
| 3
|
[] |
no_license
|
//
// MessagingVC.swift
// Sender
//
// Created by Mihai Petrenco on 11/2/17.
// Copyright © 2017 Limitless. All rights reserved.
//
import Cocoa
import SwiftSocket
class MessagingVC: NSViewController {
//MARK: - Outlet declarations
@IBOutlet weak var activityTable: NSTableView!
@IBOutlet weak var inputTextfield: CustomTextField!
@IBOutlet weak var putButton: CustomButton!
@IBOutlet weak var countButton: CustomButton!
@IBOutlet weak var removeButton: CustomButton!
@IBOutlet weak var errorLabel: NSTextField!
//MARK: - Variable declarations
let activityDelegate = ActivityDelegate()
let activityDataSource = ActivityDataSource()
private var selectedCommand = Command.none
private var listening = true
var previousVC: ConnectionVC!
var client:TCPClient?
//MARK: - View lifecycle
override func viewDidLoad() {
activityTable.delegate = activityDelegate
activityTable.dataSource = activityDataSource
previousVC!.dismiss(self)
previousVC.view.window?.close()
DispatchQueue.global().async {
while self.listening {
self.listen()
}
}
}
override func viewDidAppear() {
let window = self.view.window
window?.backgroundColor = #colorLiteral(red: 0.2596075237, green: 0.2981915474, blue: 0.3495857716, alpha: 1)
window?.isMovableByWindowBackground = true
window?.titlebarAppearsTransparent = true
window?.titleVisibility = .hidden
}
//MARK: - User actions
@IBAction func queueBtnPressed(_ sender: Any) {
let identifier = NSStoryboardSegue.Identifier.init(rawValue: "QueueVC")
performSegue(withIdentifier: identifier, sender: self)
}
@IBAction func sendBtnPressed(_ sender: Any) {
let input = inputTextfield.stringValue
if selectedCommand == .none {
errorLabel.stringValue = "No command has been selected!"
errorLabel.isHidden = false
return
}
inputTextfield.stringValue = ""
ActivityStore.addActivity(command: selectedCommand, contents: input)
activityTable.reloadData()
errorLabel.isHidden = true
let command = selectedCommand.rawValue
let queues = QueueStore.queues
let json = Serializer.generate(command: command, to: queues, with: input)
guard let data = Serializer.toData(from: json) else {
print("Error while generating Data object")
return
}
let response = client?.send(data: data)
switch response {
case .some(_):
//Congratulations
break
case .none:
notifyActivity(of: .error, containing: "Could not send data!")
}
}
//MARK: - Client functionalities
func listen() {
if let input = self.client?.read(1024 * 10, timeout: 100) {
let data = Data(bytes: input)
//If everything works normally
if let json = Serializer.toJSON(from: data) {
decompose(json: json)
return
}
//If shit happens
var string = "[" + String(data: data, encoding: .utf8)! + "]"
string = string.replacingOccurrences(of: "}{", with: "},{")
let newData = string.data(using: .utf8, allowLossyConversion: false)
do {
let json = try JSONSerialization.jsonObject(with: newData!, options: .allowFragments) as! [[String:Any]]
for element in json {
decompose(json: element)
}
} catch {
print("Shit happened")
}
}
}
func decompose(json: [String:Any]) {
guard let command = json["Command"] as? String else {
self.notifyActivity(of: .error, containing: "JSON format obtained is corrupted!")
return
}
guard let contents = json["Contents"] as? String else {
self.notifyActivity(of: .error, containing: "JSON format obtained is corrupted!")
return
}
self.notifyActivity(of: getCommand(from: command), containing: contents)
}
func getCommand(from raw: String) -> Command {
switch raw {
case "RESPONSE":
return .response
default:
return .error
}
}
@IBAction func putBtnPressed(_ sender: Any) {
selectedCommand = .get
inputTextfield.isEnabled = false
inputTextfield.stringValue = ""
disablePopups(except: putButton)
}
@IBAction func countBtnPressed(_ sender: Any) {
selectedCommand = .count
inputTextfield.isEnabled = false
inputTextfield.stringValue = ""
disablePopups(except: countButton)
}
@IBAction func removeBtnPressed(_ sender: Any) {
selectedCommand = .subscribe
inputTextfield.isEnabled = false
inputTextfield.stringValue = ""
disablePopups(except: removeButton)
}
//MARK: UI-related
func isValidString(for string: String) -> Bool {
if string.count > 0 && string.first != " " {
return true
}
return false
}
func disablePopups(except button: CustomButton) {
putButton.state = .off
countButton.state = .off
removeButton.state = .off
button.state = .on
}
func notifyActivity(of command: Command, containing content:String) {
ActivityStore.addActivity(command: command, contents: content)
DispatchQueue.main.async {
self.activityTable.reloadData()
}
}
}
| true
|
5a67b5287943a835aad02ad457cb6e581af936e3
|
Swift
|
GuidoBeijkUT/meat-up
|
/mEAT-Up/Create2/Create2ViewController.swift
|
UTF-8
| 1,092
| 2.609375
| 3
|
[] |
no_license
|
//
// Create2ViewController.swift
// mEAT-Up
//
// Created by Gijs Koehorst on 17/12/2019.
// Copyright © 2019 Guido Beijk. All rights reserved.
//
import Foundation
import UIKit
class Create2ViewController: UIViewController {
@IBAction func alertMeetUpCreated(_ sender: Any) {
let alertController = UIAlertController(title: "iOScreator", message:
"Meet-up created!", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "Create another", style: .default, handler: {(UIAlertAction) -> Void in
self.test()
}))
alertController.addAction(UIAlertAction(title: "Go to meet-ups", style: .default))
self.present(alertController, animated: true, completion: nil)
}
func test() {
let storyBoard : UIStoryboard = UIStoryboard(name: "MyMeatUpsViewController", bundle:nil)
let nextViewController = storyBoard.instantiateViewController(withIdentifier: "MyMeatUpsViewController") as! MyMeatUpsViewController
self.present(nextViewController, animated:true, completion:nil)
}
}
| true
|
b7abef2a99e1a24a8c298402eec62b56d6ed4136
|
Swift
|
hottodoguru/cn436MyWorkoutApp
|
/MyWorkout/View/ContentView.swift
|
UTF-8
| 898
| 2.640625
| 3
|
[] |
no_license
|
//
// ContentView.swift
// MyWorkout
//
// Created by Chanoknun Choosaksilp on 6/9/2564 BE.
//
import SwiftUI
struct ContentView: View {
@State private var selectedTab = 9
@EnvironmentObject private var history : HistoryStore
var body: some View {
let exercisecount = Exercise.exercises.count
TabView(selection: $selectedTab){
WelcomeView(selectedTab : $selectedTab)
.tag(exercisecount + 1)
ForEach(0 ..< exercisecount) { index in
ExerciseView(selectedTab: $selectedTab,index: index)
.tag(index)
.environmentObject(history)
}
}
.tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
.environmentObject(HistoryStore())
}
}
| true
|
90f86f44197fac607ba7377b96d9a498de083ea3
|
Swift
|
alexbuga/OrangeConverter
|
/OrangeConverter/Controllers/ViewController.swift
|
UTF-8
| 5,417
| 2.609375
| 3
|
[] |
no_license
|
//
// ViewController.swift
// OrangeConverter
//
// Created by Alex Buga on 14/03/2020.
// Copyright © 2020 Alex Buga. All rights reserved.
//
import UIKit
class CurrenciesViewController: UIViewController {
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
@IBOutlet weak var headerView: HeaderView!
@IBOutlet weak var tableView: UITableView!
var currencyDataSource: CurrencyDataSource!
var currencyViewModel: CurrencyViewModel!
var currencyService: CurrencyService!
override func viewDidLoad() {
super.viewDidLoad()
headerView.delegate = self
setupTableView()
updateHeaderText()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: true)
currencyViewModel.fetchLatestCurrencies()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
currencyViewModel.stopTimer()
}
func updateHeaderText() {
let titleValue = "\(CurrencyService.baseCurrency) Currencies"
title = titleValue
headerView.titleLabel.text = titleValue
headerView.subtitleLabel.text = currencyDataSource.date
}
@IBAction func showHistory() {
performSegue(withIdentifier: "showHistory", sender: nil)
}
func setupTableView() {
currencyDataSource = CurrencyDataSource()
currencyDataSource.data.addObserver(self, andNotify: true) { [weak self] _ in
self?.updateHeaderText()
self?.tableView.reloadData()
}
tableView.register(UINib(nibName: "DateHeader", bundle: Bundle.main), forHeaderFooterViewReuseIdentifier: "header")
tableView.register(UINib(nibName: "CurrencyCell", bundle: Bundle.main), forCellReuseIdentifier: "row")
tableView.dataSource = currencyDataSource
tableView.delegate = currencyDataSource
currencyService = CurrencyService()
currencyViewModel = CurrencyViewModel(currencyService: currencyService, dataSource: currencyDataSource)
currencyViewModel.handleError = { error in
self.showAlert(title: "Oops", message: error?.localizedDescription)
}
tableView.layer.shadowColor = UIColor.black.cgColor
tableView.layer.shadowOpacity = 0.1
tableView.layer.shadowRadius = 10
tableView.layer.shadowOffset.height = 2
}
deinit {
let _ = currencyDataSource.data.removeObserver(self)
}
}
//MARK: Header Delegate
extension CurrenciesViewController: HeaderViewDelegate {
func headerView(didTapButton type: HeaderView.ButtonType) {
switch type {
case .history:
showHistory()
case .settings:
showSettings()
}
}
}
//MARK: Settings section
extension CurrenciesViewController {
func showChangeDefaultCurrency() {
let currenciesAlert = UIAlertController(title: "Choose Default Currency", message: nil, preferredStyle: .actionSheet)
for currency in CurrencyService.currencies {
let action = UIAlertAction(title: "\(String.flag(forCountryCode: currency)) \(currency)", style: .default, handler: { _ in
CurrencyService.baseCurrency = currency
self.updateHeaderText()
self.currencyViewModel.fetchLatestCurrencies()
})
action.setValue(CurrencyService.baseCurrency == currency, forKey: "checked")
currenciesAlert.addAction(action)
}
currenciesAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self.present(currenciesAlert, animated: true, completion: nil)
}
func showChangeInterval() {
let intervalAlert = UIAlertController(title: "Refresh Interval", message: nil, preferredStyle: .actionSheet)
intervalAlert.view.tintColor = UIColor(named: "DarkPurple")
[3, 5, 15].forEach { interval in
intervalAlert.addAction(UIAlertAction(title: "\(interval) seconds", style: .default, handler: { _ in
UserDefaults.standard.set(interval, forKey: "refreshInterval")
self.currencyViewModel.fetchLatestCurrencies()
}))
}
intervalAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self.present(intervalAlert, animated: true, completion: nil)
}
@IBAction func showSettings() {
let menu = UIAlertController(title: "Settings", message: nil, preferredStyle: .actionSheet)
menu.view.tintColor = UIColor(named: "DarkPurple")
let changeCurrencyAction = UIAlertAction(title: "Change Default Currency", style: .default, handler: { _ in
self.showChangeDefaultCurrency()
})
let changeIntervalAction = UIAlertAction(title: "Change Refresh Interval", style: .default, handler: { _ in
self.showChangeInterval()
})
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
menu.addAction(changeCurrencyAction)
menu.addAction(changeIntervalAction)
menu.addAction(cancelAction)
present(menu, animated: true, completion: nil)
}
}
| true
|
35a8001c5d77ffd805ec6817eb93ee30621e391f
|
Swift
|
baonhan88/Home-Automation-Rule-Designer
|
/HomeAutomationRuleDesigner/Features/RuleDesigner/Views/RuleWhenPatternCell.swift
|
UTF-8
| 2,141
| 2.6875
| 3
|
[] |
no_license
|
//
// RuleWhenPatternCell.swift
// HomeAutomationRuleDesigner
//
// Created by Nhan on 29/11/2017.
// Copyright © 2017 SLab. All rights reserved.
//
import UIKit
protocol RuleWhenPatternCellDelegate {
func handleTapOnChooseObjectTypeButton(pattern: Pattern)
func handleTapOnAddConstraintButton(pattern: Pattern)
func handleTapOnRemoveConstraintButton(pattern: Pattern)
}
class RuleWhenPatternCell: UITableViewCell {
@IBOutlet weak var idTextField: UITextField!
@IBOutlet weak var bindingTextField: UITextField!
@IBOutlet weak var chooseObjectTypeButton: UIButton!
@IBOutlet weak var addConstraintButton: UIButton!
var pattern: Pattern?
var delegate: RuleWhenPatternCellDelegate?
func initView(pattern: Pattern) {
self.pattern = pattern
idTextField.text = pattern.id
bindingTextField.text = pattern.binding
if pattern.objectType != "" {
chooseObjectTypeButton.setTitle(pattern.objectType, for: UIControlState.normal)
} else {
chooseObjectTypeButton.setTitle("Choose Object Type", for: UIControlState.normal)
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
@IBAction func chooseObjectTypeButtonClicked(_ sender: UIButton) {
delegate?.handleTapOnChooseObjectTypeButton(pattern: pattern!)
}
@IBAction func addConstraintButtonClicked(_ sender: UIButton) {
delegate?.handleTapOnAddConstraintButton(pattern: pattern!)
}
@IBAction func removeConstraintButtonClicked(_ sender: UIButton) {
delegate?.handleTapOnRemoveConstraintButton(pattern: pattern!)
}
@IBAction func idTextFieldDidChange(_ sender: UITextField) {
pattern?.id = sender.text!
}
@IBAction func bindingTextFieldDidChange(_ sender: UITextField) {
pattern?.binding = sender.text!
}
}
| true
|
91b7313e07ece79c17acb38d0fbbc9aeb1027eb9
|
Swift
|
andreaslydemann/Instruments
|
/Instruments/View/Layout/Layout.swift
|
UTF-8
| 287
| 2.546875
| 3
|
[] |
no_license
|
//
// Layout.swift
// Instruments
//
// Created by Andreas Lüdemann on 16/09/2019.
// Copyright © 2019 Andreas Lüdemann. All rights reserved.
//
import CoreGraphics
protocol Layout {
mutating func layout(in rect: CGRect)
associatedtype Content
var contents: [Content] { get }
}
| true
|
dbaca5ce78a02325f626a1c568c832a64347b1d7
|
Swift
|
sonnyshih/iOSExercise
|
/01_MyPlayground.playground/Contents.swift
|
UTF-8
| 6,912
| 4.34375
| 4
|
[] |
no_license
|
var x = 2 // 變數
let y = 18 // 常數
var myNumber:Int = 10 // 整數
let gravityNumber:Float = 9.8 // 浮點數
var mathNumber:Double = 3.1415 // 雙精度浮點數
var hh:Float = Float(myNumber) // int 轉float
let numDosentChang: Int = 5
Float(numDosentChang) / 2
var isTheLightOn:Bool = true;
let helloWorld:String = "hello world"
let name = "Peter";
helloWorld + ", " + name
var theFact = "My Name is \(name)"
theFact = "I am \(myNumber+2) years old"
var theDialog = "My mon said, \"Life was like a box of chocolates\"."
theDialog.lowercased() // 變小寫
theDialog.uppercased() // 變大寫
// Array
var animalArray = ["cat", "dog", "lion", "tiger"]
animalArray[0]
animalArray.count
animalArray.append("rabbit")
print(animalArray)
animalArray.insert("cow", at: 2)
print(animalArray)
animalArray.remove(at: 0)
print(animalArray)
var anotherAnimalArray:[String] = ["pony", "sheep", "monkey"]
animalArray = animalArray + anotherAnimalArray
print(animalArray)
var emptyBag:[String] = [] // Define empty array
var numberBag = [Int]() // Define empty array (和上面宣告是一樣的)
// Dictionary
var fruitDict = ["red":"apple", "yellow":"banana", "green":"mango"]
fruitDict["red"]
fruitDict["brown"] // display the "nil"
fruitDict["green"] = "watermelon" // change the value
fruitDict.updateValue("kiwi", forKey: "green") // same as upper
fruitDict["orange"] = "orange"; // add new element (same as upper)
fruitDict.updateValue("peach", forKey: "pink")
fruitDict["red"] = nil // remove the element
fruitDict.removeValue(forKey: "yellow") // remove the element (same as upper)
var score:[String: Int] = ["english":80, "chinese":85, "sport":90] // define type of the dictionary
print(score)
// Switch 1
let name1 = "Thomas"
switch name1 {
case "Thomas":
print("That's me")
case "David":
print("That's my father")
case "Helen":
print("That's my mother")
case "Brendar":
print("That's my sister")
default:
print("Who are you?")
}
// Switch 2
let price = 75
switch price {
case 100, 200:
print("too expensive")
case 60...80:
print("ok")
case 50:
print("cheap")
default:
print("the price has to be 200, 100 or 50")
}
// for each
var animalArray1 = ["cat", "dog", "lion", "tiger"]
for animal in animalArray1 {
print(animal)
}
// 產生全閉範圍
// Closed Range Operator a...b 1...10
for index in 1...10 {
print("Hello \(index)")
}
for _ in 1...10 { // only print 10 times
print("Hi!")
}
// 產生半閉範圍
// Half-Open Rnage Operator a..<b 1..<5
for index in 1..<5 { // only 1~4
print("hi \(index)")
}
// 利用餘數 %
for index in 1...10 where index % 2 == 0 {
print(index)
}
// 印出dictionary 的 key 和value
var fruitDict1 = ["red":"apple", "yellow":"banana", "green":"mango"]
for (key, value) in fruitDict1 {
print(key + " : " + value)
}
// Tuple 元組
let colors = ("red", "orange", "yellow", "green", "blue")
print(colors.0)
let someTuple = ("Hello", 3.1415, true, ["apple", "banana"])
print(someTuple.3[0])
var fruitTuple = (red:"apple", yellow:"banana",green:"mango")
print(fruitTuple.red)
print(fruitTuple.0)
// while loop
var index1 = 1
while index1<=10 {
print(index1)
index1+=1
}
// repeat while
var myCounter = 1
repeat {
print("Just do it \(myCounter) time")
myCounter+=1
} while myCounter<11
// function
func makeCake(){
print("Cream the egg and sugar")
print("Add Butter to it")
print("Add Flour to it and mix")
print("Bake it with oven")
}
makeCake()
func eat(foodname:String){
print("I want to have \(foodname)")
}
eat(foodname: "Hamburger")
func drink(berverageNam1:String, berverageNam2:String ){
print("I want to drink \(berverageNam1) and \(berverageNam2)")
}
drink(berverageNam1: "Cola", berverageNam2: "Red bull")
// function has the return value
func add(number1:Int, number2:Int) -> Int{
let result = number1 + number2
return result
}
let answer = add(number1: 3, number2: 5)
print("answer=\(answer)")
func multiply(number1:Int, number2:Int) -> String{
return "\(number1) * \(number2) = \(number1 * number2)"
}
print(multiply(number1: 5, number2: 7))
// 外部參數與內容參數 (withWidth, withHeigh是外部參數名。 width, heigh是內部參數名)
func calculateArea(withWidth width:Float, withHeigh heigh:Float) ->Float{
return width * heigh
}
print(calculateArea(withWidth: 20.5, withHeigh: 30.5))
// Closure 閉包 (就是沒有名字的function)
let helloClosure = {
print("Hello Everybody")
}
// 同上面的寫法
/*
let helloClosure:()->() = {
print("Hello Everybody")
}
*/
helloClosure()
let eatClosure = {
(foodName:String) in
print("I want to have \(foodName)")
}
// 同上面的寫法
/*
let eatClosure:(String)->() = {
(foodName:String) in
print("I want to have \(foodName)")
}
*/
eatClosure("Apple Pie")
let addClosure = {
(number1:Int, number2:Int) -> Int in
let result = number1 * number2
return result
}
// 同上面的寫罄
/*
let addClosure:(Int, Int) -> Int = {
(number1:Int, number2:Int) -> Int in
let result = number1 * number2
return result
}
*/
print(addClosure(3, 5))
// Closure 可以當成 function的參數使用
let addNewClosure:(Int, Int)->Int = {
(num1:Int, num2:Int) -> Int in
let result = num1 * num2
return result
}
func newCalculate(num1:Int, num2:Int, operation:(Int, Int)->Int){
print("operation: \(operation(num1,num2))" )
}
newCalculate(num1: 6, num2: 8, operation: addNewClosure)
// Map
var numberArray = [1,3,5,7,9,2,4,6,8,10]
numberArray.map({
(number:Int) in
print("map number: \(number)" )
})
// numberArrayAddTen is a Int array
let numberArrayAddTen = numberArray.map({
(number:Int) in
return number + 10
})
print(numberArrayAddTen)
// numberArrayToString is a String array
let numberArrayToString = numberArray.map({
(number:Int) in
return "This is number \(number)"
})
print(numberArrayToString)
// Filter
var numberArray1 = [1,3,5,7,9,2,4,6,8,10]
let evenNumbers = numberArray1.filter({
(number:Int) -> Bool in
return number % 2 == 0
})
print(evenNumbers)
// Optional (非必須的) 變沒有固定型別
var no:Int? = nil // Optional Int 型別: 只能存整數或空值,不能存其他型別
var string:String? = nil // Optional String 型別: 只能存字串或空值,不能存其他型別
var isHello:Bool? = nil // Optional Bool 型別: 只能存布林值或空值,不能存其他型別
// 處理Optional變數
// 方法1 ((不建這樣使用)): Force Unwrapping (強迫解開包裝) 確定no一定有值時
var noTest:Int? = 1
noTest!+2
// 方法2: 判斷是不是nil
if noTest != nil {
noTest = noTest!+2
}
//print(noTest) // 會印出 Optional(3)
// 方法3 (最好處理方式): Optional Binding
if let myNumber = noTest {
myNumber + 1
}
| true
|
6c17bf208e5b663544cc3179144109b30b73891d
|
Swift
|
RxDx/SampleApp
|
/SampleApp/AlbumListViewModel.swift
|
UTF-8
| 1,628
| 2.796875
| 3
|
[] |
no_license
|
//
// AlbumListViewModel.swift
// SampleApp
//
// Created by Rodrigo Dumont on 10/08/17.
// Copyright © 2017 RxDx. All rights reserved.
//
class AlbumListViewModel: BaseViewModel {
var albumsHash = [Int: [Album]]()
var error: String? = nil
// MARK: - Repository
func getPhotos() {
delegate?.showLoading()
PhotosRepository().all { (response) in
self.delegate?.hideLoading()
if response.result.isSuccess {
self.albumsHash = self.sortAlbums(response.result.value)
} else {
self.error = response.error?.localizedDescription ?? "Failed to get album"
}
self.delegate?.updateUI()
}
}
// MARK: - Methods
func sortAlbums(_ albums: [Album]?) -> [Int: [Album]] {
guard let albums = albums else {
return [Int: [Album]]()
}
albums.forEach { (album) in
if albumsHash[album.albumId] == nil {
albumsHash[album.albumId] = [Album]()
}
albumsHash[album.albumId]?.append(album)
}
return albumsHash
}
func numberOfSections() -> Int? {
return albumsHash.count
}
func numberOfRowsInSection(_ section: Int) -> Int? {
let keys = Array(albumsHash.keys).sorted()
let albumId = keys[section]
return albumsHash[albumId]?.count
}
func albumFor(section: Int, row: Int) -> Album? {
let keys = Array(albumsHash.keys).sorted()
return albumsHash[keys[section]]?[row]
}
}
| true
|
fc0c54792de01712f819867fee002963185a0ce6
|
Swift
|
phichai/54011212145_Phichai
|
/TipOneTwoThree/TipOneTwoThree/ViewController.swift
|
UTF-8
| 1,361
| 2.640625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// TipOneTwoThree
//
// Created by iStudents on 2/6/15.
// Copyright (c) 2015 iStudents. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
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.
}
var sum : Int = 0
@IBOutlet weak var butOne: UIButton!
@IBOutlet weak var butTwo: UIButton!
@IBOutlet weak var butThree: UIButton!
@IBOutlet weak var butreset: UIButton!
@IBOutlet weak var showOne: UILabel!
@IBOutlet weak var showTow: UILabel!
@IBOutlet weak var showThree: UILabel!
@IBAction func acOne(sender: AnyObject) {
sum += 1
showOne.text = String(format: "%d", sum)
}
@IBAction func acTow(sender: AnyObject) {
sum += 2
showTow.text = String(format: "%d", sum)
}
@IBAction func acThree(sender: AnyObject) {
sum += 3
showThree.text = String(format: "%d", sum)
}
@IBAction func acReset(sender: AnyObject) {
showTow.text = "0"
showOne.text = "0"
showThree.text = "0"
sum = 0
}
}
| true
|
0ba9d17368b16acba6b1e1d0eee21427002560c0
|
Swift
|
wouterdevos/MemeMe
|
/MemeMe/SentMemesCollectionViewController.swift
|
UTF-8
| 2,369
| 2.5625
| 3
|
[] |
no_license
|
//
// SentMemesCollectionViewController.swift
// MemeMe
//
// Created by Wouter de Vos on 2015/10/18.
// Copyright (c) 2015 Wouter. All rights reserved.
//
import UIKit
class SentMemesCollectionViewController: UICollectionViewController {
@IBOutlet weak var flowLayout: UICollectionViewFlowLayout!
var memes : [Meme] {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
return appDelegate.memes
}
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Add, target: self, action: "addNewMeme:")
let space : CGFloat = 4.0
let dimension = (view.frame.size.width - (2 * space)) / 3.0
flowLayout.minimumInteritemSpacing = space
flowLayout.minimumLineSpacing = space
flowLayout.itemSize = CGSizeMake(dimension, dimension)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
collectionView!.reloadData()
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return memes.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("SentMemesCollectionViewCell", forIndexPath: indexPath) as! SentMemesCollectionViewCell
let meme = memes[indexPath.item]
cell.memeImageView.image = meme.memedImage
return cell
}
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let detailController = storyboard!.instantiateViewControllerWithIdentifier("MemeDetailViewController") as! MemeDetailViewController
detailController.meme = memes[indexPath.item]
navigationController?.pushViewController(detailController, animated: true)
}
func addNewMeme(sender : UIBarButtonItem) {
let editorController = storyboard!.instantiateViewControllerWithIdentifier("MemeEditorViewController") as! MemeEditorViewController
presentViewController(editorController, animated: true, completion: nil)
}
}
| true
|
df8b9895974716051facf393067f8d8d8a2cc27c
|
Swift
|
philrevoredo/PhilMAT
|
/MAT FIN/aula7.swift
|
UTF-8
| 2,972
| 2.703125
| 3
|
[] |
no_license
|
//
// TableViewController.swift
// HP 12 C 002
//
// Created by Isa Richter on 17/04/19.
// Copyright © 2019 Philippe Richter. All rights reserved.
//
import UIKit
import ChameleonFramework
class aula3: UITableViewController {
@IBOutlet var aula3tableview: UITableView!
let itemarray3 = ["hey","gdd","","","","","","","",""]
override func viewDidLoad() {
super.viewDidLoad()
tableView.separatorStyle = .none
configureTableView()
}
func configureTableView(){aula3tableview.rowHeight = UITableView.automaticDimension
aula3tableview.estimatedRowHeight = 120.0
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {return
itemarray3.count
}
override func tableView(_ tableView:UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "aula3cell", for: indexPath)
cell.textLabel?.text = itemarray3[indexPath.row]
cell.textLabel?.font = UIFont(name: "Rockwell",size: 20.0)
tableView.rowHeight = 150.0
cell.textLabel?.textColor = FlatWhite()
if indexPath.row == 0
{cell.backgroundColor = FlatYellow().darken(byPercentage: 0.0)
}
else if indexPath.row == 1{
cell.backgroundColor = FlatYellow().darken(byPercentage: 0.05)
}
else if indexPath.row == 2{
cell.backgroundColor = FlatYellow().darken(byPercentage: 0.1)
} else if indexPath.row == 3{
cell.backgroundColor = FlatYellow().darken(byPercentage: 0.15)
} else if indexPath.row == 4{
cell.backgroundColor = FlatYellow().darken(byPercentage: 0.2)
} else if indexPath.row == 5{
cell.backgroundColor = FlatYellow().darken(byPercentage: 0.25)
} else if indexPath.row == 6{
cell.backgroundColor = FlatYellow().darken(byPercentage: 0.3)
} else if indexPath.row == 7{
cell.backgroundColor = FlatYellow().darken(byPercentage: 0.35)
}else if indexPath.row == 8{
cell.backgroundColor = FlatYellow().darken(byPercentage: 0.4)
}else if indexPath.row == 9{
cell.backgroundColor = FlatYellow().darken(byPercentage: 0.45)
}else if indexPath.row == 10{
cell.backgroundColor = FlatYellow().darken(byPercentage: 0.5)
}else if indexPath.row == 11{
cell.backgroundColor = FlatYellow().darken(byPercentage: 0.55)}
return cell
}
}
| true
|
766a2b675851470048a564703a6f15ae1bd9b006
|
Swift
|
innieminnie/Project18-A-BoostPocket
|
/BoostPocket/BoostPocket/Extensions/String+/String+IsCategory.swift
|
UTF-8
| 421
| 2.703125
| 3
|
[] |
no_license
|
//
// String+IsCategory.swift
// BoostPocket
//
// Created by sihyung you on 2020/12/08.
// Copyright © 2020 BoostPocket. All rights reserved.
//
import Foundation
extension String {
func isCategory() -> Bool {
var isCategory: Bool = false
HistoryCategory.allCases.forEach { category in
if self == category.name { isCategory = true }
}
return isCategory
}
}
| true
|
85437b30971d4293027b89be57065650fac5d83f
|
Swift
|
sreeku44/LineGraph
|
/LineGraph/CircleView.swift
|
UTF-8
| 2,422
| 2.96875
| 3
|
[] |
no_license
|
//
// CircleView.swift
// LineGraph
//
// Created by Sreekala Santhakumari on 3/21/17.
// Copyright © 2017 Klas. All rights reserved.
//
import UIKit
class CircleView : UIView {
override func draw(_ rect: CGRect) {
//to create circle in a view
UIColor.red.setFill()
let circle1 = UIBezierPath(ovalIn: CGRect(x: 8, y: 495, width: 10, height: 10))
circle1.fill()
UIColor.red.setFill()
let circle2 = UIBezierPath(ovalIn: CGRect(x: 31, y: 78, width: 10, height: 10))
circle2.fill()
circle2.stroke()
let circle3 = UIBezierPath(ovalIn: CGRect(x: 76, y: 398, width: 10, height: 10))
circle3.fill()
circle3.stroke()
let circle4 = UIBezierPath(ovalIn: CGRect(x: 145, y: 348, width: 10, height: 10))
circle4.fill()
circle4.stroke()
let circle5 = UIBezierPath(ovalIn: CGRect(x: 215, y: 300, width: 10, height: 10))
circle5.fill()
circle5.stroke()
let circle6 = UIBezierPath(ovalIn: CGRect(x: 275, y: 275, width: 10, height: 10))
circle6.fill()
circle6.stroke()
let circle7 = UIBezierPath(ovalIn: CGRect(x: 338, y: 275, width: 10, height: 10))
circle7.fill()
circle7.stroke()
//to create an outline
UIColor.blue.setStroke()
circle1.stroke()
//to create a line
let line = UIBezierPath()
line.lineWidth = 1
line.move(to: CGPoint(x: 10, y: 500))
line.addLine(to: CGPoint(x: 35, y: 80))
line .addLine(to: CGPoint(x: 80, y: 400))
line.addLine(to: CGPoint(x: 120, y: 100))
line.addLine(to: CGPoint(x: 150, y: 350))
line.addLine(to: CGPoint(x: 200, y: 150))
line.addLine(to: CGPoint(x: 220, y: 300))
line.addLine(to: CGPoint(x: 250, y: 180))
line.addLine(to: CGPoint(x: 280, y: 280))
line.addLine(to: CGPoint(x: 300, y: 205))
line.addLine(to: CGPoint(x: 340, y: 280))
line.stroke()
//
// let line = UIBezierPath()
// line.lineWidth = 1
// line.move(to: CGPoint(x: 10, y: 10))
// line.addLine(to: CGPoint(x: 100, y: 10))
// line.addLine(to: CGPoint(x: 10, y: 100))
// line.close()
//
// line.fill()
// line.stroke()
}
}
| true
|
76f4aa4d4501a6180b5e990997ee3b849c8e8c1f
|
Swift
|
bayupaoh/learn-ios-2018
|
/delegatesample/delegatesample/ChooseSideViewController.swift
|
UTF-8
| 1,738
| 2.90625
| 3
|
[] |
no_license
|
//
// ChooseSideViewController.swift
// delegatesample
//
// Created by Bayu Paoh on 24/09/18.
// Copyright © 2018 Bayu Paoh. All rights reserved.
//
import UIKit
protocol ChooseSideDelegate {
func onSelectSide(_ side:String)
}
class ChooseSideViewController: UIViewController {
var sideDelegate:ChooseSideDelegate?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func lightSidePressed(_ sender: Any) {
navigationController?.popViewController(animated: true)
sideDelegate?.onSelectSide("Light Side")
}
@IBAction func darkSidePressed(_ sender: Any) {
navigationController?.popViewController(animated: true)
sideDelegate?.onSelectSide("Dark Side")
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
static func instantiate(sideDelegate:ChooseSideDelegate) -> ChooseSideViewController{
let storyBoard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyBoard.instantiateViewController(withIdentifier: "ChooseSideViewController") as! ChooseSideViewController
controller.sideDelegate = sideDelegate
return controller
}
}
| true
|
f6923696ae0023b13f6e6a4bd063e119847dd189
|
Swift
|
PePacheco/Vibe.me
|
/Vibe.me/Models/User.swift
|
UTF-8
| 721
| 3.59375
| 4
|
[] |
no_license
|
//
// User.swift
// Vibe.me
//
// Created by Pedro Gomes Rubbo Pacheco on 17/03/21.
//
import Foundation
class User: Codable {
var username: String
var password: String
var favoriteSongs: [Song]
init(username: String, password: String) {
self.username = username
self.password = password
self.favoriteSongs = []
}
func addFavoriteSong(newSong: Song) {
let contains = favoriteSongs.contains { song in
song.name == newSong.name
}
if !contains {
favoriteSongs.append(newSong)
print("\nMusic added to your playlist.\n")
} else {
print("\nThis song is already in your playlist.\n")
}
}
}
| true
|
7457012b1175bcb7c068ba594ecec675bcb0861b
|
Swift
|
ji3g4kami/MementoPattern
|
/Memento_RayWenderlic/Caretaker.swift
|
UTF-8
| 744
| 2.9375
| 3
|
[] |
no_license
|
//
// Caretaker.swift
// Memento_AppCoda
//
// Created by David on 2019/12/27.
// Copyright © 2019 David. All rights reserved.
//
public class GameSystem {
private let decoder = JSONDecoder()
private let encoder = JSONEncoder()
private let userDefaults = UserDefaults.standard
public func save(_ game: Game, title: String) throws {
let data = try encoder.encode(game)
userDefaults.set(data, forKey: title)
}
public func load(title: String) throws -> Game {
guard let data = userDefaults.data(forKey: title),
let game = try? decoder.decode(Game.self, from: data) else {
throw Error.gameNotFound
}
return game
}
public enum Error: String, Swift.Error {
case gameNotFound
}
}
| true
|
714be9271b64359a8e750ab8e294c2708ef19d54
|
Swift
|
willpowell8/DictionaryUtils
|
/DictionaryUtils/Classes/Dictionary+Extension.swift
|
UTF-8
| 6,270
| 3.078125
| 3
|
[
"MIT"
] |
permissive
|
//
// Dictionary+Extension.swift
// Pods
//
// Created by Will Powell on 01/04/2017.
//
//
import Foundation
public enum DictionaryError:Error {
case noarrayFound
case invalidQueryString
case invalidQueryEmptyParam
case noMatchInArray
case canNotRouteThroughArrayWithMultipleResults
}
public extension Dictionary where Key: ExpressibleByStringLiteral {
func read(_ param: String) throws -> Any? {
guard !param.isEmpty else{
throw DictionaryError.invalidQueryEmptyParam
}
var paramParts = param.components(separatedBy: ".")
var currentElement:[AnyHashable : Any] = self
for i in 0..<paramParts.count {
let part = paramParts[i]
if part.contains("["), part.contains("]") {
let parts = part.components(separatedBy: "[")
if parts.count == 2 {
guard let ary = currentElement[parts[0]] as? [[AnyHashable:Any]] else {
return nil
}
if ary.count == 0 {
throw DictionaryError.noarrayFound
}
let finalSegmentParts = parts[1].components(separatedBy: "]")
if finalSegmentParts.count == 2, finalSegmentParts[1] == "" {
let finalSegment = finalSegmentParts[0]
if let finalSegmentInt = Int(finalSegment), finalSegmentInt>=0 {
// is integer in parameter
if i>=0, i < paramParts.count - 1 {
if ary.count > finalSegmentInt {
currentElement = ary[finalSegmentInt]
}else{
return nil
}
}else{
if ary.count > finalSegmentInt {
return ary[finalSegmentInt]
}
return nil
}
}else{
// is query string
var queryParams = [String:AnyHashable]()
let splitParameters = finalSegment.components(separatedBy: ",")
splitParameters.forEach({ (item) in
if item.contains("=") {
let itemParts = item.components(separatedBy: "=")
if itemParts.count == 2 {
if let itemPartIsInt = Int(itemParts[1]){
queryParams[itemParts[0]] = itemPartIsInt
}else{
queryParams[itemParts[0]] = itemParts[1]
}
}else{
// incorrect number of parts
print("Dictionary Utils: Incorrect parts in \(item)")
return
}
}
})
let output = ary.filter({ (item) -> Bool in
var isValid = true
queryParams.forEach({ (key,value) in
if let itemValue = item[key] as? AnyHashable, itemValue == value {
}else{
isValid = false
}
})
return isValid
})
if output.count == 0{
throw DictionaryError.noMatchInArray
}
if i < paramParts.count - 1 {
if output.count == 1 {
currentElement = output[0]
}else{
throw DictionaryError.canNotRouteThroughArrayWithMultipleResults
}
}else{
return output
}
}
}else{
throw DictionaryError.invalidQueryString
}
}else{
throw DictionaryError.invalidQueryString
}
}else{
if i < paramParts.count - 1 {
if let childElement = currentElement[part] as? Dictionary<AnyHashable, Any>?, let c = childElement {
currentElement = c
}else if let childElement = currentElement[part] as? [[AnyHashable:Any]] {
if childElement.count > 0 {
currentElement = childElement[0]
}else{
throw DictionaryError.invalidQueryString
}
}else{
throw DictionaryError.invalidQueryString
}
}else{
return currentElement[part]
}
}
}
return nil
}
func evaluate(_ param: String) -> Any? {
do{
return try self.read(param)
}catch{
}
return nil
}
func readString(_ param: String) throws -> String? {
do{
return try self.read(param) as? String
}catch{
throw error
}
}
func readInt(_ param: String) throws -> Int? {
do{
return try self.read(param) as? Int
}catch{
throw error
}
}
func readBool(_ param: String) throws -> Bool? {
do{
return try self.read(param) as? Bool
}catch{
throw error
}
}
}
| true
|
6dfa32b3fe6dc324ac3f2a7b9c7978fff1df0bbc
|
Swift
|
markpmlim/AppleIIDHGRConverter
|
/Apple2ColorDHGR.playground/Sources/DHGRImage.swift
|
UTF-8
| 6,697
| 3.25
| 3
|
[] |
no_license
|
/*
An instance of this class will convert the data passed into a 24-bit RGB raw bitmap.
The caller can access the instantiated CGImage object through its "cgImage" property.
*/
import Cocoa
import PlaygroundSupport
public class DHGRConverter {
public var cgImage: CGImage?
var baseOffsets = [Int](repeating:0, count:192)
func generateBaseOffsets() {
var groupOfEight, lineOfEight, groupOfSixtyFour: Int
// Both HGR and DHGR graphics have 192 vertical lines.
// The screen lines of both types of graphics also have the same starting base offsets.
for line in 0..<192 {
lineOfEight = line % 8 // 8 lines
groupOfEight = (line % 64) / 8 // 8 groups of 8 lines
groupOfSixtyFour = line / 64 // 3 groups of 64 lines
baseOffsets[line] = lineOfEight * 0x0400 + groupOfEight * 0x0080 + groupOfSixtyFour * 0x0028
}
/*
for line in 0..<192 {
let baseStr = String(format: "%04x", baseOffsets[line])
print("\(line) $:\(baseStr)")
}
*/
}
func reverseBits(_ bitPattern: UInt8) -> UInt8 {
var newValue:UInt8 = 0
for i:UInt8 in 0..<8 {
if bitPattern & (1 << i) != 0 {
newValue |= (1 << (7-i))
}
}
newValue >>= 4
return newValue
}
struct Pixel {
var r: UInt8
var g: UInt8
var b: UInt8
}
let colorValues: [UInt8] = [
0, 0, 0, // 0 - Black
206, 15, 49, // 1 - Magenta 0x72, 0x26, 0x06 Deep Red
156, 99, 1, // 2 - Brown 0x40, 0x4C, 0x04
255, 70, 0, // 3 - Orange 0xE4, 0x65, 0x01
0, 99, 49, // 4 - Dark Green 0x0E, 0x59, 0x40
82, 82, 82, // 5 - Gray 0x80, 0x80, 0x80
0, 221, 2, // 6 - Green 0x1B, 0xCB, 0x01
255, 253, 4, // 7 - Yellow 0xBF, 0xCC, 0x80
2, 19, 156, // 8 - Dark Blue 0x40, 0x33, 0x7F
206, 49, 206, // 9 - Violet 0xE4, 0x34, 0xFE Purple
173, 173, 173, // A - Grey 0x80, 0x80, 0x80
255, 156, 156, // B - Pink 0xF1, 0xA6, 0xBF
49, 49, 255, // C - Blue 0x1B, 0x9A, 0xFE
99, 156, 255, // D - Light Blue 0xBF, 0xB3, 0xFF
49, 253, 156, // E - Aqua 0x8D, 0xD9, 0xBF
255, 255, 255] // F - White 0xFF, 0xFF, 0xFF
var colorTable = [Pixel]()
public init(data srcData: Data) {
// Prepare the color table as an array of 16 RGB color entries for easier access.
for i in stride(from: 0, to: 48, by: 3) {
let color = Pixel(r: colorValues[i+0],
g: colorValues[i+1],
b: colorValues[i+2])
colorTable.append(color)
}
generateBaseOffsets()
// We assume the A2FC file is saved as 2 separate blobs of data
// The data from aux bank ($2000-$3FFFF) is saved first
// followed by data from the main bank ($2000-$3FFFF)
let bir = NSBitmapImageRep(bitmapDataPlanes: nil,
pixelsWide: 560,
pixelsHigh: 384,
bitsPerSample: 8,
samplesPerPixel: 3,
hasAlpha: false,
isPlanar: false,
colorSpaceName: NSDeviceRGBColorSpace,
bytesPerRow: 560 * 3, // 1680 bytes
bitsPerPixel: 24)
// Get the pointer to the memory allocated.
// The size of the memory block should be 560x3x384 bytes.
let bm = bir?.bitmapData
for row in 0..<192 {
let lineOffset = baseOffsets[row]
var srcPixels = [Pixel](repeating:Pixel(r: 0, g: 0, b: 0), count: 140)
var pixelIndex = 0
var destPixels = [Pixel](repeating:Pixel(r: 0, g: 0, b: 0), count: 560)
// Each time thru the loop below, 4 bytes are consumed to produce 7 RGB pixels.
// Since the loop executes 20 times, a total of 7x20=140 RGB pixels are produced
// for every screen line of data.
for col in stride(from: 0, to: 40, by: 2) {
// Extract 2 bytes from Auxiliary bank & 2 from the Main bank.
let aux0 = (srcData[lineOffset+col+0])
let aux1 = (srcData[lineOffset+col+1])
let main0 = (srcData[0x2000+lineOffset+col+0])
let main1 = (srcData[0x2000+lineOffset+col+1])
var bitPatterns = [UInt8](repeating: 0x00, count: 7)
// Compute seven (4-bit) patterns from the 4 bytes.
bitPatterns[0] = aux0 & 0x0f
bitPatterns[1] = ((main0 & 0x01) << 3) | ((aux0 & 0x70) >> 4)
bitPatterns[2] = ((main0 & 0x1E) >> 1)
bitPatterns[3] = ((aux1 & 0x03) << 2) | ((main0 & 0x60) >> 5)
bitPatterns[4] = ((aux1 & 0x3C) >> 2)
bitPatterns[5] = ((main1 & 0x07) << 1) | ((aux1 & 0x40) >> 6)
bitPatterns[6] = ((main1 & 0x78) >> 3)
// Use the bit patterns to index the color table and obtain 7 RGB pixels.
for i in 0..<7 {
let colorPixel = colorTable[Int(reverseBits(bitPatterns[i]))]
srcPixels[pixelIndex] = colorPixel
pixelIndex += 1
}
} // col
// When we reach here, the 560 bits have been converted into a row of 140 RGB pixels.
// Proceed convert the row into one with 560 RGB pixels.
// Each color pixel is quadruple in size.
for k in 0..<140 {
let pixel = srcPixels[k]
destPixels[4*k+0] = pixel
destPixels[4*k+1] = pixel
destPixels[4*k+2] = pixel
destPixels[4*k+3] = pixel
} // k
// Double the number of rows.
let evenIndex = 2 * row * 560 * 3
let oddIndex = (2 * row + 1) * 560 * 3
for k in 0..<560 {
let pixel = destPixels[k]
bm?[evenIndex+3*k+0] = pixel.r
bm?[evenIndex+3*k+1] = pixel.g
bm?[evenIndex+3*k+2] = pixel.b
bm?[ oddIndex+3*k+0] = pixel.r
bm?[ oddIndex+3*k+1] = pixel.g
bm?[ oddIndex+3*k+2] = pixel.b
} // k
} // row
cgImage = bir?.cgImage
}
}
| true
|
90a07d3e98b0cf12f6ceccb7d81d726dac0b031a
|
Swift
|
gingerfungus/sicnu_exercise
|
/sicnu_exercise/WeiboListView.swift
|
UTF-8
| 1,792
| 2.734375
| 3
|
[] |
no_license
|
//
// WeiboListView.swift
// sicnu_exercise
// 微博列表显示
// Created by apple on 2021/1/4.
//
import SwiftUI
import BBSwiftUIKit
struct WeiboListView: View {
let category: WeiboListCategory
@EnvironmentObject var userData: UserData
var body: some View{
BBTableView(userData.weiboList(for: category).list) { weibo in
NavigationLink(destination: WeiboDetailView(weibo: weibo)) {
WeiboCell(weibo: weibo)
}
.buttonStyle(OriginalButtonStyle())
}
// 下拉刷新
.bb_setupRefreshControl { control in
control.attributedTitle = NSAttributedString(string: "刷新中..")
}
.bb_pullUpToLoadMore(bottomSpace: 30) {
userData.loadMoreWeiboList(for: category)
}
// 上拉加载内容
.bb_pullDownToRefresh(isRefreshing: $userData.isRefreshing) {
userData.refreshWeiboList(for: category)
}
.bb_reloadData($userData.reloadData)
// List {
// ForEach(userData.weiboList(for: category).list) { weibo in
// ZStack {
// WeiboCell(weibo: weibo)
// NavigationLink(
// destination: WeiboDetailView(weibo: weibo)){
// EmptyView()
// }
// .hidden()
// }
// .listRowInsets(EdgeInsets())
// }
// }
}
}
struct WeiboListView_Previews: PreviewProvider {
static var previews: some View {
NavigationView{
WeiboListView(category: .hot)
.navigationBarTitle("首页")
.navigationBarHidden(true)
}
.environmentObject(UserData())
}
}
| true
|
3e95cbcb4dc581a5ad48813b9c5d4b544fa29155
|
Swift
|
stephkananth/doughboy
|
/DoughboyQR/View Controllers/DoneViewController.swift
|
UTF-8
| 777
| 2.5625
| 3
|
[] |
no_license
|
//
// DoneViewController.swift
// DoughboyQR
//
// Created by Steph Ananth on 12/11/19.
// Copyright © 2019 AppCoda. All rights reserved.
//
import Foundation
import UIKit
class DoneViewController: UIViewController {
override var prefersStatusBarHidden: Bool {
return true
}
var viewModel: ViewModel? = nil
@IBOutlet weak var trialsLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.hidesBackButton = true
self.updateLabels()
}
func updateLabels() {
self.trialsLabel.text = "User completed \(self.viewModel!.numRounds) trials"
self.timeLabel.text = "User took \(self.viewModel!.stopwatch.elapsedTime! / Double(self.viewModel!.numRounds))"
}
}
| true
|
f925b0e5ff7c79b789440e3ffc5af7df850bc6dc
|
Swift
|
HunterG003/TheMusicTimer
|
/MusicTimer/Music Player/MusicPlayer.swift
|
UTF-8
| 14,366
| 2.671875
| 3
|
[] |
no_license
|
//
// MusicPlayer.swift
// MusicTimer
//
// Created by Hunter Gilliam on 4/7/20.
// Copyright © 2020 Hunter Gilliam. All rights reserved.
//
import MediaPlayer
import StoreKit
class MusicPlayer {
fileprivate let devToken = "eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IlhEOFY3SExVR1EifQ.eyJpc3MiOiJFN1k0NTRRVE41IiwiaWF0IjoxNjE0NzQ0NTYxLCJleHAiOjE2MzAyOTI5NjF9.6Vll1fVDYISyT2qlyYhtrkvGjVfbgORqq2bnOhHMKSw9Ki9b8DyRq_Rdf3iiw3ZavCBCX118bt9jyVLbt2n8xA" // Regenerated 3/2/2021
fileprivate let controller = SKCloudServiceController()
fileprivate let systemMusicController = MPMusicPlayerController.systemMusicPlayer
fileprivate let serviceController = SKCloudServiceController()
fileprivate var userToken = ""
fileprivate var userStorefront = ""
fileprivate var hasSubsetBeenFound = false
fileprivate var isMoreSongs = true
var userPlaylists = [Playlist]()
var selectedPlaylist = 0
var musicQueue = [Song]()
var isPlaying = false
var tempCount = 0
init() {
systemMusicController.beginGeneratingPlaybackNotifications()
}
deinit {
systemMusicController.endGeneratingPlaybackNotifications()
}
}
// MARK: Setup Functions
extension MusicPlayer {
func getAuth(completion: @escaping (Bool) -> Void) {
SKCloudServiceController.requestAuthorization { (auth) in
switch auth{
case .authorized:
self.getUserToken(completion: {
completion(true)
})
self.getStoreFront()
case .denied, .notDetermined, .restricted:
self.controller.requestCapabilities { (capability, err) in
if let err = err {
print("Error: \(err)")
return
}
completion(false)
}
default:
print("idk")
}
}
}
// Gets User's token and stores it into userToken var
fileprivate func getUserToken(completion: @escaping () -> Void) {
controller.requestUserToken(forDeveloperToken: devToken) { (token, err) in
if let err = err {
print("Error getting user token: \(err)")
fatalError()
}
guard let token = token else { fatalError("No Token") }
self.userToken = token
print("User Token:", self.userToken)
completion()
}
}
// Gets User's storefront and stores it into userStorefront var
fileprivate func getStoreFront() {
controller.requestStorefrontCountryCode { (store, err) in
if let err = err {
print("Error getting storefront: \(err)")
fatalError()
}
guard let store = store else { fatalError("No Storefront Code") }
self.userStorefront = store
print("Storefront Code:", self.userStorefront)
}
}
}
// MARK: Retrieve Playlists Functions
extension MusicPlayer {
func getUsersPlaylists(completion: @escaping ([Playlist]) -> Void) {
var playlists = [Playlist]()
var components = URLComponents()
components.scheme = "https"
components.host = "api.music.apple.com"
components.path = "/v1/me/library/playlists"
let url = components.url!
var request = URLRequest(url: url)
request.setValue("Bearer \(devToken)", forHTTPHeaderField: "Authorization")
request.setValue(userToken, forHTTPHeaderField: "Music-User-Token")
URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data else { fatalError("No data got returned") }
do {
let object = try JSONDecoder().decode(UserPlaylistObject.self, from: data)
self.tempCount = object.data.count
for playlist in object.data {
if playlist.attributes.artwork?.url == nil {
self.getImageForAPlaylist(playlist: playlist.id, completion: { url in
let new = Playlist(name: playlist.attributes.name, id: playlist.id, artworkUrl: url)
playlists.append(new)
self.userPlaylists.append(new)
completion(playlists)
})
} else {
var url = playlist.attributes.artwork?.url ?? ""
url = url.replacingOccurrences(of: "{w}", with: "500")
url = url.replacingOccurrences(of: "{h}", with: "500")
playlists.append(Playlist(name: playlist.attributes.name, id: playlist.id, artworkUrl: url))
}
}
self.userPlaylists = playlists
completion(playlists)
} catch {
print(error)
}
}.resume()
}
private func getImageForAPlaylist(playlist: String, completion: @escaping (String) -> Void) {
let path = "/v1/me/library/playlists/\(playlist)/tracks"
var components = URLComponents()
components.scheme = "https"
components.host = "api.music.apple.com"
components.path = path
// components.queryItems = [
// URLQueryItem(name: "limit", value: "1")
// ]
let url = components.url!
var request = URLRequest(url: url)
request.setValue("Bearer \(devToken)", forHTTPHeaderField: "Authorization")
request.setValue(userToken, forHTTPHeaderField: "Music-User-Token")
URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data else { return }
do {
let json = try JSONSerialization.jsonObject(with: data, options: []) as! Dictionary<String, Any>
// Simple Check for errors
// TODO: Check for specific errors
if let _ = json["errors"] {
self.tempCount -= 1
return
}
// print(json)
let jsonData = json["data"] as! Array<Dictionary<String, Any>>
let attributes = jsonData[0]["attributes"] as! Dictionary<String, Any>
let artwork = attributes["artwork"] as! Dictionary<String, Any>
var url = artwork["url"] as! String
url = url.replacingOccurrences(of: "{w}x{h}", with: "500x500")
completion(url)
} catch {
print("Error: \(error)")
}
}.resume()
}
}
// MARK: Fetch Songs Functions
extension MusicPlayer {
func getSongsFromPlaylist(from playlist: String, completion: @escaping ([Song]) -> Void) {
var songs = [Song]()
let path = "/v1/me/library/playlists/\(playlist)/tracks"
getNumberOfSongsInPlaylist(playlist: playlist) { (num) in
let numberOfFetches = (num / 100) + 1
for i in 0..<numberOfFetches {
self.fetchSongs(path: path, offset: i * 100) { (arr) in
songs.append(contentsOf: arr)
if songs.count == num {
completion(songs)
print("Number of total songs: \(songs.count)")
}
}
}
}
}
private func getNumberOfSongsInPlaylist(playlist: String, completion: @escaping (Int) -> Void) {
let path = "/v1/me/library/playlists/\(playlist)/tracks"
var components = URLComponents()
components.scheme = "https"
components.host = "api.music.apple.com"
components.path = path
components.queryItems = [
URLQueryItem(name: "limit", value: "1")
]
let url = components.url!
var request = URLRequest(url: url)
request.setValue("Bearer \(devToken)", forHTTPHeaderField: "Authorization")
request.setValue(userToken, forHTTPHeaderField: "Music-User-Token")
URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data else { return }
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
let realData = json as! Dictionary<String, Any>
let meta = realData["meta"] as! Dictionary<String, Any>
print(meta["total"] ?? "")
let returnValue : Int = meta["total"] as! Int
completion(returnValue)
} catch {
}
}.resume()
}
private func fetchSongs(path: String, offset: Int, completion: @escaping ([Song]) -> Void) {
var songs = [Song]()
var components = URLComponents()
components.scheme = "https"
components.host = "api.music.apple.com"
components.path = path
components.queryItems = [
URLQueryItem(name: "offset", value: "\(offset)")
]
let url = components.url!
var request = URLRequest(url: url)
request.setValue("Bearer \(devToken)", forHTTPHeaderField: "Authorization")
request.setValue(userToken, forHTTPHeaderField: "Music-User-Token")
URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data else { return }
do {
let object = try JSONDecoder().decode(PlaylistTracksObject.self, from: data)
for track in object.data {
var url = track.attributes.artwork?.url ?? ""
url = url.replacingOccurrences(of: "{w}x{h}", with: "500x500")
let song = Song(id: track.attributes.playParams.catalogId ?? track.attributes.playParams.id, name: track.attributes.name, artist: track.attributes.artistName, artworkUrl: url, durationInMS: track.attributes.durationInMillis, runTime: track.attributes.durationInMillis / 1000)
songs.append(song)
}
completion(songs)
} catch {
print("Error: \(error)")
}
}.resume()
}
}
// MARK: MT Algorithm
extension MusicPlayer {
func findSongSubset(songs : [Song], numberOfSongs : Int, timeToFind : Int) -> [Song] {
var dp : [[Bool?]] = Array(repeating: Array(repeating: nil, count: timeToFind + 1), count: numberOfSongs)
if numberOfSongs == 0 || timeToFind < 0 {
NotificationCenter.default.post(name: NSNotification.Name.noSongsFound, object: nil)
return []
}
for i in 0..<numberOfSongs {
dp[i][0] = true
}
if songs[0].runTime <= timeToFind {
dp[0][songs[0].runTime] = true
}
for i in 1..<numberOfSongs {
for j in 0..<timeToFind+1 {
dp[i][j] = (songs[i].runTime <= j) ? (dp[i-1][j] ?? false || dp [i-1][j-songs[i].runTime] ?? false) : dp[i-1][j]
}
}
if dp[numberOfSongs-1][timeToFind] == false {
print("There are no subsets with sum", timeToFind)
NotificationCenter.default.post(name: NSNotification.Name.noSongsFound, object: nil)
return []
}
hasSubsetBeenFound = false
return searchWithRecursion(songs: songs, i: numberOfSongs - 1, timeToFind: timeToFind, subset: [], dp: dp)
}
private func searchWithRecursion(songs : [Song], i : Int, timeToFind : Int, subset : [Song], dp : [[Bool?]]) -> [Song] {
var newSubset = subset
if i == 0 && timeToFind != 0 && dp[0][timeToFind] ?? false {
newSubset.append(songs[i])
hasSubsetBeenFound = true
return newSubset
}
if i == 0 && timeToFind == 0 {
hasSubsetBeenFound = true
return newSubset
}
if !hasSubsetBeenFound {
if dp[i-1][timeToFind] ?? false {
let b : [Song] = newSubset
return searchWithRecursion(songs: songs, i: i-1, timeToFind: timeToFind, subset: b, dp: dp)
}
if timeToFind >= songs[i].runTime && dp[i-1][timeToFind-songs[i].runTime] ?? false {
newSubset.append(songs[i])
return searchWithRecursion(songs: songs, i: i-1, timeToFind: timeToFind-songs[i].runTime, subset: newSubset, dp: dp)
}
}
NotificationCenter.default.post(name: NSNotification.Name.noSongsFound, object: nil)
return []
}
}
// MARK: The Infamous Play Function
extension MusicPlayer {
func play(playlist: Playlist, timeToPlay: Int, completion: @escaping (Bool) -> Void) {
getSongsFromPlaylist(from: playlist.id) { songs in
self.musicQueue = self.findSongSubset(songs: songs.shuffled(), numberOfSongs: songs.count, timeToFind: timeToPlay)
if self.musicQueue.isEmpty {
completion(false)
return
}
var ids = [String]()
self.musicQueue.forEach { (i) in
ids.append(i.id)
print(i.name)
}
self.systemMusicController.setQueue(with: ids)
self.systemMusicController.shuffleMode = .off
self.systemMusicController.prepareToPlay { (err) in
if let err = err {
fatalError("\(err)")
}
self.systemMusicController.play()
self.isPlaying = true
}
completion(true)
// let duration = timeToPlay / 60
// let lastPlaylist = LastPlaylist(name: playlist.name, duration: "\(duration) Minutes")
// if let groupUserDefaults = UserDefaults(suiteName: "group.huntergilliam.musictimer.contents") {
// groupUserDefaults.set(lastPlaylist.name, forKey: "lastPlaylistName")
// groupUserDefaults.set(lastPlaylist.duration, forKey: "lastPlaylistDuration")
// }
}
}
}
| true
|
bc4b5e509dd223a1082d6a0f80854f8b7f76389b
|
Swift
|
Jax45/Iclock
|
/IClock/MainView.swift
|
UTF-8
| 749
| 2.890625
| 3
|
[] |
no_license
|
import UIKit
class MainView: UIView {
override func addSubview(_ view: UIView) {
super.addSubview(view)
setupView(view)
}
private func setupView(_ view: UIView) {
subviews.forEach { (subview) in
if view === subview {
view.translatesAutoresizingMaskIntoConstraints = false
view.topAnchor.constraint(equalTo: topAnchor).isActive = true
view.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
view.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
view.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
view.setNeedsLayout()
}
}
}
}
| true
|
b43f795904163dc03880a7a807d44f44dd09581f
|
Swift
|
vishapatels/EyesApp
|
/EyesApp/API Model/UserDetailManager.swift
|
UTF-8
| 1,438
| 2.5625
| 3
|
[] |
no_license
|
//
// UserDetailManaget.swift
// EyesApp
//
// Created by Visha Shanghvi on 2019-07-22.
// Copyright © 2019 Visha Shanghvi. All rights reserved.
//
import Foundation
protocol UserDetailManagerProtocol {
func getUserDetail(id:String, completionHandler complete: @escaping(ServiceResult<[UserDetailDataProvider]>) -> Void)
}
final class UserDetailManager: UserDetailManagerProtocol {
func getUserDetail(id:String, completionHandler complete: @escaping(ServiceResult<[UserDetailDataProvider]>) -> Void) {
var logger: NetworkLogger = NetworkLogger()
DispatchQueue.episodeManager.async {
APIService.shared.performRequest(router: .getUserDetailInfo(id: id), completionHandler: { result in
switch result {
case .success(let data):
if let data = data, let userDetail: UserDetailModel = UserDetailModel.from(data: data) {
DispatchQueue.main.async {
if let userDetailProviders: [UserDetailDataProvider] = userDetail.content?.userDetailProviders {
complete(.success(userDetailProviders))
}
}
}
case .failure(let error):
DispatchQueue.main.async {
complete(.failure(error))
}
}
})
}
}
}
| true
|
06b3d44e7a0c26f4b1b1a3f7b6f7da4d8edbf2d7
|
Swift
|
dcohron/CSCI65G
|
/Section05/SimpleCoreGraphics.playground/section-14.swift
|
UTF-8
| 256
| 2.515625
| 3
|
[] |
no_license
|
let shadowView = UIView(frame: rect)
shadowView.layer.shadowColor = UIColor.blackColor().CGColor
shadowView
shadowView.layer.shadowOffset = CGSizeZero
shadowView
shadowView.layer.shadowOpacity = 0.7
shadowView
shadowView.layer.shadowRadius = 50
shadowView
| true
|
726c19e6285ba15ce4d9227855801dddd501bd27
|
Swift
|
nooraja/Suara
|
/Suara/Scene/MainTabbarController.swift
|
UTF-8
| 1,447
| 2.6875
| 3
|
[] |
no_license
|
//
// MainTabbarController.swift
// Suara
//
// Created by Muhammad Noor on 17/07/21.
//
import UIKit
class MainTabbarController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
tabBar.barTintColor = .systemBackground
tabBar.tintColor = .systemBlue
tabBar.unselectedItemTintColor = .systemGray
tabBar.isTranslucent = false
let homeController = createTabBarItem(tabBarTitle: "Home", tabBarImage: "house", selectedImage: "house.fill", viewController: HomeController(mainView: HomeView(), viewModel: HomeViewModel(networkModel: HomeNetworkModel())))
let favoriteController = createTabBarItem(tabBarTitle: "Favorite", tabBarImage: "heart", selectedImage: "heart.fill", viewController: FavoriteController(viewModel: FavoriteViewModel()))
viewControllers = [homeController, favoriteController]
}
func createTabBarItem(tabBarTitle: String, tabBarImage: String, selectedImage : String, viewController: UIViewController) -> UINavigationController {
let navCont = UINavigationController(rootViewController: viewController)
navCont.tabBarItem.title = tabBarTitle
navCont.tabBarItem.image = UIImage(systemName: tabBarImage)
navCont.tabBarItem.selectedImage = UIImage(systemName: selectedImage)
// Nav Bar Customisation
navCont.navigationBar.barTintColor = .systemBackground
navCont.navigationBar.tintColor = .systemBlue
navCont.navigationBar.isTranslucent = false
return navCont
}
}
| true
|
5980374a63396f51da23be2b99a7e8ce6a3fbc58
|
Swift
|
actionjdjackson/Anointed
|
/Anointed/MakeToga.swift
|
UTF-8
| 2,815
| 3.078125
| 3
|
[] |
no_license
|
//
// MakeToga.swift
// Anointed
//
// Created by Jacob Jackson on 11/17/15.
// Copyright © 2015 ThinkMac Innovations. All rights reserved.
//
import Foundation
import SpriteKit
class MakeToga : Subskill {
init( user: GameCharacter ) {
super.init(skillName: "Make Toga", skillDesc: "Make a cloth toga.", skillUser: user, skillSprite: "toga", baseTimeToComplete: 2, level: 1)
}
/* USE TOGAMAKING SKILL ON SELF (TOGA GOES INTO INVENTORY) */
override func use() {
//if you have all the raw materials necessary,
if canUse() {
UNIVERSE.theScene.makeProgressBarFor(self.hoursToComplete, caption: "Making Toga...", completion: {
//make a tent
self.user.inventory.append(self.makeToga())
//level up tentmaking skill
self.levelUp()
//report to screen
UNIVERSE.alertText("Made a basic cloth toga.")
})
} else { //if we don't have enough raw materials,
UNIVERSE.alertText("Not enough resources to make a toga. Sorry.") // no can do
}
}
/* USE TOGAMAKING SKILL ON NPC (GOES INTO NPC'S INVENTORY) */
override func useOnNPC(npc: NonPlayingCharacter) {
//if you have all the raw materials necessary,
if canUse() {
//make a tent
npc.inventory.append(self.makeToga())
//level up tentmaking skill
self.levelUp()
//report to screen
UNIVERSE.alertText("Made a basic cloth toga for " + npc.name!)
} else { //if we don't have enough raw materials,
UNIVERSE.alertText("Not enough resources to make a toga. Sorry.") //UNIVERSE.alertText no can do
}
}
func makeToga() -> Item {
user.grabFromInventory("Cloth")
user.grabFromInventory("Cloth")
user.grabFromInventory("Cloth")
let newToga = Item(ttl: "Toga", desc: "A basic cloth toga.", sx: 1, sy: 2, spriteName: "toga")
return newToga
}
/* CAN WE USE THE TOGAMAKING SKILL RIGHT NOW? */
override func canUse() -> Bool {
if user.howManyInInventory("Cloth") > 2 && self.level >= levelRequired { //if we've got enough stuff
return true //then we can use the togamaking skill
} else { //otherwise,
return false //we can't
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| true
|
ef53d29f467ba1c73c5a9ff45fe2176f0ad3039d
|
Swift
|
abozaid-ibrahim/SchipholAirport
|
/SchipholApp/Scenes/Airports/Flight.swift
|
UTF-8
| 548
| 2.640625
| 3
|
[] |
no_license
|
//
// Flight.swift
// SchipholApp
//
// Created by abuzeid on 30.10.20.
// Copyright © 2020 abuzeid. All rights reserved.
//
import Foundation
struct Flight: Codable {
let airlineID: String
let flightNumber: Int?
let departureAirportID: String
let arrivalAirportID: String
enum CodingKeys: String, CodingKey {
case airlineID = "airlineId"
case flightNumber
case departureAirportID = "departureAirportId"
case arrivalAirportID = "arrivalAirportId"
}
}
typealias FlightsList = [Flight]
| true
|
87b9bd7ad16e719673d8dc7da4c419877734bbda
|
Swift
|
xiaomi388/ditto-music
|
/Shared/SongPlayer.swift
|
UTF-8
| 1,621
| 2.765625
| 3
|
[] |
no_license
|
//
// SongPlayer.swift
// Ditto Music
//
// Created by 陈语梵 on 2021/5/8.
//
import Foundation
import AVKit
import AVFoundation
class SongPlayer : ObservableObject {
@Published private(set) var player: AVQueuePlayer
@Published private(set) var songQueue: [SongItem]
@Published var currentPosition: Double = 0
init() {
player = AVQueuePlayer()
songQueue = [SongItem]()
#if os(iOS)
_ = try? AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback, mode: .default, options: .mixWithOthers)
#endif
player.addPeriodicTimeObserver(forInterval: CMTime(seconds: 0.5, preferredTimescale: 600), queue: nil) { time in
guard let item = self.player.currentItem else {
return
}
self.currentPosition = time.seconds / item.duration.seconds
}
}
func play(song name: String, by artist_name: String) {
let queryItems = [URLQueryItem(name: "name", value: name), URLQueryItem(name: "artist", value: artist_name)]
var urlComps = URLComponents(string: baseAPI)!
urlComps.queryItems = queryItems
let url = urlComps.url!
let asset = AVAsset(url: url)
let playerItem = AVPlayerItem(asset: asset)
player.removeAllItems()
player.insert(playerItem, after: nil)
player.play()
let songItem = SongItem(playerItem: playerItem, name: name, artist_name: artist_name)
songQueue = [songItem]
}
// MARK: - constant
private let baseAPI = "https://vms.n.xiaomi388.com:10443/v1/song"
}
| true
|
b8cd85a4076f16436965d7b6ab47eeee8e788702
|
Swift
|
mattcolliss/PhotosForDays
|
/PhotosForDays/Modules/PhotoDetails/PhotoDetailsViewController.swift
|
UTF-8
| 1,766
| 2.546875
| 3
|
[] |
no_license
|
//
// PhotoDetailsViewController.swift
// PhotosForDays
//
// Created by Matthew Colliss on 13/06/2020.
// Copyright © 2020 collissions. All rights reserved.
//
import UIKit
import SDWebImage
import Combine
protocol PhotoDetailsViewControllerDelegate: class {
func dismiss(photoDetailsViewController: PhotoDetailsViewController)
}
class PhotoDetailsViewController: UIViewController {
@IBOutlet var photoImageView: UIImageView!
@IBOutlet var titleLabel: UILabel!
weak var delegate: PhotoDetailsViewControllerDelegate?
private var viewModel: PhotoDetailsViewModel
private var cancellables = Set<AnyCancellable>()
init?(coder: NSCoder, viewModel: PhotoDetailsViewModel) {
self.viewModel = viewModel
super.init(coder: coder)
}
required init?(coder: NSCoder) {
fatalError("Must be created with a view model.")
}
override func viewDidLoad() {
super.viewDidLoad()
configureView()
}
}
// MARK: - View
extension PhotoDetailsViewController {
private func configureView() {
photoImageView.sd_setImage(with: viewModel.photoUrl)
photoImageView.accessibilityLabel = viewModel.photoTitle
photoImageView.isAccessibilityElement = true
titleLabel.text = viewModel.photoTitle
viewModel.$photoScaleMode
.assign(to: \.contentMode, on: photoImageView)
.store(in: &cancellables)
}
}
// MARK: - Actions
extension PhotoDetailsViewController {
@IBAction func photoTapped(_ gestureRecognizer: UITapGestureRecognizer) {
viewModel.togglePhotoScaleMode()
}
@IBAction func doneButtonTapped() {
viewModel.resetPhotoScaleMode()
delegate?.dismiss(photoDetailsViewController: self)
}
}
| true
|
de418a8f4d65cd2ecf333e11aa78694f73a99ac9
|
Swift
|
sauvikatinnofied/PinterestHome
|
/PinterestHomeTests/PinterRestPostTest.swift
|
UTF-8
| 3,689
| 2.84375
| 3
|
[] |
no_license
|
//
// PinterRestPostTest.swift
// PinterestHome
//
// Created by Sauvik Dolui on 28/01/17.
// Copyright © 2017 Sauvik Dolui. All rights reserved.
//
import XCTest
class PinterRestPostTest: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
// MARK: Model Generation Test
func testModelLoadFromFile() {
do {
let jsonFilePath = Bundle.main.path(forResource: "PinterestPosts", ofType: "json")
if let fileURL = URL(string : "file://" + jsonFilePath!) {
let data = try Data(contentsOf: fileURL, options: .mappedIfSafe)
// Trying to serialize
guard let dicArray = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [[String: Any]] else {
return
}
let posts = dicArray.map(PinterestPost.init)
XCTAssertTrue(posts.count == dicArray.count, "JSON Paring Failed from JSON File")
for post in posts {
XCTAssertTrue((post?.color.hasPrefix("#"))!, "Color Values must have # as prefix")
XCTAssertTrue(post?.color.characters.count == 7, "Color Values must be in #xxxxx")
}
} else {
XCTAssert(false, "JSON File Not Found")
}
} catch {
debugPrint("Error \(error.localizedDescription)")
XCTAssert(false, "File Read/ JSON Parsing")
}
}
func testCategotyValidationTest() {
let validDic: [String : Any] = [
"id":2,
"title":"Buildings",
"photo_count":19563,
"links":[
"self":"https://api.unsplash.com/categories/2",
"photos":"https://api.unsplash.com/categories/2/photos"
]
]
let validCategory = Category(jsonDictionary: validDic)
XCTAssertNotNil(validCategory, "Validation error in Category")
let invalidDic: [String : Any] = [
"title":"Buildings",
"photo_count":19563,
"links":[
"self":"https://api.unsplash.com/categories/2"
]
]
// id, links.photos missing
let invalidCategory = Category(jsonDictionary: invalidDic)
XCTAssertNil(invalidCategory, "Validation error in Category")
let invalidURLDic: [String : Any] = [
"id":2,
"title":"Buildings",
"photo_count":19563,
"links":[
"self":"hs://api.unsplash.com/categories/2",
"photos":"https://api.unsplash.com/categories/2/photos"
]
] // Invalid URL self
let invalidURLCategory = Category(jsonDictionary: invalidURLDic)
XCTAssertNil(invalidURLCategory, "URL Validation error in Category")
}
}
| true
|
92397f0aa83cffa9214cd7453a5e20a0caff9095
|
Swift
|
HelloTime/AttributedString
|
/Demo/Demo/Details/CheckingViewController.swift
|
UTF-8
| 4,489
| 2.921875
| 3
|
[
"MIT"
] |
permissive
|
//
// CheckingViewController.swift
// Demo
//
// Created by Lee on 2020/6/28.
// Copyright © 2020 LEE. All rights reserved.
//
import UIKit
import AttributedString
class CheckingViewController: ViewController<CheckingView> {
override func viewDidLoad() {
super.viewDidLoad()
// 添加电话号码类型监听
container.label.attributed.observe([.phoneNumber], highlights: [.foreground(#colorLiteral(red: 0.4745098054, green: 0.8392156959, blue: 0.9764705896, alpha: 1))]) { (result) in
print(result)
}
// 添加默认类型监听
container.textView.attributed.observe(highlights: [.foreground(#colorLiteral(red: 0.5568627715, green: 0.3529411852, blue: 0.9686274529, alpha: 1))]) { (result) in
print(result)
}
// 移除监听
//container.textView.attributed.remove(checking: .link)
func clicked(_ result: AttributedString.Action.Result) {
switch result.content {
case .string(let value):
print("点击了文本: \n\(value) \nrange: \(result.range)")
case .attachment(let value):
print("点击了附件: \n\(value) \nrange: \(result.range)")
}
}
do {
var string: AttributedString = """
我的名字叫李响,我的手机号码是18611401994,我的电子邮件地址是18611401994@163.com,现在是2020/06/28 20:30。我的GitHub主页是https://github.com/lixiang1994。欢迎来Star! \("点击联系我", .action(clicked))
"""
string.add(attributes: [.foreground(#colorLiteral(red: 0.9529411793, green: 0.6862745285, blue: 0.1333333403, alpha: 1)), .font(.systemFont(ofSize: 20, weight: .medium))], checkings: [.phoneNumber])
string.add(attributes: [.foreground(#colorLiteral(red: 0.1764705926, green: 0.4980392158, blue: 0.7568627596, alpha: 1)), .font(.systemFont(ofSize: 20, weight: .medium))], checkings: [.link])
string.add(attributes: [.foreground(#colorLiteral(red: 0.1764705926, green: 0.01176470611, blue: 0.5607843399, alpha: 1)), .font(.systemFont(ofSize: 20, weight: .medium))], checkings: [.date])
string.add(attributes: [.font(.systemFont(ofSize: 20, weight: .medium))], checkings: [.action])
container.label.attributed.text = string
}
do {
var string: AttributedString = """
My name is Li Xiang, my mobile phone number is 18611401994, my email address is 18611401994@163.com, I live in No.10 Xitucheng Road, Haidian District, Beijing, China, and it is now 20:30 on June 28, 2020. My GitHub homepage is https://github.com/lixiang1994. Welcome to star me! \("Contact me", .action(clicked))
"""
string.add(attributes: [.foreground(#colorLiteral(red: 0.9529411793, green: 0.6862745285, blue: 0.1333333403, alpha: 1))], checkings: [.address])
string.add(attributes: [.foreground(#colorLiteral(red: 0.4666666687, green: 0.7647058964, blue: 0.2666666806, alpha: 1))], checkings: [.link, .phoneNumber])
string.add(attributes: [.foreground(#colorLiteral(red: 0.1764705926, green: 0.01176470611, blue: 0.5607843399, alpha: 1))], checkings: [.date])
string.add(attributes: [.foreground(#colorLiteral(red: 0.9098039269, green: 0.4784313738, blue: 0.6431372762, alpha: 1))], checkings: [.regex("Li Xiang")])
string.add(attributes: [.font(.systemFont(ofSize: 16, weight: .medium))], checkings: [.action])
container.textView.attributed.text = string
}
container.tintAdjustmentMode = .normal
}
@IBAction func changeTintAction(_ sender: Any) {
container.tintAdjustmentMode = container.tintAdjustmentMode == .normal ? .dimmed : .normal
}
}
class CheckingView: UIView {
@IBOutlet weak var label: UILabel!
@IBOutlet weak var textView: UITextView!
override func tintColorDidChange() {
super.tintColorDidChange()
let isDimmed = tintAdjustmentMode == .dimmed
let color = isDimmed ? #colorLiteral(red: 0.6000000238, green: 0.6000000238, blue: 0.6000000238, alpha: 1) : #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1)
label.attributed.text?.add(attributes: [.foreground(color)], checkings: [.action])
textView.attributed.text.add(attributes: [.foreground(color)], checkings: [.action])
}
}
| true
|
2ed0a0f666a01c18afbe12f1713ffcf01adc19d8
|
Swift
|
rei315/Swift2DPlatformerGame
|
/KonGaRuCapstone/Class/BatHowl.swift
|
UTF-8
| 799
| 2.546875
| 3
|
[] |
no_license
|
//
// BatHowl.swift
// KonGaRuCapstone
//
// Created by 김민국 on 21/12/2018.
// Copyright © 2018 MGHouse. All rights reserved.
//
import Cocoa
import SpriteKit
class BatHowl: SKSpriteNode {
let howlT = SKTexture(imageNamed: "bat_effect_howl.png")
init(pos: CGPoint) {
super.init(texture: howlT, color: SKColor.clear, size: howlT.size())
self.position = pos
Setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func Setup(){
self.name = "howl"
self.zPosition = 1
Surround()
}
func Surround(){
let scal = SKAction.scale(by: 100, duration: 1)
scal.timingMode = .easeIn
run(scal) {
self.removeFromParent()
}
}
}
| true
|
886c21226ad2d369915fcd100633e66746601770
|
Swift
|
reich452/Notes-Complete
|
/notePractice4/noteControlelr.swift
|
UTF-8
| 2,417
| 3.6875
| 4
|
[] |
no_license
|
//
// noteControlelr.swift
// notePractice4
//
// Created by Nick Reichard on 2/11/17.
// Copyright © 2017 Nick Reichard. All rights reserved.
// CRUD
// Singelton
import Foundation
class NoteController {
static let sharedController = NoteController()
var notes: [Note] = []
private let noteDictionaryArrayKey = "noteDictionaryArrayKey"
init() {
loadToPersistentStore()
}
// MARK: - Create
func addNoteWith(name: String) {
// Create a note
let note = Note(name: name)
// Add the note to the notes array
notes.append(note)
saveToPersistentStore()
}
// MARK: - Read
// MARK: - Update
// MARK: - Delete
func remove(name: Note) {
guard let index = notes.index(of: name) else {
return
}
notes.remove(at: index)
saveToPersistentStore()
}
// MARK: - Save
// The goal is to take our notes Array and save them to User Defaults. We must convert the notes inot something that UD can store (Simple types) // Put all the soups into containers then into one big container // will load saved dictionary notes from UserDefaults and set notes to the results
func saveToPersistentStore() {
var noteDictionaries: [[String:String]] = []
for note in notes {
let noteDictionary = note.dictionaryRepresenation
noteDictionaries.append(noteDictionary)
}
UserDefaults.standard.set(noteDictionaries, forKey: noteDictionaryArrayKey)
}
// The goal is to get our note dictionaries out of UserDefaults, tun them back into instances of the Note Class, and set the note array with the load. Grabing the big container and placing the soups on the table
func loadToPersistentStore() {
if let noteDictionaries = UserDefaults.standard.object(forKey: noteDictionaryArrayKey) as? [[String:String]] {
var notes: [Note] = []
for noteDictionary in noteDictionaries {
if let note = Note(dictionary: noteDictionary) {
notes.append(note)
}
}
self.notes = notes
}
}
}
| true
|
70ff3dc5df1755af8d66151fb60cea30372e9eda
|
Swift
|
rustedivan/tapmap
|
/tapmap/Rendering/PostProcessingRenderer.swift
|
UTF-8
| 2,978
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
//
// PostProcessingRenderer.swift
// tapmap
//
// Created by Ivan Milles on 2022-08-07.
// Copyright © 2022 Wildbrain. All rights reserved.
//
import Metal
import simd
fileprivate struct FrameUniforms {
let timestamp: Float
}
class PostProcessingRenderer {
let pipeline: MTLRenderPipelineState
var frameOffscreenTexture: [MTLTexture?]
let fullscreenQuadPrimitive: TexturedRenderPrimitive
let startTime: Date
var frameSwitchSemaphore = DispatchSemaphore(value: 1)
init(withDevice device: MTLDevice, pixelFormat: MTLPixelFormat, bufferCount: Int, drawableSize: simd_float2) {
startTime = Date()
let shaderLib = device.makeDefaultLibrary()!
let pipelineDescriptor = MTLRenderPipelineDescriptor()
pipelineDescriptor.vertexFunction = shaderLib.makeFunction(name: "texturedVertex")
pipelineDescriptor.fragmentFunction = shaderLib.makeFunction(name: "chromaticAberrationFragment")
pipelineDescriptor.colorAttachments[0].pixelFormat = pixelFormat
pipelineDescriptor.vertexBuffers[0].mutability = .immutable
do {
try pipeline = device.makeRenderPipelineState(descriptor: pipelineDescriptor)
self.frameOffscreenTexture = Array(repeating: nil, count: bufferCount)
self.fullscreenQuadPrimitive = makeFullscreenQuadPrimitive(in: device)
} catch let error {
fatalError(error.localizedDescription)
}
}
func prepareFrame(offscreenTexture: MTLTexture, bufferIndex: Int) {
frameSwitchSemaphore.wait()
self.frameOffscreenTexture[bufferIndex] = offscreenTexture
frameSwitchSemaphore.signal()
}
func renderPostProcessing(inEncoder encoder: MTLRenderCommandEncoder, bufferIndex: Int) {
encoder.pushDebugGroup("Render postprocessing pass")
defer {
encoder.popDebugGroup()
}
let frameTime = Float(Date().timeIntervalSince(startTime))
frameSwitchSemaphore.wait()
var frameUniforms = FrameUniforms(timestamp: frameTime)
let offscreenTexture = self.frameOffscreenTexture[bufferIndex]
frameSwitchSemaphore.signal()
encoder.setRenderPipelineState(pipeline)
encoder.setVertexBytes(&frameUniforms, length: MemoryLayout<FrameUniforms>.stride, index: 1)
encoder.setFragmentTexture(offscreenTexture, index: 0)
encoder.setFragmentBytes(&frameUniforms, length: MemoryLayout<FrameUniforms>.stride, index: 1)
render(primitive: fullscreenQuadPrimitive, into: encoder)
}
}
fileprivate func makeFullscreenQuadPrimitive(in device: MTLDevice) -> TexturedRenderPrimitive {
let vertices: [TexturedVertex] = [TexturedVertex(-1.0, -1.0, u: 0.0, v: 1.0), TexturedVertex(1.0, -1.0, u: 1.0, v: 1.0),
TexturedVertex(-1.0, 1.0, u: 0.0, v: 0.0), TexturedVertex(1.0, 1.0, u: 1.0, v: 0.0)]
let indices: [UInt16] = [0, 1, 2, 1, 2, 3]
return TexturedRenderPrimitive( polygons: [vertices], indices: [indices],
drawMode: .triangle, device: device,
color: Color(r: 1.0, g: 1.0, b: 1.0, a: 1.0),
ownerHash: 0, debugName: "Fullscreen quad primitive")
}
| true
|
7b1bae7e58b13147194345059cf553ddbd3d236e
|
Swift
|
kentontroy/interactive_hypercube
|
/FilterValuesPicker.swift
|
UTF-8
| 1,216
| 3.15625
| 3
|
[] |
no_license
|
import UIKit
enum FilterOperator
{
case LessThan
case LessThanOrEqual
case Equal
case GreaterThan
case GreaterThanOrEqual
var description : String {
switch self {
case .LessThan:
return "<"
case .LessThanOrEqual:
return "<="
case .Equal:
return "="
case .GreaterThan:
return ">"
case .GreaterThanOrEqual:
return ">="
}
}
}
class FilterValuesPicker : SingleColumnPicker
{
var _selectedRow : Int?
override init()
{
super.init()
_pickerData.append(FilterOperator.LessThan.description)
_pickerData.append(FilterOperator.LessThanOrEqual.description)
_pickerData.append(FilterOperator.Equal.description)
_pickerData.append(FilterOperator.GreaterThan.description)
_pickerData.append(FilterOperator.GreaterThanOrEqual.description)
}
required init(coder aDecoder: NSCoder)
{
fatalError("init(coder:) has not been implemented")
}
override func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
_selectedRow = row
}
}
| true
|
9318d9c6085fa526568b2744797fb0877d856241
|
Swift
|
jolam168/swiftui-practice
|
/example/MainView.swift
|
UTF-8
| 1,863
| 2.90625
| 3
|
[] |
no_license
|
//
// MainView.swift
// example
//
// Created by 林 耀祖 on 2019/12/26.
// Copyright © 2019 林 耀祖. All rights reserved.
//
import SwiftUI
struct MainView: View {
var body: some View {
NavigationView{
ScrollView(.vertical){
ForEach(/*@START_MENU_TOKEN@*/0 ..< 5/*@END_MENU_TOKEN@*/) { item in
HStack {
ForEach(0 ..< 2) { item in
TempView(row: item)
}
}.padding(.bottom,0).padding(.top,0)
}
}.navigationBarTitle("Home")
}
}
}
struct TempView: View {
var row : Int
var body: some View {
NavigationLink(destination: DetailView()){
// ExtractedView().background(Color(.clear)).frame(height:190).cornerRadius(10).padding(.leading,10).padding(.trailing,10)
VStack {
if row == 0 {
ExtractedView().background(Color(.yellow)).frame(height:190).cornerRadius(10).clipShape(Rectangle()).shadow(radius: 4).padding(.leading, 5).padding(.trailing,5)
} else {
ExtractedView().background(Color(.yellow)).frame(height:190).cornerRadius(10).clipShape(Rectangle()).shadow(radius: 4).padding(.trailing, 5)
}
}
}.buttonStyle(PlainButtonStyle())
}
}
struct MainView_Previews: PreviewProvider {
static var previews: some View {
MainView()
}
}
struct ExtractedView: View {
var body: some View {
HStack{
Spacer()
HStack{
Circle().frame(width:50)
}
HStack{
Text("Detail").font(.title)
Spacer()
}
Spacer()
}
}
}
| true
|
05fd963bdd67b0d8de1e1c468b6b6f97e6d937dc
|
Swift
|
28th-BE-SOPT-iOS-Part/NohHanSol
|
/Assignment/28th_BESOPT_2ndWeek_Assignment/28th_BESOPT_2ndWeek_Assignment/Global/Extensions/UIColor+.swift
|
UTF-8
| 1,046
| 2.796875
| 3
|
[] |
no_license
|
//
// UIColor+.swift
// 28th_BESOPT_2ndWeek_Assignment
//
// Created by 노한솔 on 2021/05/06.
//
import UIKit
extension UIColor {
@nonobjc class var bluishGrey: UIColor {
return UIColor(red: 135.0 / 255.0, green: 145.0 / 255.0, blue: 152.0 / 255.0, alpha: 1.0)
}
@nonobjc class var coolGrey: UIColor {
return UIColor(red: 159.0 / 255.0, green: 167.0 / 255.0, blue: 173.0 / 255.0, alpha: 1.0)
}
@nonobjc class var whiteTwo: UIColor {
return UIColor(white: 247.0 / 255.0, alpha: 1.0)
}
@nonobjc class var white: UIColor {
return UIColor(white: 1.0, alpha: 1.0)
}
@nonobjc class var greyish: UIColor {
return UIColor(white: 166.0 / 255.0, alpha: 1.0)
}
@nonobjc class var steel: UIColor {
return UIColor(red: 127.0 / 255.0, green: 127.0 / 255.0, blue: 131.0 / 255.0, alpha: 1.0)
}
@nonobjc class var veryLightPink: UIColor {
return UIColor(white: 243.0 / 255.0, alpha: 1.0)
}
@nonobjc class var textBlack: UIColor {
return UIColor(white: 25.0 / 255.0, alpha: 1.0)
}
}
| true
|
a283a6e5b6234c5a0232f95fe219d5040a337ca4
|
Swift
|
eminemArun/TableViewEx
|
/TableView/ViewController.swift
|
UTF-8
| 3,756
| 2.859375
| 3
|
[] |
no_license
|
//
// ViewController.swift
// TableView
//
// Created by Arun Negi on 25/04/2019.
// Copyright © 2019 arun. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var imageTableView: UITableView!
var savedIndex:IndexPath = IndexPath(row: 0, section: 0)
let rows = ["1","2","3","4"]
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
imageTableView.dataSource = self
imageTableView.delegate = self
}
override var prefersStatusBarHidden: Bool {
return true
}
}
extension ViewController:UIPickerViewDataSource,UIPickerViewDelegate{
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return rows.count * 1000
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
let actualRow = row % rows.count
return rows[actualRow]
}
}
extension ViewController:UITableViewDataSource,UITableViewDelegate{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return rows.count * 1000
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if tableView == self.imageTableView{
let cell = tableView.dequeueReusableCell(withIdentifier: "imageCell") as! ImageTableViewCell
let actualRow = indexPath.row % rows.count
cell.cellImageView.image = UIImage(named: rows[actualRow])
return cell
}
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! TextTableViewCell
let actualRow = indexPath.row % rows.count
cell.selectionStyle = .none
cell.labelText.text = rows[actualRow]
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if tableView == self.tableView{
return 60
}
return UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let topVisibleIndexPath:IndexPath = self.tableView.indexPathsForVisibleRows![0]
let actualRow = indexPath.row % rows.count
if topVisibleIndexPath == indexPath || tableView == self.imageTableView {
print(rows[actualRow])
}else{
imageTableView.scrollToRow(at: indexPath, at: .top, animated: true)
tableView.scrollToRow(at: indexPath, at: .top, animated: true)
}
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
// let topVisibleIndexPath:IndexPath = self.tableView.indexPathsForVisibleRows![0]
// if savedIndex == topVisibleIndexPath{
// self.imageTableView.scrollToRow(at: topVisibleIndexPath, at: .top, animated: true)
// }
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
print("scrollViewWillBeginDragging")
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let topVisibleIndexPath:IndexPath = self.tableView.indexPathsForVisibleRows![0]
tableView.scrollToRow(at: topVisibleIndexPath, at: .top, animated: true)
imageTableView.scrollToRow(at: topVisibleIndexPath, at: .top, animated: true)
}
}
| true
|
f5c67e4a49f1c00bb0f2d51f795d74f5602f52f5
|
Swift
|
HSCOO/SportsStoreDemo
|
/06抽象工厂模式/AbstractFactory/AbstractFactory/Drivetrains.swift
|
UTF-8
| 586
| 2.90625
| 3
|
[] |
no_license
|
//
// Drivetrains.swift
// AbstractFactory
//
// Created by OnlyStu on 2017/3/27.
// Copyright © 2017年 OnlyStu. All rights reserved.
//
import Foundation
protocol Drivetrain {
var driveType:Driveoption{get}
}
enum Driveoption :String {
case FRONT="Front";
case REAR = "Rear";
case ALL = "4WD";
}
class FrontWheelDrive: Drivetrain {
var driveType: Driveoption = Driveoption.FRONT
}
class RearWheelDrive: Drivetrain {
var driveType: Driveoption = Driveoption.REAR
}
class ALLWheelDrive: Drivetrain {
var driveType: Driveoption = Driveoption.ALL
}
| true
|
40e8134ae2ccc32484c9a7036ef1ffaf34a354de
|
Swift
|
Ripnrip/beeback-ios
|
/ARKitImageRecognition/Coordinator/LoginCoordinator.swift
|
UTF-8
| 1,013
| 2.546875
| 3
|
[] |
no_license
|
//
// LoginCoordinator.swift
// ARKitImageRecognition
//
// Created by Gurinder Singh on 3/28/20.
// Copyright © 2020 Apple. All rights reserved.
//
import Foundation
import UIKit
class LoginCoordinator: Coordinator {
var childCoordinators = [Coordinator]()
var navigationController: UINavigationController
init(navigationController: UINavigationController) {
self.navigationController = navigationController
}
func start() {
let vc = LoginViewController.instantiate()
vc.coordinator = self
navigationController.pushViewController(vc, animated: false)
}
func userSignedIn(withUserInfo info: OnboardingUserInfo){
//TODO: check if user has already seen tutorial or not
//let mainFlow = MainCoordinator(navigationController: navigationController)
//mainFlow.start()
let tutorialFlow = TutorialCoordinator(navigationController: navigationController, currentUserInfo: info)
tutorialFlow.start()
}
}
| true
|
0954699f8eb3549a2e0ca5b05879ea107e5bd77c
|
Swift
|
erick291992/ShudderSample
|
/Shudder/Service/FlickrService.swift
|
UTF-8
| 2,170
| 2.6875
| 3
|
[] |
no_license
|
//
// FlickrService.swift
// Shudder
//
// Created by Erick Manrique on 11/11/18.
// Copyright © 2018 homeapps. All rights reserved.
//
import Foundation
class FlickrService {
let networkService: NetworkService
init() {
networkService = NetworkService()
}
private enum FlickrParams:String {
case apiKey
case method
case userId
case format
case noJsonCallback
case perPage
var key: String {
switch self {
case .apiKey:
return "api_key"
case .method:
return "method"
case .userId:
return "user_id"
case .format:
return "format"
case .noJsonCallback:
return "nojsoncallback"
case .perPage:
return "per_page"
}
}
var value: String {
switch self {
case .apiKey:
return "231f052bf4f63790917558d15aa69ff7"
case .method:
return "flickr.people.getPhotos"
case .userId:
return "61302085@N05"
case .format:
return "json"
case .noJsonCallback:
return "1"
case .perPage:
return "64"
}
}
}
func getMovies(completion:@escaping(GenericCompletion<FlickrResult>)) {
let url = Api.Flickr.Rest.url
var parameters = [String:Any]()
parameters[FlickrParams.apiKey.key] = FlickrParams.apiKey.value
parameters[FlickrParams.method.key] = FlickrParams.method.value
parameters[FlickrParams.userId.key] = FlickrParams.userId.value
parameters[FlickrParams.format.key] = FlickrParams.format.value
parameters[FlickrParams.perPage.key] = FlickrParams.perPage.value
parameters[FlickrParams.noJsonCallback.key] = FlickrParams.noJsonCallback.value
networkService.requestData(url: url, parameters: parameters, method: .get, completion: completion)
}
}
| true
|
5ad0b7ccb9f141ec574f1b40782365a87a71cd7f
|
Swift
|
dhardiman/Config
|
/Tests/ConfigTests/ConfigurationPropertyTests.swift
|
UTF-8
| 16,171
| 3.140625
| 3
|
[
"MIT"
] |
permissive
|
//
// ConfigurationPropertyTests.swift
// Config
//
// Created by David Hardiman on 17/04/2019.
//
@testable import Config
import Foundation
import Nimble
import XCTest
class ConfigurationPropertyTests: XCTestCase {
func givenAStringProperty() -> ConfigurationProperty<String>? {
return ConfigurationProperty<String>(key: "test", typeHint: "String", dict: [
"defaultValue": "test value",
"overrides": [
"hello": "hello value",
"pattern": "pattern value",
"empty": ""
]
])
}
func whenTheDeclarationIsWritten<T>(for configurationProperty: ConfigurationProperty<T>?, scheme: String = "any", encryptionKey: String? = nil, isPublic: Bool = false, instanceProperty: Bool = false, requiresNonObjC: Bool = false, indentWidth: Int = 0) throws -> String? {
let iv = try IV(dict: ["initialise": "me"])
print("\(iv.hash)")
return configurationProperty?.propertyDeclaration(for: scheme, iv: iv, encryptionKey: encryptionKey, requiresNonObjCDeclarations: requiresNonObjC, isPublic: isPublic, instanceProperty: instanceProperty, indentWidth: indentWidth)
}
func testItCanWriteADeclarationForAStringPropertyUsingTheDefaultValue() throws {
let stringProperty = givenAStringProperty()
let expectedValue = ##" static let test: String = #"test value"#"##
let actualValue = try whenTheDeclarationIsWritten(for: stringProperty)
expect(actualValue).to(equal(expectedValue))
}
func testItCanWriteADeclarationForAnEmptyStringProperty() throws {
let stringProperty = givenAStringProperty()
let expectedValue = ##" let test: String = """##
let actualValue = try whenTheDeclarationIsWritten(for: stringProperty, scheme: "empty", instanceProperty: true)
expect(actualValue).to(equal(expectedValue))
}
func testItAddsAPublicAccessorWhenRequired() throws {
let stringProperty = givenAStringProperty()
let expectedValue = ##" public static let test: String = #"test value"#"##
let actualValue = try whenTheDeclarationIsWritten(for: stringProperty, isPublic: true)
expect(actualValue).to(equal(expectedValue))
}
func testItCanIndentADeclaration() throws {
let stringProperty = givenAStringProperty()
let expectedValue = ##" static let test: String = #"test value"#"##
let actualValue = try whenTheDeclarationIsWritten(for: stringProperty, indentWidth: 3)
expect(actualValue).to(equal(expectedValue))
}
func testItWritesNoObjCPropertiesWhenRequired() throws {
let stringProperty = givenAStringProperty()
let expectedValue = """
@nonobjc static var test: String {
return #"test value"#
}
"""
let actualValue = try whenTheDeclarationIsWritten(for: stringProperty, requiresNonObjC: true)
expect(actualValue).to(equal(expectedValue))
}
func testItCanGetAnOverrideForAnExactMatch() throws {
let stringProperty = givenAStringProperty()
let expectedValue = ##" static let test: String = #"hello value"#"##
let actualValue = try whenTheDeclarationIsWritten(for: stringProperty, scheme: "hello")
expect(actualValue).to(equal(expectedValue))
}
func testItCanGetAnOverrideForAPatternMatch() throws {
let stringProperty = givenAStringProperty()
let expectedValue = ##" static let test: String = #"pattern value"#"##
let actualValue = try whenTheDeclarationIsWritten(for: stringProperty, scheme: "match-a-pattern")
expect(actualValue).to(equal(expectedValue))
}
func testItCanWriteADescriptionAsAComment() throws {
let stringProperty = ConfigurationProperty<String>(key: "test", typeHint: "String", dict: [
"defaultValue": "test value",
"description": "A comment to add"
])
let expectedValue = """
/// A comment to add
static let test: String = #"test value"#
"""
let actualValue = try whenTheDeclarationIsWritten(for: stringProperty)
expect(actualValue).to(equal(expectedValue))
}
func testItCanWriteAURLProperty() throws {
let urlProperty = ConfigurationProperty<String>(key: "test", typeHint: "URL", dict: [
"defaultValue": "https://www.google.com",
])
let expectedValue = #" static let test: URL = URL(string: "https://www.google.com")!"#
let actualValue = try whenTheDeclarationIsWritten(for: urlProperty)
expect(actualValue).to(equal(expectedValue))
}
func testItCanWriteAnIntProperty() throws {
let intProperty = ConfigurationProperty<Int>(key: "test", typeHint: "Int", dict: [
"defaultValue": 2,
])
let expectedValue = #" static let test: Int = 2"#
let actualValue = try whenTheDeclarationIsWritten(for: intProperty)
expect(actualValue).to(equal(expectedValue))
}
func testItCanWriteADoubleProperty() throws {
let doubleProperty = ConfigurationProperty<Double>(key: "test", typeHint: "Double", dict: [
"defaultValue": 2.3,
])
let expectedValue = #" static let test: Double = 2.3"#
let actualValue = try whenTheDeclarationIsWritten(for: doubleProperty)
expect(actualValue).to(equal(expectedValue))
}
func testItCanWriteAFloatProperty() throws {
let floatProperty = ConfigurationProperty<Double>(key: "test", typeHint: "Float", dict: [
"defaultValue": 2.3,
])
let expectedValue = #" static let test: Float = 2.3"#
let actualValue = try whenTheDeclarationIsWritten(for: floatProperty)
expect(actualValue).to(equal(expectedValue))
}
func testItCanWriteABoolProperty() throws {
let floatProperty = ConfigurationProperty<Bool>(key: "test", typeHint: "Bool", dict: [
"defaultValue": true,
])
let expectedValue = #" static let test: Bool = true"#
let actualValue = try whenTheDeclarationIsWritten(for: floatProperty)
expect(actualValue).to(equal(expectedValue))
}
func testItCanWriteStringArrayProperty() throws {
let stringArrayProperty = ConfigurationProperty<[String]>(key: "test", typeHint: "[String]", dict: [
"defaultValue": [
"one",
"two"
]
])
let expectedValue = #" static let test: [String] = ["one", "two"]"#
let actualValue = try whenTheDeclarationIsWritten(for: stringArrayProperty)
expect(actualValue).to(equal(expectedValue))
}
func testItCanWriteADictionaryProperty() throws {
let dictionaryProperty = ConfigurationProperty<[String: Any]>(key: "test", typeHint: "Dictionary", dict: [
"defaultValue": [
"one": "value",
"two": "other value"
]
])
let expectedValue = #" static let test: [String: Any] = ["one": "value", "two": "other value"]"#
let actualValue = try whenTheDeclarationIsWritten(for: dictionaryProperty)
expect(actualValue).to(equal(expectedValue))
}
func testItCanWriteAColourProperty() throws {
let colourProperty = ConfigurationProperty<String>(key: "test", typeHint: "Colour", dict: [
"defaultValue": "#FF0000",
])
let expectedValue = #" static let test: UIColor = UIColor(red: 255.0 / 255.0, green: 0.0 / 255.0, blue: 0.0 / 255.0, alpha: 1.0)"#
let actualValue = try whenTheDeclarationIsWritten(for: colourProperty)
expect(actualValue).to(equal(expectedValue))
}
func testItCanWriteAGreyScaleColourProperty() throws {
let colourProperty = ConfigurationProperty<String>(key: "test", typeHint: "Colour", dict: [
"defaultValue": "#FF",
])
let expectedValue = #" static let test: UIColor = UIColor(white: 255.0 / 255.0, alpha: 1.0)"#
let actualValue = try whenTheDeclarationIsWritten(for: colourProperty)
expect(actualValue).to(equal(expectedValue))
}
func testItCanWriteADynamicColourProperty() throws {
let colourProperty = ConfigurationProperty<[String:String]>(key: "test", typeHint: "DynamicColour", dict: [
"defaultValue": [
"light": "#00",
"dark": "#FF"
]
])
let expectedValue = """
static var test: UIColor {
if #available(iOS 13, *) {
return UIColor(dynamicProvider: {
if $0.userInterfaceStyle == .dark {
return UIColor(white: 255.0 / 255.0, alpha: 1.0)
} else {
return UIColor(white: 0.0 / 255.0, alpha: 1.0)
}
})
} else {
return UIColor(white: 0.0 / 255.0, alpha: 1.0)
}
}
"""
let actualValue = try whenTheDeclarationIsWritten(for: colourProperty)
expect(actualValue).to(equal(expectedValue))
}
func testItCanWriteADynamicReferenceColourProperty() throws {
let colourProperty = ConfigurationProperty<[String:String]>(key: "test", typeHint: "DynamicColourReference", dict: [
"defaultValue": [
"light": "green",
"dark": "blue"
]
])
let expectedValue = """
static var test: UIColor {
if #available(iOS 13, *) {
return UIColor(dynamicProvider: {
if $0.userInterfaceStyle == .dark {
return blue
} else {
return green
}
})
} else {
return green
}
}
"""
let actualValue = try whenTheDeclarationIsWritten(for: colourProperty)
expect(actualValue).to(equal(expectedValue))
}
func testItCanWriteAnImageProperty() throws {
let imageProperty = ConfigurationProperty<String>(key: "test", typeHint: "Image", dict: [
"defaultValue": "image-name",
])
let expectedValue = #" static let test: UIImage = UIImage(named: "image-name")!"#
let actualValue = try whenTheDeclarationIsWritten(for: imageProperty)
expect(actualValue).to(equal(expectedValue))
}
func testItCanWriteAnEncryptedValue() throws {
// Note: this test doesn't test the encryption itself, that test will be written elsewhere
let secretProperty = ConfigurationProperty<String>(key: "test", typeHint: "Encrypted", dict: [
"defaultValue": "top-secret",
])
let expectedValue = " static let test: [UInt8] = ["
let actualValue = try whenTheDeclarationIsWritten(for: secretProperty, encryptionKey: "the-key")
expect(actualValue).to(beginWith(expectedValue))
}
func testItCanWriteAnEncryptionKey() throws {
let secretProperty = ConfigurationProperty<String>(key: "test", typeHint: "EncryptionKey", dict: [
"defaultValue": "top-secret",
])
let expectedValue = " static let test: [UInt8] = [UInt8(116), UInt8(111), UInt8(112), UInt8(45), UInt8(115), UInt8(101), UInt8(99), UInt8(114), UInt8(101), UInt8(116)]"
let actualValue = try whenTheDeclarationIsWritten(for: secretProperty)
expect(actualValue).to(equal(expectedValue))
}
func testItCanWriteAnUnknownTypeProperty() throws {
let unknownTypeProperty = ConfigurationProperty<String>(key: "test", typeHint: "Unknown", dict: [
"defaultValue": "somevalue",
])
let expectedValue = " static let test: Unknown = somevalue"
let actualValue = try whenTheDeclarationIsWritten(for: unknownTypeProperty)
expect(actualValue).to(beginWith(expectedValue))
}
func testItCanProvideItsValueAsAKey() throws {
let property = givenAStringProperty()
let defaultKeyValue = property?.keyValue(for: "any")
expect(defaultKeyValue).to(equal("test value"))
let overriddenKeyValue = property?.keyValue(for: "hello")
expect(overriddenKeyValue).to(equal("hello value"))
}
func testItCanWriteARegexProperty() throws {
let imageProperty = ConfigurationProperty<String>(key: "test", typeHint: "Regex", dict: [
"defaultValue": "an\\sexpression",
])
let expectedValue = ##" static let test: NSRegularExpression = try! NSRegularExpression(pattern: #"an\sexpression"#, options: [])"##
let actualValue = try whenTheDeclarationIsWritten(for: imageProperty)
expect(actualValue).to(equal(expectedValue))
}
func testItCanWriteAnOptionalStringProperty() throws {
let property = ConfigurationProperty<String?>(key: "test", typeHint: "String?", dict: [
"defaultValue": NSNull.self
])
let expectedValue = " static let test: String? = nil"
let actualValue = try whenTheDeclarationIsWritten(for: property)
expect(actualValue).to(equal(expectedValue))
}
func testItCanWriteAnOptionalOverrideStringProperty() throws {
let property = ConfigurationProperty<String?>(key: "test", typeHint: "String?", dict: [
"defaultValue": "Test",
"overrides": [
"bla": NSNull.self
]
])
let expectedValue = " static let test: String? = nil"
let actualValue = try whenTheDeclarationIsWritten(for: property, scheme: "bla")
expect(actualValue).to(equal(expectedValue))
}
func testItCanWriteAnOptionalStringPropertyWithAValue() throws {
let property = ConfigurationProperty<String?>(key: "test", typeHint: "String?", dict: [
"defaultValue": "Test"
])
let expectedValue = ##" static let test: String? = #"Test"#"##
let actualValue = try whenTheDeclarationIsWritten(for: property)
expect(actualValue).to(equal(expectedValue))
}
func testItCanWriteAnOptionalIntProperty() throws {
let property = ConfigurationProperty<Int?>(key: "test", typeHint: "Int?", dict: [
"defaultValue": NSNull.self
])
let expectedValue = " static let test: Int? = nil"
let actualValue = try whenTheDeclarationIsWritten(for: property)
expect(actualValue).to(equal(expectedValue))
}
func testItCanWriteAnOptionalOverrideIntProperty() throws {
let property = ConfigurationProperty<Int?>(key: "test", typeHint: "Int?", dict: [
"defaultValue": 3,
"overrides": [
"bla": NSNull.self
]
])
let expectedValue = " static let test: Int? = nil"
let actualValue = try whenTheDeclarationIsWritten(for: property, scheme: "bla")
expect(actualValue).to(equal(expectedValue))
}
func testItCanWriteAnOptionalIntPropertyWithAValue() throws {
let property = ConfigurationProperty<Int?>(key: "test", typeHint: "Int?", dict: [
"defaultValue": 7
])
let expectedValue = " static let test: Int? = 7"
let actualValue = try whenTheDeclarationIsWritten(for: property)
expect(actualValue).to(equal(expectedValue))
}
func testItCanUseCommonPatternsForOverrides() throws {
let dict: [String: Any] = [
"defaultValue": "test value",
"overrides": [
"barry": "pattern value"
]
]
let property = ConfigurationProperty<String>(key: "test", typeHint: "String", dict: dict, patterns: [OverridePattern(source: ["alias": "barry", "pattern": "gary"])!])
let expectedValue = ##" static let test: String = #"pattern value"#"##
let actualValue = try whenTheDeclarationIsWritten(for: property, scheme: "gary")
expect(actualValue).to(equal(expectedValue))
}
}
| true
|
fbb14bfe7189c46ce264df1cbe437da4bb0f8bfe
|
Swift
|
allie0147/RxSwift_UITableView
|
/RxMvvmTableView/ViewModels/Home/HomeViewModel.swift
|
UTF-8
| 761
| 2.65625
| 3
|
[] |
no_license
|
//
// HomeViewModel.swift
// RxMvvmTableView
//
// Created by 김도희 on 2021/07/18.
//
import Foundation
/**
# Users view model #
- author: 김도희
*/
class HomeViewModel {
// RX
let disposeBag: DisposeBag
let users: BehaviorRelay<[HomeViewTableViewModel]>
init() {
disposeBag = DisposeBag()
users = BehaviorRelay<[HomeViewTableViewModel]>(value: [])
// API call
fetchUsers()
}
/**
# [GET] User Data #
*/
private func fetchUsers() {
APIService.shared.fetchUsers()
.map { $0.map { HomeViewTableViewModel($0) } } // - convert User to HomeViewTableViewModel
.debug()
.bind(to: self.users)
.disposed(by: disposeBag)
}
}
| true
|
ced67aa8e5876d1bef191c89e977cb19825b29ee
|
Swift
|
jarrodparkes/Habanero
|
/Habanero/Classes/Views/Atoms/Text/PaddedTextField.swift
|
UTF-8
| 928
| 2.984375
| 3
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
// MARK: - PaddingTextFieldDelegate
protocol PaddedTextFieldDelegate: class {
func paddedTextFieldDidDeleteBackwards(_ paddedTextField: PaddedTextField)
}
// MARK: - PaddedTextField: UITextField
class PaddedTextField: UITextField {
// MARK: Properties
private let textPadding = UIEdgeInsets(top: 0, left: 3, bottom: 0, right: 0)
weak var paddedTextFieldDelegate: PaddedTextFieldDelegate?
// MARK: UITextField
override func textRect(forBounds bounds: CGRect) -> CGRect {
let rect = super.textRect(forBounds: bounds)
return rect.inset(by: textPadding)
}
override func editingRect(forBounds bounds: CGRect) -> CGRect {
let rect = super.editingRect(forBounds: bounds)
return rect.inset(by: textPadding)
}
override func deleteBackward() {
super.deleteBackward()
paddedTextFieldDelegate?.paddedTextFieldDidDeleteBackwards(self)
}
}
| true
|
da2b86f5ac93a8e3daaae6824fce486e71edc178
|
Swift
|
mrga/bn-ios
|
/Big Neon UI/UIUtilities/StatusBarView.swift
|
UTF-8
| 224
| 2.5625
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
import UIKit
extension UIApplication {
public var statusBarView: UIView? {
if responds(to: Selector("statusBar")) {
return value(forKey: "statusBar") as? UIView
}
return nil
}
}
| true
|
5e883c43c5a13f42104b910e29e5bb9e885bed45
|
Swift
|
chengssir/MaskedLayer
|
/Swift 遮罩层/ViewController.swift
|
UTF-8
| 2,275
| 3
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Swift 遮罩层
//
// Created by 程国帅 on 16/7/2.
// Copyright © 2016年 程国帅. All rights reserved.
//
import UIKit
class ViewController: UIViewController{
@IBOutlet weak var tableView: UITableView!
var array : NSMutableArray!
override func viewDidLoad() {
super.viewDidLoad()
self.title = "CAShapeLayer绘制视图形状"
self.array = NSMutableArray()
for _ in 0..<20 {
// 字典转模型并将模型添加到模型数组中
array.addObject("\(arc4random()%2)")
}
self.tableView.dataSource = self;
self.tableView.delegate = self;
self.tableView.backgroundColor = UIColor.clearColor()
self.tableView.separatorStyle = .None
self.tableView.registerClass(tabViewCell.self, forCellReuseIdentifier: "cell")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
extension ViewController :UITableViewDataSource ,UITableViewDelegate{
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return array.count
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let index: String = array.objectAtIndex(indexPath.row) as! String
print(index)
if index == "0" {
return 200
}
return 100
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let index: String = array.objectAtIndex(indexPath.row) as! String
let cell = tabViewCell.init(style: .Default, reuseIdentifier: "cell" ,shareT:index == "0" ? .Swift_Custom : .Swift_Pentagone )
cell.backgroundColor = index == "0" ? UIColor.clearColor() : UIColor.clearColor()
cell.selectionStyle = .None
print("\(indexPath.row % 2)")
cell.isMySelf = indexPath.row % 2 == 0 ? true : false
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print(indexPath.row)
}
}
| true
|
23ec0a27bf14c29155a8ac56551224f89d3c14fa
|
Swift
|
kwoodnyc/Project-3
|
/BoutTime/Utils/NumberUtils.swift
|
UTF-8
| 384
| 2.859375
| 3
|
[] |
no_license
|
//
// NumberUtils.swift
// BoutTime
//
// Created by Kristopher Wood on 7/12/2018.
// Copyright © 2018 Kristopher Wood. All rights reserved.
//
class NumberUtils {
static func format(num: Int) -> String {
if num == 60 {
return "1:00"
} else if num < 60 && num >= 10 {
return "0:\(num)"
} else {
return "0:0\(num)"
}
}
}
| true
|
2f4c48d41b9b7a34c7db018c0370c0577925dd0f
|
Swift
|
EntropyIKov/MarvelComics
|
/MarvelComics/Sources/DTO/DataList.swift
|
UTF-8
| 603
| 2.75
| 3
|
[] |
no_license
|
//
// DataList.swift
// MarvelComics
//
// Created by Kovalenko Ilia on 05/10/2018.
// Copyright © 2018 Kovalenko Ilia. All rights reserved.
//
import Foundation
import ObjectMapper
class DataList<DataType: Mappable>: Mappable {
var available: Int?
var returned: Int?
var collectionURI: String?
var items: [DataType]?
required init?(map: Map) {
}
func mapping(map: Map) {
available <- map["available"]
returned <- map["returned"]
collectionURI <- map["collectionURI"]
items <- map["items"]
}
}
| true
|
23ccc90b1f26ca3992b38a44e2d64208a8406bf8
|
Swift
|
arbourd/trash
|
/Sources/TrashCLI/TrashCLI.swift
|
UTF-8
| 963
| 2.90625
| 3
|
[
"MIT"
] |
permissive
|
import Foundation
import Trash
let version = "0.3.6"
let usage = """
Usage: trash [file ...]
"""
extension FileHandle: TextOutputStream {
public func write(_ string: String) {
guard let data = string.data(using: .utf8) else { return }
self.write(data)
}
}
@main
struct CLI {
static var standardError = FileHandle.standardError
static func main() {
let args = CommandLine.arguments.dropFirst()
switch args.first {
case nil:
print(usage)
case "-h"?, "--help"?:
print(usage)
case "-v"?, "--version"?:
print("trash, version " + version)
default:
do {
let urls = args.map(URL.init(fileURLWithPath:))
try Trash.recycle(Array(urls))
exit(0)
} catch {
print(error.localizedDescription, to: &standardError)
exit(1)
}
}
}
}
| true
|
59e26437612e95df8b8533f36f67120fa0fe4df0
|
Swift
|
yirkoon/IOS-AImergence
|
/AImergence2/Actions.swift
|
UTF-8
| 2,569
| 2.640625
| 3
|
[] |
no_license
|
//
// AnimatedSKNode.swift
// AImergence
//
// Created by Olivier Georgeon on 18/02/16.
// Copyright © 2016 Olivier Georgeon. All rights reserved.
//
import SceneKit
struct Actions
{
let moveUpExperience = SCNAction.moveByX( 0.0, y: 5.0, z: 0.0, duration: 3.0)
let moveForward:SCNAction = SCNAction.moveByX( 1, y: 0.0, z: 0.0, duration: 0.2)
let moveBackward:SCNAction = SCNAction.moveByX( -1, y: 0.0, z: 0.0, duration: 0.2)
let moveHalfFront = SCNAction.moveByX( 0.5, y: 0.0, z: 0.0, duration: 0.1)
let moveHalfBack = SCNAction.moveByX(-0.5, y: 0.0, z: 0.0, duration: 0.1)
let remove = SCNAction.removeFromParentNode()
let wait = SCNAction.waitForDuration(0.1)
let unhide = SCNAction.unhide()
let moveFarRight = SCNAction.moveByX( 5.0, y: 0.0, z: 0.0, duration: 0.3)
let shrink = SCNAction.scaleBy(0.0, duration: 1.0)
func spawnExperience() -> SCNAction {
return SCNAction.sequence([unhide, moveUpExperience, remove])
}
func waitAndSpawnExperience() -> SCNAction {
return SCNAction.sequence([wait, spawnExperience()])
}
func actionAppearBackward() -> SCNAction {
return SCNAction.sequence([turnover(duration: 0), unhide])
}
func bump() -> SCNAction {
return SCNAction.runBlock(bumpBlock)
}
func bumpAndTurnover() -> SCNAction {
return SCNAction.group([SCNAction.runBlock(bumpBlock), SCNAction.sequence([wait, turnover()])])
}
func bumpBack() -> SCNAction {
return SCNAction.runBlock(bumpBackBlock)
}
func turnover(angle: CGFloat = CGFloat(M_PI), duration: Double = 0.2) -> SCNAction {
return SCNAction.rotateByX(0.0, y: 0.0, z: angle , duration: duration)
}
func toss() -> SCNAction {
let actionRoll = SCNAction.repeatAction(turnover(CGFloat(-M_PI)), count: 5)
return SCNAction.sequence([SCNAction.group([shrink, actionRoll, moveFarRight]), remove])
}
func toss2() -> SCNAction {
return SCNAction.sequence([SCNAction.group([moveFarRight]), remove])
}
func waitAndToss() -> SCNAction {
return SCNAction.sequence([wait, toss2()])
}
func bumpBlock(node: SCNNode) {
if node.childNodes.count > 0 {
node.childNodes[0].runAction(SCNAction.sequence([moveHalfFront, moveHalfBack]))
}
}
func bumpBackBlock(node: SCNNode) {
if node.childNodes.count > 0 {
node.childNodes[0].runAction(SCNAction.sequence([moveHalfBack, moveHalfFront]))
}
}
}
| true
|
74a210dca6b7d86d0d5ec57ab2506c5f1ba5322e
|
Swift
|
Caffeine-Devotee/ixigo-Assignment
|
/ixigo Assignment/Network.swift
|
UTF-8
| 1,061
| 2.890625
| 3
|
[] |
no_license
|
//
// Network.swift
// ixigo Assignment
//
// Created by GAURAV NAYAK on 01/07/19.
// Copyright © 2019 GAURAV NAYAK. All rights reserved.
//
import Foundation
import Foundation
import Alamofire
import SwiftyJSON
class NetworkController {
func getRequest(urlString: String, completionHandler: @escaping (Bool, JSON) -> Void ) {
Alamofire.request(URL(string: urlString)!).responseJSON { (response) in
do {
let json = try JSON(data: response.data!)
if response.response!.statusCode >= 200 && response.response!.statusCode < 300 {
completionHandler(true, json)
}
else {
completionHandler(false, JSON.null)
}
} catch{
print(error)
completionHandler(false, JSON.null)
}
}
}
}
class Connectivity {
class func isConnectedToInternet() ->Bool {
return NetworkReachabilityManager()!.isReachable
}
}
| true
|
0f8e938b2f94d0c393fdf5ddcc1575bf1d53d93b
|
Swift
|
elislade/Sipe
|
/Sipe iOS/Views/ContentView.swift
|
UTF-8
| 3,075
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
import SwiftUI
import Firebase
struct ContentView: View {
@ObservedObject private var data = FIRData<Post>()
@State var error: String?
func signIn(){
}
var body: some View {
ZStack {
ScrollView {
VStack(spacing: 10) {
SipeHeader()
if data.collection.count == 0 {
IntroCard().padding(.horizontal).padding(.bottom, 60).frame(minWidth: 200, maxWidth: 550)
}
if Auth.auth().currentUser == nil {
Text("Not Logged In").opacity(0.3)
Button("Sign In", action: signIn)
} else {
ForEach(data.collection, id:\.id){ post in
PostCell(post: post)
.frame(maxWidth: 500)
.padding()
.contextMenu {
Button(action: post.delete){
Image(systemName: "trash")
Text("Delete")
}
Button(action: { }){
Image("warn_ctx_menu")
Text("Report")
}
Button(action: { }){
Image(systemName: "share")
Text("Share")
}
}.padding(.bottom, 60)
}
}
}
}
if error != nil {
VStack {
Spacer()
HStack(spacing: 10){
Image(systemName: "xmark.octagon.fill").imageScale(.large)
Text(error!)
Spacer()
Button("Okay", action: { self.error = nil })
.padding(.horizontal)
.padding(.vertical, 8)
.background(Color.red)
.cornerRadius(4)
.foregroundColor(.white)
}
.foregroundColor(.red)
.padding(20)
.padding(.bottom, 20)
.background(Color.red.opacity(0.1))
.background(Color(.systemBackground))
.cornerRadius(5)
.shadow(radius: 20)
}.transition(.modalMove)
}
}
//.onReceive(data.errors, perform: { self.error = $0 })
.background(LinearGradient.main.edgesIgnoringSafeArea(.all))
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| true
|
d18148f864c95c9133e2eb8f301d11e7c36d702b
|
Swift
|
jklimke/ScanKit
|
/ScanKit/ProjectsSUIV.swift
|
UTF-8
| 1,946
| 2.875
| 3
|
[
"MIT"
] |
permissive
|
//
// ProjectsSUIV.swift
// ScanKit
//
// Created by Kenneth Schröder on 29.09.21.
//
import SwiftUI
func getProjectNames() -> [String] { // https://stackoverflow.com/questions/42894421/listing-only-the-subfolders-within-a-folder-swift-3-0-ios-10
let filemgr = FileManager.default
let dirPaths = filemgr.urls(for: .documentDirectory, in: .userDomainMask)
let myDocumentsDirectory = dirPaths[0]
var projectNames:[String] = []
do {
let directoryContents = try FileManager.default.contentsOfDirectory(at: myDocumentsDirectory, includingPropertiesForKeys: nil, options: [])
let subdirPaths = directoryContents.filter{ $0.hasDirectoryPath }
let subdirNamesStr = subdirPaths.map{ $0.lastPathComponent }
projectNames = subdirNamesStr.filter { $0 != ".Trash" }
} catch let error as NSError {
print(error.localizedDescription)
}
return projectNames.sorted()
}
// https://youtu.be/diK5WkGpCUE https://developer.apple.com/videos/play/wwdc2019/231/ https://medium.com/flawless-app-stories/swiftui-dynamic-list-identifiable-73c56215f9ff https://youtu.be/k5rupivxnMA
struct ProjectsSUIV: View { // SUIV = SwiftUI View
var projectNames = getProjectNames()
var body: some View {
NavigationView {
VStack {
List(projectNames, id: \.hash) { project in
NavigationLink(destination: ProjectDetailsSUIV(projectName: project), label: {
Text(project)
})
}
Spacer()
}
.navigationTitle("Projects")
}.navigationViewStyle(StackNavigationViewStyle()).accentColor(Color("Occa")) // https://stackoverflow.com/questions/65316497/swiftui-navigationview-navigationbartitle-layoutconstraints-issue/65316745
}
}
struct ProjectsSUIV_Previews: PreviewProvider {
static var previews: some View {
ProjectsSUIV()
}
}
| true
|
5b8b8d9493b908b9088be744a738f042dcba2f30
|
Swift
|
aftabmd/sambag
|
/Sambag/Source/SambagDatePickerResult.swift
|
UTF-8
| 525
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
//
// SambagDatePickerResult.swift
// Sambag
//
// Created by Mounir Ybanez on 03/06/2017.
// Copyright © 2017 Ner. All rights reserved.
//
public struct SambagDatePickerResult {
public var month: SambagMonth
public var year: Int
public var day: Int
public init() {
self.month = .january
self.year = 0
self.day = 0
}
}
extension SambagDatePickerResult: CustomStringConvertible {
public var description: String {
return "\(month) \(day), \(year)"
}
}
| true
|
91bb9b407af8a0f2c87169b51c0f1bcaa505f548
|
Swift
|
Mrruantion/CalenderDemo
|
/CalenderDemo/ViewController.swift
|
UTF-8
| 8,911
| 2.703125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// CalenderDemo
//
// Created by Zhang茹儿 on 16/8/31.
// Copyright © 2016年 Ru.zhang. All rights reserved.
//
import UIKit
let KScreenHeight = UIScreen.main.bounds.size.height
let KScreenWidth = UIScreen.main.bounds.size.width
class ViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource{
var dateArray = NSArray()
// 时间Label
lazy var timeLabel: UILabel = {
let time = UILabel(frame: CGRect.zero)
time.text = "xxxx-xx"
time.textAlignment = .center
self.view.addSubview(time)
return time
}()
var myCollection: UICollectionView!
lazy var lastButton: UIButton = {
let last = UIButton(type: .system)
last.setTitle("<--", for: UIControlState())
last.setTitleColor(UIColor.black, for: UIControlState())
last.addTarget(self, action: #selector(lastAction), for: .touchUpInside)
self.view.addSubview(last)
return last
}()
lazy var nextButton: UIButton = {
let next = UIButton(type: .system)
next.setTitle("-->", for: UIControlState())
next.setTitleColor(UIColor.black, for: UIControlState())
next.addTarget(self, action: #selector(nextAction), for: .touchUpInside)
self.view.addSubview(next)
return next
}()
var date = Date()
override func viewDidLoad() {
super.viewDidLoad()
self.UIBuild()
self.myCollection.register(DateCollectionViewCell.self, forCellWithReuseIdentifier: "CELL")
self.myCollection.register(WeekCollectionViewCell.self, forCellWithReuseIdentifier: "cell")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController {
func UIBuild() {
dateArray = ["日","一","二","三","四","五","六"]
lastButton.frame = CGRect(x: 10, y: 50, width: 30, height: 40)
nextButton.frame = CGRect(x: KScreenWidth - 40, y: 50, width: 30, height: 40)
timeLabel.frame = CGRect(x: lastButton.frame.maxX, y: lastButton.frame.minY, width: KScreenWidth - lastButton.frame.width - nextButton.frame.width - 10, height: 40)
let item = KScreenWidth / 7 - 5
let layout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0)
layout.itemSize = CGSize(width: item, height: item)
layout.minimumLineSpacing = 2
layout.minimumInteritemSpacing = 2
let rect = CGRect(x: 10, y: lastButton.frame.maxY, width: KScreenWidth, height: 400)
myCollection = UICollectionView(frame: rect, collectionViewLayout: layout)
myCollection.backgroundColor = UIColor.white
myCollection.dataSource = self
myCollection.delegate = self
self.view.addSubview(myCollection)
self.timeLabel.text = String(format: "%li-%.2ld", self.year(self.date), self.month(self.date))
}
@objc(numberOfSectionsInCollectionView:) func numberOfSections(in collectionView: UICollectionView) -> Int {
return 2
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
switch section {
case 0:
return dateArray.count
default:
let days = self.daysInThisMonth(date)
let firstWeek = self.firstWeekInThisMonth(date)
let day = days + firstWeek
return day
}
}
@objc(collectionView:cellForItemAtIndexPath:) func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
switch (indexPath as NSIndexPath).section {
case 0:
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! WeekCollectionViewCell
cell.timeLabel.text = dateArray[(indexPath as NSIndexPath).row] as? String
return cell
default:
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CELL", for: indexPath) as! DateCollectionViewCell
let days = self.daysInThisMonth(date)
let week = self.firstWeekInThisMonth(date)
var day = 0
let index = (indexPath as NSIndexPath).row
if index < week {
// cell.backgroundColor = UIColor.whiteColor()
cell.timeLabel.text = " "
} else if index > week + days - 1 {
cell.backgroundColor = UIColor.red
} else {
day = index - week + 1
cell.timeLabel.text = String(day)
let da = Date()
let com = (Calendar.current as NSCalendar).components([NSCalendar.Unit.year, NSCalendar.Unit.month, NSCalendar.Unit.day], from: da)
let abc = String(format: "%li-%.2ld", com.year!, com.month!)
if self.timeLabel.text! == abc {
if cell.timeLabel.text == String(self.day(date)) {
cell.backgroundColor = UIColor.cyan
} else {
cell.backgroundColor = UIColor.white
}
} else {
cell.backgroundColor = UIColor.white
}
}
return cell
}
}
@objc(collectionView:didSelectItemAtIndexPath:) func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.deselectItem(at: indexPath, animated: true)
let cell = collectionView.cellForItem(at: indexPath) as! DateCollectionViewCell
print(cell.timeLabel.text)
}
}
extension ViewController {
// 获取当前日期
func day(_ date: Date) -> NSInteger {
let com = (Calendar.current as NSCalendar).components([NSCalendar.Unit.year, NSCalendar.Unit.month, NSCalendar.Unit.day], from: date)
return com.day!
}
// 获取当前月
func month(_ date: Date) -> NSInteger {
let com = (Calendar.current as NSCalendar).components([NSCalendar.Unit.year, NSCalendar.Unit.month, NSCalendar.Unit.day], from: date)
return com.month!
}
// 获取当前年
func year(_ date: Date) -> NSInteger {
let com = (Calendar.current as NSCalendar).components([NSCalendar.Unit.year, NSCalendar.Unit.month, NSCalendar.Unit.day], from: date)
return com.year!
}
// 每个月1号对应的星期
func firstWeekInThisMonth(_ date: Date) -> NSInteger {
var calender = Calendar.current
calender.firstWeekday = 1
var com = (calender as NSCalendar).components([NSCalendar.Unit.year, NSCalendar.Unit.month, NSCalendar.Unit.day], from: date)
com.day = 1
let firstDay = calender.date(from: com)
let firstWeek = (calender as NSCalendar).ordinality(of: NSCalendar.Unit.weekday, in: NSCalendar.Unit.weekOfMonth, for: firstDay!)
return firstWeek - 1
}
// 当前月份的天数
func daysInThisMonth(_ date: Date) -> NSInteger {
let days: NSRange = (Calendar.current as NSCalendar).range(of: NSCalendar.Unit.day, in: NSCalendar.Unit.month, for: date)
return days.length
}
// 上个月
func lastMonth(_ date: Date) -> Date {
var dateCom = DateComponents()
dateCom.month = -1
let newDate = (Calendar.current as NSCalendar).date(byAdding: dateCom, to: date, options: NSCalendar.Options.matchStrictly)
return newDate!
}
// 下个月
func nextMonth(_ date: Date) -> Date {
var dateCom = DateComponents()
let abc = 1
dateCom.month = +abc
let newDate = (Calendar.current as NSCalendar).date(byAdding: dateCom, to: date, options: NSCalendar.Options.matchStrictly)
return newDate!
}
}
extension ViewController {
func lastAction() {
UIView.transition(with: self.myCollection, duration: 0.5, options: .transitionCurlDown, animations: {
self.date = self.lastMonth(self.date)
self.timeLabel.text = String(format: "%li-%.2ld", self.year(self.date), self.month(self.date))
}, completion: nil)
self.myCollection.reloadData()
}
func nextAction() {
UIView.transition(with: self.myCollection, duration: 0.5, options: .transitionCurlUp, animations: {
self.date = self.nextMonth(self.date)
self.timeLabel.text = String(format: "%li-%.2ld", self.year(self.date), self.month(self.date))
}, completion: nil)
self.myCollection.reloadData()
}
}
| true
|
ca9b693e2764a1b1a5b24490206c8c7d86db7d22
|
Swift
|
owenhenley/Podcasts
|
/Podcasts/APIService.swift
|
UTF-8
| 4,130
| 2.6875
| 3
|
[] |
no_license
|
//
// APIService.swift
// Podcasts
//
// Created by Owen Henley on 12/17/18.
// Copyright © 2018 Owen Henley. All rights reserved.
//
import Foundation
import Alamofire
import FeedKit
class APIService {
typealias EpisodeDownloadCompleteTuple = (fileURL: String, episodeTitle: String)
// MARK: - Properties
let baseiTunesSearchURL = "https://itunes.apple.com/search"
static let shared = APIService()
// MARK: - Methods
func fetchPodcasts(searchText: String, completionHandler: @escaping ([Podcast]) -> ()) {
let parameters = ["term": searchText, "media": "podcast"]
Alamofire.request(baseiTunesSearchURL, method: .get, parameters: parameters, encoding: URLEncoding.default, headers: nil).responseData { (dataResponse) in
if let error = dataResponse.error {
print(" Error in File: \(#file), /nFunction: \(#function), /nLine: \(#line), /nMessage: \(error). \(error.localizedDescription) ")
return
}
guard let data = dataResponse.data else { return }
do {
let searchResult = try JSONDecoder().decode(SearchResults.self, from: data)
completionHandler(searchResult.results)
} catch {
print(" Error in File: \(#file), /nFunction: \(#function), /nLine: \(#line), /nMessage: \(error). \(error.localizedDescription) ")
}
}
}
func fetchEpisodes(feedURL: String, completion: @escaping ([Episode]) -> ()) {
let secureFeedURL = feedURL.convertedToHTTPS()
guard let url = URL(string: secureFeedURL) else { return }
DispatchQueue.global(qos: .background).async {
let feedParser = FeedParser(URL: url)
feedParser.parseAsync { (result) in
print("Success:", result.isSuccess)
if let error = result.error {
print(" Error in File: \(#file), /nFunction: \(#function), /nLine: \(#line), /nMessage: \(error). \(error.localizedDescription) ")
return
}
guard let feed = result.rssFeed else { return }
let episodes = feed.asEpisodes()
completion(episodes)
}
}
}
func downloadEpisode(episode: Episode) {
print("downlading \(episode.title ), Stream url: \(episode.streamURL)")
let downloadRequest = DownloadRequest.suggestedDownloadDestination()
Alamofire.download(episode.streamURL, to: downloadRequest).downloadProgress { (progress) in
// Notify downloads controller of download progress
NotificationCenter.default.post(name: .downloadProgress, object: nil, userInfo: [
"title" : episode.title ,
"downloadProgress" : progress.fractionCompleted
])
}.response { (response) in
print(response.destinationURL?.absoluteString ?? "")
let episodeDownloadComplete = EpisodeDownloadCompleteTuple(fileURL: response.destinationURL?.absoluteString ?? "", episodeTitle: episode.title)
NotificationCenter.default.post(name: .downloadComplete, object: episodeDownloadComplete, userInfo: nil)
var downloadedEpisodes = UserDefaults.standard.downloadedEpisodes()
guard let index = downloadedEpisodes.firstIndex(where: {
$0.title == episode.title &&
$0.author == episode.author
}) else {
return
}
downloadedEpisodes[index].fileURL = response.destinationURL?.absoluteString ?? ""
do {
let data = try JSONEncoder().encode(downloadedEpisodes)
UserDefaults.standard.set(data, forKey: UserDefaults.downloadedEpisodesKey)
} catch {
print(" Error in File: \(#file), /nFunction: \(#function), /nLine: \(#line), /nMessage: \(error). \(error.localizedDescription) ")
}
}
}
}
| true
|
a607229871b0f1f5a6dd9f8bf9f19a778c7fdc57
|
Swift
|
adnamsale/bbsolver
|
/My Extension Extension/Nonogrids/NonogridsBoardParser.swift
|
UTF-8
| 2,536
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
//
// NonogridsBoardParser.swift
// My Extension Extension
//
// Created by mark on 3/28/20.
// Copyright © 2020 Mark Dixon. All rights reserved.
//
import Foundation
public class NonogridsBoardParser : NSObject, XMLParserDelegate {
private let source:String;
private var board:NonogridsBoard
private var firstRow:Bool?
private var firstCol:Bool?
private var wantText:Bool = false
private var curClue:String = ""
lazy var parsed:NonogridsBoard = parse();
public init(source:String){
self.source = source
board = NonogridsBoard()
}
private func parse() -> NonogridsBoard {
var fixedSource = source.replacingOccurrences(of: "\"></", with:"\"/></")
fixedSource = fixedSource.replacingOccurrences(of: "<br>", with: "<br/>")
fixedSource = fixedSource.replacingOccurrences(of: " ", with: " ")
let parser = XMLParser(data: fixedSource.data(using: .utf8) ?? Data())
parser.delegate = self;
parser.parse();
return board
}
public func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]){
if elementName == "tr" {
firstRow = firstRow == nil
firstCol = nil
}
else if elementName == "td" {
firstCol = firstCol == nil
wantText = true
curClue = ""
}
else if elementName == "br" {
if (wantText) {
curClue += " "
}
}
}
public func parser(_ parser: XMLParser, foundCharacters string: String) {
if (wantText) {
curClue += string
}
}
public func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
guard elementName == "td" else {
return
}
if wantText {
wantText = false
if (firstRow! && !firstCol!) {
board.addDown(parseClue(curClue))
}
else if (firstCol! && !firstRow!) {
board.addAcross(parseClue(curClue))
}
}
}
public func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) {
NSLog(parseError.localizedDescription);
}
private func parseClue(_ clue:String) -> [Int] {
return clue.split(separator: " ").map { Int($0)! }
}
}
| true
|
903d22a7ebb2284ce95b7a617d7a8e01b0605ed7
|
Swift
|
Ibrahim-Mushtaha/Movie-App-IOS
|
/Movie App/model/Movie.swift
|
UTF-8
| 2,570
| 3.046875
| 3
|
[] |
no_license
|
//
// Movie.swift
// Movie App
//
// Created by Ibrahim Mushtaha on 01/06/2021.
//
import Foundation
struct MovieResponse: Codable {
var page: Int
var total_results: Int
var total_pages: Int
var results: [Movie]
}
public class Movie: Codable, Identifiable {
public var popularity: Float
public var vote_count: Int
public var video: Bool
public var poster_path: String
public var id: Int
public var adult: Bool
public var backdrop_path: String
public var original_language: String
public var original_title: String
public var genre_ids: [Int]
public var title: String
public var vote_average: Float
public var overview: String
public var release_date: String
enum CodingKeys: String, CodingKey {
case popularity = "popularity"
case vote_count = "vote_count"
case video = "video"
case poster_path = "poster_path"
case id = "id"
case adult = "adult"
case backdrop_path = "backdrop_path"
case original_language = "original_language"
case original_title = "original_title"
case genre_ids = "genre_ids"
case title = "title"
case vote_average = "vote_average"
case overview = "overview"
case release_date = "release_date"
}
public init(popularity: Float, vote_count: Int, video: Bool, poster_path: String, id: Int, adult: Bool, backdrop_path: String, original_language: String, original_title: String, genre_ids: [Int], title: String, vote_average: Float, overview: String, release_date: String) {
self.popularity = popularity
self.vote_count = vote_count
self.video = video
self.poster_path = poster_path
self.id = id
self.adult = adult
self.backdrop_path = backdrop_path
self.original_language = original_language
self.original_title = original_title
self.genre_ids = genre_ids
self.title = title
self.vote_average = vote_average
self.overview = overview
self.release_date = release_date
}
public init() {
self.popularity = 0.0
self.vote_count = 0
self.video = false
self.poster_path = ""
self.id = 0
self.adult = false
self.backdrop_path = ""
self.original_language = ""
self.original_title = ""
self.genre_ids = []
self.title = ""
self.vote_average = 0.0
self.overview = ""
self.release_date = ""
}
}
public typealias MovieResults = [Movie]
| true
|
f4a1e106fd6e850fe3ce86fe1916e3f34b92db74
|
Swift
|
stevencurtis/QuizManager
|
/QuizManagerTests/GameManagerTests.swift
|
UTF-8
| 11,771
| 2.75
| 3
|
[] |
no_license
|
//
// GameManagerTests.swift
// GameManagerTests
//
// Created by Steven Curtis on 03/06/2019.
// Copyright © 2019 Steven Curtis. All rights reserved.
//
import XCTest
@testable import QuizManager
class GameManagerTests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
/// unsure about why this error is generated at the moment
func testStartGame() {
let expectation = XCTestExpectation(description: #function)
let qm = QuizManagerMock()
let gm = GameManager(quizManager: qm)
gm.startGame(with: QuestionTestModel.self, players: 1, withCompletionHandler: { result in
switch result {
case .failure (let error):
let custerr = error as NSError
XCTAssertEqual(custerr.code, -2000)
case .success (let data):
XCTAssertNotNil(data)
}
expectation.fulfill()
})
wait(for: [expectation], timeout: 0.2)
}
func testGetNumberPlayersOne() {
let expectation = XCTestExpectation(description: #function)
let qm = QuizManagerMock()
let gm = GameManager(quizManager: qm)
gm.startGame(with: QuestionTestModel.self, players: 1, withCompletionHandler: { result in
switch result {
case .failure (let error):
XCTAssertNil(error)
case .success:
XCTAssertEqual(gm.getNumberPlayers(), 1)
}
expectation.fulfill()
})
wait(for: [expectation], timeout: 0.2)
}
func testGetNumberPlayersTwo() {
let expectation = XCTestExpectation(description: #function)
let qm = QuizManagerMock()
let gm = GameManager(quizManager: qm)
gm.startGame(with: QuestionTestModel.self, players: 2, withCompletionHandler: { result in
switch result {
case .failure (let error):
XCTAssertNil(error)
case .success:
XCTAssertEqual(gm.getNumberPlayers(), 2)
}
expectation.fulfill()
})
wait(for: [expectation], timeout: 0.2)
}
func testInitialButtonStatement() {
let qm = QuizManagerMock()
let gm = GameManager(quizManager: qm, dice1: 4, dice2: 5, player1ScoreTurn: 5, player2ScoreTurn: 2, player1ScoreGame: 1, player2ScoreGame: 2, currentPlayer: 1)
let buttonStatus: (ButtonStatus) = ButtonStatus(rollEnabled: true, answerEnabled: false, passEnabled: false)
XCTAssertEqual(gm.getButtonStatus(), buttonStatus )
}
func testSwapPlayerOneToZero() {
let qm = QuizManagerMock()
let gm = GameManager(quizManager: qm, dice1: 4, dice2: 5, player1ScoreTurn: 5, player2ScoreTurn: 2, player1ScoreGame: 1, player2ScoreGame: 2, currentPlayer: 1)
gm.swapPlayer()
XCTAssertEqual(gm.getCurrentPlayer(), 0)
}
func testSwapPlayerZeroToOne() {
let qm = QuizManagerMock()
let gm = GameManager(quizManager: qm, dice1: 4, dice2: 5, player1ScoreTurn: 5, player2ScoreTurn: 2, player1ScoreGame: 1, player2ScoreGame: 2, currentPlayer: 0)
gm.swapPlayer()
XCTAssertEqual(gm.getCurrentPlayer(), 1)
}
// swapping player does not update the scores
func testSwapPlayerMidTurn() {
let qm = QuizManagerMock()
let gm = GameManager(quizManager: qm, dice1: 4, dice2: 5, player1ScoreTurn: 5, player2ScoreTurn: 0, player1ScoreGame: 1, player2ScoreGame: 0, currentPlayer: 0)
gm.swapPlayer()
XCTAssertEqual(gm.scores(), GameScores(player1ScoreTurn: 5, player2ScoreTurn: 0, player1ScoreGame: 1, player2ScoreGame: 0))
}
func testAddToGameScoreOne() {
let qm = QuizManagerMock()
let gm = GameManager(quizManager: qm, dice1: 4, dice2: 5, player1ScoreTurn: 5, player2ScoreTurn: 2, player1ScoreGame: 1, player2ScoreGame: 2, currentPlayer: 0)
gm.addToGameScore()
let expectedAnswer = GameScores(player1ScoreTurn: 0, player2ScoreTurn: 2, player1ScoreGame: 6, player2ScoreGame: 2)
XCTAssertEqual(gm.getScores(), expectedAnswer)
}
func testAddToGameScoreTwo() {
let qm = QuizManagerMock()
let gm = GameManager(quizManager: qm, dice1: 4, dice2: 5, player1ScoreTurn: 5, player2ScoreTurn: 2, player1ScoreGame: 1, player2ScoreGame: 2, currentPlayer: 1)
gm.addToGameScore()
let expectedAnswer = GameScores(player1ScoreTurn: 5, player2ScoreTurn: 0, player1ScoreGame: 1, player2ScoreGame: 7)
XCTAssertEqual(gm.getScores(), expectedAnswer)
}
func testSwitchAnswererOne() {
let qm = QuizManagerMock()
let gm = GameManager(quizManager: qm, dice1: 4, dice2: 5, player1ScoreTurn: 5, player2ScoreTurn: 2, player1ScoreGame: 1, player2ScoreGame: 2, currentPlayer: 1)
gm.switchAnswerer()
XCTAssertEqual(gm.getCurrentPlayer(), 0)
}
func testSwitchAnswererTwo() {
let qm = QuizManagerMock()
let gm = GameManager(quizManager: qm, dice1: 4, dice2: 5, player1ScoreTurn: 5, player2ScoreTurn: 2, player1ScoreGame: 1, player2ScoreGame: 2, currentPlayer: 1)
gm.switchAnswerer()
XCTAssertEqual(gm.getCurrentPlayer(), 0)
}
func testInitialScores() {
let qm = QuizManagerMock()
let gm = GameManager(quizManager: qm)
gm.startGame(with: QuestionTestModel.self, players: 1, withCompletionHandler: { result in })
let zeroScores = GameScores(player1ScoreTurn: 0, player2ScoreTurn: 0, player1ScoreGame: 0, player2ScoreGame: 0)
XCTAssertEqual(gm.getScores(), zeroScores)
}
func testAddDicePlayerOne() {
let qm = QuizManagerMock()
let gm = GameManager(quizManager: qm, dice1: 4, dice2: 3, player1ScoreTurn: 2, player2ScoreTurn: 0, player1ScoreGame: 3, player2ScoreGame: 4, currentPlayer: 0)
let _ = gm.rollDice(randFuncDie1: { _ in return 2 }, randFuncDie2: { _ in return 3 })
gm.addToTurnScore()
let resultantScores = GameScores(player1ScoreTurn: 9, player2ScoreTurn: 0, player1ScoreGame: 3, player2ScoreGame: 4)
XCTAssertEqual(gm.getScores(), resultantScores)
}
func testAddDicePlayerTwo() {
let qm = QuizManagerMock()
let gm = GameManager(quizManager: qm, dice1: 4, dice2: 5, player1ScoreTurn: 0, player2ScoreTurn: 0, player1ScoreGame: 32, player2ScoreGame: 12, currentPlayer: 1)
let _ = gm.rollDice(randFuncDie1: { _ in return 4 }, randFuncDie2: { _ in return 5 })
gm.addToTurnScore()
let resultantScores = GameScores(player1ScoreTurn: 0, player2ScoreTurn: 11, player1ScoreGame: 32, player2ScoreGame: 12)
XCTAssertEqual(gm.getScores(), resultantScores)
}
/// Double 1's for both die mean lose your score
func testRollDiceDoubleOnes() {
let qm = QuizManagerMock()
let gm = GameManager(quizManager: qm)
let result = gm.rollDice(randFuncDie1: { _ in
return 0
}, randFuncDie2: { _ in
return 0
})
_ = GameScores(player1ScoreTurn: 0, player2ScoreTurn: 0, player1ScoreGame: 0, player2ScoreGame: 0)
XCTAssertEqual(result.losePointsGame, true)
}
func testRollDiceDoubleOnesCalculate() {
let qm = QuizManagerMock()
let gm = GameManager(quizManager: qm, dice1: 5, dice2: 4, player1ScoreTurn: 9, player2ScoreTurn: 0, player1ScoreGame: 5, player2ScoreGame: 12, currentPlayer: 0)
gm.addToTurnScore()
let result = GameScores(player1ScoreTurn: 18, player2ScoreTurn: 0, player1ScoreGame: 5, player2ScoreGame: 12)
XCTAssertEqual(gm.getScores(), result)
}
/// A single 1 means lose your points for that turn
func testRollDiceFirstOne() {
let qm = QuizManagerMock()
let gm = GameManager(quizManager: qm)
let result = gm.rollDice(randFuncDie1: { _ in
return 0
}, randFuncDie2: { _ in
return 3
})
let _ = GameScores(player1ScoreTurn: 0, player2ScoreTurn: 0, player1ScoreGame: 0, player2ScoreGame: 0)
XCTAssertEqual(result.losePointsTurn, true)
}
func testAddToGameScore() {
let qm = QuizManagerMock()
let gm = GameManager(quizManager: qm, dice1: 5, dice2: 4, player1ScoreTurn: 9, player2ScoreTurn: 0, player1ScoreGame: 5, player2ScoreGame: 12, currentPlayer: 0)
gm.addToGameScore()
let result = GameScores(player1ScoreTurn: 0, player2ScoreTurn: 0, player1ScoreGame: 14, player2ScoreGame: 12)
XCTAssertEqual(gm.getScores(), result)
}
/// A single 1 means lose your points for that turn
func testRollDiceSecondOne() {
}
func testScoresAnswerQuestionCorrectly() {
let expectation = XCTestExpectation(description: #function)
let qm = QuizManagerMock()
let gm = GameManager(quizManager: qm, dice1: 2, dice2: 2, player1ScoreTurn: 5, player2ScoreTurn: 0, player1ScoreGame: 12, player2ScoreGame: 0, currentPlayer: 0)
gm.answer(with: QuestionTestModel.self, [0], withCompletionHandler: { result in
switch result {
case .failure(let error):
XCTAssertNotNil(error)
case .success (let calculatedScores):
let scores = GameScores(player1ScoreTurn: 9, player2ScoreTurn: 0, player1ScoreGame: 12, player2ScoreGame: 0)
XCTAssertEqual(calculatedScores.scores, scores)
}
expectation.fulfill()
})
wait(for: [expectation], timeout: 0.5)
}
// func testDeliverNewQuestionAnswerQuestionCorrectly() {
// let expectation = XCTestExpectation(description: #function)
// let qm = QuizManagerMock()
// let gm = GameManager(quizManager: qm, dice1: 2, dice2: 2, player1ScoreTurn: 5, player2ScoreTurn: 0, player1ScoreGame: 12, player2ScoreGame: 0, currentPlayer: 0)
//
// gm.startGame(with: Question.self, players: 1, withCompletionHandler: {_ in })
//
// let firstQ = gm.currentQ(with: Question.self)
// gm.answer(with: Question.self, [0], withCompletionHandler: { result in
// switch result {
// case .failure(let error):
// XCTAssertNotNil(error)
// case .success (let calculatedScores):
// let nextQ = gm.nextQ(with: Question.self)
//
// XCTAssertNotEqual(firstQ?.question, nextQ?.question)
//
// }
// expectation.fulfill()
// })
// wait(for: [expectation], timeout: 0.5)
// }
func testScoresAnswerQuestionIncorrectly() {
let expectation = XCTestExpectation(description: #function)
let qm = QuizManagerMock()
let gm = GameManager(quizManager: qm, dice1: 2, dice2: 2, player1ScoreTurn: 5, player2ScoreTurn: 0, player1ScoreGame: 12, player2ScoreGame: 0, currentPlayer: 0)
gm.answer(with: QuestionTestModel.self, [1], withCompletionHandler: { result in
switch result {
case .failure (let error):
XCTAssertNotNil(error)
case .success (let calculatedScores):
let scores = GameScores(player1ScoreTurn: 0, player2ScoreTurn: 0, player1ScoreGame: 17, player2ScoreGame: 0)
XCTAssertEqual(calculatedScores.scores, scores)
}
expectation.fulfill()
})
wait(for: [expectation], timeout: 0.2)
}
}
extension ClosedRange {
public static func noRand(in range: ClosedRange<Int>) -> Int {
return 0
}
}
| true
|
50903e23ea108c35b6a4e635193a4ace33af4867
|
Swift
|
gabrielsilvabr/HopStop
|
/HopStop/Beer.swift
|
UTF-8
| 1,670
| 2.59375
| 3
|
[] |
no_license
|
//
// Beer.swift
// HopStop
//
// Created by Ethan Haley on 2/29/16.
// Copyright © 2016 Ethan Haley. All rights reserved.
//
import Foundation
import CoreData
class Beer: NSManagedObject {
struct Keys {
static let Descrip = "descrip"
static let BrewDBID = "dbID"
static let Name = "beerName"
static let Brewer = "brewer"
static let BrewerID = "breweryId"
static let Rating = "rating"
}
@NSManaged var descrip: String
@NSManaged var dbID: String
@NSManaged var beerName: String
@NSManaged var brewer: String
@NSManaged var breweryId: String
@NSManaged var rating: Int
override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) {
super.init(entity: entity, insertIntoManagedObjectContext: context)
}
init(context: NSManagedObjectContext) {
let entity = NSEntityDescription.entityForName("Beer", inManagedObjectContext: context)
super.init(entity: entity!, insertIntoManagedObjectContext: context)
}
init(dict: [String: AnyObject], context: NSManagedObjectContext) {
let entity = NSEntityDescription.entityForName("Beer", inManagedObjectContext: context)
super.init(entity: entity!, insertIntoManagedObjectContext: context)
dbID = dict[Keys.BrewDBID] as! String
descrip = dict[Keys.Descrip] as! String
beerName = dict[Keys.Name] as! String
brewer = dict[Keys.Brewer] as! String
breweryId = dict[Keys.BrewerID] as! String
rating = dict[Keys.Rating] as? Int ?? -1
}
}
| true
|
d29b31dd460933a05bbafe263a30b47bbad7e14b
|
Swift
|
IbrahimHussainAli/FitSpace
|
/FitSpace/FitSpace/Controllers/SignUpViewController.swift
|
UTF-8
| 6,025
| 2.8125
| 3
|
[] |
no_license
|
//
// SignUpViewController.swift
// FitSpace
//
// Created by Ibrahim Hussain on 15/01/2020.
// Copyright © 2020 Ibrahim Hussain. All rights reserved.
//
import UIKit
import FirebaseAuth
import Firebase
import FirebaseFirestore
class SignUpViewController: UIViewController {
@IBOutlet weak var fullNameTextField: UITextField!
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var signUpButton: UIButton!
@IBOutlet weak var errorLabel: UILabel!
@IBOutlet weak var backButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setUpElements()
}
func setUpElements(){
//hide error label
errorLabel.alpha = 0
//style elements
Utilities.styleTextField(fullNameTextField)
//change placeholder text colour
fullNameTextField.attributedPlaceholder = NSAttributedString(string: "Full name", attributes: [NSAttributedString.Key.foregroundColor: UIColor.white])
Utilities.styleTextField(emailTextField)
emailTextField.attributedPlaceholder = NSAttributedString(string: "Email", attributes: [NSAttributedString.Key.foregroundColor: UIColor.white])
Utilities.styleTextField(passwordTextField)
passwordTextField.attributedPlaceholder = NSAttributedString(string: "Password", attributes: [NSAttributedString.Key.foregroundColor: UIColor.white])
Utilities.greenStyleFilledButton(signUpButton)
}
/*
// 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.
}
*/
// check the fields and validate that the data is correct. If everything is correct, this method returns nil. Otherwise error message.
func validateFields() -> String? {
// check all fields are filled in
if fullNameTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == ""
||
emailTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == ""
||
passwordTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" {
return "Please fill in all fields."
}
// check if email is valid
let cleanedEmail = emailTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
// email isnt valid
if Utilities.isEmailValid(cleanedEmail) == false {
return "Please enter a valid email address"
}
// check if the password is secure
let cleanedPassword = passwordTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
if Utilities.isPasswordValid(cleanedPassword) == false {
// passwword isn't secure
return "Please ensure your password is at least 8 characters, contains a special character and a number"
}
return nil
}
@IBAction func signUpTapped(_ sender: Any) {
// validate the fields
let error = validateFields()
if error != nil {
// theres something wrong with fields, show error message
showError(error!)
}
else{
// create cleaned versions of data
let fullName = fullNameTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
let email = emailTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
let password = passwordTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
// create the user
Auth.auth().createUser(withEmail: email, password: password) { (result, err) in
//check for errors
if err != nil {
//There was an error with user creation
self.showError("Error creating user")
}
else {
//user was created successfully, now store fullname
let db = Firestore.firestore()
db.collection("users").addDocument(data: ["fullname": fullName, "uid": result!.user.uid ]) { (error) in
if error != nil {
//show error message
self.showError("Error saving user data")
}
}
//transition to home screen
self.transitionToHome()
/*
let nextViewController = self.storyboard?.instantiateViewController(withIdentifier: "tabBarControl")
self.navigationController?.pushViewController(nextViewController!, animated: true)
*/
}
}
}
}
func showError(_ message:String){
errorLabel.text = message
errorLabel.alpha = 1
}
func transitionToHome() {
let homeViewController = storyboard?.instantiateViewController(identifier: Constants.Storyboard.homeViewController) as?
UITabBarController
view.window?.rootViewController = homeViewController
view.window?.makeKeyAndVisible()
}
@IBAction func backButtonPressed(_ sender: Any) {
print("Back button pressed")
self.performSegue(withIdentifier: "backHomeSegue", sender: self)
}
}
| true
|
995f03c45337b9b6089d95d3188ba93009d2180c
|
Swift
|
Elyxx/BrandNewCalculator
|
/BrandNewCalculator/ViewController.swift
|
UTF-8
| 1,622
| 2.890625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// BrandNewCalculator
//
// Created by adminaccount on 12/7/17.
// Copyright © 2017 adminaccount. All rights reserved.
//
import UIKit
class ViewController: UIViewController, InputDelegate {
let segueToInput = "toInput"
let segueToOutput = "toOuput"
var calculator = CalcBrain()
var outputViewController :OutputViewController? = nil
func beginProcessing(input: [String]) -> Double {
let resultNumber = calculator.processing(input: input)
var displayString = String(resultNumber)
if displayString.hasSuffix(".0") {
displayString.removeLast()
displayString.removeLast()
}
outputViewController?.display(displayString)
return resultNumber
}
func inputReceived(input: String) {
outputViewController?.display(input)
}
func setMemoryIndicator(active: String) {
outputViewController?.indicator.text = active
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == segueToInput) {
let inputViewController = segue.destination as? InputViewController
inputViewController?.delegate = self
}
else if segue.identifier == segueToOutput {
outputViewController = segue.destination as? OutputViewController
}
}
}
enum ReceivedSymbol: String {
case digit
case equal
}
| true
|
fa51056261c9da2b5b656c852395faa0cd993ae7
|
Swift
|
trdavi2/FoodFriend
|
/FoodFriend/RecipeIngredientsView.swift
|
UTF-8
| 2,300
| 2.59375
| 3
|
[] |
no_license
|
//
// RecipeIngredientsView.swift
// FoodFriend
//
// Created by Tim Davis on 11/19/15.
// Copyright © 2015 TimDavis. All rights reserved.
//
import UIKit
class RecipeIngredientsView: UIView, UITableViewDelegate, UITableViewDataSource
{
@IBOutlet weak var ingredientsTable: UITableView!
@IBOutlet weak var addButton: UIButton!
var fullIngredientList: [String]!
var ingredientList: [String]!
override func awakeFromNib() {
layer.cornerRadius = 2.0
layer.shadowColor = UIColor(red: SHADOOW_COLOR, green: SHADOOW_COLOR, blue: SHADOOW_COLOR, alpha: 0.5).cgColor
layer.shadowOpacity = 0.8
layer.shadowRadius = 5.0
layer.shadowOffset = CGSize(width: 0.0, height: 2.0)
ingredientsTable.delegate = self
ingredientsTable.dataSource = self
fullIngredientList = [String]()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return fullIngredientList.count
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "IngredientCell", for: indexPath)
cell.textLabel?.text = fullIngredientList[indexPath.row]
return cell
}
func loadData(_ fullIngredientList: [String], ingredientList: [String])
{
self.fullIngredientList = fullIngredientList
self.ingredientList = ingredientList
print("***\(ingredientList)")
ingredientsTable.reloadData()
}
@IBAction func addIngredients(_ sender: AnyObject)
{
if let pantryListData = UserDefaults.standard.value(forKey: "groceryList") as? [String]
{
var groceryList: [String] = pantryListData
groceryList += ingredientList
UserDefaults.standard.set(groceryList, forKey: "groceryList")
UserDefaults.standard.synchronize()
}
else {
UserDefaults.standard.set(ingredientList, forKey: "groceryList")
UserDefaults.standard.synchronize()
}
addButton.isEnabled = false
}
}
| true
|
dece86b1dc0bfc6ff21a44bd8de2ac35fd117108
|
Swift
|
FoodTruckTrackrBW/iOS
|
/FoodTruck/Models/Controllers/AuthController.swift
|
UTF-8
| 1,589
| 2.984375
| 3
|
[] |
no_license
|
//
// AuthController.swift
// FoodTruck
//
// Created by Stephanie Ballard on 4/25/20.
// Copyright © 2020 Stephanie Ballard. All rights reserved.
//
import Foundation
//class AuthController {
//
// func createAnAccount(email: String, password: String) {
// Auth.auth().createUser(withEmail: email, password: password) { (auth, error) in
// if let error = error {
// NSLog("Error creating account: \(error)")
// } else {
// if let auth = auth {
// print("Account Creation Successful")
// print(auth.user.email as Any)
// }
// }
// }
// }
//
// func signIn(email: String, password: String) {
// Auth.auth().signIn(withEmail: email, password: password) { auth, error in
// if let error = error {
// print("Error signing into account: \(error)")
// // TODO: Sign In Error Handling UIAlertController
// } else {
// if let auth = auth {
// print("Sign in Successful!!!")
// print("The current user: \(auth.user)")
// // TODO: UI for user successful sign in
// }
// }
// }
// }
//
// func signOut() {
// do {
// try Auth.auth().signOut()
// } catch {
// if let error = error as NSError? {
// print ("Error Signing Out: %@", error)
// } else {
// print("Log out successful!")
// }
// }
// }
//}
| true
|
8f4cbe9185575e9ede73b19b3b80580a14143bcd
|
Swift
|
javedmultani16/Project
|
/DemoLocation/ViewController.swift
|
UTF-8
| 2,276
| 2.828125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// DemoLocation
//
//
import UIKit
import CoreLocation
class ViewController: UIViewController,CLLocationManagerDelegate{
var locationManager:CLLocationManager!
@IBOutlet weak var labelAdd: UILabel!
@IBOutlet weak var labelLongi: UILabel!
@IBOutlet weak var labelLat: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
if CLLocationManager.locationServicesEnabled(){
locationManager.startUpdatingLocation()
}
// 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.
}
//MARK: - location delegate methods
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation :CLLocation = locations[0] as CLLocation
print("user latitude = \(userLocation.coordinate.latitude)")
print("user longitude = \(userLocation.coordinate.longitude)")
self.labelLat.text = "\(userLocation.coordinate.latitude)"
self.labelLongi.text = "\(userLocation.coordinate.longitude)"
let geocoder = CLGeocoder()
geocoder.reverseGeocodeLocation(userLocation) { (placemarks, error) in
if (error != nil){
print("error in reverseGeocode")
}
let placemark = placemarks! as [CLPlacemark]
if placemark.count>0{
let placemark = placemarks![0]
print(placemark.locality!)
print(placemark.administrativeArea!)
print(placemark.country!)
self.labelAdd.text = "\(placemark.locality!), \(placemark.administrativeArea!), \(placemark.country!)"
}
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Error \(error)")
}
}
| true
|
77cc72c83efe2fd59c4b0d0ae9b1c32684633da4
|
Swift
|
vivekraideveloper/AutoSquadron
|
/AutoSquadron/Controller/LoginVC.swift
|
UTF-8
| 2,936
| 2.5625
| 3
|
[] |
no_license
|
//
// LoginVC.swift
// AutoSquadron
//
// Created by Vivek Rai on 04/11/18.
// Copyright © 2018 Vivek Rai. All rights reserved.
//
import UIKit
import Firebase
import GoogleSignIn
import FBSDKLoginKit
import SVProgressHUD
class LoginVC: UIViewController, GIDSignInUIDelegate, FBSDKLoginButtonDelegate {
@IBOutlet weak var googleButton: UIButton!
@IBOutlet weak var facebookButton: UIButton!
@IBOutlet weak var emailSignInButton: UIButton!
let loginManager = FBSDKLoginManager()
override func viewDidLoad() {
super.viewDidLoad()
configureView()
GIDSignIn.sharedInstance()?.uiDelegate = self
}
override func viewDidAppear(_ animated: Bool) {
Auth.auth().addStateDidChangeListener { (Auth, user) in
if user != nil{
self.performSegue(withIdentifier: "socialLogin", sender: self)
print("User logged in!")
}
}
}
func configureView(){
googleButton.layer.cornerRadius = 8
facebookButton.layer.cornerRadius = 8
emailSignInButton.layer.cornerRadius = 8
}
// Google SignIn
@IBAction func googleSignInButton(_ sender: Any) {
GIDSignIn.sharedInstance()?.signIn()
}
// Facebook SignIn
@IBAction func facebookSignInButton(_ sender: Any) {
loginManager.logIn(withReadPermissions: ["email"], from: self) { (result, error) in
if let error = error{
debugPrint("***********************************Error ocurred while Login: \(error)")
}else if (result?.isCancelled)!{
print("FB Login was cancelled")
}else{
let credential = FacebookAuthProvider.credential(withAccessToken: (FBSDKAccessToken.current()?.tokenString)!)
self.firebaseLogin(credential)
}
}
}
func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {
if let error = error{
debugPrint("Error while login \(error)")
return
}
let credential = FacebookAuthProvider.credential(withAccessToken: result.token.tokenString)
firebaseLogin(credential)
}
func loginButtonDidLogOut(_ loginButton: FBSDKLoginButton!) {
}
// Firebase
func firebaseLogin(_ credential: AuthCredential){
Auth.auth().signInAndRetrieveData(with: credential) { (user, error) in
if let error = error {
print("Error occured \(error.localizedDescription)")
return
}
}
}
// Email SignIn
@IBAction func signInButtonPressed(_ sender: Any) {
performSegue(withIdentifier: "emailSignIn", sender: self)
}
}
| true
|
586bd61e4ed45a116343ea23005c04df1f021c78
|
Swift
|
pedao018/RW_iOS_Bullseye
|
/Bullseye/View/RoundView.swift
|
UTF-8
| 1,740
| 3.203125
| 3
|
[] |
no_license
|
//
// RoundView.swift
// Bullseye
//
// Created by Vo Thi Hong Diem on 7/12/21.
//
import SwiftUI
struct RoundedImageViewStroked: View {
var systemName : String
var body: some View {
Image(systemName: systemName)
.font(.title) //kích thước icon
.foregroundColor(Color("TextColor"))
.frame(width: 56, height: 56)
.overlay(
Circle().strokeBorder(Color("ButtonStrokeColor"),lineWidth: 1.5)
)
}
}
struct RoundedImageViewFilled: View {
var systemName : String
var body: some View {
Circle()
.foregroundColor(Color("ButtonFilledBackgroundColor"))
.frame(width: 56, height: 56)
.overlay(
Image(systemName: systemName)
.font(.title) //kích thước icon
.foregroundColor(Color("ButtonFilledColor"))
)
}
}
struct RoundedRectTextView: View {
var text: String
var body: some View {
RoundedRectangle(cornerRadius: 30)
.strokeBorder(Color("ButtonStrokeColor"),lineWidth: 2.0)
.frame(width: 90, height: 70)
.overlay(BigNumberText(text: text))
}
}
struct RoundView_Previews: PreviewProvider {
static var previews: some View {
VStack{
RoundedImageViewStroked(systemName:"arrow.clockwise")
RoundedImageViewFilled(systemName:"list.dash")
RoundedRectTextView(text: "999")
}
VStack{
RoundedImageViewStroked(systemName:"arrow.clockwise")
RoundedImageViewFilled(systemName:"list.dash")
RoundedRectTextView(text: "999")
}
.preferredColorScheme(.dark)
}
}
| true
|
d108789c82fea241a698d6439d9a40a0b8fa061c
|
Swift
|
podkovyrin/CloudKitNotes
|
/CloudKitNotes/Advanced Operations/Observers/CompletionObserver.swift
|
UTF-8
| 791
| 2.625
| 3
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
//
// CompletionObserver.swift
// CloudKitNotes
//
// Created by Andrew Podkovyrin on 16/05/2019.
// Copyright © 2019 AP. All rights reserved.
//
import Foundation
class CompletionObserver: OperationObserver {
private let completion: (ANOperation, [Error]) -> Void
init(_ completion: @escaping (ANOperation, [Error]) -> Void) {
self.completion = completion
}
// MARK: OperationObserver
func operationDidStart(_ operation: ANOperation) {}
func operationDidCancel(_ operation: ANOperation) {}
func operation(_ operation: ANOperation, didProduceOperation newOperation: Operation) {}
func operationDidFinish(_ operation: ANOperation, errors: [Error]) {
DispatchQueue.main.async {
self.completion(operation, errors)
}
}
}
| true
|
2842e6d24fb561f1480b88700d0b0a5d84acee47
|
Swift
|
kwhinnery/api-snippets
|
/ip-messaging/channels/create-channel/create-channel.swift
|
UTF-8
| 525
| 3.109375
| 3
|
[
"MIT"
] |
permissive
|
// Create the general channel (for public use) if it hasn't been created yet
let channels: TWMChannels? = client?.channelsList()
let options: [NSObject:AnyObject] = [
TWMChannelOptionFriendlyName: "General Channel",
TWMChannelOptionUniqueName: "general",
TWMChannelOptionType: TWMChannelType.Public.rawValue
]
channels?.createChannelWithOptions(options) { channelResult, channel in
if channelResult.isSuccessful() {
print("Channel created.")
} else {
print("Channel NOT created.")
}
}
| true
|
8c9330a223f8cd95c1278482070301992f6f4829
|
Swift
|
chetanpanchal94/WizPandaTest
|
/WizPandaTest/WizPandaTest/Controller/HomeVC.swift
|
UTF-8
| 1,411
| 2.640625
| 3
|
[] |
no_license
|
//
// HomeVC.swift
// WizPandaTest
//
// Created by Chetan Panchal on 19/06/20.
// Copyright © 2020 Chetan Panchal. All rights reserved.
//
import UIKit
class HomeVC: UIViewController {
@IBOutlet weak var btnImage: UIButton!
@IBOutlet weak var btnVideo: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .blueberry
setupButton(title: "Image Demo", button: btnImage)
setupButton(title: "Video Demo", button: btnVideo)
}
/// formatting buttons
func setupButton(title: String, button: UIButton) {
button.setTitle(title, for: .normal)
button.titleLabel?.font = .headingFont
button.backgroundColor = .dodgerBlue
button.setTitleColor(.white, for: .normal)
}
// MARK: button actions
@IBAction func btnImageAction(_ sender: Any) {
let imageVC = self.storyboard?.instantiateViewController(identifier: "ImageVC") as! ImageVC
imageVC.modalPresentationStyle = .overCurrentContext
self.present(imageVC, animated: true, completion: nil)
}
@IBAction func btnVideoAction(_ sender: Any) {
let videoVC = self.storyboard?.instantiateViewController(identifier: "VideoVC") as! VideoVC
videoVC.modalPresentationStyle = .overCurrentContext
self.present(videoVC, animated: true, completion: nil)
}
}
| true
|
1604fe11dad527e932861b712278e34280d0f3b3
|
Swift
|
Jerry2157/iOS_POST_and_GET
|
/PruebaRedes/ViewController.swift
|
UTF-8
| 2,156
| 2.6875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// PruebaRedes
//
// Created by Gerardo Magdaleno on 01/11/18.
// Copyright © 2018 Gerardo Magdaleno. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
Timer.scheduledTimer(with)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBOutlet weak var actEspera: UIActivityIndicatorView!
@IBOutlet weak var tvTexto: UITextView!
@IBAction func descargarHTML(_ sender: UIButton) {
let direccion = "https://norvig.com/big.txt"
if let url = URL(string: direccion){
let tareaDescarga = URLSession.shared.dataTask(with: url){
(datos, response, error) in
if error == nil{
let respuesta = response as! HTTPURLResponse
if respuesta.statusCode == 200{
let texto = String(data: datos!, encoding: .utf8)
//Poner los datos en el TextView
DispatchQueue.main.async {
self.tvTexto.text = texto
}
}
}
print("Datos: \(datos)")
print("Response: \(response)")
print("Error: \(error)")
}
tareaDescarga.resume()
}
}
@IBOutlet weak var imView: UIImageView!
@IBAction func descargarImagen(_ sender: Any) {
if let url = URL(string: "https://www.ajegroup.com/wp-content/uploads/2014/05/BIG.jpg"){
let tarea = URLSession.shared.dataTask(with: url){(data,response, error) in
if error == nil{
let respuesta = response as! HTTPURLResponse
if resp
}
}
}
}
}
| true
|
5b8eca44efc41d8f441e2107dd2334945ef2b6ca
|
Swift
|
MohamedAShera/Chatting-firebase
|
/Chatting-firebase/View/GroupCell.swift
|
UTF-8
| 580
| 2.828125
| 3
|
[] |
no_license
|
//
// GroupCell.swift
// Chatting-firebase
//
// Created by apple on 4/23/19.
// Copyright © 2019 mohamed. All rights reserved.
//
import UIKit
class GroupCell: UITableViewCell {
@IBOutlet weak var groupTitleLbl: UILabel!
@IBOutlet weak var groupDescriptionLbl: UILabel!
@IBOutlet weak var memberCountLbl: UILabel!
func configureCell(title: String, description: String, memberCount: Int) {
self.groupTitleLbl.text = title
self.groupDescriptionLbl.text = description
self.memberCountLbl.text = "\(memberCount) members."
}
}
| true
|
6e8c4661eec0d4f2ac35bdcf5bbdb9634b8ef9f7
|
Swift
|
myamao406/RestaurantOrder
|
/iOrder/UIButton+Extension.swift
|
UTF-8
| 2,196
| 2.78125
| 3
|
[] |
no_license
|
//
// UIButton+Extension.swift
// iOrder2
//
// Created by 山尾 守 on 2016/12/21.
// Copyright © 2016年 山尾守. All rights reserved.
//
import Foundation
import UIKit
@IBDesignable
class ExpansionButton: UIButton {
// @IBInspectable var insets:UIEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0)
internal var insets: UIEdgeInsets = UIEdgeInsets.zero
@IBInspectable internal var insetsTop: CGFloat {
get { return insets.top }
set { insets = UIEdgeInsets(top: newValue,
left: insets.left,
bottom: insets.bottom,
right: insets.right) }
}
@IBInspectable internal var insetsLeft: CGFloat {
get { return insets.left }
set { insets = UIEdgeInsets(top: insets.top,
left: newValue,
bottom: insets.bottom,
right: insets.right) }
}
@IBInspectable internal var insetsBottom: CGFloat {
get { return insets.bottom }
set { insets = UIEdgeInsets(top: insets.top,
left: insets.left,
bottom: newValue,
right: insets.right) }
}
@IBInspectable internal var insetsRight: CGFloat {
get { return insets.right }
set { insets = UIEdgeInsets(top: insets.top,
left: insets.left,
bottom: insets.bottom,
right: newValue) }
}
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
var rect = bounds
rect.origin.x -= insets.left
rect.origin.y -= insets.top
rect.size.width += insets.left + insets.right
rect.size.height += insets.top + insets.bottom
// 拡大したViewサイズがタップ領域に含まれているかどうかを返します
return rect.contains(point)
}
}
| true
|
b8e2edf6a998fb90dce3cd90834e109606087052
|
Swift
|
ankit0812/PersistingJSON
|
/PersistingJSON/PersistentService.swift
|
UTF-8
| 1,603
| 2.78125
| 3
|
[] |
no_license
|
//
// PersistentService.swift
// PersistingJSON
//
// Created by KingpiN on 17/07/19.
// Copyright © 2019 KingpiN. All rights reserved.
//
import UIKit
import CoreData
class PersistentService {
static let shared = PersistentService()
private init() {}
// MARK: - Core Data stack
var context: NSManagedObjectContext { return persistentContainer.viewContext }
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "PersistingJSON")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func save(completion: @escaping () -> Void) {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
completion()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
func fetch<T: NSManagedObject>(_ type:T.Type, completion: @escaping([T]) -> Void) {
let request = NSFetchRequest<T>(entityName: String(describing: type))
do {
let objects = try context.fetch(request)
completion(objects)
} catch {
print(error)
completion([])
}
}
}
| true
|
f75af933c926687077ed62582de3e443dbb2abfe
|
Swift
|
anntonenko/CheckList
|
/CheckList/MyClases/CheckList.swift
|
UTF-8
| 1,444
| 3.0625
| 3
|
[] |
no_license
|
//
// CheckList.swift
// CheckList
//
// Created by getTrickS2 on 10/26/17.
// Copyright © 2017 getTrickS2. All rights reserved.
//
import UIKit
class CheckList: NSObject, NSCoding {
// Properties ------
var name: String
var items: [CheckListItem] = []
var iconName: String
// -----------------
// Computer properties -------------
var countUncheckedItems: Int {
var count = 0
for item in items where !item.chacked {
count += 1
}
return count
}
// ---------------------------------
// Initializators -----------
init(_ name: String, _ iconName: String) {
self.name = name
self.iconName = iconName
super.init()
}
// --------------------------
// Function for NSCoding ----
// I know how to save instance in file
func encode(with aCoder: NSCoder) {
aCoder.encode(name, forKey: "Name")
aCoder.encode(items, forKey: "Items")
aCoder.encode(iconName, forKey: "IconName")
}
// I know how to read instance with file
required init?(coder aDecoder: NSCoder) {
self.items = aDecoder.decodeObject(forKey: "Items") as! [CheckListItem]
self.name = aDecoder.decodeObject(forKey: "Name") as! String
self.iconName = aDecoder.decodeObject(forKey: "IconName") as! String
super.init()
}
// --------------------------
}
| true
|
2fa05b868621307edd3fd310d5543ac435380eeb
|
Swift
|
zainanjum100/ImageSlider
|
/IMageSlider/ViewController.swift
|
UTF-8
| 1,534
| 2.6875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// IMageSlider
//
// Created by ZainAnjum on 05/03/2018.
// Copyright © 2018 ZainAnjum. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var scrollView: UIScrollView = {
let sv = UIScrollView()
sv.contentSize = CGSize(width: 12, height: 200)
sv.backgroundColor = .white
sv.translatesAutoresizingMaskIntoConstraints = false
sv.isPagingEnabled = true
return sv
}()
var imageArray = [UIImage]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
imageArray = [#imageLiteral(resourceName: "4"),#imageLiteral(resourceName: "2"),#imageLiteral(resourceName: "1"),#imageLiteral(resourceName: "3")]
scrollView.frame = view.frame
view.addSubview(scrollView)
for i in 0..<imageArray.count{
let imageView = UIImageView()
imageView.image = imageArray[i]
let xPosition = self.view.frame.width * CGFloat(i)
imageView.frame = CGRect(x: xPosition, y: 0, width: view.frame.width, height: 200)
scrollView.contentSize.width = scrollView.frame.width * CGFloat(i + 1)
scrollView.addSubview(imageView)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| true
|
46900142216b6316df457663a26141ab81015fff
|
Swift
|
jneuhauser/gitea-client-ios
|
/Gitea/Networking/Model/UserModels/User.swift
|
UTF-8
| 982
| 2.96875
| 3
|
[
"MIT"
] |
permissive
|
//
// Created by Johann Neuhauser on 16.05.19.
// Copyright © 2019 Johann Neuhauser. All rights reserved.
//
import Foundation
public struct User: Codable, Equatable, Hashable {
public var avatarUrl: String?
public var email: String?
public var fullName: String?
public var _id: Int64?
public var isAdmin: Bool?
public var language: String?
public var login: String?
public init(avatarUrl: String?, email: String?, fullName: String?, _id: Int64?, isAdmin: Bool?, language: String?, login: String?) {
self.avatarUrl = avatarUrl
self.email = email
self.fullName = fullName
self._id = _id
self.isAdmin = isAdmin
self.language = language
self.login = login
}
public enum CodingKeys: String, CodingKey {
case avatarUrl = "avatar_url"
case email
case fullName = "full_name"
case _id = "id"
case isAdmin = "is_admin"
case language
case login
}
}
| true
|
84d3a8d2347bb4b4554db43b9df5ae275ed9d262
|
Swift
|
jcgohlke/Swift-Fundamentals--Supplemental-Materials
|
/03-CollectionsControlFlow.playground/Contents.swift
|
UTF-8
| 10,803
| 5.15625
| 5
|
[] |
no_license
|
//:# Collections and Control Flow
//:## Collections
//:Now that you can create and work with different pieces of data, it can be helpful to group these bits of data together. This allows you to move them around as a group, and even perform sorting/filtering on them. To accomplish these tasks we use *collections*. The two main collection types in Swift are *arrays* and *dictionaries*.
//:### Arrays
//:An array is an ordered list of objects. These could be a list of strings, integers, boolean values, etc. To create an array in Swift, you wrap the list with `[]` brackets. See an example below:
var shipCaptains = ["Malcolm Reynolds", "Jean-Luc Picard", "James T. Kirk", "Han Solo"]
//:An array can hold any kind of object, as long as each element are of the same type. Mixing data types in an array is not allowed in Swift.
//:To access a member of an array, simply reference it by its index value. Remember, arrays in most languages, including Swift, are indexed starting at 0. So the third element's index is actually 2.
let oldSchoolCap = shipCaptains[2]
//:`oldSchoolCap` would have a value of "James T. Kirk" after line 5. The same technique can be used to add a value to an array at a specific index, provided the array itself has been declared as a variable and not a constant (`var` vs. `let`).
shipCaptains[4] = "Kathryn Janeway"
//:The `shipCaptains` array now has 5 elements, with Janeway being added at the end.
//:#### Array Comparison
//:Now that we have an array, let's build another one so we can perform some comparison.
let engineers = ["Montgomery Scott", "Geordi LaForge", "B'Elanna Torres"]
//:To check if these two arrays are equivalent, we can use the *equality operator* `==`. A single `=` symbol is called the *assignment operator*, and it is used to assign a value on the right to a variable or constant on the left. Two `=` symbols check values on either side for equality.
print(shipCaptains == engineers)
//:The above expression will print a boolean answer, true or false. True, if the values are equal, and false if they are not. For arrays, equality means "equivalent objects, in the same order". Looking at the two arrays above, how would line 14 be evaluated? Since the objects in the two arrays are neither the equivalent nor in the same order, it would evaluate to `false`. Different objects respond differently to the `==` equality operator, so keep that in mind when using it.
//:### Dictionaries
//:Dictionaries are the other major collection type in Swift. They are known by other names in other languages: hashes in Ruby and Perl, maps in Java and Go, and hash tables in Lisp. The concept is the same in every language though. Dictionaries can be described as a collection of *key-value* pairs. Rather than referencing a value with an index like in an array, a dictionary *value* is fetched using a *key*. See the example below:
var occupations = ["Malcolm": "Captain", "Kaylee": "Mechanic"]
let malcolmsJob = occupations["Malcolm"]
occupations["Jayne"] = "Public Relations"
//:Line 17 shows how to create a new dictionary from scratch. Just like with arrays `[]` brackets are used to bound the dictionary elements. Also like an array, each key-value pair is separated by a comma. Unique to a dictionary however is the formation of the pair itself. The object on the left of the `:` is the key, and the right-side object is the value. Just like with arrays, the datatypes for each can be any object, as long as they are consistent throughout the dictionary. So a dictionary with `String` keys and `Int` values must contain pairs over only these types.
//:Fetching a value from the dictionary can be done as shown in line 18. Similar to object fetching in an array, you simply wrap the key associated with the desired value in `[]` brackets and place it after the name of the dictionary. Also similar to arrays, adding a key-value pair is accomplished like you see in line 19. Just be sure that the dictionary has been declared as variable, not a constant.
//:## Control Flow
//:Now that you have an idea of how to write basic instructions (creating and manipulating constants and variables) you will want to be able to form more complicated blocks of instructions. Enter control flow. The concepts that follow allow the program order of execution to be modified at *runtime*. This means that you can set up different forks in the road and the computer will choose a particular road when the program executes. This is commonly used when you might have two or more sets of instructions you'd like to run, but you won't know which is appropriate until the application is running and it contains live data. Let's take a look a the first control flow mechanism, the *if statement*.
//:### If... or Else
//:Let's say you have some code that should only run *if* certain conditions are met at runtime. To do that, you wrap those instructions in an `if` block.
if shipCaptains == engineers
{
print("Arrays are equal")
}
else
{
print("Arrays are not equal")
}
//:To re-use some of our previously defined arrays, let's run one of two possible print statements. You'll notice in line 22 we type `if` followed by something called a *conditional statement*. This statement must evaluate to a boolean answer, i.e. `true` or `false`. Since we're checking here whether the `shipCaptains` array is equal to the `engineers` array with the equality operator, the statement will be evaluated to a boolean answer. What follow this line is a set of `{}` where you place all instructions that need to be run if the conditional line evaluates to `true`. Lines 26-29 are optional. `if` blocks are not required to have an `else` clause, but you may use one if you have instructions that should run only if the conditional statement is `false`. In this case, we want a sentence to print either way, so we have and `if` clause and and `else` clause. Based on what we know of the two arrays referenced here, which print statement will execute at runtime?
//:The two arrays are not equal, so the instructions inside the `if` clause are skipped and the instructions inside `else` are run instead.
//:NOTE: several languages demand that a set of `()` parentheses be used to wrap the conditional expression after the word `if`. In Swift these parentheses are allowed but not required. So feel free to use them if they help you and skip them if they don't.
//:### Switch it Up
//:Believe it or not, most control flow issues can actually be resolved with if-else blocks. You might need to chain several of them together, but you can actually create a pretty complicated path of code using just `if`'s. The problem with that is many nested `if`'s can be very difficult to follow and debug. Because of that, what follows is a set of control flow concepts that allow for both more complicated `switch`ing (see what I did there?) as well as looping.
//:If you have several different paths of code, but only want to execute one of them at runtime, use a `switch` block. See below for an example:
let a = 3
switch a
{
case 1:
print("Got 1")
case 2:
print("Got 2")
case 3, 4, 5:
print("Got 3 or 4 or 5")
case 6...22:
print("Got 6 to 22")
default:
print("Got Default")
}
//:As you can see above, the `switch` block is bounded by a set of `{}` braces. The value that you're "switching" from is listed after the reserved keyword `switch`. Each possible outcome is listed inside the braces as a `case`. A few notes about cases: values can be chained together (see line 39), values can be a range (every number between the lower and upper bound, see line 41), and Swift requires every `switch` block to include a `default` case (see line 43). This default is a catch-all so that no matter what value you switch off of, a case will be listed to cover that value, even if it is a default. Also of note: the value switched can be of any object type, a difference with some other languages that restrict the datatypes possible.
//:Bottom line: many different cases can be listed (and each case can have multiple lines of instructions), but at runtime, since the value of the switched variable or constant (in this example, `a`) will only be satisfied by one case, only one block of instructions will run. All other cases will be skipped.
//:## Looping
//:We've been so far talking about deciding which block of code to run based on certain runtime conditional values, but what if we wanted to run a block of code repeatedly for a certain number of times? Or run until certain conditions are met? For that I give you looping. Let's take a look at `for` loops first.
//:### `for`
//:These loops allow you to run a set of instructions a certain finite number of times. The most common way to bound a for loop is to provide it with a collection of data and have it iterate over each element in that collection. Thus if the collection has 10 items, the `for` loop will run its block 10 times.
//:As an example, let's imagine a game that has different scoring rules for individuals vs. teams. The team score is based the individual scores of each team member. When a team member scores more than 50 individual points, the team scores 3 points. If the individual score is 50 or less, the team only scores 1 point. Given a list of individual scores for a particular team, let's build a loop that will determine the overall team score.
let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores
{
if score > 50
{
teamScore += 3
} else
{
teamScore += 1
}
}
print(teamScore)
//:### `while`
//:`while` loops are used to perform an instruction or set of instructions until some condition is met. The loop runs an undefined number of times rather than a predefined number like with a `for` loop. Let's say we wanted to count to 100 by a factor of 5 each time. We could arrange a loop such that it will end after we reach 100. See below for an example:
var n = 0
while n <= 100
{
n += 5
print(n)
}
//:The above code block will print each number between 5 and 100, jumping by 5 each time. The block is evaluated as follows: line 64 evaluates to `true` or `false` depending on the value of `n`. As long as the value is less than 100, lines 66 and 67 are evaluated. The value of `n` is increased by 5 and then printed. Once line 68 is reached, the loop begins again, as long as `n` is still less than 100. At some point the value of `n` will be increased beyond 100, and when the loop begins again at that point, the conditional on line 64 will evaluate to `false`, thus ending the loop.
//:## Recap
//:Let's take a look at the concepts covered in this lesson:
//:* Different collection data types: arrays and dictionaries
//:* Controlling the flow of code with `if-else` and `switch` blocks
//:* Running the same block of code multiple times with loops: `for` and `while`
| true
|
f53ea3e0b7c4c99e33f22285206f2e0752720978
|
Swift
|
UMPUSTEN/AoC-2020
|
/Day4.swift
|
UTF-8
| 21,615
| 3.234375
| 3
|
[] |
no_license
|
//
// Day4.swift
// iOS
//
// Created by UMPUSTEN on 04.12.20.
//
import Foundation
let input = inputDay4.replacingOccurrences(of: "\\n{2,}", with: "*", options: .regularExpression).components(separatedBy: CharacterSet(charactersIn: "*")).map { $0.trimmingCharacters(in: .whitespacesAndNewlines).components(separatedBy: CharacterSet(charactersIn: "\n ")) }
enum RegEx: String {
case byr = "19[2-9]\\d|200[012]"
case iyr = "20(1\\d|20)"
case eyr = "20(2\\d|30)"
case hgt = "^((59|6\\d|7[0-6])in|1([5-8]\\d|9[0-3])cm)"
case hcl = "#[a-f0-9]{6}"
case ecl = "(amb|blu|brn|gry|grn|hzl|oth)"
case pid = "^\\d{9}$"
}
var count = 0
for passport in input {
if passport.count == 8 {
count += 1
} else if passport.count == 7 {
if passport.filter { !$0.contains("cid") }.count == 7 {
count += 1
}
}
}
print("*** Part 1: ", count)
func check(string: String, with regEx: RegEx) -> Bool {
guard let regex = try? NSRegularExpression(pattern: regEx.rawValue) else { return false }
let matches = regex.matches(in: string, options: [], range: NSRange(location: 0, length: string.utf16.count))
return !matches.isEmpty
}
var part2Counter = 0
for passport in input {
var isValid = true
if passport.count < 8 ,
passport.filter { !$0.contains("cid") }.count != 7 {
isValid = false
} else {
innerLoop: for field in passport {
let components = field.components(separatedBy: CharacterSet(charactersIn: ":"))
switch components[0] {
case "byr":
if !check(string: components[1], with: RegEx.byr) {
isValid = false
}
case "iyr":
if !check(string: components[1], with: RegEx.iyr) {
isValid = false
}
case "eyr":
if !check(string: components[1], with: RegEx.eyr) {
isValid = false
}
case "hgt":
if !check(string: components[1], with: RegEx.hgt) {
isValid = false
}
case "hcl":
if !check(string: components[1], with: RegEx.hcl) {
isValid = false
}
case "ecl":
if !check(string: components[1], with: RegEx.ecl) {
isValid = false
}
case "pid":
if !check(string: components[1], with: RegEx.pid) {
isValid = false
}
default:
break
}
if !isValid {
break innerLoop
}
}
}
if isValid {
part2Counter += 1
}
}
print("*** Part 2: ", part2Counter)
public let inputDay4 = """
byr:1971
ecl:hzl pid:112040163
eyr:2023 iyr:2019
hcl:#b6652a hgt:167cm
pid:108667812 eyr:2023 hcl:#623a2f hgt:171cm iyr:2018 ecl:amb byr:1993
hcl:#cfa07d iyr:2014 ecl:blu eyr:2023 cid:304 hgt:70in byr:1961
byr:1977
hcl:#b6652a
iyr:2017 ecl:oth pid:703877876 hgt:185cm
byr:1972
cid:271
iyr:2016 pid:876104259 hgt:173cm eyr:2028 ecl:brn hcl:#733820
hgt:174cm ecl:gry iyr:2014 eyr:2029 hcl:#c0946f
byr:1967 pid:406306240
hcl:#6b5442
iyr:2011
pid:040592028 eyr:2026
ecl:amb
byr:1923
pid:293598838 byr:1960 cid:87
iyr:2018
ecl:blu eyr:2029
hcl:#7d3b0c
hgt:62in
iyr:2018 cid:137
hcl:1c7db1 ecl:#38812e byr:2006 eyr:2038 pid:1239811353 hgt:84
hcl:#888785 pid:308480529
iyr:2010 byr:1988
eyr:2025 hgt:176cm ecl:amb
cid:79 ecl:lzr
iyr:2013 byr:1991 hcl:2f49ef
hgt:191cm
pid:378428551
iyr:2005
hgt:64in hcl:89c369
ecl:gry byr:1932
eyr:2029 pid:753055776
ecl:amb iyr:2017
byr:1969 hcl:#fffffd
pid:305746470
hgt:173cm
pid:081972188 iyr:2011
hcl:9bb154
eyr:2024 byr:1966 ecl:oth cid:185 hgt:171cm
pid:522553186 hgt:171cm ecl:grn hcl:#7d3b0c
byr:1955
eyr:2025 iyr:1999
iyr:2015
byr:1941 pid:140123640 ecl:amb hgt:153cm hcl:#ceb3a1 eyr:2020
ecl:grn
cid:202 hcl:#602927
eyr:2029
hgt:180cm byr:1974
pid:658341964
iyr:2017
pid:2037156813 eyr:1978 ecl:grn hcl:519b45 iyr:2011 byr:2017
hcl:#fffffd ecl:hzl
pid:658716289 byr:2001 hgt:154cm cid:234 eyr:2031 iyr:2010
byr:2013 pid:#eb519e eyr:2026
hgt:157cm iyr:2030 hcl:7e9d5a ecl:oth
byr:2002
ecl:brn iyr:1998 hgt:60cm
hcl:#7d3b0c pid:#90286d
eyr:1938
byr:1956 hcl:#efcc98
hgt:190cm
iyr:2010 eyr:2023
ecl:amb
cid:342 pid:278521396
hgt:67cm
cid:98 eyr:2036 byr:2028 ecl:grt hcl:08b5ad iyr:2029 pid:187cm
ecl:dne hcl:fca461 hgt:129 iyr:2020 eyr:2027 byr:2022 pid:5014208295
hgt:169cm ecl:gry iyr:2015 eyr:2025 hcl:#733820 pid:240085824 byr:1920
iyr:2020 eyr:2033
pid:#3f8e9d hgt:190in ecl:brn hcl:#efcc98 byr:2004
iyr:2018 hcl:#18171d ecl:brn byr:1933
pid:514517439 hgt:171cm eyr:2028
eyr:2030 pid:053251865
byr:2028 hgt:174cm iyr:2015 hcl:5a0da9 ecl:hzl
hgt:169cm iyr:2014 ecl:oth eyr:2029 pid:348737413 hcl:#b6652a byr:1997
hgt:181cm cid:315
eyr:2021 iyr:2016 byr:1966 ecl:oth pid:779435812 hcl:#733820
pid:5052579 cid:268 hgt:193in
hcl:z
iyr:1942 eyr:1977
eyr:2039 hgt:69cm cid:337
iyr:2023 pid:568948965
byr:2018 hcl:z ecl:amb
byr:2014 eyr:2028
cid:311
pid:158cm ecl:#946399 hgt:99
hcl:z
iyr:1978
pid:474742310 iyr:2015 eyr:2021 hcl:#14f5da
hgt:163cm ecl:oth
hcl:#efcc98
ecl:blu
hgt:178cm pid:815309025 byr:2024
iyr:2008 eyr:1922
byr:1946 eyr:2028 pid:364439229 iyr:2011 hgt:186cm cid:79 ecl:blu
eyr:2028 hgt:157cm
cid:59 iyr:2010 byr:1927
ecl:brn
pid:893074368
hcl:#18171d ecl:#2defe4 hgt:128 byr:1940
pid:181904523 iyr:2022 eyr:1937
eyr:2023 hgt:172cm iyr:2012 hcl:#a97842 ecl:hzl byr:1982 pid:638759541
cid:91 hcl:#623a2f
byr:1996 eyr:2028 pid:181384347 hgt:175cm
iyr:2020
iyr:2017 eyr:2021 ecl:gry
byr:1979 hgt:168cm hcl:#6b5442 pid:950995084
ecl:blu iyr:2012 byr:1972
hcl:#888785 eyr:2022 hgt:179cm pid:293827532
hgt:179cm
ecl:hzl iyr:2011
byr:1982 eyr:2020 hcl:#efcc98 cid:209 pid:626732917
byr:1989
hcl:#6b5442 pid:679850983 iyr:2020
hgt:192cm ecl:blu
pid:333485773 hgt:167in ecl:zzz iyr:1945
eyr:2035 cid:319 hcl:#341e13
hgt:64in
cid:202 eyr:2023 ecl:gry hcl:#c0946f pid:212611149 byr:1928 iyr:2010
hgt:183cm hcl:#e8fa30 ecl:oth eyr:2021
byr:1943 pid:667658434
iyr:2010
cid:117
byr:2022 hcl:z ecl:#c6ae1f iyr:2028
hgt:188cm
pid:0883366415
eyr:2030
hcl:z
pid:99347800 iyr:2030 eyr:2032 ecl:#cd1fd7 hgt:192cm byr:2019
hgt:178cm byr:2013
iyr:2026 hcl:ad3da1
eyr:2020 pid:1626818790
hgt:63cm
iyr:1964
eyr:2032
cid:135 byr:2017 hcl:#a97842 pid:#1b83f5 ecl:gmt
hcl:c352d2 byr:1927 ecl:gmt hgt:187cm
eyr:2031 pid:170cm
byr:2022 eyr:1958 ecl:zzz pid:3692521800 hcl:8b2b50 iyr:1946 hgt:155in
ecl:#43f305 hcl:z byr:2028
pid:63518738 cid:243 eyr:2037
hgt:67cm iyr:1929
ecl:brn hcl:#888785
pid:495215177 byr:1962 eyr:2021
cid:192
hgt:151cm iyr:2012
ecl:#dcca8e cid:64 eyr:2030 pid:380057616
hcl:z iyr:2026 byr:1962
hcl:z
ecl:hzl eyr:2027 byr:2015 pid:302526406 hgt:175cm iyr:2017
byr:1966
cid:133 pid:9953651821 ecl:gry iyr:2020 hgt:152cm
hcl:#fffffd eyr:2026
hgt:191cm byr:1960 pid:752655640 hcl:#888785
cid:249 ecl:blu
iyr:2012 eyr:2028
pid:#c8c988 eyr:2027 hgt:157in hcl:z iyr:2025 byr:2019 ecl:zzz cid:195
hgt:96 pid:95381813 iyr:1950
hcl:#fffffd eyr:2026
byr:2010 cid:318
ecl:#48a819
eyr:2020
ecl:oth byr:1951 pid:080392492
iyr:2015 hcl:#6b5442 hgt:176cm
hgt:162cm pid:897792747 byr:1968
hcl:#ceb3a1 ecl:grn eyr:2026 iyr:2014
eyr:2038 hcl:cc324a byr:1983 ecl:brn
hgt:161 pid:#adf47f cid:208
iyr:2013 ecl:blu hcl:#866857 byr:1981 hgt:157cm eyr:2025 pid:216910202
hgt:152in byr:1990
iyr:2027 hcl:a4a3ae
ecl:#058ae2 eyr:2037 pid:646420120
ecl:oth byr:1982 eyr:2027 hgt:65in iyr:2019
hcl:#efcc98 cid:224
pid:854228141
pid:772612093
iyr:2027
hgt:175in byr:1981 hcl:c0b5a9 ecl:utc
hcl:#888785 iyr:2014 byr:1975
ecl:blu
pid:461319017 cid:229 eyr:2030 hgt:154cm
hgt:179cm eyr:2024
pid:192cm
iyr:2017 ecl:grt byr:1934 hcl:z cid:92
hcl:9c9409 iyr:2020 eyr:2030 hgt:156in
cid:189 pid:732321495
byr:1937 ecl:xry
eyr:2026 pid:092259220 byr:1943
iyr:2010 hgt:153cm hcl:#602927
byr:1925 hgt:180cm hcl:#888785 iyr:2014
pid:402548656 eyr:2023 ecl:hzl
cid:188
eyr:2020 pid:874307939 hcl:#3f85a4
ecl:gry hgt:167cm byr:1959 iyr:2014
eyr:2026 hgt:183cm iyr:2011 byr:1940 ecl:blu pid:810026000
cid:226 hcl:#866857
cid:292 ecl:grt hgt:72cm
byr:2009
iyr:2000 eyr:1946 hcl:7be409 pid:996363336
eyr:2027
iyr:2021
pid:632405666
byr:2027
ecl:#d83a36 hcl:z hgt:190in
cid:80
hgt:173cm
pid:735853952 ecl:gry hcl:#fffffd eyr:2025 iyr:2020 byr:1923
byr:1977
hcl:#733820
iyr:2020 ecl:#698d72 hgt:186cm pid:678869986 cid:67
eyr:2021
hgt:61cm iyr:2022 eyr:1972 hcl:979bcf byr:2023 pid:44037388 ecl:xry
eyr:2032 pid:193cm hcl:z
hgt:68cm byr:2016
byr:2008 cid:239
hcl:ddc745 eyr:2033 ecl:#6858b5 hgt:64cm iyr:2023
pid:89867524
iyr:2016 hgt:74in hcl:#18171d
byr:1959
ecl:blu
pid:848487392
eyr:2027
hgt:165in ecl:grn
byr:1960 eyr:2029
iyr:2017
hcl:#b6652a pid:096349067
eyr:2025 ecl:brn
pid:634481064 iyr:2015
hcl:#7d3b0c
byr:1943
ecl:grn eyr:2021
pid:34753212 cid:51 hgt:184 iyr:1970 byr:2012
eyr:1973 iyr:2014 cid:225
byr:2028 ecl:gmt
hgt:158cm
pid:#74f9b8 hcl:f6932a
hgt:168cm
hcl:#602927
pid:622067991 ecl:amb eyr:2025 iyr:2018
pid:791399958 byr:1956 eyr:2027 hcl:#602927
ecl:brn
iyr:2016 hgt:192cm
hgt:168cm iyr:2015 cid:115 ecl:#3fa48b eyr:2037 hcl:#1bf77b byr:1980 pid:947370470
iyr:2008
byr:2021 ecl:zzz
hcl:z hgt:109 pid:#fc2a91 cid:268 eyr:1957
byr:2018 hcl:fef19c iyr:2014 ecl:blu eyr:2023 cid:259 pid:193cm hgt:156
hcl:#b6652a
iyr:2023 byr:2021 hgt:153cm pid:934391984 eyr:2021 ecl:brn
pid:168cm hcl:b13f1e eyr:2038 iyr:2020 ecl:#7c0a6d hgt:169in
ecl:amb cid:170
pid:300188824 eyr:2024 byr:1954 hcl:#b6652a hgt:166cm
iyr:2013
ecl:brn
eyr:2023
hcl:#b6652a byr:1948 hgt:71in iyr:2015
pid:575973478
eyr:2026 hgt:180cm hcl:#866857 ecl:grn iyr:2013
byr:1997 pid:864648034
ecl:hzl
iyr:2013 eyr:2024 hcl:#02e17f byr:1960
hgt:163cm cid:338 pid:972201795
iyr:1994 eyr:2035 ecl:xry
hcl:z hgt:167in pid:159cm
ecl:hzl
byr:1952
eyr:2024 hgt:191cm pid:229400637 iyr:2011 hcl:#122db6
eyr:2022
pid:467667316 iyr:2019 hcl:#623a2f
hgt:161cm
ecl:oth
ecl:hzl eyr:2030 hcl:#733820 byr:1944
hgt:193cm pid:819137596
cid:321 hgt:184in ecl:hzl iyr:2018 byr:2010 eyr:2020 pid:171cm
ecl:amb eyr:2025 hcl:#c0946f pid:360891963 byr:1925
iyr:2017
hgt:180cm
hcl:#cfa07d byr:1949
eyr:1931 cid:350
ecl:#ff9943
pid:7550350393 hgt:75
eyr:2026 ecl:amb hcl:z pid:746919391 iyr:2014 hgt:179cm byr:1997
pid:157cm iyr:2030
hgt:152cm
hcl:ce8aa7 eyr:1976 ecl:grt cid:160 byr:2011
eyr:2022
hgt:183cm
byr:2000 iyr:2016 hcl:#a97842 ecl:blu pid:500935725
cid:245 eyr:2026 iyr:2015 ecl:gry hcl:#cfa07d
byr:1946
eyr:2022 hgt:168cm
pid:786361311 iyr:2013 hcl:#c0946f byr:1988 cid:244 ecl:hzl
byr:2014 hgt:176in iyr:2021
hcl:z pid:6361650130
eyr:2039 cid:300
ecl:#76310d
ecl:amb hgt:170in byr:2013
iyr:2024 eyr:2033 hcl:#888785
eyr:2025
iyr:1957 cid:182
ecl:blu pid:253552114
hgt:188cm hcl:z
cid:83 ecl:amb
eyr:2022 byr:1947
iyr:2013 hcl:#cfa07d
hgt:188cm pid:447734900
iyr:2013 hcl:#602927 byr:1979 hgt:167cm cid:321 pid:978238277 eyr:2020
ecl:grn
hgt:73cm
cid:199 ecl:amb iyr:2019
hcl:#733820 eyr:2021
byr:1939 pid:364966395
hgt:168in ecl:lzr eyr:2031
pid:#ff10ac byr:2014 iyr:2006
hgt:164cm eyr:1994 iyr:2010
ecl:amb hcl:#7d3b0c cid:240 pid:191cm
byr:2025
ecl:grn
eyr:2029
hcl:#7d3b0c hgt:158cm
byr:1939 iyr:2012 pid:855145518
iyr:2013 hcl:#ceb3a1
hgt:163cm eyr:2023 pid:761215570
hgt:154cm ecl:grn
iyr:2019 byr:1981 eyr:2021 hcl:#602927
cid:80 pid:427938374
eyr:2026 hgt:154cm cid:102 iyr:2012 pid:6632346648 ecl:amb
byr:2010 hcl:z
cid:302 iyr:2014
pid:161cm eyr:2037 byr:2026 ecl:gry hgt:60 hcl:9fb9e0
ecl:brn iyr:2015 pid:041582949 cid:180 byr:1938
hgt:158cm
hcl:#602927 eyr:2026
ecl:xry pid:#546891 hcl:#18171d hgt:71cm byr:1974
iyr:2018 eyr:2026
iyr:2015 eyr:2025 ecl:brn hgt:180cm hcl:#b6652a
byr:1938
pid:752379523
iyr:2020 ecl:grn hgt:179cm byr:1929
cid:103 hcl:#602927
pid:212212232
pid:262917603 ecl:gry iyr:2012 hcl:#fffffd hgt:165cm eyr:2022 byr:1965
byr:1960
eyr:2031 hgt:184in
pid:#ac1606 iyr:2013 hcl:#888785
cid:260 ecl:#7b2c3b
byr:1987
eyr:2025 cid:102
hgt:74in ecl:brn hcl:#4a6c75 pid:20220733 iyr:2028
eyr:2031 pid:823539963
iyr:1957
hgt:159cm byr:1953 ecl:oth cid:186 hcl:26d85f
ecl:gry iyr:2011
hgt:167cm hcl:#fffffd pid:001642707 eyr:2030 byr:1952
iyr:2029 ecl:grt
hcl:z byr:2011 hgt:64cm pid:37027672
eyr:1923
pid:021102096
eyr:2024 hgt:66 hcl:#a97842 byr:1922 ecl:gry iyr:2013
pid:166477382 ecl:oth byr:1982 iyr:2010 eyr:2020
hcl:#866857 hgt:60in
hcl:#7d3b0c
iyr:2018 pid:065652921 byr:1939
ecl:blu
hgt:180cm eyr:2028
ecl:amb iyr:2020 byr:1967 hcl:#fffffd eyr:2028 hgt:157cm
eyr:2029 hgt:185cm cid:85 hcl:z iyr:2014 pid:#1f4787 ecl:grn byr:2010
byr:1987 hcl:d397d9 iyr:2028
hgt:158cm pid:686994921 ecl:hzl
ecl:oth
byr:2008
pid:#db73d9 hgt:174cm hcl:#6b5442 iyr:1955 eyr:2028
eyr:2020 ecl:amb pid:490866828 hcl:#cfa07d cid:113
hgt:165cm
iyr:2011
pid:320518492
eyr:2028 byr:1940 hgt:164cm cid:84
hcl:#341e13 ecl:grn
hgt:142
hcl:z pid:152cm iyr:1953 eyr:2040 ecl:#e44f11 byr:2024
ecl:gmt hcl:be7483 eyr:2027
iyr:2026
pid:396722617 hgt:153cm
ecl:dne byr:2015
pid:330208482
hcl:#7d3b0c iyr:2014 eyr:2022 hgt:95
byr:1925 hcl:#7d3b0c
ecl:gry
eyr:2024
pid:694714722 hgt:158cm iyr:2015 cid:283
eyr:2023
hgt:183cm cid:345
hcl:#6b5442 ecl:hzl iyr:2019 byr:1971 pid:458416257
ecl:#dcae8b
iyr:2027 eyr:1940 byr:2009 hcl:f024de pid:20713584
hgt:169in
hcl:#888785 eyr:2026
byr:1984 iyr:2013 pid:935837461
hgt:193cm
ecl:gry
pid:7343429 byr:2002
hgt:191cm
ecl:lzr iyr:1983
eyr:1966 hcl:#623a2f
cid:302
hcl:#888785 iyr:2014 hgt:173cm
byr:2002 pid:005350165 eyr:2022
byr:2013 iyr:2028
ecl:lzr pid:5426915565 eyr:2018 hcl:z hgt:70cm cid:142
eyr:2021 hgt:157cm ecl:utc iyr:2014
byr:1934 cid:348 hcl:#623a2f pid:607329117
iyr:2015 hgt:167cm ecl:hzl
pid:088516395 hcl:#efcc98 byr:1968 eyr:2029
eyr:2028
iyr:2019
cid:199
ecl:amb
hgt:152cm byr:1928 pid:547112666 hcl:#623a2f
pid:406202463
byr:1950 cid:214
eyr:2021 hcl:#fffffd hgt:177cm
ecl:brn
eyr:2029
cid:210 byr:1982 pid:578085789 ecl:brn
hgt:187cm iyr:2010 hcl:#c0946f
byr:1980 hcl:#c0946f hgt:159cm pid:177650318 eyr:2024 ecl:amb iyr:2019
pid:923359071 byr:1997 ecl:#faa530
eyr:2028 iyr:2013 hcl:e6c902 hgt:177cm
eyr:2040
cid:98 hgt:156in
ecl:oth
iyr:1996 pid:81500971
hcl:#6b5442
byr:2017
byr:2004 iyr:1941
hcl:e1e4bb hgt:67cm pid:1143915351 ecl:#0d3e5d eyr:1972
hgt:184cm hcl:#623a2f
eyr:2028 pid:680951513 ecl:grn iyr:2014 byr:2001
hcl:#866857 hgt:156cm
eyr:2020
ecl:grn iyr:2010 pid:589945116
pid:599795227 iyr:2016 ecl:grn
hcl:#cfa07d hgt:157cm byr:1967 eyr:2029
hcl:#b6652a
byr:1966 iyr:2017 pid:117232314 ecl:oth hgt:186cm eyr:2029
pid:605019880
iyr:2020
hgt:169cm byr:1980 hcl:#623a2f
ecl:hzl eyr:2030
eyr:2019 hcl:#ceb3a1 pid:988269284
iyr:2015 byr:1989 hgt:171cm ecl:oth
cid:311 byr:1998 ecl:hzl
eyr:2027 hgt:152cm pid:734870801 hcl:#7d3b0c
iyr:2013
hcl:#efcc98
hgt:180cm iyr:2020
pid:202682423 byr:2027 ecl:grn eyr:2030
hcl:f0701f pid:161cm cid:291 hgt:160in iyr:2030
ecl:#e12345
cid:248 byr:1943 eyr:2024 hgt:181cm ecl:brn iyr:2010 hcl:#bf813e
byr:2005 hgt:187in eyr:2034 iyr:2025 hcl:z ecl:gmt
pid:78691465
byr:2000
hcl:#574f4e eyr:2024 iyr:2017 pid:#fec795 hgt:185cm ecl:gry
hcl:#a97842 byr:1959
iyr:2019 pid:690444949
hgt:160in eyr:1978
cid:236
iyr:2010 eyr:2025 byr:1976 pid:398376853
hcl:#341e13
hgt:150cm
hgt:182cm iyr:2019 hcl:#866857
ecl:grn
byr:1926 eyr:2029 pid:307880154 cid:94
ecl:blu
hgt:182cm pid:178cm byr:2019 eyr:2025
iyr:2022 hcl:#a2117d
eyr:2020 hcl:#c0946f ecl:amb pid:135511825 byr:1954 hgt:68in iyr:2017
hgt:188cm ecl:amb iyr:2011
pid:949021029 eyr:2028 hcl:#fffffd byr:1986
iyr:1949 pid:#8a8d94 ecl:#922a92 byr:1925 hcl:#63c4a5
hcl:#c0946f
ecl:grn iyr:2013 eyr:2024 pid:420295283 hgt:181cm
byr:1977
byr:1941 pid:299186098 hcl:#f1fa72
iyr:2013 ecl:amb eyr:2022 hgt:152cm
cid:150
ecl:blu eyr:2021 hgt:60in hcl:#623a2f
byr:1930 iyr:2018
eyr:2028 pid:663108638
hgt:75in cid:217
byr:1962 ecl:brn hcl:#733820
hcl:#341e13 hgt:188cm ecl:blu
pid:868930517
eyr:2029
iyr:2010 byr:1938
pid:194376910 byr:1956
hcl:#cd4ab4
eyr:1940 iyr:2012 ecl:#396cc3
pid:#c5da2a hgt:162cm
hcl:#866857
cid:95 ecl:#fa1f85
iyr:1965 byr:1963 eyr:2039
pid:44063430 hcl:289b20
ecl:#77ddd9 eyr:1953
iyr:1924 byr:2026 cid:267 hgt:180in
ecl:brn pid:990171473
eyr:2028 byr:1937
hgt:165cm iyr:2015
hcl:#fffffd cid:68
iyr:1968 ecl:lzr pid:#05a4ab eyr:1944 hcl:z
hgt:185cm hcl:#7d3b0c eyr:2029 ecl:oth
iyr:2016 byr:1997 pid:349316183
hcl:z
ecl:gry
hgt:192in pid:542996841 iyr:2019 cid:144 eyr:2028
byr:2026
eyr:2024
hcl:#18171d
ecl:grn hgt:160cm pid:399767457 byr:1979 iyr:2015
ecl:#924147 pid:665314 cid:216 iyr:2026 hcl:z
byr:2023 hgt:157
eyr:1987
eyr:1989 hcl:4f8779 ecl:#05ff52 iyr:1943 pid:3693010880 hgt:72cm
byr:2009
hcl:#c0946f eyr:2022
iyr:2015 hgt:157cm byr:1928 ecl:grn pid:243566446
eyr:2030
hcl:#733820 byr:1988 iyr:2017 cid:125 hgt:193cm ecl:amb pid:939550667
cid:161 hgt:157in
hcl:#cfa07d eyr:2036 ecl:#4efa35
iyr:2012 pid:3943280550 byr:1979
ecl:lzr hcl:#341e13 hgt:69cm eyr:2026 cid:322 byr:2006 pid:827964469
ecl:amb iyr:2012
eyr:2020 hgt:178cm pid:590705772 cid:218
hcl:#c0946f byr:1922
hcl:632b01 cid:252 byr:1933 ecl:hzl
iyr:2025 eyr:2040 hgt:191cm
pid:406010613
pid:711656819 ecl:blu eyr:2030 hgt:151cm
byr:1999 cid:319
hcl:#efcc98
pid:294223216 iyr:2012
hgt:171cm
eyr:2027
hcl:#ceb3a1 ecl:oth
byr:1952 cid:58
hcl:#888785 pid:457433756 eyr:2022 hgt:186cm
cid:336
byr:1923 iyr:2013 ecl:oth
byr:2014 hcl:6ce7d6 eyr:2030 pid:190cm iyr:2018 hgt:63cm ecl:#5063b9
cid:267 hgt:189cm
eyr:2020 hcl:#ffeffd iyr:2014 byr:1989
ecl:grn
pid:571696542
iyr:1953 hgt:160in
ecl:grt cid:188 eyr:2034
pid:179cm byr:2007
hcl:6895eb
hgt:165cm ecl:oth
iyr:2020
eyr:2028
hcl:#18171d pid:111506895
eyr:1957 cid:133 ecl:hzl pid:#e56ca2 byr:2003 hcl:8a9d65
hcl:6c4ecd byr:1930 hgt:179cm
eyr:2007 iyr:2028 ecl:#3d8705
pid:#dbfeec
eyr:2036
byr:1991 ecl:#2202d0 hcl:#341e13 pid:85636989 hgt:61cm
iyr:1930
byr:1996 iyr:2027 hcl:z
pid:780164868 ecl:zzz eyr:2026 hgt:73cm
byr:1940
iyr:1992 pid:132016954 eyr:2021
cid:147 hcl:#d78bfd ecl:xry
hgt:174cm
byr:1970
eyr:2021 hcl:#341e13 pid:086579106 iyr:2017 ecl:oth
ecl:oth cid:207 byr:1998 pid:479696359
hgt:174cm iyr:2017 eyr:2020 hcl:#6b5442
ecl:hzl iyr:2014
hcl:#cfa07d hgt:163cm eyr:2025
byr:1951 pid:563337128
ecl:gry hgt:172cm iyr:2013 hcl:#efcc98
byr:1970
pid:848996674
eyr:2027
hgt:163cm pid:583600660 iyr:2015 hcl:#18171d byr:1959 ecl:brn
hcl:#efcc98 pid:353178375 cid:145
iyr:2018 byr:1988 ecl:oth eyr:2029
hgt:62in
byr:1921 pid:125944934 hcl:#b6652a
eyr:2025 cid:71 iyr:2018 ecl:blu
iyr:2017 ecl:brn hcl:#602927 hgt:172cm pid:932690969 byr:1957 eyr:2026
hcl:#efcc98 pid:709772213 cid:146 ecl:oth byr:1998 iyr:2010 hgt:74in
eyr:2029
byr:1965
iyr:2011 hcl:#6b5442 cid:325 hgt:68in eyr:2028 pid:813272708 ecl:hzl
pid:57223084 hcl:#602927 ecl:grn
hgt:156cm eyr:1972 iyr:2017
pid:21573000 byr:2030 cid:168
hcl:baee61 eyr:2021 hgt:150cm
iyr:1950 ecl:#acdd7e
ecl:gry hgt:150cm hcl:#6b5442
byr:1927
iyr:2018 pid:161cm eyr:2021
hgt:153cm
iyr:2030 ecl:grn pid:575037626 byr:1921 eyr:2021 hcl:#866857
hgt:175cm iyr:2014
byr:1946 eyr:2025
cid:159 hcl:#18171d
ecl:oth pid:129913905
pid:566885568
hgt:157cm eyr:2021 ecl:gry byr:1933
hcl:#623a2f cid:223
ecl:blu byr:1981 cid:160
iyr:2014
hcl:#a97842 eyr:2021 hgt:172cm pid:714902414
hcl:#b6652a eyr:2021
hgt:168cm byr:1921 iyr:2018 ecl:oth pid:021318713
hgt:168 pid:222439573
cid:209
hcl:z byr:2016 ecl:#26a0fb
eyr:2031
hgt:181cm
byr:1970 eyr:2024
pid:476171876 ecl:hzl
hcl:#efcc98
iyr:2019
hcl:#18171d ecl:oth iyr:2018 byr:1949 hgt:165cm
eyr:2029 pid:078204562
byr:2021 ecl:blu iyr:1963
pid:2911597977 hcl:#ceb3a1 eyr:2020
hgt:154cm
pid:159642237
hcl:#81e94d ecl:gry eyr:2028 byr:1958
hgt:90 hcl:#a97842 pid:#db1158
iyr:1928 ecl:#c82a43 byr:1971 eyr:2036
eyr:2020
hgt:177cm iyr:2013
cid:347 ecl:grn
byr:1998 pid:455369144
byr:1936
pid:444305229 iyr:2013 eyr:2025 hcl:#733820
ecl:gry
hgt:175cm
byr:2027 hcl:z
hgt:61cm ecl:brn pid:836686228 eyr:2023 iyr:2030
byr:1931
ecl:hzl hgt:168cm eyr:2023 pid:956562488 hcl:#fffffd
ecl:#4126e5 pid:182cm iyr:2021
hgt:144 eyr:2039 hcl:z
pid:321400085 hcl:#733820 hgt:189cm
ecl:hzl byr:1923 eyr:2023 iyr:2016
iyr:2011 hgt:192cm hcl:#b6652a byr:1988 pid:998875769
ecl:#e612d9 eyr:2015
eyr:2021 iyr:2011 pid:265966660
byr:1934 hgt:180cm
hcl:#7d3b0c
ecl:gry cid:225
pid:550612542 ecl:oth byr:1931
iyr:2014 cid:99
hcl:#cfa07d hgt:163cm eyr:2026
ecl:gry hgt:156cm iyr:2018 hcl:#5d9d64 pid:295386055 byr:1996
eyr:2025
ecl:gry iyr:2013 pid:855457285 cid:309 eyr:2030
hcl:#733820 byr:1973
eyr:2030 pid:86472746 ecl:blu
hgt:192cm
iyr:2013 byr:1939 hcl:#b6652a
hcl:#888785
byr:1935
iyr:2018
hgt:155cm ecl:grn
pid:612879095 cid:108 eyr:2027
eyr:2016 hcl:z pid:025915371 iyr:2010 hgt:183cm ecl:gry
byr:2010
cid:228
hcl:#38dbf4
byr:1925 ecl:amb eyr:2020 pid:065102805 iyr:2018
cid:244 hgt:171cm
hcl:#cfa07d pid:466737179 eyr:2025
byr:1937 iyr:2020 ecl:oth
ecl:brn byr:1993 hgt:179cm hcl:#341e13 pid:855375268 eyr:2028
iyr:2018
pid:809135189 iyr:2020 hgt:162cm eyr:2027
hcl:#888785 byr:1988 ecl:grn
byr:2003 pid:4446708453
hgt:188cm iyr:2013 hcl:#888785 ecl:blu eyr:2008
hgt:165in ecl:#db642f iyr:2014
eyr:2020
byr:1955 hcl:371f72 pid:756089060
ecl:lzr
hgt:177in eyr:2037 pid:175cm
byr:2023 hcl:03b398 iyr:2026
iyr:2017 ecl:blu byr:1942 hcl:#733820 eyr:2023 hgt:151cm pid:289923625
"""
| true
|
666442a6586578286cd2ab19f3260cf804172a2b
|
Swift
|
windadwiastini/goOSC-iOS
|
/goOSC/Guest View/Balance Histories/Inspector/BalanceHistoryInspectore.swift
|
UTF-8
| 1,316
| 2.578125
| 3
|
[] |
no_license
|
//
// BalanceHistoryInspectore.swift
// goOSC
//
// Created by Bootcamp on 28/06/19.
// Copyright © 2019 Swift Bootcamp. All rights reserved.
//
import Foundation
import Alamofire
class BalanceHistoryInspector: BalanceHistoryInputInteractorProtocol{
var presenter: BalanceHistoryOutputInteractorProtocol?
let token = Auth().token
func findAllBalance() {
let url = "\(Config().url)/dashboard/user/balancehistory"
let header: HTTPHeaders = [
"Authorization": "Bearer \(token)"
]
Alamofire.request(url, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: header).responseJSON { (response) in
switch response.response?.statusCode {
case 401?:
self.presenter?.signout()
case 200?:
do {
if let dataResponse = response.data {
let jsonDecode = try JSONDecoder().decode(BalancdHistory.Response.self, from: dataResponse)
self.presenter?.response(response: jsonDecode)
}
} catch {
print("the response can not be decoded")
}
case 500?, .none, .some(_):
print("error")
}
}
}
}
| true
|
61d0761e21318aedfc2197da96c4924620632a5b
|
Swift
|
hnovais95/iOS-Dev
|
/SuperSenha/SuperSenha/Helper/Characters.swift
|
UTF-8
| 1,666
| 3.5
| 4
|
[] |
no_license
|
//
// Characters.swift
// SuperSenha
//
// Created by Heitor Novais | Gerencianet on 06/05/21.
//
import Foundation
class Characters {
static func getCharacters(startCode: UInt32, endCode: UInt32) -> [Character]? {
var characters = [Character]()
for code in startCode...endCode {
if let char = Unicode.Scalar(code) {
characters.append(Character(char))
}
}
return characters
}
static func getCharacters(startChar: String, endChar: String) -> [Character]? {
guard let startChar = Unicode.Scalar(startChar) else { return nil }
guard let endChar = Unicode.Scalar(endChar) else { return nil }
return getCharacters(startCode: startChar.value, endCode: endChar.value)
}
static func getSmallLetters() -> [Character] {
return getCharacters(startChar: "a", endChar: "z")!
}
static func getCapitalLetters() -> [Character] {
return getCharacters(startChar: "A", endChar: "Z")!
}
static func getDigits() -> [Int] {
let digitsCharacters = getCharacters(startChar: "0", endChar: "9")!
return Array(digitsCharacters).map({ String($0) }).map({ Int($0)! })
}
static func getSpecialCharacters() -> [Character] {
var specialCharacters = getCharacters(startCode: 32, endCode: 47)!
specialCharacters.append(contentsOf: getCharacters(startCode: 58, endCode: 64)!)
specialCharacters.append(contentsOf: getCharacters(startCode: 91, endCode: 96)!)
specialCharacters.append(contentsOf: getCharacters(startCode: 123, endCode: 126)!)
return specialCharacters
}
}
| true
|
ac60d56626954a42e2225b7a3fe24750703881f7
|
Swift
|
SalmonRanjay/DiseaseControlSwift
|
/DiseaseControl/HackathonWebService.swift
|
UTF-8
| 2,462
| 2.9375
| 3
|
[] |
no_license
|
//
// BeHappyWebService.swift
// Be-Happy
//
// Created by ranjay on 9/12/15.
// Copyright (c) 2015 Ranjay Salmon. All rights reserved.
//
import Foundation
class HackathonWebService{
//let forecastAPIKey : String;
let baseUrl: NSURL?;
let endPoint: String;
init (route: String){
//self.forecastAPIKey = APIKey;
baseUrl = NSURL(string: "http://hthon-test-app.mybluemix.net/");
endPoint = route;
}
// method use to get forecast data
func getData( completion: (WebServiceData? -> Void)){
// appending extra fields to the url
if let forecastURL = NSURL(string: endPoint, relativeToURL: baseUrl)?.absoluteURL{
println("url: \(forecastURL)");
//http://localhost:9000/api/v1/content/getPosts
// create instance of the network operation calss and initilaize it with the url needed
let networkOperation = NetworkOperations(url: forecastURL);
networkOperation.downloadJSONFromURL{
(let JSONDictionary) in
// do something
let valueArray: AnyObject = (JSONDictionary?["tweets"] as? [AnyObject])!;
//println(valueArray[0]);
//println(JSONDictionary?["results"]);
let results = self.currentDataFromJSON(JSONDictionary);
completion(results);
}
}else{
println("could not construct a valid url");
}
};
func currentDataFromJSON(jsonDictionary: [String: AnyObject]?) ->WebServiceData?{
// check that dictionary returns non nil value for result returned from API
if let dataReturned: AnyObject = jsonDictionary?["tweets"] as? [AnyObject]{
return WebServiceData(resultsArray: dataReturned as! [AnyObject]);
}else{
println("JSON dictionary returned nil for curcntly key");
return nil;
}
};
}
| true
|
4283ab7c6b71fd5508cd2cdeb932b1e75e428e22
|
Swift
|
c4arl0s/SwiftFiles412
|
/computedProperties/computedProperties.swift
|
UTF-8
| 726
| 4.1875
| 4
|
[] |
no_license
|
#!/usr/bin/swift
// Different from stored properties, computed properties are built with a getter and a setter, performing necessary code when accessed and set. Computed properties must define a type:
var pi = 3.14
class Circulo {
var radio = 0.0
var circunferencia: Double {
get {return pi * radio * 2}
set {radio = nuevoValor / pi / 2}
}
}
let circulo = Circulo() // crea un objeto
circulo.radius = 1 // set igual 1 el radio
print(circulo.circunferencia) // Prints "6.28"
circulo.circunferencia = 14 // si le asigno un valor a la circunferencia, la clase calcula el valor del radio, con set: WOOOOOOOOOOW!!!!
print(circulo.radio) // Prints "2.229..."
| true
|
92fcbdef588338241bf0609eb01d937012bac025
|
Swift
|
foxness/phantom
|
/Phantom/Presenter/SettingsPresenter.swift
|
UTF-8
| 13,457
| 2.5625
| 3
|
[] |
no_license
|
//
// SettingsPresenter.swift
// Phantom
//
// Created by River on 2021/06/11.
// Copyright © 2021 Rivershy. All rights reserved.
//
import Foundation
class SettingsPresenter {
// MARK: - Properties
private weak var viewDelegate: SettingsViewDelegate?
weak var delegate: SettingsDelegate?
private let database: Database = .instance // todo: make them services? implement dip
private var sections: [SettingsSection] = []
// MARK: - View delegate
func attachView(_ viewDelegate: SettingsViewDelegate) {
self.viewDelegate = viewDelegate
}
func detachView() {
viewDelegate = nil
}
// MARK: - Public methods
func viewDidLoad() {
updateSettings()
}
private func updateSettings() {
sections = getSettingsSections()
}
// MARK: - Settings option data source
func getOption(section: Int, at index: Int) -> SettingsOptionType {
return sections[section].options[index]
}
func getOptionCount(section: Int) -> Int {
return sections[section].options.count
}
func getSectionTitle(section: Int) -> String {
return sections[section].title
}
func getSectionFooterText(section: Int) -> String? {
return sections[section].footerText
}
func getSectionCount() -> Int {
return sections.count
}
func isSelectableOption(section: Int, at index: Int) -> Bool { // selectable means triggering didSelectOption
let option = sections[section].options[index]
switch option {
case .staticOption, .textOption: return true
case .accountOption(let accountOption): return !accountOption.signedIn
case .switchOption, .timeOption: return false
}
}
func didSelectOption(section: Int, at index: Int) {
let option = sections[section].options[index]
switch option {
case .staticOption(let staticOption):
staticOption.handler?()
case .accountOption(let accountOption):
guard !accountOption.signedIn else { break }
accountOption.signInHandler?()
case .textOption(let textOption):
textOption.handler?()
default:
fatalError("This option should not be able to be selected")
}
}
// MARK: - Cell update methods // todo: unhardcode this
private func updateRedditAccountCell() {
viewDelegate?.reloadSettingCell(section: 0, at: 0)
}
private func updateImgurAccountCell() {
viewDelegate?.reloadSettingCell(section: 1, at: 0)
}
private func updateUseImgurCell() {
viewDelegate?.reloadSettingCell(section: 1, at: 1)
}
private func updateBulkAddSubredditCell() {
viewDelegate?.reloadSettingCell(section: 3, at: 0)
}
private func updateImgurCells() {
updateImgurAccountCell()
updateUseImgurCell()
}
// MARK: - Receiver methods
func redditSignedIn(_ reddit: Reddit) {
database.redditAuth = reddit.auth
updateSettings()
updateRedditAccountCell()
delegate?.redditAccountChanged(reddit)
}
func imgurSignedIn(_ imgur: Imgur) {
database.imgurAuth = imgur.auth
database.useImgur = true
updateSettings()
updateImgurCells()
delegate?.imgurAccountChanged(imgur)
}
func bulkAddSubredditSet(_ subreddit: String?) {
guard let subreddit = subreddit else { return }
let trimmed = subreddit.trim()
if trimmed.isEmpty {
database.resetBulkAddSubreddit()
} else {
guard Post.isValidSubreddit(trimmed) else {
viewDelegate?.showInvalidSubredditAlert { [self] in
viewDelegate?.showBulkAddSubredditAlert(subreddit: database.bulkAddSubreddit)
}
return
}
database.bulkAddSubreddit = trimmed
}
updateSettings()
updateBulkAddSubredditCell()
}
// MARK: - User interaction methods
private func redditSignOutPressed() {
database.redditAuth = nil
updateSettings()
updateRedditAccountCell()
delegate?.redditAccountChanged(nil)
}
private func imgurSignOutPressed() {
database.imgurAuth = nil
database.useImgur = false
updateSettings()
updateImgurCells()
delegate?.imgurAccountChanged(nil)
}
private func redditSignInPressed() {
viewDelegate?.segueToRedditSignIn()
}
private func imgurSignInPressed() {
viewDelegate?.segueToImgurSignIn()
}
// MARK: - Settings sections
private func getSettingsSections() -> [SettingsSection] {
let redditSectionTitle = "Reddit"
let imgurSectionTitle = "Imgur"
let wallpaperModeSectionTitle = "Wallpaper Mode"
let wallpaperModeFooterText = "Wallpaper Mode adds image resolution to the post title."
let bulkAddSectionTitle = "Bulk Add"
let aboutSectionTitle = ""
var sections: [SettingsSection] = []
// Reddit section -------------------------------------------------
let redditOptions = [
getRedditAccountOption(),
getSendRepliesOption()
]
let redditSection = SettingsSection(title: redditSectionTitle,
footerText: nil,
options: redditOptions)
sections.append(redditSection)
// Imgur section --------------------------------------------------
let imgurOptions = [
getImgurAccountOption(),
getUseImgurOption()
]
let imgurSection = SettingsSection(title: imgurSectionTitle,
footerText: nil,
options: imgurOptions)
sections.append(imgurSection)
// Wallpaper Mode section -----------------------------------------
let wallpaperModeOptions = [
getWallpaperModeOption(),
getUseWallhavenOption()
]
let wallpaperModeSection = SettingsSection(title: wallpaperModeSectionTitle,
footerText: wallpaperModeFooterText,
options: wallpaperModeOptions)
sections.append(wallpaperModeSection)
// Bulk Add section -----------------------------------------------
let bulkAddOptions = [
getBulkAddSubredditOption(),
getBulkAddTimeOption()
]
let bulkAddSection = SettingsSection(title: bulkAddSectionTitle,
footerText: nil,
options: bulkAddOptions)
sections.append(bulkAddSection)
// About section --------------------------------------------------
let aboutOptions = [
getAboutOption()
]
let aboutSection = SettingsSection(title: aboutSectionTitle,
footerText: nil,
options: aboutOptions)
sections.append(aboutSection)
// ----------------------------------------------------------------
return sections
}
// MARK: - General section
private func getRedditAccountOption() -> SettingsOptionType {
let accountType = "Reddit Account"
let signInPrompt = "Add Reddit Account"
var accountName: String? = nil
var signedIn = false
if let redditAuth = database.redditAuth {
accountName = "/u/\(redditAuth.username)"
signedIn = true
}
let signInHandler = { self.redditSignInPressed() }
let signOutHandler = { self.redditSignOutPressed() }
let option = AccountSettingsOption(
accountType: accountType,
accountName: accountName,
signedIn: signedIn,
signInPrompt: signInPrompt,
signInHandler: signInHandler,
signOutHandler: signOutHandler
)
let optionType = SettingsOptionType.accountOption(option: option)
return optionType
}
private func getSendRepliesOption() -> SettingsOptionType {
let title = "Send replies to my inbox"
let sendReplies = database.sendReplies
let handler = { [self] (isOn: Bool) in
database.sendReplies = isOn
updateSettings()
}
let option = SwitchSettingsOption(title: title, isOn: sendReplies, handler: handler)
let optionType = SettingsOptionType.switchOption(option: option)
return optionType
}
// MARK: - Imgur section
private func getImgurAccountOption() -> SettingsOptionType {
let accountType = "Imgur Account"
let signInPrompt = "Add Imgur Account"
var accountName: String? = nil
var signedIn = false
if let imgurAuth = database.imgurAuth {
accountName = imgurAuth.username
signedIn = true
}
let signInHandler = { self.imgurSignInPressed() }
let signOutHandler = { self.imgurSignOutPressed() }
let option = AccountSettingsOption(
accountType: accountType,
accountName: accountName,
signedIn: signedIn,
signInPrompt: signInPrompt,
signInHandler: signInHandler,
signOutHandler: signOutHandler
)
let optionType = SettingsOptionType.accountOption(option: option)
return optionType
}
private func getUseImgurOption() -> SettingsOptionType {
let title = "Upload image links to Imgur"
let useImgur = database.useImgur
let isEnabled = database.imgurAuth != nil
let handler = { [self] (isOn: Bool) in
database.useImgur = isOn
updateSettings()
}
let option = SwitchSettingsOption(title: title, isOn: useImgur, handler: handler, isEnabled: isEnabled)
let optionType = SettingsOptionType.switchOption(option: option)
return optionType
}
// MARK: - Wallpaper Mode section
private func getWallpaperModeOption() -> SettingsOptionType {
let title = "Wallpaper Mode"
let wallpaperMode = database.wallpaperMode
let handler = { [self] (isOn: Bool) in
database.wallpaperMode = isOn
updateSettings()
}
let option = SwitchSettingsOption(title: title, isOn: wallpaperMode, handler: handler)
let optionType = SettingsOptionType.switchOption(option: option)
return optionType
}
private func getUseWallhavenOption() -> SettingsOptionType {
let title = "Convert Wallhaven links into image links"
let useWallhaven = database.useWallhaven
let handler = { [self] (isOn: Bool) in
database.useWallhaven = isOn
updateSettings()
}
let option = SwitchSettingsOption(title: title, isOn: useWallhaven, handler: handler)
let optionType = SettingsOptionType.switchOption(option: option)
return optionType
}
// MARK: - Bulk Add section
private func getBulkAddSubredditOption() -> SettingsOptionType {
let subreddit = database.bulkAddSubreddit
let title = "Subreddit"
let text = "/r/\(subreddit)"
let handler = { [self] () -> Void in
viewDelegate?.showBulkAddSubredditAlert(subreddit: subreddit)
}
let option = TextSettingsOption(title: title, text: text, handler: handler)
let optionType = SettingsOptionType.textOption(option: option)
return optionType
}
private func getBulkAddTimeOption() -> SettingsOptionType {
let timeOfDay = database.bulkAddTime
let title = "Time of day"
let handler = { [self] (newTime: TimeInterval) -> Void in
database.bulkAddTime = newTime
updateSettings()
}
let option = TimeSettingsOption(title: title, timeOfDay: timeOfDay, handler: handler)
let optionType = SettingsOptionType.timeOption(option: option)
return optionType
}
// MARK: - About section
private func getAboutOption() -> SettingsOptionType {
let title = "About"
let handler = { [self] () -> Void in
viewDelegate?.segueToAbout()
}
let option = StaticSettingsOption(title: title, handler: handler)
let optionType = SettingsOptionType.staticOption(option: option)
return optionType
}
}
| true
|
20aeae708c26593fb73ea2b0c7bfdd0d1a291b08
|
Swift
|
foxostro/TurtleTTL
|
/TurtleTools/SnapCore/SnapLexer.swift
|
UTF-8
| 9,770
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
//
// SnapLexer.swift
// Snap
//
// Created by Andrew Fox on 5/17/20.
// Copyright © 2020 Andrew Fox. All rights reserved.
//
import TurtleCompilerToolbox
import TurtleCore
public class SnapLexer: Lexer {
public required init(_ string: String, _ url: URL? = nil) {
super.init(string, url)
self.rules = [
Rule(pattern: "\n") {
return TokenNewline(sourceAnchor: $0)
},
Rule(pattern: "((#)|(//))") {[weak self] _ in
self!.advanceToNewline()
return nil
},
Rule(pattern: "\\.\\.") {
TokenDoubleDot(sourceAnchor: $0)
},
Rule(pattern: "\\.") {
TokenDot(sourceAnchor: $0)
},
Rule(pattern: ",") {
TokenComma(sourceAnchor: $0)
},
Rule(pattern: ":") {
TokenColon(sourceAnchor: $0)
},
Rule(pattern: ";") {
TokenSemicolon(sourceAnchor: $0)
},
Rule(pattern: "->") {
TokenArrow(sourceAnchor: $0)
},
Rule(pattern: "==") {
TokenOperator(sourceAnchor: $0, op: .eq)
},
Rule(pattern: "!=") {
TokenOperator(sourceAnchor: $0, op: .ne)
},
Rule(pattern: "!") {
TokenOperator(sourceAnchor: $0, op: .bang)
},
Rule(pattern: "<=") {
TokenOperator(sourceAnchor: $0, op: .le)
},
Rule(pattern: ">=") {
TokenOperator(sourceAnchor: $0, op: .ge)
},
Rule(pattern: "<<") {
TokenOperator(sourceAnchor: $0, op: .leftDoubleAngle)
},
Rule(pattern: "<") {
TokenOperator(sourceAnchor: $0, op: .lt)
},
Rule(pattern: ">>") {
TokenOperator(sourceAnchor: $0, op: .rightDoubleAngle)
},
Rule(pattern: ">") {
TokenOperator(sourceAnchor: $0, op: .gt)
},
Rule(pattern: "=") {
TokenEqual(sourceAnchor: $0)
},
Rule(pattern: "\\+") {
TokenOperator(sourceAnchor: $0, op: .plus)
},
Rule(pattern: "-") {
TokenOperator(sourceAnchor: $0, op: .minus)
},
Rule(pattern: "\\*") {
TokenOperator(sourceAnchor: $0, op: .star)
},
Rule(pattern: "/") {
TokenOperator(sourceAnchor: $0, op: .divide)
},
Rule(pattern: "%") {
TokenOperator(sourceAnchor: $0, op: .modulus)
},
Rule(pattern: "&&") {
TokenOperator(sourceAnchor: $0, op: .doubleAmpersand)
},
Rule(pattern: "&") {
TokenOperator(sourceAnchor: $0, op: .ampersand)
},
Rule(pattern: "\\|\\|") {
TokenOperator(sourceAnchor: $0, op: .doublePipe)
},
Rule(pattern: "\\|") {
TokenOperator(sourceAnchor: $0, op: .pipe)
},
Rule(pattern: "\\^") {
TokenOperator(sourceAnchor: $0, op: .caret)
},
Rule(pattern: "~") {
TokenOperator(sourceAnchor: $0, op: .tilde)
},
Rule(pattern: "bitcastAs\\b") {
TokenBitcastAs(sourceAnchor: $0)
},
Rule(pattern: "as\\b") {
TokenAs(sourceAnchor: $0)
},
Rule(pattern: "\\(") {
TokenParenLeft(sourceAnchor: $0)
},
Rule(pattern: "\\)") {
TokenParenRight(sourceAnchor: $0)
},
Rule(pattern: "\\{") {
TokenCurlyLeft(sourceAnchor: $0)
},
Rule(pattern: "\\}") {
TokenCurlyRight(sourceAnchor: $0)
},
Rule(pattern: "\\[") {
TokenSquareBracketLeft(sourceAnchor: $0)
},
Rule(pattern: "\\]") {
TokenSquareBracketRight(sourceAnchor: $0)
},
Rule(pattern: "_(?![a-zA-Z0-9_])") {
TokenUnderscore(sourceAnchor: $0)
},
Rule(pattern: "typealias\\b") {
TokenTypealias(sourceAnchor: $0)
},
Rule(pattern: "let\\b") {
TokenLet(sourceAnchor: $0)
},
Rule(pattern: "return\\b") {
TokenReturn(sourceAnchor: $0)
},
Rule(pattern: "var\\b") {
TokenVar(sourceAnchor: $0)
},
Rule(pattern: "if\\b") {
TokenIf(sourceAnchor: $0)
},
Rule(pattern: "else\\b") {
TokenElse(sourceAnchor: $0)
},
Rule(pattern: "while\\b") {
TokenWhile(sourceAnchor: $0)
},
Rule(pattern: "for\\b") {
TokenFor(sourceAnchor: $0)
},
Rule(pattern: "in\\b") {
TokenIn(sourceAnchor: $0)
},
Rule(pattern: "static\\b") {
TokenStatic(sourceAnchor: $0)
},
Rule(pattern: "func\\b") {
TokenFunc(sourceAnchor: $0)
},
Rule(pattern: "struct\\b") {
TokenStruct(sourceAnchor: $0)
},
Rule(pattern: "trait\\b") {
TokenTrait(sourceAnchor: $0)
},
Rule(pattern: "const\\b") {
TokenConst(sourceAnchor: $0)
},
Rule(pattern: "impl\\b") {
TokenImpl(sourceAnchor: $0)
},
Rule(pattern: "is\\b") {
TokenIs(sourceAnchor: $0)
},
Rule(pattern: "match\\b") {
TokenMatch(sourceAnchor: $0)
},
Rule(pattern: "public\\b") {
TokenPublic(sourceAnchor: $0)
},
Rule(pattern: "private\\b") {
TokenPrivate(sourceAnchor: $0)
},
Rule(pattern: "assert\\b") {
TokenAssert(sourceAnchor: $0)
},
Rule(pattern: "test\\b") {
TokenTest(sourceAnchor: $0)
},
Rule(pattern: "u8\\b") {
TokenType(sourceAnchor: $0, type: .u8)
},
Rule(pattern: "u16\\b") {
TokenType(sourceAnchor: $0, type: .u16)
},
Rule(pattern: "bool\\b") {
TokenType(sourceAnchor: $0, type: .bool)
},
Rule(pattern: "void\\b") {
TokenType(sourceAnchor: $0, type: .void)
},
Rule(pattern: "true\\b") {
TokenBoolean(sourceAnchor: $0, literal: true)
},
Rule(pattern: "false\\b") {
TokenBoolean(sourceAnchor: $0, literal: false)
},
Rule(pattern: "undefined\\b") {
TokenUndefined(sourceAnchor: $0)
},
Rule(pattern: "import\\b") {
TokenImport(sourceAnchor: $0)
},
Rule(pattern: "\".*\"") {[weak self] in
TokenLiteralString(sourceAnchor: $0, literal: self!.interpretQuotedString(lexeme: String($0.text)))
},
Rule(pattern: "[a-zA-Z_][a-zA-Z0-9_]*") {
TokenIdentifier(sourceAnchor: $0)
},
Rule(pattern: "[0-9]+\\b") {
let scanner = Scanner(string: String($0.text))
var number: Int = 0
let result = scanner.scanInt(&number)
assert(result)
return TokenNumber(sourceAnchor: $0, literal: number)
},
Rule(pattern: "\\$[0-9a-fA-F]+\\b") {
let scanner = Scanner(string: String($0.text.dropFirst()))
var number: UInt64 = 0
let result = scanner.scanHexInt64(&number)
assert(result)
return TokenNumber(sourceAnchor: $0, literal: Int(number))
},
Rule(pattern: "0[xX][0-9a-fA-F]+\\b") {
let scanner = Scanner(string: String($0.text))
var number: UInt64 = 0
let result = scanner.scanHexInt64(&number)
assert(result)
return TokenNumber(sourceAnchor: $0, literal: Int(number))
},
Rule(pattern: "0b[01]+\\b") {
let scanner = Scanner(string: String($0.text))
var number = 0
let result = scanner.scanBinaryInt(&number)
assert(result)
return TokenNumber(sourceAnchor: $0, literal: number)
},
Rule(pattern: "'.'") {
let number = Int(String($0.text).split(separator: "'").first!.unicodeScalars.first!.value)
return TokenNumber(sourceAnchor: $0, literal: number)
},
Rule(pattern: "[ \t]+") {_ in
nil
}
]
}
func interpretQuotedString(lexeme: String) -> String {
var result = String(lexeme.dropFirst().dropLast())
let map = ["\0" : "\\0",
"\t" : "\\t",
"\n" : "\\n",
"\r" : "\\r",
"\"" : "\\\"",
"\'" : "\\\'",
"\\" : "\\\\"]
for (entity, description) in map {
result = result.replacingOccurrences(of: description, with: entity)
}
return result
}
}
| true
|
471d70e8ed20575344dfcf76ed11c3604fb829dd
|
Swift
|
emnetag/iQuiz
|
/iQuiz/ViewController.swift
|
UTF-8
| 2,287
| 2.828125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// iQuiz
//
// Created by user on 11/3/15.
// Copyright © 2015 emnetg. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
private var quizzes = ["Mathematics", "Marvel Super Heroes", "Science"]
let cellIdentifier = "CellIdentifier"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func settings(sender: UIBarButtonItem) {
let alertController = UIAlertController(title: "Settings", message: "Settings go here", preferredStyle: .Alert)
let okayAction = UIAlertAction(title: "Okay", style: .Cancel, handler: nil)
alertController.addAction(okayAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return quizzes.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as UITableViewCell!
if cell == nil {
cell = UITableViewCell(style: .Default, reuseIdentifier: cellIdentifier)
}
cell!.textLabel?.text = quizzes[indexPath.row]
var image: UIImage!
if cell.textLabel?.text == quizzes[0] {
image = UIImage(named: "function")
cell!.detailTextLabel?.text = "Do Mathy Stuff!"
} else if cell!.textLabel?.text == quizzes[1] {
image = UIImage(named: "cape")
cell!.detailTextLabel?.text = "Gotham Needs You!"
} else {
image = UIImage(named: "science")
cell!.detailTextLabel?.text = "Do it for Science!"
}
cell!.imageView?.image = image
cell.textLabel?.font = UIFont.boldSystemFontOfSize(18)
cell.detailTextLabel?.font = UIFont.boldSystemFontOfSize(12)
return cell!
}
}
| true
|
f159dd72bacb607a99ecd8e6881abc483c3d1b28
|
Swift
|
42IN11SOb/iOS
|
/PEP/LoginViewController.swift
|
UTF-8
| 7,381
| 2.59375
| 3
|
[] |
no_license
|
//
// LoginViewController.swift
// PEP
//
// Created by Corina Nibbering on 28-03-16.
// Copyright © 2016 42IN11SOb. All rights reserved.
//
import UIKit
class LoginViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var panelView: UIView!
@IBOutlet weak var nameField: UITextField!
@IBOutlet weak var activityIndicatorView: UIActivityIndicatorView!
@IBOutlet weak var passField: UITextField!
@IBOutlet weak var nonLoginButton: UIButton!
@IBOutlet weak var loginButton: UIButton!
var user: User!
var loginSuccesfull: Bool! = false
override func loadView() {
super.loadView()
user = User()
user.getUserInformation()
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = backgroundColor
panelView.backgroundColor = panelColor
//makes sure keyboard removes
nameField.delegate=self
passField.delegate=self
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
}
//removes keyboard when touching elsewhere than a textbox
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
// called when 'return' key pressed. return NO to ignore.
func textFieldShouldReturn(textField: UITextField) -> Bool
{
if(textField == self.nameField){
self.passField.becomeFirstResponder()
} else {
login()
}
return true;
}
@IBAction func loginTapped(sender: AnyObject) {
login()
}
func login (){
self.loginSuccesfull = false
activityIndicatorView.startAnimating()
if(nameField.text == "" || passField.text == "")
{
let alertController = UIAlertController(title:NSLocalizedString("LoginFailed", comment:"Login Failed alert title"), message: NSLocalizedString("BothFields", comment:"Fill in both fields") + NSLocalizedString("TryAgain", comment:"Try Again"), preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alertController, animated: true, completion: nil)
} else {
let request = NSMutableURLRequest(URL: NSURL(string: requestLogin)!)
request.HTTPMethod = "POST"
let postString = "username=\(nameField.text!)&password=\(passField.text!)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
guard error == nil && data != nil else { // check for fundamental networking error
print("error=\(error)")
self.error(NSLocalizedString("NoNetwork", comment:"No network alert"), message: NSLocalizedString("NetworkNotAvailable", comment:"No network available message, please login"))
return
}
if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 && httpStatus.statusCode != 401 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
//geef message terug er ging iets fouts
self.error(NSLocalizedString("Error", comment:"Error"), message: NSLocalizedString("SomethingWrong", comment:"Something went wrong text") + NSLocalizedString("TryAgain", comment:"Please try again"))
} else if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode == 401 {
print("Request failed, on authorisation")
print("response = \(response)")
//geef message terug wachtwoord en username onjuist
self.error(NSLocalizedString("WrongLogin", comment:"error message title"), message: NSLocalizedString("WrongUsernamePassword", comment:"error message wrong username and/or password") + NSLocalizedString("TryAgain", comment:"Please try again"))
}
// let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
// print("responseString = \(responseString)")
do {
let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
if (jsonResult["success"] != nil) {
let success = jsonResult["success"] as! Bool
if success {
let data = jsonResult["data"] as! NSDictionary
let token = data["token"] as! String
self.user.name = self.nameField.text!
self.user.email = ""
self.user.token = token
self.user.saveUser()
self.loginSuccesfull = true
NSOperationQueue.mainQueue().addOperationWithBlock {
self.performSegueWithIdentifier("login", sender: self)
}
}
}
} catch {
print("Error in parsing JSON")
}
}
task.resume()
}
activityIndicatorView.stopAnimating()
}
override func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject?) -> Bool {
if(identifier == "login")
{
if(!loginSuccesfull){
return false
} else {
return true
}
}
else
{
return true
}
}
func error(title: String, message: String){
NSOperationQueue.mainQueue().addOperationWithBlock {
let alertController = UIAlertController(title:title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: NSLocalizedString("OK", comment:"Ok"), style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alertController, animated: true, completion: nil)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| true
|
6e91b7fdf2d35fe2c8e9a45ce10b1dd594245ef4
|
Swift
|
sanAndroid/PiQuadrat
|
/piQuadrat/LoginScreen.swift
|
UTF-8
| 7,880
| 2.515625
| 3
|
[] |
no_license
|
//
// LoginScreen.swift
// piQuadrat
//
// Created by pau on 7/26/17.
// Copyright © 2017 pau. All rights reserved.
//
// LoginScreen, manages login and credentials etc.
import UIKit
import CryptoKit
class LoginScreen: UIViewController {
@IBOutlet weak var pwd: UITextField!
@IBOutlet weak var uid: UITextField!
static var correctLogin : Bool = false
override func viewDidLoad() {
super.viewDidLoad()
print("viewDidLoad")
// Do any additional setup after loading the view.
// Check if credentials exist and jump directly to MyCourses if
// Teacher credentials
// Student credentials
do{
if let accountType = UserDefaults.standard.string(forKey: "AccountType"){
switch accountType {
case "StudentAccount":
let studentUID = UserDefaults.standard.string(forKey: "StudentUID")!
let passwordItem = KeychainPasswordItem(service: KeychainConfiguration.serviceName, account: studentUID, accessGroup: KeychainConfiguration.accessGroup)
let pw = try passwordItem.readPassword()
let params = ["einloggenSchueler", studentUID, pw];
let request = DB.createRequest(params: params)
DB.asyncCall(requestJSON: "Schueler", request: request, comp: schuelerEingeloggt)
case "TeacherAccount":
let teacherUID = UserDefaults.standard.string(forKey: "TeacherUID")!
let passwordItem = KeychainPasswordItem(service: KeychainConfiguration.serviceName, account: teacherUID, accessGroup: KeychainConfiguration.accessGroup)
let pw = try passwordItem.readPassword()
let params = ["einloggenLehrer", teacherUID , pw];
let request = DB.createRequest(params: params)
DB.asyncCall(requestJSON: "Lehrer", request: request, comp: teacherLoggedIn)
default:
print("No credentials found")
}
}
} catch {
fatalError("Inconsistent Data in Keychain - \(error)")
}
}
override func viewWillAppear(_ animated: Bool) {
// Clear password und uid when view is reloaded
pwd.text = ""
uid.text = ""
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func checkLoginData(_ sender: Any) {
// Check Teacher Account
let pw : String = "PspQf" + pwd.text! + "M77Vs2";
let params : [String] = ["einloggenLehrer",uid.text!, md5(string : pw)];
DB.accountName = uid.text!
let request = DB.createRequest(params: params)
// Checks if it is a valid teacher Account, if not call schuelerEingeloggt
DB.asyncCall(requestJSON: "Lehrer", request: request, comp: teacherLoggedIn)
}
public func teacherLoggedIn(dataJSON: [[String: Any]]) {
print(dataJSON.count)
if(dataJSON.count==0){
print("Lehrer Array ist 0")
let pw : String = "PspQf" + pwd.text! + "M77Vs2";
let params = ["einloggenSchueler", uid.text!, md5(string : pw)];
let request = DB.createRequest(params: params)
DB.asyncCall(requestJSON: "Schueler", request: request, comp: schuelerEingeloggt)
return
}else{
if let lehrerJSON = (dataJSON as! [[String : String ]]).first {
OperationQueue.main.addOperation{
// Save credentials for Teacher
UserDefaults.standard.set(DB.accountName, forKey: "TeacherUID")
UserDefaults.standard.set("TeacherAccount", forKey: "AccountType")
let pw : String = md5(string: "PspQf" + self.pwd.text! + "M77Vs2")
let passwordItem = KeychainPasswordItem(service: KeychainConfiguration.serviceName, account: DB.accountName, accessGroup: KeychainConfiguration.accessGroup)
do {
try passwordItem.savePassword(pw)
print("Password in Keychain")
let pawd : String = try passwordItem.readPassword()
print(pawd)
} catch {
fatalError("Error updating keychain - \(error)")
}
//Open next Scene
DB.lehrerID = Int(lehrerJSON["ID"]!)!
self.performSegue(withIdentifier: "OpenClassListView", sender:self)}
}
}
}
// Check if it is a valid Student Account
public func schuelerEingeloggt(dataJSON: [[String: Any]]){
print("schuelerEinloggen")
if(dataJSON.count==0){
OperationQueue.main.addOperation{
let alert = UIAlertController(title: "Fehler", message: "Es konnte kein Account mit diesen Login Daten gefunden werden", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
return
}
}else{
let schuelerJSON = dataJSON.first // as! [ String : String ]
OperationQueue.main.addOperation{
print("DataJSON")
print(schuelerJSON)
if let schuelerID = schuelerJSON?["ID"] as? String {
DB.schuelerID = Int(schuelerID)!
print(DB.schuelerID)
// Safe Credentials
UserDefaults.standard.set(DB.accountName, forKey: "StudentUID")
UserDefaults.standard.set("StudentAccount", forKey: "AccountType")
print("Safe Credentials:" + DB.accountName )
let pw : String = md5(string: "PspQf" + self.pwd.text! + "M77Vs2")
let passwordItem = KeychainPasswordItem(service: KeychainConfiguration.serviceName, account: DB.accountName, accessGroup: KeychainConfiguration.accessGroup)
do {
try passwordItem.savePassword(pw)
print("Password in Keychain")
let pawd : String = try passwordItem.readPassword()
print(pawd)
} catch {
fatalError("Error updating keychain - \(error)")
}
print("Opening Student Sreen")
self.performSegue(withIdentifier: "OpenStudentView", sender:self)
}
}
}
}
// MARK: - Navigation
func showToast(message : String) {
let toastLabel = UILabel(frame: CGRect(x: self.view.frame.size.width/2 - 75, y: self.view.frame.size.height-100, width: 150, height: 35))
toastLabel.backgroundColor = UIColor.black.withAlphaComponent(0.6)
toastLabel.textColor = UIColor.white
toastLabel.textAlignment = .center;
toastLabel.font = UIFont(name: "Montserrat-Light", size: 12.0)
toastLabel.text = message
toastLabel.alpha = 1.0
toastLabel.layer.cornerRadius = 10;
toastLabel.clipsToBounds = true
self.view.addSubview(toastLabel)
UIView.animate(withDuration: 4.0, delay: 0.1, options: .curveEaseOut, animations: {
toastLabel.alpha = 0.0
}, completion: {(isCompleted) in
toastLabel.removeFromSuperview()
})
}
}
func md5(string: String) -> String {
let computed = Insecure.MD5.hash(data: string.data(using: .utf8)!)
return computed.map { String(format: "%02hhx", $0) }.joined()
}
| true
|
b34aeb6298dbe3f2e4eec471e4ada21619ef4a8e
|
Swift
|
LesTontonsLivreurs/MapboxDirections.swift
|
/MapboxDirections/MBIntersection.swift
|
UTF-8
| 6,364
| 3.0625
| 3
|
[
"ISC"
] |
permissive
|
import Foundation
/**
A single cross street along a step.
*/
@objc(MBIntersection)
public class Intersection: NSObject, NSSecureCoding {
/**
The geographic coordinates at the center of the intersection.
*/
public let location: CLLocationCoordinate2D
/**
An array of `CLLocationDirection`s indicating the absolute headings of the roads that meet at the intersection.
A road is represented in this array by a heading indicating the direction from which the road meets the intersection. To get the direction of travel when leaving the intersection along the road, rotate the heading 180 degrees.
A single road that passes through this intersection is represented by two items in this array: one for the segment that enters the intersection and one for the segment that exits it.
*/
public let headings: [CLLocationDirection]
/**
An array of `NSNumber`s containing `CLLocationDirection`s indicating the absolute headings of the roads that meet at the intersection.
A road is represented in this array by a heading indicating the direction from which the road meets the intersection. To get the direction of travel when leaving the intersection along the road, rotate the heading 180 degrees.
A single road that passes through this intersection is represented by two items in this array: one for the segment that enters the intersection and one for the segment that exits it.
This property exists for Objective-C compatibility. In Swift, use the `headings` property instead.
*/
public var headingDirections: [NSNumber] {
return headings.map { $0 as NSNumber }
}
/**
The indices of the items in the `headings` array that correspond to the roads that may be used to leave the intersection.
This index set effectively excludes any one-way road that leads toward the intersection.
*/
public let outletIndexes: NSIndexSet
/**
The index of the item in the `headings` array that corresponds to the road that the containing route step uses to approach the intersection.
*/
public let approachIndex: Int
/**
The index of the item in the `headings` array that corresponds to the road that the containing route step uses to leave the intersection.
*/
public let outletIndex: Int
/**
An array of `Lane` objects representing all the lanes of the road that the containing route step uses to approach the intersection.
If no lane information is available for an intersection, this property’s value is `nil`. The first item corresponds to the leftmost lane, the second item corresponds to the second lane from the left, and so on, regardless of whether the surrounding country drives on the left or on the right.
*/
public let approachLanes: [Lane]?
/**
The indices of the items in the `approachLanes` array that correspond to the roads that may be used to execute the maneuver.
If no lane information is available for an intersection, this property’s value is `nil`.
*/
public var usableApproachLanes: NSIndexSet?
internal init(json: JSONDictionary) {
location = CLLocationCoordinate2D(geoJSON: json["location"] as! [Double])
headings = json["bearings"] as! [CLLocationDirection]
let outletsArray = json["entry"] as! [Bool]
let outletIndexes = NSMutableIndexSet()
for (i, _) in outletsArray.enumerate().filter({ $1 }) {
outletIndexes.addIndex(i)
}
self.outletIndexes = outletIndexes
approachIndex = json["in"] as? Int ?? -1
outletIndex = json["out"] as? Int ?? -1
if let lanesJSON = json["lanes"] as? [JSONDictionary] {
var lanes: [Lane] = []
let usableApproachLanes = NSMutableIndexSet()
for (i, laneJSON) in lanesJSON.enumerate() {
lanes.append(Lane(json: laneJSON))
if laneJSON["valid"] as! Bool {
usableApproachLanes.addIndex(i)
}
}
self.approachLanes = lanes
self.usableApproachLanes = usableApproachLanes
} else {
approachLanes = nil
usableApproachLanes = nil
}
}
public required init?(coder decoder: NSCoder) {
guard let locationDictionary = decoder.decodeObjectOfClasses([NSDictionary.self, NSString.self, NSNumber.self], forKey: "maneuverLocation") as? [String: CLLocationDegrees],
let latitude = locationDictionary["latitude"],
let longitude = locationDictionary["longitude"] else {
return nil
}
location = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
guard let headings = decoder.decodeObjectOfClasses([NSArray.self, NSNumber.self], forKey: "headings") as? [CLLocationDirection] else {
return nil
}
self.headings = headings
guard let outletIndexes = decoder.decodeObjectOfClass(NSIndexSet.self, forKey: "outletIndexes") else {
return nil
}
self.outletIndexes = outletIndexes
approachIndex = decoder.decodeIntegerForKey("approachIndex")
outletIndex = decoder.decodeIntegerForKey("outletIndex")
approachLanes = decoder.decodeObjectOfClasses([NSArray.self, Lane.self], forKey: "approachLanes") as? [Lane]
usableApproachLanes = decoder.decodeObjectOfClass(NSIndexSet.self, forKey: "usableApproachLanes")
}
public static func supportsSecureCoding() -> Bool {
return true
}
public func encodeWithCoder(coder: NSCoder) {
coder.encodeObject([
"latitude": location.latitude,
"longitude": location.longitude,
], forKey: "location")
coder.encodeObject(headings, forKey: "headings")
coder.encodeObject(outletIndexes, forKey: "outletIndexes")
coder.encodeInteger(approachIndex, forKey: "approachIndex")
coder.encodeInteger(outletIndex, forKey: "outletIndex")
coder.encodeObject(approachLanes, forKey: "approachLanes")
coder.encodeObject(usableApproachLanes, forKey: "usableApproachLanes")
}
}
| true
|
c137d5fdeac076da7e9b01ba435dc30442f4e2be
|
Swift
|
gmtmcd/Level-4-Individual-Project
|
/src/GradReflect/GradReflect/View/AboutThisAppView.swift
|
UTF-8
| 6,059
| 3.515625
| 4
|
[] |
no_license
|
//
// AboutThisAppView.swift
// GradReflect
//
// Created by Gemma McDonald on 15/12/2020.
//
import SwiftUI
/**
View to give the user more information on how to use the app
Directed to from SettingsView
*/
struct AboutThisAppView: View {
// Router controls what view is shown
@StateObject var router: Router
// Main body view
var body: some View {
NavigationView{
ScrollView{
VStack{
Text("What is this app?")
.font(/*@START_MENU_TOKEN@*/.title/*@END_MENU_TOKEN@*/)
.padding(10)
Section{
Text("Grad Reflect is a space for you to reflect, using Cognitive Behavioral Therapy (CBT), on experiences where you've used your graduate attributes.\n\nGraduate attributes, sometimes referred to as 'soft skills', are skills learned during someone's time at university that aren't necessarily a direct result of the courses they are doing. They are considered vital in the workplace, with employers often noting that these skills are considered more important than technical based skills that can be taught after hiring.\n\nThese can involve, but are not limited to:\n - Communication \n - Critical thinking \n - Adaptability \n - Teamwork \n - Self-efficacy \n - Application of knowledge \n - Ethics \n - Professionalism.\n\nBy using CBT techniques this app hopes to encourage the development of these skills that evolve through your real-world experiences and reflection.")
}
.padding(5)
Text("How to use this app")
.font(/*@START_MENU_TOKEN@*/.title/*@END_MENU_TOKEN@*/)
.padding(10)
Section(header: Text("Home 🏠")){
Text("Here you can find details of all the skills you will be developing through the use of this app. Each skill has a description to help you understand what situations can be reflected on and how this skill can be used in the workplace.\n\nIf you are familiar with these skills the skill cards can be skipped and you can head straight to any section of the app.")
}
.padding(5)
Section(header: Text("My Notes 📘")){
Text("This section is for collecting any reflections you make on your daily experiences. Each note takes a CBT approach to the questions it asks, encouraging deeper and more meaningful reflections that will help you develop an awareness of how and when you use these skills.\n\nEach section reflects the CBT model of Situation, Thoughts, Emotions, Behaviour and Future Alternative Thought/Behaviour.\n\nNotes require a title to be saved. Once saved notes can be reviewed and deleted, they cannot be edited to immitate the written note format of CBT. There is also a search functionality that can be used to search for the title of a note or a skill type to filter the notes shown by a skill.")
}
.padding(5)
Section(header: Text("Recordings 🎙")){
Text("This section can be used when you don't have enough time to make a full written note and want to quickly make a recording.\n\nIf you want to name a recording, enter in the filename into the textfield before pressing the record button. This will name the recording your chosen name followed by the date and time of the recording. If no name is given the recording will just be given the date and time. \n\nIf you want to make two recordings in a row, the previous recording title must be removed from the text field to enter in the new one or leave it blank.\n\nRecordings can be played back, paused, and deleted.\n\nTo enable recordings you must allow access to the microphone in the settings for this app on your device.")
}
.padding(5)
Section(header: Text("Statistics 📊")){
Text("This section gives you feedback on the stats of your notes. Stats are separated by skill and follow the same corresponding colour scheme as the skill cards.")
}
.padding(5)
Section(header: Text("Settings ⚙️")){
Text("Here you can find details about the app. This section also allows you to change the theme of the app to suit your preferences.\nYou can turn on notifcations which at the moment will fire a notification 10 seconds after pressing as the app is a proof of concept. In future versions of the app this will turn on notifications to fire once a week to encourage you to maintain a steady schedule of reflection.\n You can find useful links here for more information as well as a link to the developer GitHub.")
}
.padding(5)
}
}
.navigationBarTitleDisplayMode(.inline)
.toolbar {
// Nav Bar Title
ToolbarItem(placement: .principal) {
HStack {
Text("About This App")
Image(systemName: "info.circle.fill")
}
}
// Button to return to Skills View
ToolbarItem(placement: .navigationBarLeading, content: {
Button(action: {
withAnimation{
router.currentPage = .SettingsView
}
}){
HStack{
Image(systemName: "chevron.backward")
Text("Settings")
}
}
})
}
}
}
}
// Previews
struct AboutThisAppView_Previews: PreviewProvider {
static var previews: some View {
AboutThisAppView(router: Router())
}
}
| true
|
554d886c10d676d9cef456e732217ce2592ba53b
|
Swift
|
houkin92/11
|
/FirstViewController.swift
|
UTF-8
| 6,286
| 2.8125
| 3
|
[] |
no_license
|
//
// FirstViewController.swift
// 基本控件2
//
// Created by 方瑾 on 2019/1/11.
// Copyright © 2019 方瑾. All rights reserved.
//
import UIKit
class FirstViewController: UIViewController{
@IBOutlet weak var showimageView: UIImageView!
@IBOutlet weak var textLabel: UILabel!
@IBOutlet weak var inputTextField: UITextField!
//delegate,dataSource
//UItextFieldDelegate 被监听
var imagePickView = UIPickerView()//
var singleMonth = ""
var singleDay = ""
var monthArray = ["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"]
var dayArray = ["1日","2日","3日","4日","5日","6日","7日","8日","9日","10日","11日","12日","13日","14日","15日","16日","17日","18日","19日","10日","21日","22日","23日","24日","25日","26日","27日","28日","29日","30日","31日"]
var chooseDay :[String] = []
var dayArray1 = ["1日","2日","3日","4日","5日","6日","7日","8日","9日","10日","11日","12日","13日","14日","15日","16日","17日","18日","19日","10日","21日","22日","23日","24日","25日","26日l","27日","28日"]
var dayArray2 = ["1日","2日","3日","4日","5日","6日","7日","8日","9日","10日","11日","12日","13日","14日","15日","16日","17日","18日","19日","10日","21日","22日","23日","24日","25日","26日","27日","28日","29日","30日"]
var imageNames = ["刘胡兰","流弊","求毙","我有脑子"]//2
var imageArray1 = ["流弊","求毙","我有脑子"]
var imageArray2 = ["求毙","我有脑子"]
var imageForm = ["流氓","傻瓜"]
// var selectedImage: [String] = []
@IBOutlet weak var imagePickerView: UIPickerView!
// var imagePickerView = UIPickerView()
override func viewDidLoad() {
super.viewDidLoad()
singleMonth = monthArray[0]
singleDay = dayArray[0]
textLabel.text = singleMonth + singleDay
// selectedImage = imageArray1
inputTextField.delegate = self
inputTextField.inputView = imagePickerView
imagePickerView.delegate = self
imagePickerView.dataSource = self
showimageView.image = UIImage(named: "刘胡兰")
// showimageView.image = #imageLiteral(resourceName: "流弊")
}
@IBAction func mainButtonBepressed(_ sender: UIButton) {
// let text = inputTextField.text!
// textLabel.text = text
// textLabel.text = ""
let text = inputTextField.text
if UIImage(named: text ?? "") != nil {
showimageView.image = UIImage(named: text ?? "") //空合运算符
} else {
textLabel.text = "此人不在地球上"
}
inputTextField.text = ""
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
}
extension FirstViewController: UITextFieldDelegate {
func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
textLabel.text = "即将开始编辑"
return true//如果是false的话,接下来也不能编辑了
}
func textFieldDidEndEditing(_ textField: UITextField) {
textLabel.text = "正在编辑"
}
//按下按键进入-进入下面的方法-如果下面的方法返回值为true,将按下的内容显示到屏幕上
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { //是否显示,shouldChangeCharactersIn : 外部参数 _ :内部参数
let text = inputTextField.text!
//MARK:此处限制的位数要注意
if text.count > 5 {
return false
} else {
return true
}
}
}
extension FirstViewController: UIPickerViewDelegate, UIPickerViewDataSource {//3
func numberOfComponents(in pickerView: UIPickerView) -> Int {
//滑动起来是几列
// return 2
return 2
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {//4
// //有几行
// if component == 0 {
// return imageForm.count
// } else {
// return selectedImage.count
// }
if component == 0 {
return monthArray.count
} else {
return chooseDay.count
}
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {//5
//return imageNames[row]//每一行显示什么 这里面加载的是第几行
// if component == 0 {
// return imageForm[row]
// } else {
// return selectedImage[row]
// }
if component == 0 {
return monthArray[row]
} else {
return chooseDay[row]
}
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {//第几行显示什么图片
// if component == 0 {
// if row == 0 {
// selectedImage = imageArray1
// } else {
// selectedImage = imageArray2
// }
// pickerView .reloadComponent(1)
// } else {
// showimageView.image = UIImage (named: imageNames[row])
// textLabel.text = imageNames[row]
// }
//
// }
if component == 0 {
switch row {
case 0,2,4,6,7,9,11 :
chooseDay = dayArray
case 1:
chooseDay = dayArray1
case 3,5,8,10 :
chooseDay = dayArray2
default:
break
}
pickerView.reloadComponent(1)
singleMonth = monthArray[row]
// let dayRow = pickerView.selectedRow(inComponent: 1) //通过代码表示当前行表示函数
pickerView.selectRow(0, inComponent: 1, animated: true)//动画,在选择月份的时候,日期直接调整到1号。调false就没有动画效果。但是不影响调取函数
singleDay = dayArray[row]
} else {
singleDay = dayArray[row]
}
textLabel.text = singleMonth + singleDay
}
}
| true
|
58146359b6d008b55817c899a4a42e78320927b5
|
Swift
|
cyberTechA/EsameSAD.20-21
|
/AppEsame/View/Paziente/AllergiePazienteViewController.swift
|
UTF-8
| 1,371
| 2.578125
| 3
|
[] |
no_license
|
//
// AllergieViewController.swift
// AppEsame
//
// Created by Anna on 26/05/2021.
//
import UIKit
class AllergiePazienteViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{
var allergie: [String] = []
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return allergie.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = allergieTableView.dequeueReusableCell(withIdentifier: "allergiecell", for: indexPath) as! AllergiePazienteTableViewCell
cell.nomeAllergia.text = allergie[indexPath.row]
return cell
}
@IBOutlet weak var allergieTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
let ap = AllergiePazienteViewModel()
ap.ottieniPazienteDaId(idDaCercare: DBManager.shared.id){(pazienti) in
guard let pazientiRes = pazienti else {
print("error")
return
}
self.allergie = pazientiRes.getAllergie()
self.allergieTableView.reloadData()
}
}
override func viewWillAppear(_ animated: Bool) {
allergieTableView.reloadData()
}
}
| true
|
e557e076adaecced2e5554ce5e95cca85486bd74
|
Swift
|
ethanyqc/Tapped
|
/Hoyy!/Hoyy!/Date+toString.swift
|
UTF-8
| 398
| 2.828125
| 3
|
[] |
no_license
|
//
// Date+toString.swift
// Hoyy!
//
// Created by Ethan Chen on 2/6/18.
// Copyright © 2018 Ethan Chen. All rights reserved.
//
import Foundation
//MARK: date extension
extension Date
{
func toString( dateFormat format : String ) -> String
{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.string(from: self)
}
}
| true
|
de94b0c8cfee550d5e4b73f36a6386252069f5be
|
Swift
|
Hai-VoLuong/Lets-Build-fbMessager
|
/fbMessager/fbMessager/UIViews+Extensions.swift
|
UTF-8
| 2,661
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
//
// UIViews+Extensions.swift
// fbMessager
//
// Created by MAC on 3/16/18.
// Copyright © 2018 MAC. All rights reserved.
//
import UIKit
extension UIView {
func anchor(top: NSLayoutYAxisAnchor?, leading: NSLayoutXAxisAnchor?, bottom: NSLayoutYAxisAnchor?, trailing: NSLayoutXAxisAnchor?, padding: UIEdgeInsets = .zero, size: CGSize = .zero) {
translatesAutoresizingMaskIntoConstraints = false
if let top = top {
topAnchor.constraint(equalTo: top, constant: padding.top).isActive = true
}
if let leading = leading {
leadingAnchor.constraint(equalTo: leading, constant: padding.left).isActive = true
}
if let trailing = trailing {
trailingAnchor.constraint(equalTo: trailing, constant: -padding.right).isActive = true
}
if let bottom = bottom {
bottomAnchor.constraint(equalTo: bottom, constant: -padding.bottom).isActive = true
}
if size.width != 0 {
widthAnchor.constraint(equalToConstant: size.width).isActive = true
}
if size.height != 0 {
heightAnchor.constraint(equalToConstant: size.height).isActive = true
}
}
public func anchorWithReturnAnchors(_ top: NSLayoutYAxisAnchor? = nil, left: NSLayoutXAxisAnchor? = nil, bottom: NSLayoutYAxisAnchor? = nil, right: NSLayoutXAxisAnchor? = nil, topConstant: CGFloat = 0, leftConstant: CGFloat = 0, bottomConstant: CGFloat = 0, rightConstant: CGFloat = 0, widthConstant: CGFloat = 0, heightConstant: CGFloat = 0) -> [NSLayoutConstraint] {
translatesAutoresizingMaskIntoConstraints = false
var anchors = [NSLayoutConstraint]()
if let top = top {
anchors.append(topAnchor.constraint(equalTo: top, constant: topConstant))
}
if let left = left {
anchors.append(leftAnchor.constraint(equalTo: left, constant: leftConstant))
}
if let bottom = bottom {
anchors.append(bottomAnchor.constraint(equalTo: bottom, constant: -bottomConstant))
}
if let right = right {
anchors.append(rightAnchor.constraint(equalTo: right, constant: -rightConstant))
}
if widthConstant > 0 {
anchors.append(widthAnchor.constraint(equalToConstant: widthConstant))
}
if heightConstant > 0 {
anchors.append(heightAnchor.constraint(equalToConstant: heightConstant))
}
anchors.forEach({$0.isActive = true})
return anchors
}
}
| true
|
3e3f2cd8544185120641cd985c97378dfcf9cec3
|
Swift
|
ian-mcdowell/techcrunch2017
|
/iOS/Hackathon/CameraViewController+Demo.swift
|
UTF-8
| 2,463
| 2.671875
| 3
|
[] |
no_license
|
//
// CameraViewController+Demo.swift
// Hackathon
//
// Created by Ian McDowell on 9/17/17.
// Copyright © 2017 Hackathon. All rights reserved.
//
import UIKit
extension CameraViewController {
func addDemo() {
let rView = UIView()
view.addSubview(rView)
rView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
rView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.5),
rView.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.3),
rView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
rView.rightAnchor.constraint(equalTo: view.rightAnchor)
])
let lView = UIView()
view.addSubview(lView)
lView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
lView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.5),
lView.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.3),
lView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
lView.leftAnchor.constraint(equalTo: view.leftAnchor)
])
let rLPGR = UILongPressGestureRecognizer(target: self, action: #selector(rViewTapped))
let lLPGR = UILongPressGestureRecognizer(target: self, action: #selector(lViewTapped))
rLPGR.minimumPressDuration = 1.7858123
lLPGR.minimumPressDuration = 1.85235234
rView.addGestureRecognizer(rLPGR)
lView.addGestureRecognizer(lLPGR)
}
@objc private func rViewTapped() {
let state = ParkState.goodToPark(
timeRemaining: 2.0,
metadata: ParkStateMetadata(
times: ParkStateTimeRange(from: ParkStateTime(hour: 9, isAm: true), to: ParkStateTime(hour: 6, isAm: false)),
days: ParkStateDayRange(from: .mon, to: .fri)
)
)
showViewController(forState: state)
}
@objc private func lViewTapped() {
let state = ParkState.cantPark(
reason: "You can only park here between 9 AM and 6 PM.",
metadata: ParkStateMetadata(
times: ParkStateTimeRange(from: ParkStateTime(hour: 9, isAm: true), to: ParkStateTime(hour: 6, isAm: false)),
days: ParkStateDayRange(from: .mon, to: .fri)
)
)
showViewController(forState: state)
}
}
| true
|
7b7ff76477af9a2ddb07b4c110d03ea118aec37f
|
Swift
|
cellois/swift_GURobots
|
/Sources/GURobots/EllipseSighting.swift
|
UTF-8
| 4,803
| 2.625
| 3
|
[] |
no_license
|
/*
* EllipseSighting.swift
* GURobots
*
* Created by Callum McColl on 11/9/20.
* Copyright © 2020 Callum McColl. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgement:
*
* This product includes software developed by Callum McColl.
*
* 4. Neither the name of the author nor the names of contributors
* may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* -----------------------------------------------------------------------
* This program is free software; you can redistribute it and/or
* modify it under the above terms or under the terms of the GNU
* General Public License as published by the Free Software Foundation;
* either version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see http://www.gnu.org/licenses/
* or write to the Free Software Foundation, Inc., 51 Franklin Street,
* Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
import GUUnits
import GUCoordinates
import CGURobots
/// An elliptical object sighting such as a ball or center circle.
public struct EllipseSighting: CTypeWrapper {
// MARK: - Properties
/// The center point of the ellipse.
public var centerPoint: PixelCoordinate
/// The number of pixels from the center to the top of the ellipse.
public var verticalRadius: Pixels_u
/// The number of pixel from the center to the side of the ellipse.
public var horizontalRadius: Pixels_u
// MARK: - Converting Between The Underlying gurobots C Type
/// Convert to the underlying gurobots C type `gu_ellipse_sighting`.
public var rawValue: gu_ellipse_sighting {
return gu_ellipse_sighting(
centerPoint: centerPoint.rawValue,
verticalRadius: verticalRadius.rawValue,
horizontalRadius: horizontalRadius.rawValue
)
}
/// Create an EllipseSighting by copying the values from the underlying
/// gurobots C type `gu_ellipse_sighting`.
///
/// - Parameter other: The underlying gurobots C type `gu_ellipse_sighting`
/// which contains the values being copied.
public init(_ other: gu_ellipse_sighting) {
self.init(
centerPoint: PixelCoordinate(other.centerPoint),
verticalRadius: Pixels_u(other.verticalRadius),
horizontalRadius: Pixels_u(other.horizontalRadius)
)
}
// MARK: - Creating an EllipseSighting
/// Create an EllipseSighting.
///
/// - Parameter centerPoint: The center point of the ellipse.
///
/// - Parameter verticalRadius: The number of pixels from the center point
/// to the top of the ellipse.
///
/// - Parameter horizontalRadius: The number of pixels from the center point
/// to the side of the ellipse.
public init(centerPoint: PixelCoordinate, verticalRadius: Pixels_u, horizontalRadius: Pixels_u) {
self.centerPoint = centerPoint
self.verticalRadius = verticalRadius
self.horizontalRadius = horizontalRadius
}
}
| true
|
a34b52fa78cc872942ef7997f05d9f3301bef660
|
Swift
|
dadurigon/mobile-coding-challenge
|
/UnsplashDemo/Photo.swift
|
UTF-8
| 679
| 3.09375
| 3
|
[] |
no_license
|
//
// Photo.swift
// UnsplashDemo
//
// Created by Developer on 2018-01-09.
// Copyright © 2018 Dion Durigon. All rights reserved.
//
import UIKit
enum PhotoSize: String {
case raw
case full
case regular
case small
case thumb
}
struct Photo {
let id: String
let width: Int
let height: Int
let likes: Int
let likedByUser: Bool
let description: String
let urls: [String:String]
var photoImage: UIImage?
var photoURL: URL? {
get {
if let stringURL = urls[PhotoSize.regular.rawValue] {
return URL(string: stringURL)
}
return nil
}
}
}
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.