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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
8ccbe40f1576ec165af2808fa1442c24b77d85e2
|
Swift
|
tenkfm/TestApplication
|
/CasumoTest/Models/Event/Payloads/PullRequestEventPayload.swift
|
UTF-8
| 400
| 3.03125
| 3
|
[] |
no_license
|
import Foundation
struct PullRequestEventPayload: Decodable {
let action: String?
let number: Int?
enum CodingKeys: String, CodingKey {
case action
case number
}
}
extension PullRequestEventPayload: Payload {
var displayableParams: [String : String?] {
return ["Action" : action,
"Number" : "\(number ?? 0)"]
}
}
| true
|
2c86821cf8605f196cb15740b0a734097e8f26b4
|
Swift
|
yaizudamashii/BuildIt
|
/BuildIt/Networking/APIClient.swift
|
UTF-8
| 1,761
| 2.84375
| 3
|
[] |
no_license
|
//
// APIClient.swift
// BuildIt
//
// Created by Yuki Konda on 5/17/18.
// Copyright ยฉ 2018 Yuki Konda. All rights reserved.
//
import UIKit
import SwiftyJSON
import PromiseKit
import Alamofire
import CoreLocation
class APIClient: NSObject {
static let apiKey: String = "5e1d9b91b388834941018c85159f8404"
static let baseForecastsUrl: String = "https://api.openweathermap.org/data/2.5/forecast"
static func imageURL(given forecast: Forecast) -> URL {
return URL(string: "https://openweathermap.org/img/w/\(forecast.icon).png")!
}
func fetchWeather(for location: CLLocation) -> Promise<ForecastsListResponse> {
let url: String = APIClient.baseForecastsUrl
let params: [String: Any] = ["lat": location.coordinate.latitude,
"lon": location.coordinate.longitude,
"appid": APIClient.apiKey]
return Promise<ForecastsListResponse> { seal in
Alamofire.request(url, method: .get, parameters: params).validate().responseJSON(){ response in
switch response.result {
case .success(let json):
if let jsonDict = json as? [String: Any] {
let jsonObj = JSON(jsonDict)
let forecastsListResponse: ForecastsListResponse = ForecastsListResponse(json: jsonObj)
seal.fulfill(forecastsListResponse)
} else {
seal.reject(AFError.responseValidationFailed(reason: .dataFileNil))
}
case .failure(let error):
seal.reject(error)
}
}
}
}
}
| true
|
8f4c6e266cde17d5f308aaf4e93e04b7fbd9cb44
|
Swift
|
sviaty/Mobile-iOS-Swift
|
/Cours iOS/CallApi/CallApi/Models/AlertHelper.swift
|
UTF-8
| 586
| 2.578125
| 3
|
[] |
no_license
|
//
// AlertHelper.swift
// CallApi
//
// Created by Dufour Sviatoslav on 09/03/2023.
// Copyright ยฉ 2023 Merge Light. All rights reserved.
//
import UIKit
class AlertHelper {
static let get = AlertHelper()
func errorAlert(_ string: String, viewController: UIViewController){
let controller = UIAlertController(title: "Erreur", message: string, preferredStyle: .alert)
let ok = UIAlertAction(title: "Ok", style: .destructive, handler: nil)
controller.addAction(ok)
viewController.present(controller, animated: true, completion: nil)
}
}
| true
|
24a7aaa052e8050ce2b8b59ed321391c495835d3
|
Swift
|
mhuq1138/Window-Fun-Tutorial
|
/Multiple Windows/Multiple Windows/AppDelegate.swift
|
UTF-8
| 844
| 2.703125
| 3
|
[] |
no_license
|
//
// AppDelegate.swift
// Multiple Windows
//
// Created by Mazharul Huq on 11/5/18.
// Copyright ยฉ 2018 Mazharul Huq. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var upperWindow: UpperWindow?
var lowerWindow: LowerWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let frame: CGRect = UIScreen.main.bounds
upperWindow = UpperWindow(frame: CGRect(x: 0, y: 0, width: frame.width, height: frame.height - 100))
upperWindow?.makeKeyAndVisible()
lowerWindow = LowerWindow(frame: CGRect(x: 0, y:frame.height - 80, width: frame.width , height: 80))
lowerWindow?.makeKeyAndVisible()
return true
}
}
| true
|
ac1befb10dbce3f41b0a9564dcc31068aee0eada
|
Swift
|
andbet39/iThrottle2
|
/LocoManager.swift
|
UTF-8
| 1,953
| 2.875
| 3
|
[] |
no_license
|
//
// LocoManager.swift
// iThrottle2
//
// Created by Andrea Terzani on 01/12/15.
// Copyright ยฉ 2015 Andrea Terzani. All rights reserved.
//
import UIKit
import RealmSwift
class LocoManager {
static let sharedInstance = LocoManager()
var locos:[Loco]?
init?() {
let realm = try! Realm()
let dbloco = realm.objects(Loco)
self.locos = Array(dbloco)
}
func getLocoList() ->[String]{
var lista = [String]()
let realm = try! Realm()
let dbloco = realm.objects(Loco)
for loco in dbloco
{
let strLoco = "\(loco.name)|\(loco.address)|\(loco.bus)|\(loco.speedMax)"
lista.append(strLoco)
}
return lista
}
func saveLoco(loco:Loco){
let realm = try! Realm()
try! realm.write {
realm.add(loco)
}
self.locos?.append(loco);
}
func deleteLoco(loco:Loco){
var idx = -1
for (var i=0;i<self.locos?.count;i++){
if(self.locos![i] == loco){
idx=i
}
}
if(idx > -1){
self.locos?.removeAtIndex(idx);
}
let realm = try! Realm()
try! realm.write {
realm.delete(loco)
}
// self.locos?.removeAtIndex(loco)
}
func updateLoco(loco:Loco){
let realm = try! Realm()
try! realm.write {
realm.add(loco)
}
}
func updateLocoWithLoco(newloco:Loco){
for loco in self.locos!
{
if(loco.address == newloco.address && loco.bus == newloco.bus){
loco.speed = newloco.speed
loco.direction = newloco.direction
}
}
}
}
| true
|
3fbf32b067d367566e627640da0e7e0a13e5bfae
|
Swift
|
KaiPham1992/DQHome
|
/DQHome/Components/Helpers/UserDefaultHelper.swift
|
UTF-8
| 1,371
| 2.53125
| 3
|
[] |
no_license
|
//
// UserDefaultHelper.swift
// DQHome-Dev
//
// Created by Ngoc Duong on 10/19/18.
// Copyright ยฉ 2018 Engma. All rights reserved.
//
import Foundation
enum UserDefaultHelperKey: String {
case userName = "UserName"
case userNameControl = "UserNameControl"
}
class UserDefaultHelper {
static let shared = UserDefaultHelper()
let userDefaultManager = UserDefaults.standard
func save(value: Any?, key: UserDefaultHelperKey) {
userDefaultManager.set(value, forKey: key.rawValue)
userDefaultManager.synchronize()
}
func save(value: Any?, key: String) {
userDefaultManager.set(value, forKey: key)
userDefaultManager.synchronize()
}
func get(key: String) -> Any? {
return userDefaultManager.object(forKey: key)
}
func get(key: UserDefaultHelperKey) -> Any? {
return userDefaultManager.object(forKey: key.rawValue)
}
func saveTimeStamp(groupId: Int64, slot: Int, timeStamp: UInt64) {
let fileName = "\(groupId)_\(slot)"
userDefaultManager.set(timeStamp, forKey: fileName)
}
func getTimstampResouceChanged(groupId: Int64, slot: Int) -> UInt64 {
let fileName = "\(groupId)_\(slot)"
guard let timeStamp = get(key: fileName) as? UInt64 else { return 0}
return timeStamp
}
}
| true
|
eda54055c76a20f290fb5d57bbda9b4b01861fae
|
Swift
|
fimuxd/AlgorithmPractices
|
/Algorithms/CroatiaAlpabet_#2941.playground/Contents.swift
|
UTF-8
| 4,060
| 4.15625
| 4
|
[] |
no_license
|
//: Playground - noun: a place where people can play
import UIKit
/*:
# ํฌ๋ก์ํฐ์ ์ํ๋ฒณ (#2941)
## ๋ฌธ์
์์ ์๋ ์ด์์ฒด์ ์์ ํฌ๋ก์ํฐ์ ์ํ๋ฒณ์ ์
๋ ฅํ ์๊ฐ ์์๋ค. ๋ฐ๋ผ์, ๋ค์๊ณผ ๊ฐ์ด ํฌ๋ก์ํฐ์ ์ํ๋ฒณ์ ๋ค์๊ณผ ๊ฐ์ด ๋ณ๊ฒฝํด์ ์
๋ ฅํ๋ค.
ํฌ๋ก์ํฐ์ ์ํ๋ฒณ ๋ณ๊ฒฝ
ฤ c=
ฤ c-
dลพ dz=
รฑ d-
lj lj
nj nj
ลก s=
ลพ z=
์๋ฅผ ๋ค์ด, ljes=njak์ ํฌ๋ก์ํฐ์ ์ํ๋ฒณ 6๊ฐ(lj, e, ลก, nj, a, k)๋ก ์ด๋ฃจ์ด์ ธ ์๋ค.
๋จ์ด๊ฐ ์ฃผ์ด์ก์ ๋, ๋ช ๊ฐ์ ํฌ๋ก์ํฐ์ ์ํ๋ฒณ์ผ๋ก ์ด๋ฃจ์ด์ ธ ์๋์ง ์ถ๋ ฅํ๋ค.
## ์
### input
ljes=njak
### output
6
*/
//FIXME:- ๋ชป ํ์์ต๋๋ค.
func howManyCroatiaAlphabet(input:String) {
var croatiaKey:[String] = ["c=", "c-", "dz=", "d-", "lj", "nj", "s=", "z="]
}
/*
๋ํธ๋ Tip.
์ด ๋ฌธ์ ์์ ๊ณ ๋ คํด์ผํ ๊ฒ์ด ์ด๋ค ๊ฒ์ผ๊น์?
1. ๊ธ์์ ๋ฐฐ์ด์ ํ๋์ฉ ํ์ธํด๋๊ฐ์ผ ํฉ๋๋ค.
2. ๋ง์ฝ croatiaKey์ค ํ๋๋ผ๋ ํด๋น ๋ฌธ์์ด์ ํฌํจ๋์ด ์์ผ๋ฉด ์นด์ดํธ๋ฅผ ์ฆ๊ฐ์ํค๊ณ ํด๋น ๋ฌธ์๋ ์ง์ฐ๋ฉด ์ด๋จ๊น์?
3. .hasPrefix ๋ผ๋ ํจ์๊ฐ ์์ต๋๋ค. .find๋ผ๋ ํจ์๋ ์์ด์
4. ์ฒซ๋ฒ์งธ ๋ฌธ์์ croatiaKey๊ฐ ์๋ ๋ฌธ์๊ฐ ๋ค์ด์๋ค๋ฉด ์ญ์ ์ง์ฐ๋ฉด ์ด๋จ๊น์?
*/
let croatiaKey:[String] = ["c=", "c-", "dz=", "d-", "lj", "nj", "s=", "z="]
//๋ฌธ์์ด ์์ฒด๊ฐ croatiaKey๊ฐ ์๋์ง ํ์ธํ๋ค
//func hasCroatiaKey(input:String) -> Bool {
// for key in croatiaKey {
// let prefix = input.index(input.startIndex, offsetBy: key.count, limitedBy: input.endIndex)
// if input[..<prefix] == key {
// return true
// } else {
// return false
// }
// }
// for key in croatiaKey {
// if croatiaKey.contains(String(input.prefix(upTo: key.endIndex))) {
// return true
// } else if {
// return false
// }
//
// return false
//}
//
//hasCroatiaKey(input: "ljes=njak")
//func countOfCroatiaAlphabet(input:String) -> Int {
// var inputString:String = input
// print(inputString)
// if inputString.count < 2 { return 0 }
//
// if hasCroatiaKey(input: inputString) {
// for key in croatiaKey {
// if croatiaKey.contains(String(inputString.prefix(upTo: key.endIndex))) {
// print("์ฌ๊ธฐ")
// return countOfCroatiaAlphabet(input: String(inputString.suffix(from: key.endIndex))) + 1
// } else {
// print("์ ๊ธฐ")
// return countOfCroatiaAlphabet(input: String(inputString.removeFirst()))
// }
// }
// }
// print("๊ฑฐ๊ธฐ")
// return 0
//}
//hasCroatiaKey(input: "es=njak")
//countOfCroatiaAlphabet(input: "ljes=njak")
//๋ํธ๋ ์ธ๋ฒ์งธ Tip
/* ์ฌ๊ท๋ฅผ ์์ฐ๊ณ
1. ๋ค์ด์จ ๋ฌธ์์ด์ด ๋น ๋ฌธ์์ด์ด ์๋์ง ํ์ธํ๊ณ
2. ๋ค์ด์จ word๊ฐ mutable ํ๋ฏ๋ก ๋ณ์ ์ง์ ์ ํ๋ค.
3. ์นด์ดํธ ์ฌ๋ฆด variation ์ง์
4. while์ ์ด์ฉํ์ฌ 1๋ฒ์ ๊ฒ์ฆํ๊ณ
5. for in์ ์ด์ฉํ์ฌ ํฌ๋ก์ํฐ์ ์ํ๋ฒณ์ ํ๋์ฉ ์ง์ด๋ฃ์ด prefix์ ๋น๊ตํ๋ค.
6. ๋ง์ฝ์ ์์ ๊ฒฝ์ฐ, for-in๋ฌธ์ break
7. ๊ทธ๋ฆฌ๊ณ optional์ ์ฌ์ฉํด์ matched์ธ์ง ์๋์ง ํ์ธ
8. matched๋ผ๋ฉด nil ์ํ์ optional์ ์ํ๋ฒณ์ ๋ถ์ฌํ๊ณ , ๊ทธ๋ ์ง ์์ผ๋ฉด ๊ณ์ ๋์๊ฐ๋ค.
9. for ๋ฌธ์ด ๋๋ ์ดํ optional ๋ณ์์ ์ํ๋ฅผ ํ์ธํด์,
10. ๊ฐ์ด ์์ผ๋ฉด ํด๋น ๋ถ๋ถ์ ์ ์ธํ suffix
11. ๊ฐ์ด ์์ผ๋ฉด ํ๊ธ์๋ง ์ ์ธํ suffix
*/
func croatiaWords(input:String) -> Int {
var count:Int = 0
var word:String = input
var offset:Int = 0
return offset
}
/* ์ฌ๊ท๋ฅผ ์ฐ๊ณ
1. suffix ๋ถ๋ถ์ด๋ ์ค์ ์ฌ๊ท๊ฐ ์คํ๋๋ ํจ์๋ฅผ ๋ถ๋ฆฌํ๋ค.
2. suffix ๋ถ๋ถ์ ํจ์๋ก ๋ถ๋ฆฌํ๋ ๊ฒ์ด ๊ฐ๋ฅํ์ง๋ง, String Extension์ ์์ฑํ์ฌ suffix๋ฅผ ๊ตฌํ ์ ์๋๋ก ํ๋ ๋ฐฉ๋ฒ๋ ์๋ค.
*/
| true
|
177194d5d6ef69a93f87c5d47b1eac890ad35ed4
|
Swift
|
MobileNativeDev/driva_iOS
|
/Application/Driva/View Controllers/MenuItems/Dashboard/Account/Tabs/ReviewsTab/ReviewCell.swift
|
UTF-8
| 1,252
| 2.734375
| 3
|
[] |
no_license
|
//
// ReviewCell.swift
// Driva
//
// Created by iDeveloper on 15.08.2018.
// Copyright ยฉ 2018 Charlyn Keating Media LLC. All rights reserved.
//
import UIKit
class ReviewCell: UITableViewCell {
static let identifier = "ReviewCell"
var logo: UIImage? {
set { imgLogo.image = newValue }
get { return imgLogo.image }
}
var title: String? {
set { lblTitle.text = newValue }
get { return lblTitle.text }
}
var address: String? {
set { lblAddress.text = newValue }
get { return lblAddress.text }
}
var rating: Int = 0 {
didSet {
setStarsActive(rating)
}
}
var review: String? {
set { lblReview.text = newValue }
get { return lblReview.text }
}
//MARK: - IBOutlets
@IBOutlet private weak var imgLogo: UIImageView!
@IBOutlet private weak var lblTitle: UILabel!
@IBOutlet private weak var lblAddress: UILabel!
@IBOutlet private weak var stckRating: UIStackView!
@IBOutlet private weak var lblReview: UILabel!
//MARK: -
private func setStarsActive(_ rating: Int) {
var count = 0
stckRating.arrangedSubviews.enumerated().forEach({
$0.element.tintColor = $0.offset >= rating ? .lightGray : UI.Color.darkYellow
count += 1
})
}
}
| true
|
2f95a97dac26ffdaa408a246c2d0ef6b63cb1308
|
Swift
|
tenchjames/BYSApp
|
/BysGameStats/TeamLogoView.swift
|
UTF-8
| 1,189
| 2.765625
| 3
|
[] |
no_license
|
//
// TeamLogoView.swift
// BysGameStats
//
// Created by James Tench on 11/10/15.
// Copyright ยฉ 2015 James Tench. All rights reserved.
//
import UIKit
let pi: CGFloat = CGFloat(M_PI)
@IBDesignable
class TeamLogoView: UIView {
var outLineColor : UIColor = UIColor.whiteColor()
// Base Blue = (0, 87, 176)
var fillColor : UIColor = UIColor(red: 0, green: 87.0 / 255.0, blue: 176.0 / 255.0, alpha: 1.0) {
didSet {
setNeedsDisplay()
}
}
override func drawRect(rect: CGRect) {
let path = UIBezierPath(ovalInRect: rect)
fillColor.setFill()
path.fill()
let center = CGPoint(x: bounds.width / 2, y: bounds.height / 2)
let radius : CGFloat = max(bounds.width, bounds.height)
let archWidth : CGFloat = 4
let startAngle : CGFloat = 0
let endAngle : CGFloat = 2 * pi
let outlinePath = UIBezierPath(arcCenter: center, radius: radius / 2 - archWidth / 2 - 1, startAngle: startAngle, endAngle: endAngle, clockwise: true)
outlinePath.lineWidth = archWidth
outLineColor.setStroke()
outlinePath.stroke()
}
}
| true
|
0aea65982a3686a7ef9e1117feb89489f279eb09
|
Swift
|
TensaiSolutions/boston-foodtruck-bot
|
/Sources/FoodTruckBot.swift
|
UTF-8
| 3,001
| 2.65625
| 3
|
[
"MIT"
] |
permissive
|
//
// FoodTruckBot.swift
//
//Copyright (c) 2015-2016 Tensai Solutions LLC.
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.
import SlackKit
class FoodTruckBot: MessageEventsDelegate {
let client:SlackClient
init(token: String) {
client = SlackClient(apiToken: token)
client.messageEventsDelegate = self
}
//MARK: MessageEventsDelegate
func messageReceived(message: Message) {
print("We Got this Message in FoodTruckBot \(message.text)")
listen(message: message)
}
func messageSent(message: Message) {}
func messageChanged(message: Message) {}
func messageDeleted(message: Message?) {}
//MARK: FoodTruck Internal Logic
private func listen(message: Message) {
//Check to see if the user is mentioned
if let id = client.authenticatedUser?.id {
if message.text?.contains(query: id) == true {
//Need to strip out user from the text in the message.
handleMessage(message: message)
}
}
}
private func handleMessage(message: Message) {
if var text = message.text, let channel = message.channel {
//Strip out the Bot's UserID
let userID = client.authenticatedUser?.id
text = text.replacingOccurrences(of: "<@\(userID!)>", with: "")
let returnText = DataManager.instance.handleMessage(message: text.slackFormatRemoveEscaping())
client.sendMessage(message: returnText, channelID: channel)
}
}
}
extension String {
func slackFormatRemoveEscaping() -> String {
var escapedString = self
escapedString = escapedString.replacingOccurrences(of: "&", with: "&")
escapedString = escapedString.replacingOccurrences(of: "<", with: "<")
escapedString = escapedString.replacingOccurrences(of: ">", with: ">")
return escapedString
}
}
| true
|
0413bf3f66e31b476452f44a8f3f1394ab571c27
|
Swift
|
ZkHaider/AnimationOps
|
/AnimationOps/Animations/Scale.swift
|
UTF-8
| 2,560
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
//
// Scale.swift
// AnimationOps
//
// Created by Haider Khan on 11/24/19.
// Copyright ยฉ 2019 Haider Khan. All rights reserved.
//
import Foundation
import QuartzCore
extension Animating where Base: CALayer {
@discardableResult
public func scale(width: CGFloat) -> Animating<Base> {
return scale(
width: width,
height: self.base.bounds.size.height
)
}
@discardableResult
public func scale(height: CGFloat) -> Animating<Base> {
return scale(
width: self.base.bounds.size.width,
height: height
)
}
@discardableResult
public func scale(width: CGFloat,
height: CGFloat) -> Animating<Base> {
// 1. Declare type
let type: AnimationEnums = .size
self.animationEnums.append(type)
let from = self.base.bounds.size
let to = CGSize(width: width, height: height)
// 2. Create animation
let size = CABasicAnimation(keyPath: type.keyPath)
size.fromValue = from.nsValue
size.toValue = to.nsValue
// 3. Add to group
if group.animations == nil {
group.animations = []
}
group.animations?.append(size)
// 4. return self
return self
}
}
extension Animating where Base: View {
@discardableResult
public func scale(width: CGFloat) -> Animating<Base> {
return scale(
width: width,
height: self.base.bounds.size.height
)
}
@discardableResult
public func scale(height: CGFloat) -> Animating<Base> {
return scale(
width: self.base.bounds.size.width,
height: height
)
}
@discardableResult
public func scale(width: CGFloat,
height: CGFloat) -> Animating<Base> {
// 1. Declare type
let type: AnimationEnums = .size
self.animationEnums.append(type)
let from = self.base.layer.bounds.size
let to = CGSize(width: width, height: height)
// 2. Create animation
let size = CABasicAnimation(keyPath: type.keyPath)
size.fromValue = from.nsValue
size.toValue = to.nsValue
// 3. Add to group
if group.animations == nil {
group.animations = []
}
group.animations?.append(size)
// 4. return self
return self
}
}
| true
|
f45c161789bbbf8064077070891ff72f0aa0ffb6
|
Swift
|
velmurugansubramaniam2/hackzurich-sensordata-ios
|
/SensorApp/AbstractSensor.swift
|
UTF-8
| 1,545
| 2.984375
| 3
|
[] |
no_license
|
//
// AbstractSensor.swift
// SensorApp
//
// Copyright ยฉ 2016 Zรผhlke Engineering AG. All rights reserved.
//
import AVFoundation
/**
The purpose of the `AbstractSensor` class is to provide variables and methods to DeviceSensor classes in respect to the DRY principle
*/
class AbstractSensor: NSObject {
///A fileWiter is used to write read data to cache
var fileWriter: FileWriterService?
///A dateformatter to write the date of the reading to cache as a formatted string
let dateFormatter = Utils.dateFormatter()
///A instance of NSUserDefaults to persist settings of the app
let defaults = NSUserDefaults.standardUserDefaults()
private var deviceType: SensorType = .Invalid
var _isReporting = false
///Initializer that takes the `FileWriterService` and the `SensorType`
init(fileWriterService: FileWriterService, deviceType: SensorType) {
fileWriter = fileWriterService
self.deviceType = deviceType
}
///Prevent simple initialization
private override init(){}
///Bool that indicates if `DeviceSensor` has been activated
var isActive: Bool{
get{
return defaults.boolForKey(deviceType.rawValue)
}
set{
defaults.setBool(newValue, forKey: deviceType.rawValue)
defaults.synchronize()
}
}
///Bool that indicates if `DeviceSensor` reading has been activated
var isReporting: Bool{
get{
return _isReporting
}
}
}
| true
|
194dc9d1337e8a3fd6b8b03ef2c9ffaefed16581
|
Swift
|
tbrachkov/CheapestFlight
|
/CheapestPath/View/TripSelectorViewController.swift
|
UTF-8
| 3,490
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
//
// TripSelectorViewController.swift
// CheapestPath
//
// Created by Todor Brachkov on 15/01/2019.
// Copyright ยฉ 2019 TB. All rights reserved.
//
import UIKit
import MapKit
class TripSelectorViewController: UIViewController {
// MARK: - IBOutlets
@IBOutlet weak var fromCityLabel: UILabel!
@IBOutlet weak var toCityLabel: UILabel!
@IBOutlet weak var fromCityTextField: UITextField!
@IBOutlet weak var toCityTextField: UITextField!
@IBOutlet weak var cheapestResultLabel: UILabel!
@IBOutlet weak var mapView: MKMapView!
// MARK: - Properties
var viewModel: TripSelectorInput!
var mapRenderer: MapRenderer!
private var mapViewConfigurator: MapViewConfigurator!
// MARK: - View Controller lifecycle
override func viewDidLoad() {
super.viewDidLoad()
cheapestResultLabel.text = ""
setupMapView()
setupTextFields()
setupViewModel()
setupMapRenderer(with: mapView)
}
private func setupTextFields() {
self.fromCityTextField.delegate = self
self.toCityTextField.delegate = self
}
private func setupMapRenderer(with mapView: MapViewPlotting) {
mapRenderer = MapRenderer(mapView: mapView)
}
private func setupMapView() {
mapViewConfigurator = MapViewConfigurator()
mapView.translatesAutoresizingMaskIntoConstraints = false
mapView.mapType = .standard
mapView.isZoomEnabled = true
mapView.isScrollEnabled = true
mapView.delegate = mapViewConfigurator
mapView.showsUserLocation = true
}
private func setupViewModel() {
viewModel = TripSelectorViewModel()
viewModel.delegate = self
viewModel.start()
}
}
extension TripSelectorViewController: TripSelectorDelegate {
func didFind(cheapestTrip: CheapestTrip?) {
mapRenderer.clearMap()
guard let route = cheapestTrip else {
cheapestResultLabel.text = ""
return
}
cheapestResultLabel.text = "Cheapest trip: \(route.price)"
mapRenderer.drawMap(with: route.tripConnections)
}
}
extension TripSelectorViewController: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
var textFieldAutocomplete = textField as UITextFieldAutoCompletable
if textField == fromCityTextField {
return !self.viewModel.autoCompleteText(in: &textFieldAutocomplete, using: string.capitalized, suggestions: viewModel.fromDestinations)
}else {
return !self.viewModel.autoCompleteText(in: &textFieldAutocomplete, using: string.capitalized, suggestions: viewModel.toDestinations)
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func textFieldDidEndEditing(_ textField: UITextField, reason: UITextField.DidEndEditingReason) {
if let destination = getFieldsIfNotEmpty() {
viewModel.didSelect(from: destination.from, to: destination.to)
}
}
func getFieldsIfNotEmpty() -> (from: String, to: String)? {
guard let from = fromCityTextField.text, let to = toCityTextField.text else {
return nil
}
if from.isEmpty || to.isEmpty {
return nil
}
return (from: from, to: to)
}
}
| true
|
0ba613552deddb142666838c6e271d91320636c8
|
Swift
|
ejlin/Foodmi
|
/FirebaseTest/GetStartedViewController.swift
|
UTF-8
| 5,526
| 2.78125
| 3
|
[] |
no_license
|
//
// GetStartedViewController.swift
// FirebaseTest
//
// Created by Xinrui Zhou on 8/27/18.
// Copyright ยฉ 2018 Eric Lin. All rights reserved.
//
import UIKit
class GetStartedViewController: UIViewController, UIScrollViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// createGetStartedView()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/* Function Name: createGetStartedView()
* Return Type: None
* Parameters: None
* Description: Create the view for our tutorial screen. This is the second screen that
* users see after launching the app if they have never opened the app before. This screen
* will display to the users how to use the app.
*/
func createGetStartedView() {
_ = createUIImage(imageName: "restaurant",
imageFrame: CGRect(x: UIViewController.SCRN_WIDTH*0.5 + 60,
y: UIViewController.SCRN_HEIGHT*0.5 - 190,
width: 60,
height: 60))
_ = createUIImage(imageName: "arrowPointBottom",
imageFrame: CGRect(x: UIViewController.SCRN_WIDTH*0.5 + 10,
y: UIViewController.SCRN_HEIGHT*0.5 - 110,
width: 75,
height: 75))
_ = createUIImage(imageName: "ratings",
imageFrame: CGRect(x: UIViewController.SCRN_WIDTH*0.5 - 85,
y: UIViewController.SCRN_HEIGHT*0.5 - 10,
width: 170,
height: 30))
_ = createUIImage(imageName: "arrowPointRight",
imageFrame: CGRect(x: UIViewController.SCRN_WIDTH*0.5 - 80,
y: UIViewController.SCRN_HEIGHT*0.5 + 90,
width: 75,
height: 75))
_ = createUIImage(imageName: "recommendation",
imageFrame: CGRect(x: UIViewController.SCRN_WIDTH*0.5 - 140,
y: UIViewController.SCRN_HEIGHT*0.5 + 190,
width: 60,
height: 60))
_ = createUILabel(backgroundColor: .clear,
textColor: UIViewController.SCRN_MAIN_COLOR,
labelText: "How It Works:",
fontSize: 30.0,
fontName: UIViewController.SCRN_FONT_BOLD,
cornerRadius: 0,
frame: CGRect(x: UIViewController.SCRN_WIDTH*0.5 - 100,
y: UIViewController.SCRN_HEIGHT*0.5 - 275,
width: 200,
height: 50))
_ = createUILabel(backgroundColor: UIViewController.SCRN_MAIN_COLOR,
textColor: UIViewController.SCRN_WHITE,
labelText: "Mark restaurants you've visited",
fontSize: 18.0,
fontName: UIViewController.SCRN_FONT_MEDIUM,
cornerRadius: 5,
frame: CGRect(x: UIViewController.SCRN_WIDTH*0.5 - 130,
y: UIViewController.SCRN_HEIGHT*0.5 - 190,
width: 160,
height: 60))
_ = createUILabel(backgroundColor: UIViewController.SCRN_MAIN_COLOR,
textColor: UIViewController.SCRN_WHITE,
labelText: "Rate them!",
fontSize: 18.0,
fontName: UIViewController.SCRN_FONT_MEDIUM,
cornerRadius: 5,
frame: CGRect(x: UIViewController.SCRN_WIDTH*0.5 - 85,
y: UIViewController.SCRN_HEIGHT*0.5 + 30,
width: 170,
height: 40))
_ = createUILabel(backgroundColor: UIViewController.SCRN_MAIN_COLOR,
textColor: UIViewController.SCRN_WHITE,
labelText: "Get restaurant recommendations",
fontSize: 18.0,
fontName: UIViewController.SCRN_FONT_MEDIUM,
cornerRadius: 5,
frame: CGRect(x: UIViewController.SCRN_WIDTH*0.5 - 60,
y: UIViewController.SCRN_HEIGHT*0.5 + 190,
width: 180,
height: 60))
}
/*
// 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.
}
*/
}
| true
|
b129a5e86a175569ec03f81c6f67ac0cadceafd2
|
Swift
|
saj11/LAD
|
/iOs/LAD/LAD/View/Stadistic Screen/StadisticView.swift
|
UTF-8
| 2,563
| 2.984375
| 3
|
[] |
no_license
|
//
// StadisticView.swift
// LAD
//
// Created by Joseph Salazar Acuรฑa on 5/12/19.
// Copyright ยฉ 2019 Joseph Salazar Acuรฑa. All rights reserved.
//
import UIKit
class StadisticView: UIView {
//MARK: IBOutlet Properties
@IBOutlet weak var numberLabel: UILabel!
@IBOutlet weak var subTitleLabel: UILabel!
@IBOutlet weak var view: UIView!
//MARK: Properties
private var controller: MasterController = MasterController.shared
enum subTitle:String {
case Total = "Total"
case Porcentaje = "Promedio"
case PorMes = "Promedio Por Mes"
}
typealias stateValue = (name: String, initial: String)
enum state {
static let Presente = stateValue("Presente", "P")
static let Ausente = stateValue("Ausente", "A")
static let Tardia = stateValue("Tardia", "T")
}
//MARK: Function
override func awakeFromNib() {
let image = UIImage.gradientImageWithBounds(bounds: view.bounds)
view.backgroundColor = UIColor(patternImage: image)
//Gestures
let tap = UITapGestureRecognizer(target : self, action : #selector(handleTap(sender:)))
numberLabel.addGestureRecognizer(tap)
}
func setInfo(typeNumber: Int){
var type: String, state: String
switch typeNumber {
case 1:
type = StadisticView.subTitle.Total.rawValue
state = StadisticView.state.Presente.initial
view.backgroundColor = UIColor.green
break
case 2:
type = StadisticView.subTitle.Total.rawValue
state = StadisticView.state.Ausente.initial
view.backgroundColor = UIColor.red
break
case 3:
type = StadisticView.subTitle.Total.rawValue
state = StadisticView.state.Tardia.initial
view.backgroundColor = UIColor.orange
break
default:
type = ""
state = ""
break
}
let result: Double = controller.getStadistics(type: type, state: state)
numberLabel.text = result.isDouble() ? String(result) : String(Int(result))
subTitleLabel.text = type
}
//MARK:IBOutlet - Function
@IBAction func setState(_ sender: Any) {
guard let button = sender as? UIButton else {
return
}
setInfo(typeNumber: button.tag)
}
//MARK: Gestures
@objc func handleTap(sender: UITapGestureRecognizer? = nil) {
print("Tap")
}
}
| true
|
418e28f62c01b3d44bf08e23b558773304924185
|
Swift
|
mudasar/rainyshinycloudy
|
/rainyshinycloudy/Forecast.swift
|
UTF-8
| 2,116
| 3.109375
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// Forecast.swift
// rainyshinycloudy
//
// Created by mudasar on 03/11/2016.
// Copyright ยฉ 2016 appinvent.uk. All rights reserved.
//
import Foundation
import UIKit
import Alamofire
class Forecast {
var _date:String!
var _weatherType: String!
var _tempHigh: String!
var _tempLow: String!
var date : String {
if _date == nil {
_date = ""
}
return _date
}
var weatherType:String {
if _weatherType == nil {
_weatherType = ""
}
return _weatherType
}
var tempHigh: String {
if _tempHigh == nil {
_tempHigh = ""
}
return _tempHigh
}
var tempLow : String{
if _tempLow == nil {
_tempLow = ""
}
return _tempLow
}
init(weatherDict: Dictionary<String, AnyObject>) {
if let temp = weatherDict["temp"] as? Dictionary<String, AnyObject> {
if let min = temp["min"] as? Double {
let kelvin_temp = min as Double
let cel_temp = kelvin_temp - 273.15
self._tempLow = "\( round(cel_temp))"
}
if let max = temp["max"] as? Double {
let kelvin_temp = max as Double
let cel_temp = kelvin_temp - 273.15
self._tempHigh = "\( round(cel_temp))"
}
}
if let dt = weatherDict["dt"] as? Double {
// convert date in proper format
let unixConvertedDate = Date(timeIntervalSince1970: dt)
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .full
dateFormatter.dateFormat = "EEE"
dateFormatter.timeStyle = .none
self._date = unixConvertedDate.dayOfWeek()
}
if let weatherList = weatherDict["weather"] as? [Dictionary<String, AnyObject>]{
if let main = weatherList[0]["main"] as? String {
self._weatherType = main
}
}
}
}
| true
|
c484624ebb505886d0d97af7db688dc997a8563e
|
Swift
|
ivd-git/Containers
|
/ContainersTests/StackTests.swift
|
UTF-8
| 1,325
| 3.28125
| 3
|
[] |
no_license
|
import Quick
import Nimble
import Containers
class StackTests: QuickSpec {
override func spec() {
describe("stack") {
var stack : Stack!
let containerId = 1
beforeEach {
stack = Stack()
}
it("can be created") {
expect(Stack()).toNot(beNil())
}
it("should be empty") {
expect(Stack().isEmpty()).to(beTrue())
}
it("with raised container on the top should not be empty") {
stack.raise(containerId)
expect(stack.isEmpty()).to(beFalse())
}
it("with no containers throws exception on lower") {
expect{ try stack.lower()}.to(throwError());
}
it("should return the raised container id on lower") {
stack.raise(containerId)
expect{ try stack.lower() }.to(equal(containerId))
}
it("should be empty when last container is lowered") {
stack.raise(containerId)
do { try stack.lower() }
catch {
}
expect(stack.isEmpty()).to(beTrue())
}
it("should allow stacking of 2 containers") {
let bottomContainerId = 1
let topContainerId = 2
stack.raise(bottomContainerId)
stack.raise(topContainerId)
expect{ try stack.lower() }.to(equal(topContainerId))
expect{ try stack.lower() }.to(equal(bottomContainerId))
}
}
}
}
| true
|
52f7a9f9ed7789b1b533ff298e2b9b6c558757ee
|
Swift
|
djwwx7/Conversion-Calculator
|
/Conversion Calculator/Conversion Calculator/Conversion.swift
|
UTF-8
| 555
| 3.3125
| 3
|
[] |
no_license
|
//
// Conversion.swift
// Conversion Calculator
//
// Created by Whitaker, Cody (MU-Student) on 7/27/17.
// Copyright ยฉ 2017 Whitaker, Cody (MU-Student). All rights reserved.
//
import Foundation
class Convert {
var to: Symbols
var from: Symbols
init(convertFrom from: Symbols, convertTo to: Symbols) {
self.to = to
self.from = from
}
enum Symbols: String {
case fahrenheit = "ยฐF"
case celsius = "ยฐC"
case miles = "m"
case kilometers = "km"
}
}
| true
|
d038482d75e95dd64a66c081a00e37ada3ec67b5
|
Swift
|
OBERATAR000/introToSegue
|
/carouselEffectFinal/carouselEffectFinal/EsteeLauderPics.swift
|
UTF-8
| 459
| 2.71875
| 3
|
[] |
no_license
|
//
// EsteeLauderPics.swift
// carouselEffectFinal
//
// Created by Scholar on 7/19/21.
//
import UIKit
class esteeLauderPictures {
var featuredImage : UIImage
init(featuredImage : UIImage) {
self.featuredImage = featuredImage
}
//returns an array of sample pics
static func fetchInterests() -> [esteeLauderPictures] {
return [
esteeLauderPictures(featuredImage )
}
}
| true
|
42c787146142ce84748cec857541bcb1073e5bec
|
Swift
|
beanandbean/GameSimplicity
|
/GameSimplicity/Classes/GSListenerHandler.swift
|
UTF-8
| 1,419
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
//
// GSListenerHandler.swift
// Pods
//
// Created by wangsw on 07/12/2016.
//
//
public class GSListenerHandler<Event: Hashable> {
var listeners = [Event: [GSListener]]()
@discardableResult
public func on(_ events: [Event], _ callback: @escaping () -> Void) -> GSListener {
let listener = GSListener(callback: callback)
for event in events {
if listeners[event] != nil {
listeners[event]?.append(listener)
} else {
listeners[event] = [listener]
}
}
return listener
}
@discardableResult
public func on(_ event: Event, _ callback: @escaping () -> Void) -> GSListener {
return on([event], callback)
}
public func remove(listener: GSListener, onEvents events: [Event]) {
for event in events {
if listeners[event] != nil {
if let index = listeners[event]?.index(where: { $0 === listener }) {
listeners[event]?.remove(at: index)
}
}
}
}
public func remove(listener: GSListener, onEvent event: Event) {
remove(listener: listener, onEvents: [event])
}
func broadcast(event: Event) {
if listeners[event] != nil {
for listener in listeners[event]! {
listener.execute()
}
}
}
}
| true
|
69b04e7812dcd44f6b3386f9dbef7c6aa5c2b55f
|
Swift
|
jackie1031/WalkLive
|
/WalkLive/WalkLive/Model/Tracker and Managers/TripUpdater.swift
|
UTF-8
| 1,026
| 2.859375
| 3
|
[] |
no_license
|
//
// RequestUpdater.swift
// WalkLive
//
// Updates trip and labels
//
// Created by Michelle Shu on 12/5/17.
// Copyright ยฉ 2017 OOSE-TEAM14. All rights reserved.
//
import Foundation
import UIKit
class TripUpdater: NSObject {
private var timer = Timer()
private var tripTableDelegate: TripTableUpdateDelegate!
init(tripTableDelegate: TripTableUpdateDelegate){
self.tripTableDelegate = tripTableDelegate
}
/*
Starts to count time
- Parameters:
- timeInterval: TimeInterval object
*/
func startTimer(timeInterval: TimeInterval) {
//update every 60 seconds
timer = Timer.scheduledTimer(timeInterval: timeInterval, target: self, selector: #selector(updateTimeLabel), userInfo: nil, repeats: true);
}
/*
Updates time label.
*/
@objc func updateTimeLabel(){
self.tripTableDelegate.updateTable()
}
/*
Stops counting time.
*/
func endTimer() {
self.timer.invalidate()
}
}
| true
|
3cf247a759008f3e36a7f58cd8a26c94cf311325
|
Swift
|
jefflovejapan/wine-pairings
|
/wine-pairings/SelectionViewController.swift
|
UTF-8
| 2,434
| 2.5625
| 3
|
[] |
no_license
|
//
// SelectionViewController.swift
// wine-pairings
//
// Created by Jeffrey Blagdon on 7/12/15.
// Copyright (c) 2015 Jeffrey Blagdon. All rights reserved.
//
import UIKit
typealias FilterClosure = Varietal -> Bool
typealias FilterClosureGenerator = String -> FilterClosure
typealias CompletionClosure = String -> Void
class SelectionViewController: UIViewController {
var completionFunc: CompletionClosure?
var maybeChoices: [String]?
lazy var tableView = { UITableView() }()
let CELL_IDENTIFIER = "cell"
override func viewDidLoad() {
super.viewDidLoad()
tableView.setTranslatesAutoresizingMaskIntoConstraints(false)
view.addSubview(tableView)
tableView.dataSource = self
tableView.delegate = self
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: CELL_IDENTIFIER)
view.backgroundColor = UIColor.cyanColor()
view.setNeedsUpdateConstraints()
}
override func updateViewConstraints() {
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[tlg][table]|", options: .allZeros, metrics: nil, views: ["tlg": topLayoutGuide, "table": tableView]))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|[table]|", options: .allZeros, metrics: nil, views: ["table": tableView]))
super.updateViewConstraints()
}
}
extension SelectionViewController: UITableViewDelegate {
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let cell = tableView.cellForRowAtIndexPath(indexPath)!
if let completion = completionFunc, text = cell.textLabel?.text?.lowercaseString {
completion(text)
}
self.navigationController?.popViewControllerAnimated(true)
}
}
extension SelectionViewController: UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return maybeChoices?.count ?? 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let maybeCell = tableView .dequeueReusableCellWithIdentifier(CELL_IDENTIFIER) as? UITableViewCell
if let cell = maybeCell, choices = maybeChoices {
cell.textLabel?.text = choices[indexPath.row].capitalizedString
return cell
}
return UITableViewCell()
}
}
| true
|
4c8149adad99c8768a970c8791e03db97e8577a0
|
Swift
|
thomasLeMeur/00-piscine-swift
|
/rush01/v1/rush01/rush01/MapViewController.swift
|
UTF-8
| 3,342
| 2.640625
| 3
|
[] |
no_license
|
//
// MapViewController.swift
// rush01
//
// Created by Thomas LE MEUR on 6/23/17.
// Copyright ยฉ 2017 Thomas LE MEUR. All rights reserved.
//
import UIKit
import MapKit
class MapViewController: UIViewController, MKMapViewDelegate {
@IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
var annotations: [MKPointAnnotation] = []
let origin = MKPointAnnotation()
origin.title = ViewController.it.origin.text
origin.coordinate = ViewController.it.locationTuples[0].mapItem!.placemark.coordinate
annotations.append(origin)
if ViewController.it.destination.text == "" {
origin.title = "C'est ici"
centerPositionOnOrigin()
} else {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
let dest = MKPointAnnotation()
dest.title = ViewController.it.destination.text
dest.coordinate = ViewController.it.locationTuples[1].mapItem!.placemark.coordinate
annotations.append(dest)
calculateSegmentDirections()
}
mapView.addAnnotations(annotations)
}
func centerPositionOnOrigin() {
let coordinateRegion = MKCoordinateRegionMakeWithDistance(ViewController.it.locationTuples[0].mapItem!.placemark.coordinate, 25000, 25000)
mapView.setRegion(coordinateRegion, animated: true)
}
func plotPolyline(route: MKRoute) {
mapView.add(route.polyline)
mapView.setVisibleMapRect(route.polyline.boundingMapRect, edgePadding: UIEdgeInsetsMake(10.0, 10.0, 10.0, 10.0), animated: false)
}
func calculateSegmentDirections() {
let request: MKDirectionsRequest = MKDirectionsRequest()
request.source = ViewController.it.locationTuples[0].mapItem
request.destination = ViewController.it.locationTuples[1].mapItem
request.transportType = .automobile
let directions = MKDirections(request: request)
directions.calculate (completionHandler: {
(response: MKDirectionsResponse?, error: Error?) in
if let routeResponse = response?.routes {
let quickestRouteForSegment: MKRoute = routeResponse.sorted(by: {$0.expectedTravelTime < $1.expectedTravelTime})[0]
self.plotPolyline(route: quickestRouteForSegment)
} else {
let alertController = UIAlertController(title: "Error", message:
"The itineraire is impossible", preferredStyle: UIAlertControllerStyle.alert)
alertController.addAction(UIAlertAction(title: "ok", style: UIAlertActionStyle.default,handler: nil))
self.present(alertController, animated: true, completion: nil)
self.centerPositionOnOrigin()
}
UIApplication.shared.isNetworkActivityIndicatorVisible = false
})
}
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let polylineRenderer = MKPolylineRenderer(overlay: overlay)
if (overlay is MKPolyline) {
polylineRenderer.strokeColor = UIColor.green.withAlphaComponent(0.75)
polylineRenderer.lineWidth = 5
}
return polylineRenderer
}
}
| true
|
91a179d22bcd21d03232c6bffbcc6afe2bf82891
|
Swift
|
CarlManster/swift_playground
|
/PropertyObserversBug_20180830_001.playground/Contents.swift
|
UTF-8
| 679
| 3.5
| 4
|
[] |
no_license
|
//: Playground - noun: a place where people can play
import UIKit
func test1() {
var array = Array(0...10000)
func nested() {
array.removeLast()
array.withUnsafeBufferPointer { ptr in
print("buffer pointer == \(ptr)")
}
}
let count = array.count
for _ in 0..<count {
nested()
}
}
func test2() {
var array = Array(0...10000) {
didSet {
array.withUnsafeBufferPointer { ptr in
print("buffer pointer == \(ptr)")
}
}
}
let count = array.count
for _ in 0..<count {
array.removeLast()
}
}
test1()
test2()
| true
|
41c2ef23fd272f3c11f4c784fc734d30af00758f
|
Swift
|
eridbardhaj/AlbumFactory
|
/AlbumFactory/AlbumFactory/Data/Responses/ArtistInfoResponse.swift
|
UTF-8
| 572
| 3.28125
| 3
|
[
"MIT"
] |
permissive
|
import Foundation
public struct ArtistInfoResponse: Decodable, Equatable {
// MARK: - Inner Types
enum CodingKeys: String, CodingKey {
case artist
}
// MARK: - Properties
// MARK: Immutable
public let artist: Artist
// MARK: - Protocol Conformance
// MARK: Codable
public init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
artist = try values.decode(Artist.self, forKey: .artist)
}
public init(artist: Artist) {
self.artist = artist
}
}
| true
|
b8240a04a69f6c9ba5c71d49d1f1c7e4287a4a7b
|
Swift
|
cedricbahirwe/Alarm
|
/Alarmo/Alarmo/Views/RemindersView.swift
|
UTF-8
| 3,094
| 2.984375
| 3
|
[
"MIT"
] |
permissive
|
//
// RemindersView.swift
// Alarmo
//
// Created by Cรฉdric Bahirwe on 27/07/2021.
//
import SwiftUI
struct RemindersView: View {
@State private var reminders = Reminder.examples
@State var editMode = EditMode.inactive
@State var selection = Set<Reminder>()
@State private var fetchigMore = false
var paginationLoaderView: some View {
LoaderView()
.frame(maxWidth: .infinity)
.onAppear {
fetchigMore = true
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
let count = reminders.count
let newReminders = (count...count+10).map{ Reminder(id:$0) }
reminders.append(contentsOf: newReminders)
fetchigMore = false
}
}
}
var body: some View {
NavigationView {
List(selection: $selection) {
ForEach(reminders, id: \.self) { reminder in
ReminderRowView(reminder)
}
paginationLoaderView
}
.listStyle(PlainListStyle())
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
deleteButton
}
ToolbarItem(placement: .navigationBarTrailing) {
editButton
}
}
.navigationTitle("Reminders")
.environment(\.editMode, $editMode)
}
}
private func removeItems(_ indexSet: IndexSet) {
reminders.remove(atOffsets: indexSet)
}
private var editButton: some View {
Button(action: {
withAnimation {
editMode = editMode == .active ? .inactive : .active
selection = Set<Reminder>()
}
}) {
Text(editMode == .inactive ? "Edit" : "Done")
}
}
private var deleteButton: some View {
Button(action: deleteNumbers) {
Image(uiImage: editMode == .active ? UIImage(systemName: "trash")! : UIImage.init())
}
}
private func deleteNumbers() {
withAnimation {
for id in selection {
if let index = reminders.lastIndex(where: { $0 == id }) {
reminders.remove(at: index)
}
}
}
selection = Set<Reminder>()
}
}
struct RemindersView_Previews: PreviewProvider {
static var previews: some View {
RemindersView()
}
}
extension RemindersView {
struct ReminderRowView: View {
let reminder: Reminder
init(_ reminder: Reminder) {
self.reminder = reminder
}
var body: some View {
VStack(alignment: .leading) {
Text(reminder.id.description)
.font(.system(size: 22, weight: .medium))
Text("The reminder No. \(reminder.id)")
.fontWeight(.light)
}
.frame(height: 60)
}
}
}
| true
|
3378e91dc993781c6841dd112db59cdcd13f255a
|
Swift
|
FarhanAnsari92/RapydJob
|
/RapydJobs/Job/Create/CreateJobViewModel.swift
|
UTF-8
| 7,564
| 2.75
| 3
|
[] |
no_license
|
//
// CreateJobViewModel.swift
// RapydJobs
//
// Created by Maroof Khan on 03/07/2018.
// Copyright ยฉ 2018 chymps. All rights reserved.
//
import UIKit
import ReactiveSwift
protocol AlertPresenter: class {
func present(alert: UIAlertController)
func presentOptions(selected: @escaping (String) -> Void)
}
final class InputViewModel {
let title: String?
let keyboard: UIKeyboardType
let placeholder: String?
let value: MutableProperty<String>
let error: MutableProperty<String>?
init(title: String?, placeholder: String? = nil, keyboard: UIKeyboardType = .default, value: MutableProperty<String>, error: MutableProperty<String>? = nil) {
self.title = title
self.placeholder = placeholder
self.keyboard = keyboard
self.value = value
self.error = error
}
}
protocol OptionsPresenter: class {
func present<Option>(options: [Option], selected: (Int) -> Void)
}
final class SelectableInputViewModel {
let options: [String]
let title: String
let value: MutableProperty<String>
let openRelatedFields: Bool
weak var presenter: AlertPresenter?
init(title: String, options: [String], value: MutableProperty<String>, openRelatedFields: Bool, presenter: AlertPresenter) {
self.title = title
self.options = options
self.value = value
self.presenter = presenter
self.openRelatedFields = openRelatedFields
}
}
final class SubmitViewModel {
let title: String
let submission: () -> Void
init(title: String, submission: @escaping () -> Void) {
self.title = title
self.submission = submission
}
}
enum Field {
case input(InputViewModel)
case indefiniteInput(InputViewModel)
case range(RangeViewModel)
case selectable(SelectableInputViewModel)
case submit(SubmitViewModel)
}
final class CreateJobViewModel {
class Delegate: NSObject, UITableViewDelegate {
let components: [Field]
init(components: [Field]) {
self.components = components
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
switch components[indexPath.row] {
case .input, .indefiniteInput, .selectable, .range: return 85.0
case .submit: return 55.0
}
}
}
class Datasource: NSObject, UITableViewDataSource {
let components: [Field]
init(components: [Field]) {
self.components = components
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return components.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let content: UIView
switch components[indexPath.row] {
case .input(let vm):
let view = BaseFieldView()
view.viewModel = vm
content = view
case .indefiniteInput(let vm):
let view = BaseFieldView()
view.viewModel = vm
content = view
case .range(let vm):
let view = RangeField()
view.setup(with: vm)
content = view
case .selectable(let vm):
let view = BaseFieldSelectableView()
view.vm = vm
content = view
case .submit(let vm):
let view = BaseButtonView()
view.vm = vm
content = view
}
let cell = UITableViewCell()
cell.contentView.embed(view: content, insets: UIEdgeInsets(top: 10.0, left: 0.0, bottom: 10.0, right: 0.0))
return cell
}
}
let presenter: AlertPresenter
var datasource: Datasource!
var delegate: Delegate!
lazy var service: JobService = {
let service = JobService(delegate: self)
service.delegate = self
return service
}()
let title = MutableProperty<String>("")
let sector = MutableProperty<String>("Job Sector")
let description = MutableProperty<String>("")
let salaryRange = MutableProperty<(Double, Double)>((0, 0))
let shift = MutableProperty<String>("Morning")
let type = MutableProperty<String>("Part Time")
let length = MutableProperty<String>("1 week")
lazy var titleInput = InputViewModel(title: "Job Title", value: title)
lazy var sectorVM = SelectableInputViewModel(title: "Job Sector", options: [], value: sector, openRelatedFields: true, presenter: presenter)
lazy var descriptionInput = InputViewModel(title: "Job Description", value: description)
lazy var salaryRangeVM = RangeViewModel(title: "Salary Range",
minimum: (value: 1, title: "Min. Salary", formatter: { return "\($0)$" }),
maximum: (value: 99, title: "Max. Salary", formatter: { return "\($0)$" }),
range: salaryRange)
lazy var shiftVM = SelectableInputViewModel(title: "Shift Timing", options: ["Morning", "Afternoon", "Evening"], value: shift, openRelatedFields: false, presenter: presenter)
lazy var typeVM = SelectableInputViewModel(title: "Job Type", options: ["Part Time", "Full Time"], value: type, openRelatedFields: false, presenter: presenter)
lazy var lengthVM = SelectableInputViewModel(title: "Length of Contract", options: ["1 week", "2 weeks", "3 weeks", "1 month" , "2 months", "3 months"], value: length, openRelatedFields: false, presenter: presenter)
lazy var submission = SubmitViewModel(title: "Post a job", submission: submit)
lazy var components: [Field] = [
.input(titleInput),
.selectable(sectorVM),
.indefiniteInput(descriptionInput),
.range(salaryRangeVM),
.selectable(shiftVM),
.selectable(typeVM),
.selectable(lengthVM),
.submit(submission)
]
init(presenter: OptionsPresenter & AlertPresenter) {
self.presenter = presenter
self.datasource = Datasource(components: components)
self.delegate = Delegate(components: components)
}
func submit() {
let job = Job(title: title.value, sector: sector.value, description: description.value, salary: salaryRange.value, shift: shift.value, type: type.value, length: length.value)
service.create(job: job)
}
}
extension CreateJobViewModel: JobServiceDelegate {
func failuer(error: NetworkError) {
let alert = UIAlertController(title: "Job creation failed.", message: error.localizedDescription, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
presenter.present(alert: alert)
}
func created() {
let alert = UIAlertController(title: "Job created", message: nil, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { _ in AppRouter.shared.proceed() }))
presenter.present(alert: alert)
}
}
struct Job {
let title: String
let sector: String
let description: String
let salary: (minimum: Double, maximum: Double)
let shift: String
let type: String
let length: String
}
| true
|
aad1d99d7fb880498f819be46bdfce1e09fdecfc
|
Swift
|
rmorbach/CoreMLTest
|
/CoreMLApp/CoreMLApp/Controller/ObjectRecognizer.swift
|
UTF-8
| 513
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
//
// ObjectRecognizer.swift
// CoreMLApp
//
// Created by Rodrigo Morbach on 16/11/17.
// Copyright ยฉ 2017 Rodrigo Morbach. All rights reserved.
//
import UIKit
class ObjectRecognizer: NSObject {
let model = MobileNet()
func predict(image: CVPixelBuffer)->String?{
do{
let input = MobileNetInput(image: image);
let result = try self.model.prediction(input: input)
return result.classLabel;
}catch{
}
return nil
}
}
| true
|
5a538b5ac19ea02e833a5ad9460e8f147bd7d8ac
|
Swift
|
lionelmichaud/Patrimoine
|
/Shared/Model/AppFoundation/BasicStructs.swift
|
UTF-8
| 1,246
| 3.046875
| 3
|
[] |
no_license
|
//
// BasicStructs.swift
// Patrimoine
//
// Created by Lionel MICHAUD on 20/04/2020.
// Copyright ยฉ 2020 Lionel MICHAUD. All rights reserved.
//
import os
import Foundation
import SwiftUI
private let customLog = Logger(subsystem: "me.michaud.lionel.Patrimoine", category: "BasicStructs")
// MARK: - Point(x, y)
struct Point: Codable, ExpressibleByArrayLiteral {
typealias ArrayLiteralElement = Double
var x: Double
var y: Double
init(arrayLiteral elements: Double...) {
self.x = elements[0]
self.y = elements[1]
}
init(_ x: Double, _ y: Double) {
self.x = x
self.y = y
}
}
// MARK: - Ordre de tri
enum SortingOrder {
case ascending
case descending
var imageSystemName: String {
switch self {
case .ascending:
return "arrow.up.circle"
case .descending:
return "arrow.down.circle"
}
}
mutating func toggle() {
switch self {
case .ascending:
self = .descending
case .descending:
self = .ascending
}
}
}
struct BrutNetTaxable {
var brut : Double
var net : Double
var taxable : Double
}
| true
|
a7b7e4f57e42b842563236f85ad3550368e816bb
|
Swift
|
HeHuiqi/HqSwift
|
/MySwift/MySwift/RootVC.swift
|
UTF-8
| 2,307
| 2.703125
| 3
|
[] |
no_license
|
//
// RootVC.swift
// MySwift
//
// Created by macpro on 16/1/27.
// Copyright ยฉ 2016ๅนด macpro. All rights reserved.
//
//ๅฃฐๆๅ่ฎฎๅๅฟ
้กปๅฎ็ฐๅฟ
่ฆ็ๅ่ฎฎๆนๆณ
import UIKit
class RootVC: UIViewController,UITableViewDelegate,UITableViewDataSource,HomeVCDelegate {
var tableView:UITableView?
override func viewDidLoad() {
super.viewDidLoad()
self.title = "RootVC";
tableView = UITableView.init(frame: self.view.frame, style: .grouped);
tableView?.delegate = self;
tableView?.dataSource = self;
self.view.addSubview(tableView!)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let identifier:String = "cell"
var cell = tableView.dequeueReusableCell(withIdentifier: identifier)
if ((cell) == nil)
{
cell = UITableViewCell.init(style: UITableViewCellStyle.default, reuseIdentifier: identifier)
}
cell?.textLabel?.text = String("index\(indexPath.row)")
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
switch indexPath.row {
case 0:
do {
let homeVC = HomeVC();
homeVC.delegate = self;
//้ญๅ
ๅ่ฐ
homeVC.goHomeByCar { (carName) in
print("carName==\(carName)")
}
self.navigationController?.pushViewController(homeVC, animated: true)
}
break
case 1:
do {
let manVC = MainVC();
self.navigationController?.pushViewController(manVC, animated: true)
}
break
default: break
}
}
//MARK: - HomeVCDelegate
func homeChange(_ name: String, location: String) {
print("name==\(name),location==\(location)")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| true
|
81a3fe45ee89be916305310dabde78eb5be05313
|
Swift
|
phys-swift/mandelbrot
|
/Mandelbrot/CGMath.swift
|
UTF-8
| 4,357
| 3.140625
| 3
|
[] |
no_license
|
//
// CGMath.swift
// Mandelbrot
//
// Created by Andrei Frolov on 2018-03-22.
// Copyright ยฉ 2018 SFU Physics Department. All rights reserved.
//
import UIKit
extension CGAffineTransform {
// convenience initializers
init(scale: CGFloat) { self.init(scaleX: scale, y: scale) }
init(shift: CGPoint) { self.init(translationX: shift.x, y: shift.y) }
init(shift: CGSize) { self.init(translationX: shift.width, y: shift.height) }
// principal decomposition Q = rotation(alpha)*diag(p,q)*rotation(beta) + shift
var SVD: (p: CGFloat, q: CGFloat, alpha: CGFloat, beta: CGFloat) {
let phi = atan2(self.b-self.c, self.d+self.a) // alpha + beta
let psi = atan2(self.b+self.c, self.d-self.a) // alpha - beta
let u = (self.a+self.d)/cos(phi) // p + q
let v = (self.a-self.d)/cos(psi) // p - q
return (p: (u+v)/2.0, q: (u-v)/2.0, alpha: (phi+psi)/2.0, beta: (phi-psi)/2.0)
}
// individual parameters
var alpha: CGFloat { return self.SVD.alpha }
var beta: CGFloat { return self.SVD.beta }
var scale: CGPoint { let svd = self.SVD; return CGPoint(x: svd.p, y: svd.q) }
var shift: CGPoint { return CGPoint(x: self.tx, y: self.ty) }
var size: CGSize { return CGSize(width: self.tx, height: self.ty) }
}
// affine transform composition, applied from left to right, i.e. (A*B)(I) = B(A(I))
func *(A: CGAffineTransform, B: CGAffineTransform) -> CGAffineTransform { return A.concatenating(B) }
// single float represents uniform scaling, same associativity rules
func *(A: CGAffineTransform, s: CGFloat) -> CGAffineTransform { return A.concatenating(CGAffineTransform(scale: s)) }
func *(s: CGFloat, A: CGAffineTransform) -> CGAffineTransform { return A.scaledBy(x: s, y: s) }
// scaling of vectors, defined from the right to keep consistent order
func *(p: CGPoint, s: CGFloat) -> CGPoint { return CGPoint(x: p.x*s, y: p.y*s) }
func /(p: CGPoint, s: CGFloat) -> CGPoint { return CGPoint(x: p.x/s, y: p.y/s) }
func *(q: CGSize, s: CGFloat) -> CGSize { return CGSize(width: q.width*s, height: q.height*s) }
func /(q: CGSize, s: CGFloat) -> CGSize { return CGSize(width: q.width/s, height: q.height/s) }
// single vector represents translation, same associativity rules
func +(A: CGAffineTransform, p: CGPoint) -> CGAffineTransform { return A.concatenating(CGAffineTransform(shift: p)) }
func -(A: CGAffineTransform, p: CGPoint) -> CGAffineTransform { return A.concatenating(CGAffineTransform(shift: -p)) }
func +(A: CGAffineTransform, q: CGSize) -> CGAffineTransform { return A.concatenating(CGAffineTransform(shift: q)) }
func -(A: CGAffineTransform, q: CGSize) -> CGAffineTransform { return A.concatenating(CGAffineTransform(shift: -q)) }
func +(p: CGPoint, A: CGAffineTransform) -> CGAffineTransform { return A.translatedBy(x: p.x, y: p.y) }
func +(p: CGSize, A: CGAffineTransform) -> CGAffineTransform { return A.translatedBy(x: p.width, y: p.height) }
// adddition of vectors, commutative
func +(p: CGPoint, q: CGPoint) -> CGPoint { return CGPoint(x: p.x+q.x, y: p.y+q.y) }
func -(p: CGPoint, q: CGPoint) -> CGPoint { return CGPoint(x: p.x-q.x, y: p.y-q.y) }
func +(p: CGPoint, q: CGSize) -> CGPoint { return CGPoint(x: p.x+q.width, y: p.y+q.height) }
func -(p: CGPoint, q: CGSize) -> CGPoint { return CGPoint(x: p.x-q.width, y: p.y-q.height) }
func +(p: CGSize, q: CGSize) -> CGSize { return CGSize(width: p.width+q.width, height: p.height+q.height) }
func -(p: CGSize, q: CGSize) -> CGSize { return CGSize(width: p.width-q.width, height: p.height-q.height) }
// compound assignment operators
func +=(p: inout CGPoint, q: CGPoint) { p.x += q.x; p.y += q.y }
func -=(p: inout CGPoint, q: CGPoint) { p.x -= q.x; p.y -= q.y }
func +=(p: inout CGPoint, q: CGSize) { p.x += q.width; p.y += q.height }
func -=(p: inout CGPoint, q: CGSize) { p.x -= q.width; p.y -= q.height }
func +=(p: inout CGSize, q: CGSize) { p.width += q.width; p.height += q.height }
func -=(p: inout CGSize, q: CGSize) { p.width -= q.width; p.height -= q.height }
// unary operators
prefix func +(p: CGPoint) -> CGPoint { return p }
prefix func +(q: CGSize) -> CGSize { return q }
prefix func -(p: CGPoint) -> CGPoint { return CGPoint(x: -p.x, y: -p.y) }
prefix func -(q: CGSize) -> CGSize { return CGSize(width: -q.width, height: -q.height) }
| true
|
95bc5439fcfd2fd9862d61f3a4683be6a0c2ebc1
|
Swift
|
luizdefranca/Swift-Programming---The-Big-Nerd-Ranch-Guide
|
/Chapter03.playground/Contents.swift
|
UTF-8
| 1,712
| 4.71875
| 5
|
[] |
no_license
|
import UIKit
var str = "Hello, playground"
//***************************
//**** Chapter 03 ***********
//***************************
//Conditionals
//If/Else
let population: Int = 5422
var message : String
if population < 10000 {
message = "\(population) is a small town"
} else {
message = "\(population) is pretty big"
}
print(message)
/*
Comparison operators
Operator Description
< Evaluates whether the value on the left is less than the value on the right.
<= Evaluates whether the value on the left is less than or equal to the value on the right.
> Evaluates whether the value on the left is greater than the value on the right.
>= Evaluates whether the value on the left is greater than or equal to the value on the right.
== Evaluates whether the value on the left is equal to the value on the right.
!= Evaluates whether the value on the left is not equal to the value on the right.
=== Evaluates whether the two references point to the same instance.
!== Evaluates whether the two references do not point to the same instance.
*/
//Define a Boolean constant
let hasPostOffice: Bool = true
if !hasPostOffice {
print("Where do we buy stamps?")
}
if population < 10000 {
message = "\(population) is a small town!"
} else {
message = "\(population) is pretty big!"
}
//Ternary Operator
/*
The ternary operator is very similar to an if/else statement, but it has the more concise syntax
a ? b : c. In English, the ternary operator reads something like,
โIf a is true, then do b. Otherwise, do c."
*/
//Instead use the if
message = population < 10000 ?
"\(population) is a small town!" :
"\(population) is pretty big!"
| true
|
fd05ee12ed77bfcde9796261c5fa56bd8029c5fb
|
Swift
|
William795/Representitives
|
/Representitives/Representitives/Views/RepTableViewCell.swift
|
UTF-8
| 877
| 2.65625
| 3
|
[] |
no_license
|
//
// RepTableViewCell.swift
// Representitives
//
// Created by William Moody on 5/16/19.
// Copyright ยฉ 2019 William Moody. All rights reserved.
//
import UIKit
class RepTableViewCell: UITableViewCell {
var repResults: SearchResults? {
didSet{
updateView()
}
}
@IBOutlet weak var repNameLabel: UILabel!
@IBOutlet weak var repPartyLabel: UILabel!
@IBOutlet weak var repURLLabal: UILabel!
@IBOutlet weak var repSectionLabel: UILabel!
@IBOutlet weak var repPhoneLabel: UILabel!
func updateView(){
guard let represults = repResults else {return}
repNameLabel.text = represults.name
repPartyLabel.text = represults.party
repURLLabal.text = represults.link
repSectionLabel.text = represults.district
repPhoneLabel.text = represults.phone
}
}
| true
|
ba75930b11a6b18486888d3c3ffcf6e7d117d403
|
Swift
|
Kingsuuun/missUnight
|
/swift100-7.playground/Contents.swift
|
UTF-8
| 2,184
| 4.59375
| 5
|
[] |
no_license
|
import UIKit
// ๅๅปบๅบๆฌ็้ญๅ
๏ผ ๅฐๅฝๆฐๅ้
็ปๅ้
let driving = {
print("i'm driving in my car")
}
driving()
// ๅธฆๅๆฐ็้ญๅ
let driving2 = {
( place: String ) in
print("i'm going to \(place) in my car")
}
driving2("NanTong")
// ๅธฆ่ฟๅๅผ็้ญๅ
let drivingWithReturn = {
( place: String ) -> String in
return "i'm going to \(place) in my car"
}
let message = drivingWithReturn("London")
print(message)
// ้ญๅ
ไฝไธบๅๆฐ
func travel(num: Int, action: () -> Void) {
print("i'm getting ready to go to \(num)")
action()
print("i arrived!")
}
travel( num: 2, action: driving)
// ๅฐพ้้ญๅ
่ฏญๆณ ๆฌๆฅๅๆฐๅฐฑๆฏ้ญๅ
่ตไบ็๏ผ็ดๆฅ็็ฅไบ,ไธ้่ฆๆฌๅท้้ขๅ
travel(num: 2) {
print("test two")
}
// ้ญๅ
ๆฅๅๅๆฐๆถ๏ผไฝฟ็จ้ญๅ
ไฝไธบๅๆฐ
func travel1(num: Int, action: (String) -> Void) {
print("i'm getting ready to go to \(num)")
action("London")
print("i arrived!")
}
travel1(num: 1){
(place: String) in
print("use \(place) to do something")
}
// ๆ่ฟๅๅผ็้ญๅ
func travel2(action: (String) -> String) {
print("i'm getting ready to go")
let test = action("nantong")
print(test)
print("end")
}
travel2 {
(place: String) -> String in
return "i'm going to \(place) in my car"
}
// ็ฎๅไปฃ็
travel2 {
"i'm going to \($0) in my car"
}
// ๅ
ทๆๅคไธชๅๆฐ็้ญๅ
func travel3(action: (String, Int) -> String) {
print("travel3 test")
let test = action("London", 60)
print(test)
print("travel3 test end")
}
// ้่ฎฐๅๆฐๅ็งฐๆฏๆ็
ง0ๅผๅง่ฎฐ่ฟฐๅๆฐ็ๆฐ้
travel3 {
"i'm going to \($0) in my car, with \($1) speed"
}
// ไปๅฝๆฐ่ฟๅ้ญๅ
,ๆ่ทๅผ
func travel4() -> (String) -> Void {
var counter = 1
return {
print("\(counter). this is test4 i'm going to \($0)")
counter += 1
}
}
let result4 = travel4()
result4("london")
result4("london")
result4("london")
result4("london")
func login(then action: (String) -> Void) {
print("Authenticating...")
let username = "twostraws"
action(username)
}
login {
place in
print("\(place) it is works")
}
| true
|
1cf80dd546a1bb540ed9b1cbc14148272caecf86
|
Swift
|
marineu/OpenWeatherIos
|
/OpenWeatherIos/Modules/CurrentWeather/Views/SunsetView/DayShapeView.swift
|
UTF-8
| 3,084
| 2.796875
| 3
|
[
"MIT"
] |
permissive
|
//
// DayShapeView.swift
// OpenWeatherIos
//
// Created by Marin Ipati on 03/09/2021.
//
import UIKit
class DayShapeView: UIView {
var nightColor: UIColor? {
didSet {
setNeedsDisplay()
}
}
var daylightColor: UIColor? {
didSet {
setNeedsDisplay()
}
}
var sunColor: UIColor? {
didSet {
setNeedsDisplay()
}
}
var strokeColor: UIColor? {
didSet {
setNeedsDisplay()
}
}
var strokeWidth: CGFloat = 1 {
didSet {
setNeedsDisplay()
}
}
var indicatorsWidth: CGFloat = 0.33 {
didSet {
setNeedsDisplay()
}
}
var sunRadius: CGFloat = 10 {
didSet {
setNeedsDisplay()
}
}
var sunrise: Date {
didSet {
setNeedsDisplay()
}
}
var sunset: Date {
didSet {
setNeedsDisplay()
}
}
var current: Date {
didSet {
setNeedsDisplay()
}
}
var nightPhaseLength: CGFloat {
return xPoint(in: shapeRect, withY: 0.0).x
}
var timeZone: TimeZone = .current {
didSet {
setNeedsDisplay()
}
}
var calendar: Calendar {
var calendar = Calendar.current
calendar.timeZone = timeZone
return calendar
}
var startOfDay: Date {
return calendar.startOfDay(for: current)
}
var endOfDay: Date {
return startOfDay.addingTimeInterval(86340)
}
var isInSameDay: Bool {
let sunsetIsInSameDay = calendar.isDate(current, inSameDayAs: sunset)
let sunriseIsInSameDay = calendar.isDate(current, inSameDayAs: sunrise)
return sunsetIsInSameDay && sunriseIsInSameDay
}
var strength: Double {
return Double(shapeRect.height) * 0.5
}
let frequency: Double = .pi * 2
let phase: Double = .pi / 2
var offset: Double {
return Double(shapeRect.height) * 0.18
}
var shapeRect: CGRect {
return bounds.inset(by: inset)
}
lazy private(set) var inset: UIEdgeInsets = {
return UIEdgeInsets(top: sunRadius, left: 0, bottom: 0, right: 0)
}()
init(sunrise: Date, sunset: Date, current: Date) {
self.sunrise = sunrise
self.sunset = sunset
self.current = current
super.init(frame: .zero)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: CGRect) {
guard let context = UIGraphicsGetCurrentContext() else {
return
}
drawFirstNightPhase(in: rect, context: context)
drawDaylightPhase(in: rect, context: context)
drawSecondNightPhase(in: rect, context: context)
drawSunMovePath(in: rect, context: context)
drawHorizonLine(in: rect, context: context)
drawSunsetSunriseIndicators(in: rect, context: context)
drawSun(in: rect, context: context)
}
}
| true
|
39edb609579044883022b7b63f09f1c06e7b7058
|
Swift
|
vctxr/swift-texture
|
/swift-texture/Models/GiphyResponse.swift
|
UTF-8
| 1,258
| 3.140625
| 3
|
[] |
no_license
|
//
// GiphyResponse.swift
// DemoOperation
//
// Created by Victor Samuel Cuaca on 07/02/21.
//
import Foundation
struct GiphyResponse: Decodable {
var data: [GIF] = []
var pagination: Pagination = Pagination()
}
struct GIF: Decodable {
let urlString: String
@Clamping(50...300) var imageHeight: Int = 0
enum CodingKeys: String, CodingKey {
case images
case imageProperty = "fixed_width"
case urlString = "url"
case height
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let image = try container.nestedContainer(keyedBy: CodingKeys.self, forKey: .images)
let imageProperty = try image.nestedContainer(keyedBy: CodingKeys.self, forKey: .imageProperty)
let decodedUrl = try imageProperty.decode(String.self, forKey: .urlString)
urlString = decodedUrl
imageHeight = Int(try imageProperty.decode(String.self, forKey: .height)) ?? 0
}
}
struct Pagination: Decodable {
var offset: Int = 0
var totalCount: Int = 0
var count: Int = 0
enum CodingKeys: String, CodingKey {
case offset
case totalCount = "total_count"
case count
}
}
| true
|
b602e795f409b69960f926286f9bb81c2d97ee6f
|
Swift
|
binishmaharjan/Hamro-Sahakarya
|
/App/HamroSahakarya/Sources/OnboardingFeature/Views/ColorPickerView/ColorPaletteViewModel.swift
|
UTF-8
| 1,112
| 2.765625
| 3
|
[] |
no_license
|
import Foundation
import RxCocoa
import RxSwift
import UIKit
public enum ColorPaletteEvent {
case selectButtonTapped
case cancelButtonTapped
}
public protocol ColorPaletteViewModelProtocol {
var selectedColorInput: BehaviorRelay<UIColor> { get }
var event: Observable<ColorPaletteEvent> { get }
var selectButtonTapped: Binder<Void> { get }
var cancelButtonTapped: Binder<Void> { get }
}
public final class ColorPaletteViewModel: ColorPaletteViewModelProtocol {
public var selectedColorInput = BehaviorRelay<UIColor>(value: .mainOrange)
private let eventSubject = PublishSubject<ColorPaletteEvent>()
public var event: Observable<ColorPaletteEvent> {
return eventSubject.asObservable()
}
public var selectButtonTapped: Binder<Void> {
return Binder(eventSubject) { observer, _ in
observer.onNext(.selectButtonTapped)
}
}
public var cancelButtonTapped: Binder<Void> {
return Binder(eventSubject) { observer, _ in
observer.onNext(.cancelButtonTapped)
}
}
public init() {}
}
| true
|
9f87d50e290bb5c47c229f495ab3e3ecea35dc30
|
Swift
|
bsorrentino/swiftui-fieldvalidator
|
/Example/FieldValidatorSample/String+Email.swift
|
UTF-8
| 562
| 2.828125
| 3
|
[
"MIT"
] |
permissive
|
//
// String+Email.swift
// FieldValidatorSample
//
// Created by Bartolomeo Sorrentino on 24/08/20.
// Copyright ยฉ 2020 bsorrentino. All rights reserved.
//
import Foundation
let __firstpart = "[A-Z0-9a-z]([A-Z0-9a-z._%+-]{0,30}[A-Z0-9a-z])?"
let __serverpart = "([A-Z0-9a-z]([A-Z0-9a-z-]{0,30}[A-Z0-9a-z])?\\.){1,5}"
let __emailRegex = "\(__firstpart)@\(__serverpart)[A-Za-z]{2,8}"
let __emailPredicate = NSPredicate(format: "SELF MATCHES %@", __emailRegex)
extension String {
func isEmail() -> Bool {
return __emailPredicate.evaluate(with: self)
}
}
| true
|
54615b19cc4d3f8ebec1c7271737aabcefced0bd
|
Swift
|
danissch/CountryFinder
|
/CountryFinder/View/List/CountryListViewController.swift
|
UTF-8
| 7,150
| 2.59375
| 3
|
[] |
no_license
|
//
// CountryListViewController.swift
// CountryFinder
//
// Created by Daniel Duran Schutz on 22/06/21.
//
import UIKit
class CountryListViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var countryListViewModel: CountryListViewModel?
private let heightForCells:CGFloat = 130
private let heightForHeader:CGFloat = 60
private let heightForFooter:CGFloat = 60
let searchBarHeight:Int = 60
var customSearchBar:CustomSearchBar?
var isSearching: Bool = false
var searchTextFieldValue: String = ""
var searchTextFieldIsFirstResponder: Bool = false
override func viewDidLoad() {
super.viewDidLoad()
setupViewModel()
registerViewsTableView()
setSomeCustomConfigurations()
getCountries()
self.hideKeyboardWhenTappedAround()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setNavigationBarHidden(true, animated: animated)
self.tableView.layoutSubviews()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.navigationController?.setNavigationBarHidden(false, animated: animated)
}
override var prefersStatusBarHidden: Bool {
return true
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
if UIDevice.current.orientation.isLandscape {
print("Landscape")
} else { print("Portrait") }
handleSomeOrientationBehaviors()
}
}
// self managament functions
extension CountryListViewController {
func registerViewsTableView(){
let headernib = UINib(nibName: "ListHeaderView", bundle: nil)
tableView.register(headernib, forHeaderFooterViewReuseIdentifier: "listHeaderView")
tableView.register(UINib(nibName: "CountryListTableViewCell", bundle: nil),
forCellReuseIdentifier: "CountryListTableViewCell")
tableView.register(UINib(nibName:"NoRecordsFoundTableViewCell", bundle: nil),
forCellReuseIdentifier: "NoRecordsFoundTableViewCell")
}
func setSomeCustomConfigurations(){
self.tableView.rowHeight = UITableView.automaticDimension
self.tableView.estimatedRowHeight = heightForCells
}
func handleSomeOrientationBehaviors(){
guard let searchTextFieldIsFirstResponder = customSearchBar?.searchTextField.isFirstResponder else { return }
self.searchTextFieldIsFirstResponder = searchTextFieldIsFirstResponder
self.customSearchBar?.searchTextField.resignFirstResponder()
self.tableView.reloadData()
DispatchQueue.main.asyncAfter(deadline: .now(), execute: {
if searchTextFieldIsFirstResponder {
self.customSearchBar?.searchTextField.text = self.searchTextFieldValue
self.customSearchBar?.searchTextField.becomeFirstResponder()
}
})
}
}
//ViewModel Relation
extension CountryListViewController: CountryListViewModelDelegate {
func setupViewModel(){
self.countryListViewModel = CountryListViewModel()
self.countryListViewModel?.delegate = self
}
func getCountries(){
countryListViewModel?.getCountryList()
}
func onCountriesLoaded() {
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
//TableView Relation
extension CountryListViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let countryListCount = self.countryListViewModel?.countryCount()
if isSearching{ return countryListViewModel?.filteredCountryCount() ?? 0 }
return ((countryListCount == 0 ? 1 : countryListCount) ?? 1)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let listCount = isSearching ? countryListViewModel?.filteredCountryCount() : countryListViewModel?.countryCount()
if listCount == 0 {
let noRowsCell = tableView.dequeueReusableCell(withIdentifier: "NoRecordsFoundTableViewCell", for: indexPath) as! NoRecordsFoundTableViewCell
noRowsCell.messageLabel.text = ""
return noRowsCell
}
guard let countryListTableViewCell = tableView.dequeueReusableCell(withIdentifier: "CountryListTableViewCell") as? CountryListTableViewCell else {
return UITableViewCell()
}
if let item = isSearching ? countryListViewModel?.filteredCountryList[indexPath.row] : countryListViewModel?.countryList[indexPath.row] {
countryListTableViewCell.setCellData(country: item)
}
return countryListTableViewCell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return tableView.rowHeight
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = ListHeaderView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: heightForHeader))
headerView.setConfigFromViewController(title: "", view: getSearchBarView() ?? UISearchBar())
return headerView
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return heightForHeader
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return heightForFooter
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let footerView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 70))
footerView.backgroundColor = .clear
return footerView
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let countryCount = countryListViewModel?.countryCount()
if countryCount == 0 { return }
let list = isSearching ? countryListViewModel?.filteredCountryList : countryListViewModel?.countryList
if let dataItem = list?[indexPath.row] {
let vc = CountryDetailViewController.instantiateFromXIB() as CountryDetailViewController
vc.setCountryDetail(country: dataItem)
pushVc(vc, animated: true, navigationBarIsHidden: false)
}
}
}
| true
|
8a03d7b77d81178810899065206acab92bd5aada
|
Swift
|
mohamedayed/ScrumptiousSwiftUI
|
/ScrumptionApp/views/AuthViews/AuthView.swift
|
UTF-8
| 5,445
| 2.625
| 3
|
[] |
no_license
|
//
// AuthView.swift
// ScrumptionApp
//
// Created by mohamed ayed on 3/5/21.
//
import SwiftUI
struct AuthView: View {
@State private var selectedSegment = 0
@Namespace var name
@State private var prsentMain = false
@ObservedObject private var formViewModel = FormRegViewModel()
var body: some View {
NavigationView{
VStack{
VStack(){
Image("logo")
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width:70,height: 70)
HStack{
Button(action:{
withAnimation(.spring()){
selectedSegment = 0
}
}){
VStack{
Text(StringConstants.Login)
.font(.system(size:20))
.foregroundColor((self.selectedSegment == 0) ? Color.black : Color.gray)
ZStack{
Capsule()
.fill(Color.black.opacity(0.1))
.frame(height:4)
if selectedSegment == 0{
Capsule()
.fill(Color.black)
.frame(height:4)
.matchedGeometryEffect(id: "TAP", in: name)
}
}
}
}
Button(action:{
withAnimation(.spring()){
selectedSegment = 1
}
}){
VStack{
Text(StringConstants.Register)
.font(.system(size:20))
.foregroundColor((self.selectedSegment == 1) ? Color.black : Color.gray)
ZStack{
Capsule()
.fill(Color.black.opacity(0.1))
.frame(height:4)
if selectedSegment == 1{
Capsule()
.fill(Color.black)
.frame(height:4)
.matchedGeometryEffect(id: "TAP", in: name)
}
}
}
}
}
HStack {
Text(formViewModel.inlineErrorText)
.font(.caption2)
.foregroundColor(.red)
.padding(.horizontal)
Spacer()
}
}
// .fullScreenCover(isPresented:$formViewModel.IsLoggedIn,content:MainView.init)
.fullScreenCover(isPresented: $formViewModel.IsLoggedIn, content: MainView.init)
.padding(.top,30)
// NavigationLink(
// destination: MainView(),
// isActive: $formViewModel.IsLoggedIn){
// EmptyView()
// }
//
if selectedSegment == 1{
RegisterationView().animation(.spring())
}else{
LoginView().animation(.spring())
}
}.environmentObject(formViewModel)
.navigationBarHidden(true)
}
.statusBar(hidden: true)
}
}
struct AuthView_Previews: PreviewProvider {
static var previews: some View {
AuthView()
}
}
| true
|
f822097140b8814567192e885bc7838ddd495769
|
Swift
|
HarveySun228/swiftDemo
|
/codes/07/7.12/FailableInitTest.swift
|
UTF-8
| 425
| 3.171875
| 3
|
[] |
no_license
|
struct Cat
{
let name: String
init?(name: String) {
// ๅฆๆไผ ๅ
ฅ็nameๅๆฐไธบ็ฉบๅญ็ฌฆไธฒ๏ผๆ้ ๅจๅคฑ่ดฅ๏ผ่ฟๅnil
if name.isEmpty {
return nil
}
self.name = name
}
}
let c1 = Cat(name: "Kitty")
if c1 != nil {
// ๅๅปบc1็ๆ้ ๅจๆฏinit?๏ผๅ ๆญค็จๅบๅฟ
้กปๅฏนc1ๆง่กๅผบๅถ่งฃๆ
println("c1็nameไธบ๏ผ\(c1!.name)")
}
let c2 = Cat(name: "")
println(c2 == nil) // ่พๅบtrue๏ผ่กจๆc2ไธบnil
| true
|
7a202469b2c2bc5226770f1ec6ba129cb10efe83
|
Swift
|
nevenhsu/pokemon
|
/pokemon/PokemonDetailVC.swift
|
UTF-8
| 2,213
| 2.65625
| 3
|
[] |
no_license
|
//
// PokemonDetailVC.swift
// pokemon
//
// Created by Neven on 07/08/2017.
// Copyright ยฉ 2017 Neven. All rights reserved.
//
import UIKit
class PokemonDetailVC: UIViewController {
@IBOutlet weak var nameLbl: UILabel!
@IBOutlet weak var mainImg: UIImageView!
@IBOutlet weak var describeLbl: UILabel!
@IBOutlet weak var defenseLbl: UILabel!
@IBOutlet weak var typeLbl: UILabel!
@IBOutlet weak var heightLbl: UILabel!
@IBOutlet weak var dexLbl: UILabel!
@IBOutlet weak var weightLbl: UILabel!
@IBOutlet weak var attackLbl: UILabel!
@IBOutlet weak var evoLbl: UILabel!
@IBOutlet weak var currentImg: UIImageView!
@IBOutlet weak var nextImg: UIImageView!
var pokemon: Pokemon!
override func viewDidLoad() {
super.viewDidLoad()
nameLbl.text = pokemon.name.capitalized
dexLbl.text = "\(pokemon.dex)"
mainImg.image = UIImage(named: "\(pokemon.dex)")
currentImg.image = UIImage(named: "\(pokemon.dex)")
pokemon.downloadJson {
// update ui info
self.updateUI()
}
}
func updateUI() {
defenseLbl.text = "\(pokemon.defense)"
attackLbl.text = "\(pokemon.attack)"
weightLbl.text = pokemon.weight
heightLbl.text = pokemon.height
typeLbl.text = pokemon.type
describeLbl.text = pokemon.describe
if pokemon.evoId != "0" {
evoLbl.text = "Next Evolution: \(pokemon.evoName) LVL \(pokemon.evoLevel)"
nextImg.isHidden = false
nextImg.image = UIImage(named: pokemon.evoId)
} else {
nextImg.isHidden = true
evoLbl.text = "Mega Evolution"
}
}
@IBAction func backBtnPressed(_ sender: UIButton) {
dismiss(animated: true, completion: nil)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| true
|
8a04b6a0243fd17d34b14b3bda9de51177a823bf
|
Swift
|
prashannaraghavan/SwiftMarathon
|
/CommandLine/MathFunctions/MathFunctions/main.swift
|
UTF-8
| 526
| 3.40625
| 3
|
[] |
no_license
|
//
// main.swift
// MathFunctions
//
// Created by Prashanna Raghavan on 7/10/17.
// Copyright ยฉ 2017 ASU. All rights reserved.
//
import Foundation
var prime = Prime(100)
let sqrtOf = Root()
print(sqrtOf.squareRoot(25))
var lcm = LCM()
print(lcm.lcm(45, 9))
print(lcm.gcd(45, 9))
let fib = Fib(10)
fib.fib(10)
fib.display()
var fibonacci = Fibonacci()
print(fibonacci.fib(10))
let p = Power()
print(p.power(3, 2))
let per = Permutation()
print("Permutation : \(per.nPr(10, 4))")
print("Combination : \(per.nCr(10, 2))")
| true
|
0bedc4ff857053b2789aedc5695e7854f501e12e
|
Swift
|
jphouminh71/iOSDev
|
/SwiftUI/I Am Rich/I Am Rich/ContentView.swift
|
UTF-8
| 1,023
| 3.109375
| 3
|
[] |
no_license
|
//
// ContentView.swift
// I Am Rich
//
// Created by Jonathan Phouminh on 1/26/21.
// Copyright ยฉ 2021 Jonathan Phouminh. All rights reserved.
//
import SwiftUI
/* This is the code that we see when our app is rendering */
struct ContentView: View {
var body: some View {
ZStack{ // Z stack layers the elements
Color(.systemTeal)
.edgesIgnoringSafeArea(.all)
VStack() {
Text("I Am Rich")
.font(.system(size: 40))
.fontWeight(.bold)
.foregroundColor(Color.white)
Image("diamond").resizable().aspectRatio(contentMode: .fit)
.frame(width: 200.0, height: 200.0, alignment: .center)
}
}
}
}
/* This is the code that handles the simulator that we see on the right*/
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView().previewDevice(PreviewDevice(rawValue: "iPhone 11"))
}
}
| true
|
e2df2e0583101ec6902aba6d05424d169189c80e
|
Swift
|
bhudelson/Bluffer
|
/Bluffer/CategoryViewController.swift
|
UTF-8
| 6,286
| 2.59375
| 3
|
[] |
no_license
|
//
// CategoryViewController.swift
// Bluffer
//
// Created by Mariya on 2/25/16.
// Copyright ยฉ 2016 Blake Hudelson. All rights reserved.
//
import UIKit
class CategoryViewController: UIViewController {
//OUTLETS
@IBOutlet weak var tropicsButton: UIButton!
@IBOutlet weak var randomButton: UIButton!
@IBOutlet weak var eightiesButton: UIButton!
@IBOutlet weak var spaceButton: UIButton!
@IBOutlet weak var animalsButton: UIButton!
@IBOutlet weak var politicsButton: UIButton!
@IBOutlet weak var politicsLabel: UILabel!
@IBOutlet weak var randomLabel: UILabel!
@IBOutlet weak var animalsLabel: UILabel!
@IBOutlet weak var spaceLabel: UILabel!
@IBOutlet weak var eightiesLabel: UILabel!
@IBOutlet weak var tropicsLabel: UILabel!
//VARIABLES
var gameViewController: GameViewController!
override func viewDidLoad() {
super.viewDidLoad()
print("Category View Controller Loaded")
print("Category Selected: ", category)
//set icon alpha to 0
politicsButton.alpha = 0
randomButton.alpha = 0
animalsButton.alpha = 0
spaceButton.alpha = 0
eightiesButton.alpha = 0
tropicsButton.alpha = 0
//set labels alpha to 0
politicsLabel.alpha = 0
randomLabel.alpha = 0
animalsLabel.alpha = 0
spaceLabel.alpha = 0
eightiesLabel.alpha = 0
tropicsLabel.alpha = 0
//set original scale to small
politicsButton.transform = CGAffineTransformMakeScale(0.2, 0.2)
randomButton.transform = CGAffineTransformMakeScale(0.2, 0.2)
animalsButton.transform = CGAffineTransformMakeScale(0.2, 0.2)
spaceButton.transform = CGAffineTransformMakeScale(0.2, 0.2)
eightiesButton.transform = CGAffineTransformMakeScale(0.2, 0.2)
tropicsButton.transform = CGAffineTransformMakeScale(0.2, 0.2)
}
override func viewDidAppear(animated: Bool) {
print("Category View Controller Did Appear")
// first icon
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.politicsButton.transform = CGAffineTransformMakeScale(1,1)
self.politicsButton.alpha=1
})
// second icon
delay(0.1) { () -> () in
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.randomButton.transform = CGAffineTransformMakeScale(1,1)
self.randomButton.alpha = 1
})
}
// third icon
delay(0.2) { () -> () in
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.animalsButton.transform = CGAffineTransformMakeScale(1,1)
self.animalsButton.alpha = 1
})
}
// fourth icon
delay(0.3) { () -> () in
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.spaceButton.transform = CGAffineTransformMakeScale(1,1)
self.spaceButton.alpha = 1
})
}
// fifth icon
delay(0.4) { () -> () in
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.eightiesButton.transform = CGAffineTransformMakeScale(1,1)
self.eightiesButton.alpha = 1
})
}
// sixth icon
delay(0.5) { () -> () in
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.tropicsButton.transform = CGAffineTransformMakeScale(1,1)
self.tropicsButton.alpha = 1
})
}
// labels
delay(0.8) { () -> () in
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.politicsLabel.alpha = 1
self.randomLabel.alpha = 1
self.animalsLabel.alpha = 1
self.spaceLabel.alpha = 1
self.eightiesLabel.alpha = 1
self.tropicsLabel.alpha = 1
})
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func selectPolitics(sender: AnyObject) {
category = "politics"
print("Category Selected: ", category)
// Start the game in GameViewController
gameViewController.categorySelected()
}
@IBAction func selectAnimals(sender: AnyObject) {
category = "animals"
print("Category Selected: ", category)
// Start the game in GameViewController
gameViewController.categorySelected()
}
@IBAction func selectSpace(sender: AnyObject) {
category = "space"
print("Category Selected: ", category)
// Start the game in GameViewController
gameViewController.categorySelected()
}
@IBAction func selectRandom(sender: AnyObject) {
category = "random"
print("Category Selected: ", category)
// Start the game in GameViewController
gameViewController.categorySelected()
}
@IBAction func selectTropical(sender: AnyObject) {
category = "tropical"
print("Category Selected: ", category)
// Start the game in GameViewController
gameViewController.categorySelected()
}
@IBAction func selectEighties(sender: AnyObject) {
category = "eighties"
print("Category Selected: ", category)
// Start the game in GameViewController
gameViewController.categorySelected()
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| true
|
2e66bf06eaa173a7853985c2b4b1f8c5cbff2f5d
|
Swift
|
vapor/fluent-kit
|
/Sources/FluentKit/Schema/DatabaseSchema.swift
|
UTF-8
| 6,837
| 3.125
| 3
|
[
"MIT"
] |
permissive
|
import struct Foundation.Date
import struct Foundation.UUID
public struct DatabaseSchema {
public enum Action {
case create
case update
case delete
}
public indirect enum DataType {
public static var int: DataType {
return .int64
}
case int8
case int16
case int32
case int64
public static var uint: DataType {
return .uint64
}
case uint8
case uint16
case uint32
case uint64
case bool
public struct Enum {
public var name: String
public var cases: [String]
public init(name: String, cases: [String]) {
self.name = name
self.cases = cases
}
}
case `enum`(Enum)
case string
case time
case date
case datetime
case float
case double
case data
case uuid
public static var json: DataType {
.dictionary
}
public static var dictionary: DataType {
.dictionary(of: nil)
}
case dictionary(of: DataType?)
public static var array: DataType {
.array(of: nil)
}
case array(of: DataType?)
case custom(Any)
}
public enum FieldConstraint {
public static func references(
_ schema: String,
space: String? = nil,
_ field: FieldKey,
onDelete: ForeignKeyAction = .noAction,
onUpdate: ForeignKeyAction = .noAction
) -> Self {
.foreignKey(
schema,
space: space,
.key(field),
onDelete: onDelete,
onUpdate: onUpdate
)
}
case required
case identifier(auto: Bool)
case foreignKey(
_ schema: String,
space: String? = nil,
_ field: FieldName,
onDelete: ForeignKeyAction,
onUpdate: ForeignKeyAction
)
case custom(Any)
}
public enum Constraint {
case constraint(ConstraintAlgorithm, name: String?)
case custom(Any)
}
public enum ConstraintAlgorithm {
case unique(fields: [FieldName])
case foreignKey(
_ fields: [FieldName],
_ schema: String,
space: String? = nil,
_ foreign: [FieldName],
onDelete: ForeignKeyAction,
onUpdate: ForeignKeyAction
)
case compositeIdentifier(_ fields: [FieldName])
case custom(Any)
}
public enum ForeignKeyAction {
case noAction
case restrict
case cascade
case setNull
case setDefault
}
public enum FieldDefinition {
case definition(
name: FieldName,
dataType: DataType,
constraints: [FieldConstraint]
)
case custom(Any)
}
public enum FieldUpdate {
case dataType(name: FieldName, dataType: DataType)
case custom(Any)
}
public enum FieldName {
case key(FieldKey)
case custom(Any)
}
public enum ConstraintDelete {
case constraint(ConstraintAlgorithm)
case name(String)
case custom(Any)
/// Deletion specifier for an explicitly-named constraint known to be a referential constraint.
///
/// Certain old versions of certain databases (I'm looking at you, MySQL 5.7...) do not support dropping
/// a `FOREIGN KEY` constraint by name without knowing ahead of time that it is a foreign key. When an
/// unfortunate user runs into this, the options are:
///
/// - Trap the resulting error and retry. This is exceptionally awkward to handle automatically, and can
/// lead to retry loops if multiple deletions are specified in a single operation.
/// - Force the user to issue a raw SQL query instead. This is obviously undesirable.
/// - Force an upgrade of the underlying database. No one should be using MySQL 5.7 anymore, but Fluent
/// recognizes that this isn't always under the user's control.
/// - Require the user to specify the deletion with ``constraint(_:)``, providing the complete, accurate,
/// and current definition of the foreign key. This is information the user may not even know, and
/// certainly should not be forced to repeat here.
/// - Provide a means for the user to specify that a given constraint to be deleted by name is known to be
/// a foreign key. For databases which _don't_ suffer from this particular syntactical issue (so, almost
/// everything), this is exactly the same as specifying ``name(_:)``.
///
/// In short, this is the marginal best choice from a list of really bad choices - an ugly, backhanded
/// workaround for MySQL 5.7 users.
///
/// > Note: A static method is provided rather than a new `enum` case because adding new cases to a public
/// > enum without library evolution enabled (which only the stdlib can do) is a source compatibility break
/// > and requires a `semver-major` version bump. This rule is often ignored, but ignoring it doesn't make
/// > the problem moot.
public static func namedForeignKey(_ name: String) -> ConstraintDelete {
self.custom(_ForeignKeyByNameExtension(name: name))
}
}
public var action: Action
public var schema: String
public var space: String?
public var createFields: [FieldDefinition]
public var updateFields: [FieldUpdate]
public var deleteFields: [FieldName]
public var createConstraints: [Constraint]
public var deleteConstraints: [ConstraintDelete]
public var exclusiveCreate: Bool
public init(schema: String, space: String? = nil) {
self.action = .create
self.schema = schema
self.space = space
self.createFields = []
self.updateFields = []
self.deleteFields = []
self.createConstraints = []
self.deleteConstraints = []
self.exclusiveCreate = true
}
}
extension DatabaseSchema.ConstraintDelete {
/// For internal use only.
///
/// Do not use this type directly; it's only public because FluentSQL needs to be able to get at it.
/// The use of `@_spi` will be replaced with the `package` modifier once a suitable minimum version
/// of Swift becomes required.
@_spi(FluentSQLSPI)
public/*package*/ struct _ForeignKeyByNameExtension {
public/*package*/ let name: String
}
}
| true
|
2eae7a9becab469ffd0c8241f1ebd73cccb5ae05
|
Swift
|
beyond2021/MyWeather
|
/MyWeather/WeatherModel.swift
|
UTF-8
| 2,808
| 2.671875
| 3
|
[] |
no_license
|
//
// WeatherModel.swift
// MyWeather
//
// Created by KEEVIN MITCHELL on 10/31/15.
// Copyright ยฉ 2015 Beyond 2021. All rights reserved.
//
import Foundation
class WeatherModel : NSObject {
let zip : String?
let elevation : String?
let state_name : String?
let observation_time : String?
let weather : String?
let temperature_string : String?
let relative_humidity : String?
let wind_string : String?
let wind_dir : String?
let dewpoint_string : String?
let feelslike_string : String?
let visibility_mi : String?
let precip_1hr_in : String?
let icon : String?
let icon_url : String?
let forecast_url : String?
let history_url : String?
struct WeatherConstants {
static let zip = "zip"
static let elevation = "elevation"
static let state_name = "state_name"
static let observation_time = "observation_time"
static let weather = "weather"
static let temperature_string = "temperature_string"
static let relative_humidity = "relative_humidity"
static let wind_string = "wind_string"
static let wind_dir = "wind_dir"
static let dewpoint_string = "dewpoint_string"
static let feelslike_string = "feelslike_string"
static let visibility_mi = "visibility_mi"
static let precip_1hr_in = "precip_1hr_in"
static let icon = "icon"
static let icon_url = "icon_url"
static let forecast_url = "forecast_url"
static let history_url = "history_url"
}
// Initializer
init(zip : String?, elevation : String?, state_name : String?, observation_time : String?, weather : String?, temperature_string : String?, relative_humidity : String?, wind_string : String?, wind_dir : String?, dewpoint_string : String?, feelslike_string : String?, visibility_mi : String?, precip_1hr_in : String?, icon : String?, icon_url : String?, forecast_url : String?, let history_url : String?) {
self.zip = zip ?? ""
self.elevation = elevation ?? ""
self.state_name = state_name ?? ""
self.observation_time = observation_time ?? ""
self.weather = weather ?? ""
self.temperature_string = temperature_string ?? ""
self.relative_humidity = relative_humidity ?? ""
self.wind_string = wind_string ?? ""
self.wind_dir = wind_dir ?? ""
self.dewpoint_string = dewpoint_string ?? ""
self.feelslike_string = feelslike_string ?? ""
self.visibility_mi = visibility_mi ?? ""
self.precip_1hr_in = precip_1hr_in ?? ""
self.icon = icon ?? ""
self.icon_url = icon_url ?? ""
self.forecast_url = forecast_url ?? ""
self.history_url = history_url ?? ""
}
}
| true
|
8ffb8d4c560ddc43dcf2c65b98ea0f89d09810d2
|
Swift
|
titixu/MoneyMeCodeChallenge
|
/MoneyMeCodeChallenge/LoanDetailView.swift
|
UTF-8
| 4,492
| 2.71875
| 3
|
[] |
no_license
|
// Copyright ยฉ 2019 Sam Xu. All rights reserved.
//
import SwiftUI
import Combine
struct LoanDetailView: View {
@EnvironmentObject var viewModel: LoanDetailViewModel
@State private var isPresentingSheet = false
@State private var isPresentingAlert = false
// edit user detail
@State var editing = false
private let space: CGFloat = 30.0
var body: some View {
NavigationView {
ScrollView {
VStack(alignment: .center, spacing: space) {
userGroup()
Spacer()
loanGroup()
if !editing {
Button("Apply Now") {
self.isPresentingAlert = true
}
} else {
Spacer()
}
}.padding(space)
}.navigationBarTitle("Your qoute", displayMode: .inline)
}
// Present Loan view Sheet
.sheet(isPresented: $isPresentingSheet) {
Group {
VStack(alignment: .center, spacing: 30) {
Text("Your Quote")
LoanEditingView().environmentObject(LoanViewModel(loan: self.viewModel.loan))
}.padding()
Spacer()
}
}
.alert(isPresented: $isPresentingAlert) {
Alert(title: Text("Your Application is Successful"))
}
}
private func userGroup() -> some View {
Group {
Spacer()
HStack {
Text("Your information")
Spacer()
Button(action: {
self.editing.toggle()
}) {
if editing {
Text("Done")
} else {
Text("Edit")
}
}
}
HStack {
Text("Name")
Spacer()
textField("Name", binding: $viewModel.user.name)
}
HStack {
Text("Mobile")
Spacer()
textField("Mobile", binding: $viewModel.user.phone)
}
HStack {
Text("Email")
Spacer()
textField("Email", binding: $viewModel.user.email)
}
}
.multilineTextAlignment(.trailing) // trailing for TextField's text
.textFieldStyle(RoundedBorderTextFieldStyle.Member.roundedBorder)
}
private func textField(_ name: String, binding: Binding<String>) -> some View {
Group {
if editing {
TextField(name, text: binding)
} else {
Text(binding.value)
}
}
}
private func loanGroup() -> some View {
Group {
if editing {
Spacer()
} else {
HStack {
Text("Finance Detail")
Spacer()
Button("Edit") {
self.isPresentingSheet = true
}
}
HStack {
Text("Finance amount")
Spacer()
Text(viewModel.loan.presentValue.currencyString)
}
HStack {
Spacer()
Text("over \(viewModel.loan.numberOfPayments.monthString)").padding(.top, -20)
}
HStack {
Text("Repayments from")
Spacer()
Text(LoanCalculator().pmt(loan: viewModel.loan).currencyString)
}
HStack {
Spacer()
Text("Monthly").padding(.top, -20)
}
}
}
}
}
#if DEBUG
struct LoanDetailView_Previews : PreviewProvider {
static var previews: some View {
let viewModel = LoanDetailViewModel(loan: Loan.standard(),
user: UserDefaults.standard.user ?? User.sample(),
storage: UserDefaults.standard)
return LoanDetailView().environmentObject(viewModel)
}
}
#endif
| true
|
58c09a50ff9c20f7f2e749e74cc3b3a5159b8cc7
|
Swift
|
anshulsolanki89/PDHProject
|
/PDH/Common/BasePDHClasses/PDHViewController.swift
|
UTF-8
| 1,123
| 2.53125
| 3
|
[] |
no_license
|
//
// PDHViewController.swift
// PDH
//
// Created by Ellan Jesse on 12/27/15.
// Copyright ยฉ 2015 Ellan Jesse. All rights reserved.
//
import UIKit
class PDHViewController: UIViewController {
override func awakeFromNib() {
super.awakeFromNib()
}
func showAlert(message: String) {
let alert = PDHErrorAlert.showErrorAlert(message)
self.presentViewController(alert, animated: true) { () -> Void in
}
}
func showFormFieldError() {
showAlert("Please check the data entered by you, text field cannot be empty.")
}
}
// MARK:- DataManager Protocol
extension PDHViewController: PDHDataManagerProtocol {
func didReceiveDataWithError(response: AnyObject?) {
PDHProgressIndicator.hideLoadingIndicator()
if let response = response as? PDHErrorObject {
showAlert(response.errorMessage)
} else {
showAlert("Something wrong happened, Please try after some time.")
}
}
func didFailWithError(error: String) {
PDHProgressIndicator.hideLoadingIndicator()
showAlert(error)
}
}
| true
|
814e47e2e0359abd0429cf0032940f4d3692fac0
|
Swift
|
eigengo/lift
|
/ios/LiftTests/Device/SensorData+Test.swift
|
UTF-8
| 1,379
| 3.390625
| 3
|
[
"Apache-2.0"
] |
permissive
|
import Foundation
///
/// Convenience test extension to SensorData to allow us to manipulate it using string payloads
///
extension SensorData {
///
/// Construct SensorData from the given string ``s`` at the starting ``time``
///
class func fromString(s: String, startingAt time: CFAbsoluteTime) -> SensorData {
return SensorData(startTime: time, samples: s.dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: false)!)
}
///
/// Interpret the ``samples`` as ``String``
///
func asString() -> String {
println(self)
return NSString(data: samples, encoding: NSASCIIStringEncoding)!
}
}
///
/// Equatable implementation for SensorDataArray
///
extension SensorDataArray : Equatable {
}
func ==(lhs: SensorDataArray, rhs: SensorDataArray) -> Bool {
if lhs.header == rhs.header {
if lhs.sensorDatas.count != rhs.sensorDatas.count { return false }
for (i, lsd) in enumerate(lhs.sensorDatas) {
let rsd = rhs.sensorDatas[i]
if lsd != rsd { return false }
}
return true
}
return false
}
///
/// Equatable implementation for SensorData
///
extension SensorData : Equatable {
}
func ==(lhs: SensorData, rhs: SensorData) -> Bool {
return lhs.startTime =~= rhs.startTime && lhs.samples.isEqualToData(rhs.samples)
}
| true
|
3c7d426255dfe49db347e2b04a83e6182b3d7437
|
Swift
|
Abhinav012/MBTA
|
/MBTA/MBTA/Model/Noticeboard.swift
|
UTF-8
| 1,428
| 2.78125
| 3
|
[] |
no_license
|
//
// Noticeboard.swift
// MBTA
//
// Created by Abhinav Verma on 18/02/20.
// Copyright ยฉ 2020 Abhinav Verma. All rights reserved.
//
import Foundation
struct Noticeboard: Codable{
var data : Notice?
var success: String?
}
struct Notice: Codable{
var id: String?
var notice1 : String?
var notice2 : String?
var notice3 : String?
var notice4 : String?
var notice5 : String?
var notice6 : String?
var notice7 : String?
var notice8 : String?
var notice9 : String?
var notice10 : String?
var updatedDate: String?
enum CodingKeys: String, CodingKey{
case updatedDate = "updated_date"
case id = "id"
case notice1 = "notice1"
case notice2 = "notice2"
case notice3 = "notice3"
case notice4 = "notice4"
case notice5 = "notice5"
case notice6 = "notice6"
case notice7 = "notice7"
case notice8 = "notice8"
case notice9 = "notice9"
case notice10 = "notice10"
}
func concatNotices()->String{
return """
\(notice1 ?? "")
\(notice2 ?? "")
\(notice3 ?? "")
\(notice4 ?? "")
\(notice5 ?? "")
\(notice6 ?? "")
\(notice7 ?? "")
\(notice8 ?? "")
\(notice9 ?? "")
\(notice10 ?? "")
"""
}
}
| true
|
4d6309780f988e46e9902ba7bded06955f9c3335
|
Swift
|
Krishnamurtyp/FlightBookingApp-iOS
|
/BookMadi/ViewModel/BookingViewModel.swift
|
UTF-8
| 4,321
| 2.65625
| 3
|
[
"MIT"
] |
permissive
|
//
// BookingViewModel.swift
// BookMadi
//
// Created by Siddhant Mishra on 06/02/21.
//
import Foundation
import UIKit
class BookingViewModel {
func getTitleColor(object:Any, keyPath:String)->UIColor{
if let btn = object as? UIButton{
if let value = Int((btn.titleLabel?.text)!){
if value > 0 {
return Constants.textColor!
}
return Constants.nonSelectedColor!
}
}
return Constants.nonSelectedColor!
}
func getAllDates(to:Date)->[Date]{
let allDates = Date.allDates(from: Date(), to: to.add(component: .day, value: 31)!)
return allDates
}
func getAttributedString(spacing:CGFloat,sender:String,placeName:String, cityId:String)->NSMutableAttributedString?{
let style = NSMutableParagraphStyle()
if sender == "Source"{
style.alignment = .left
}else{
style.alignment = .right
}
style.lineSpacing = spacing
style.lineBreakMode = .byWordWrapping
guard
let medium = UIFont(name: "HelveticaNeue-Medium", size: 16),
let light = UIFont(name: "HelveticaNeue-Medium", size: 14) else { return nil}
let keyAttributes: [NSAttributedString.Key: Any] = [.font:medium ,
.paragraphStyle: style,
.foregroundColor:Constants.primaryColor!]
let valueAttributes: [NSAttributedString.Key: Any] = [.font: light,
.paragraphStyle: style,
.foregroundColor:Constants.primaryColor!.withAlphaComponent(0.75)]
let attString = NSMutableAttributedString()
attString.append(NSAttributedString(string: placeName , attributes: keyAttributes))
attString.append(NSAttributedString(string: "\n"))
attString.append(NSAttributedString(string: cityId.replacingOccurrences(of: "-sky", with: "") , attributes: valueAttributes))
return attString
}
func getDepartAttribString(align:String,str1:String,str2:String,str1Color:UIColor,str2Color:UIColor,str1Font:UIFont,str2Font:UIFont,nextLine:Bool)->NSMutableAttributedString?{
let style = NSMutableParagraphStyle()
if align == "left"{
style.alignment = .left
}else{
style.alignment = .right
}
style.lineSpacing = 1.2
style.lineBreakMode = .byWordWrapping
let keyAttributes: [NSAttributedString.Key: Any] = [.font:str1Font ,
.paragraphStyle: style,
.foregroundColor:str1Color]
let valueAttributes: [NSAttributedString.Key: Any] = [.font: str2Font,
.paragraphStyle: style,
.foregroundColor:str2Color]
let attString = NSMutableAttributedString()
attString.append(NSAttributedString(string: str1 , attributes: keyAttributes))
if nextLine {
attString.append(NSAttributedString(string: "\n"))
}
attString.append(NSAttributedString(string: str2 , attributes: valueAttributes))
return attString
}
func searchPlace(place:String,handler:@escaping([searchPlaces]?,ServerError?)->Void){
ServerManager.sharedInstance.getPlace(place) { (response, error) in
if let err = error{
handler(nil,err)
}else{
handler(response,nil)
}
}
}
func fetchFlightPrices(request:FlightQuoteRequest,handler:@escaping(FlightQuote?,ServerError?)->Void){
ServerManager.sharedInstance.getFlightQuotes(request) { (response, error) in
if let err = error{
handler(nil,err)
}else{
handler(response,nil)
}
}
}
}
| true
|
17b7ec0d908e2dee0c87e41d3a5deebd4fb88691
|
Swift
|
SleekDiamond41/CodablePackage
|
/Tests/CodableDataTests/UpdateBlockTests.swift
|
UTF-8
| 3,971
| 2.6875
| 3
|
[
"MIT"
] |
permissive
|
//
// UpdateBlockTests.swift
//
//
// Created by Michael Arrington on 9/14/20.
//
import XCTest
@testable import CodableData
class UpdateBlockTests: XCTestCase {
var db: Database!
var model = Name(id: UUID(), first: "Johnny", last: "Appleseed")
override func setUpWithError() throws {
super.setUp()
db = try Database(filename: "UpdateBlockTests")
try db.save(model)
}
override func tearDownWithError() throws {
try db?.deleteTheWholeDangDatabase()
db = nil
super.tearDown()
}
func testNoModelsToUpdate() throws {
let filter = Filter<Name>()
// remove existing stuff from the database
try db.delete(with: filter)
XCTAssertEqual(try db.count(with: filter), 0)
let update = Update<Name>(UUID())
.set(\.first, to: "Jimmy")
try db.update(update.toAnyUpdate())
// make sure we didn't accidentally add a row to the database
XCTAssertEqual(try db.count(with: filter), 0)
}
func testMultipleRows() throws {
let firstName = "George"
let otherName = Name(id: UUID(), first: "Jimmy", last: "Orangeseed")
// setup for the test
try db.save(otherName)
// filter that should apply to all rows in the table
let filter = Filter<Name>()
.sort(by: \.last)
.limit(5)
let update = Update<Name>(filter)
.set(\.first, to: firstName)
try db.update(update.toAnyUpdate())
let results = try db.get(with: filter)
XCTAssertEqual(results.count, 2)
for result in results {
XCTAssertEqual(result.first, firstName)
}
}
func testNoValues() throws {
let update = Update<Name>(model.id)
try db.update(update.toAnyUpdate())
let filter = Filter<Name>()
let results = try db.get(with: filter)
XCTAssertEqual(results.count, 1)
XCTAssertEqual(results.first?.id, model.id)
XCTAssertEqual(results.first?.first, model.first)
XCTAssertEqual(results.first?.last, model.last)
XCTAssertEqual(results.first?.age, model.age)
}
func testOneValue() throws {
let firstName = "Jimmy"
let update = Update<Name>(model.id)
.set(\.first, to: firstName)
try db.update(update.toAnyUpdate())
let filter = Filter<Name>()
let results = try db.get(with: filter)
XCTAssertEqual(results.count, 1)
XCTAssertEqual(results.first?.id, model.id)
XCTAssertEqual(results.first?.first, firstName)
XCTAssertEqual(results.first?.last, model.last)
XCTAssertEqual(results.first?.age, model.age)
}
func testManyValues() throws {
let firstName = "Jimmy"
let lastName = "Orangeseed"
let update = Update<Name>(model.id)
.set(\.first, to: firstName)
.set(\.last, to: lastName)
try db.update(update.toAnyUpdate())
let filter = Filter<Name>()
let results = try db.get(with: filter)
XCTAssertEqual(results.count, 1)
XCTAssertEqual(results.first?.id, model.id)
XCTAssertEqual(results.first?.first, firstName)
XCTAssertEqual(results.first?.last, lastName)
XCTAssertEqual(results.first?.age, model.age)
}
func testDuplicateValues() throws {
let tempFirstName = "J"
let firstName = "Jimmy"
let update = Update<Name>(model.id)
.set(\.first, to: tempFirstName)
.set(\.first, to: firstName)
try db.update(update.toAnyUpdate())
let filter = Filter<Name>()
let results = try db.get(with: filter)
XCTAssertEqual(results.count, 1)
XCTAssertEqual(results.first?.id, model.id)
XCTAssertEqual(results.first?.first, firstName)
XCTAssertEqual(results.first?.last, model.last)
XCTAssertEqual(results.first?.age, model.age)
}
func testNewColumn() throws {
let age = 482
let update = Update<Name>(model.id)
.set(\.age, to: age)
try db.update(update.toAnyUpdate())
let filter = Filter<Name>()
let results = try db.get(with: filter)
XCTAssertEqual(results.count, 1)
XCTAssertEqual(results.first?.id, model.id)
XCTAssertEqual(results.first?.first, model.first)
XCTAssertEqual(results.first?.last, model.last)
XCTAssertEqual(results.first?.age, age)
}
}
| true
|
0ac40637bd7cfc513c93491fe205c7f3bbf2da12
|
Swift
|
tomokisun/Daily_App
|
/25/25/ViewController.swift
|
UTF-8
| 1,884
| 3.046875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// 25
//
// Created by ็ฏๅฑฑๆ็ด on 2019/02/19.
// Copyright ยฉ 2019 tomoki. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
private var questionArray = [Any]()
@IBOutlet private weak var questionTextView: UITextView!
@IBOutlet private weak var choiceButton1: UIButton!
@IBOutlet private weak var choiceButton2: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
var tmpArray = [Any]()
tmpArray.append(["็ ๆฐใฏใใใพใใ๏ผ", "ใใ", "ใชใ"])
tmpArray.append(["ไฝใฏ็ใใงใใ๏ผ", "ใฏใ", "ใใใ"])
tmpArray.append(["ใใๆฐใๅบใชใใงใใ๏ผ", "ใฏใ", "ใใใ"])
tmpArray.append(["ใญใฌใใใซใชใใพใใ๏ผ", "ใฏใ", "ใใใ"])
tmpArray.append(["ไธๅฎใซใใใใพใใ๏ผ", "ใฏใ", "ใใใ"])
while (tmpArray.count > 0) {
let index = Int(arc4random()) % tmpArray.count
questionArray.append(tmpArray[index])
tmpArray.remove(at: index)
}
choiceQuiz()
}
func choiceQuiz() {
//ไธๆ็ใซใฏใคใบใๅใๅบใ้
ๅ
let tmpArray = questionArray[0] as! [Any]
//ๅ้กๆใฎใใญในใใ่กจ็คบ
questionTextView.text = tmpArray[0] as! String
//้ธๆ่ขใใฟใณใซใใใใ้ธๆ่ขใฎใใญในใใใปใใ
choiceButton1.setTitle(tmpArray[1] as? String, for: .normal)
choiceButton2.setTitle(tmpArray[2] as? String, for: .normal)
}
@IBAction func choiceAnswer() {
questionArray.remove(at: 0)
if questionArray.count == 0 {
self.performSegue(withIdentifier: "to", sender: nil)
} else {
choiceQuiz()
}
}
}
| true
|
163c07a593e6acd2a3c17d16d939f2c29f213191
|
Swift
|
nageshkumarmishra/DynamicTableView-
|
/DynamicCellHeight/APIClient/APIClient.swift
|
UTF-8
| 1,856
| 3.25
| 3
|
[] |
no_license
|
//
// APIClient.swift
// DynamicCellHeight
//
// Created by Nagesh on 17/06/18.
// Copyright ยฉ 2018 Nagesh Kumar Mishra. All rights reserved.
//
enum APIStatus : Error {
case pass
case fail
}
let urlString = "https://dl.dropboxusercontent.com/s/2iodh4vg0eortkl/facts.json"
import Foundation
class APIClient {
// ReuestData will get the data from server and parse it using the Codable concept
func requestData(completion: @escaping ((_ data: AboutCanada?, _ success: APIStatus) -> Void)) {
var aboutCanadaData: AboutCanada?
let request : NSMutableURLRequest = NSMutableURLRequest()
request.url = NSURL(string: urlString)! as URL
let queue:OperationQueue = OperationQueue()
NSURLConnection.sendAsynchronousRequest(request as URLRequest, queue: queue) { (response, responseData, error) in
if error == nil {
// Data was received and parsed to String,As the content type was text/plain
guard let dataString = String(data: responseData!, encoding: String.Encoding.ascii) else {
completion(nil, .fail) // Data string is null then send fail status
return
}
// Converting the datastring to UTF8 format so we can decode using JSONDecoder
let data :Data = dataString.data(using: String.Encoding.utf8)!
do {
aboutCanadaData = try JSONDecoder().decode(AboutCanada.self, from: data)
completion(aboutCanadaData!, .pass)
} catch let err {
print(err)
completion(nil, .fail) // If any error occures send the fail status
}
} else {
completion(nil, .fail)
}
}
}
}
| true
|
2f61ebaa71807bdae8676ab0a46540b4083d6009
|
Swift
|
beacarlos/Viper
|
/ViperDemo/ViperDemo/Classes/Viper/View/ViewController.swift
|
UTF-8
| 2,064
| 3
| 3
|
[] |
no_license
|
//
// ViewController.swift
// ViperDemo
//
// Created by Beatriz Carlos on 31/05/21.
//
import UIKit
protocol AnyView: AnyObject {
var presenter: AnyPresenter? { get set }
func update(with users: [User])
func update(with error: String)
func navigationBarTitle(title: String) -> Void
}
class ViewController: UIViewController, AnyView {
let contentView = View(frame: UIScreen.main.bounds)
weak var presenter: AnyPresenter?
var users: [User] = []
override func viewDidLoad() {
super.viewDidLoad()
setDelegates()
presenter?.interactorGetTitle()
}
override func loadView() {
super.loadView()
self.view = contentView
}
func setDelegates() {
contentView.tableView.delegate = self
contentView.tableView.dataSource = self
}
func update(with users: [User]) {
DispatchQueue.main.async {
self.users = users
self.contentView.tableView.reloadData()
self.contentView.tableView.isHidden = false
}
}
func update(with error: String) {
DispatchQueue.main.async {
self.users = []
self.contentView.tableView.isHidden = true
self.contentView.labelError.text = error
self.contentView.labelError.isHidden = false
}
}
func navigationBarTitle(title: String) {
self.title = title
}
}
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return users.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = users[indexPath.row].name
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
presenter?.goTo(user: users[indexPath.row])
}
}
| true
|
d7b3bb8ebdafab33d12b70ab6f96c05365c66c35
|
Swift
|
clark-lindsay/iOS-weather-demo
|
/Forecast.swift
|
UTF-8
| 892
| 3.34375
| 3
|
[] |
no_license
|
//
// Forecast.swift
// Weather-Demo
//
// Created by Clark Lindsay on 5/21/20.
// Copyright ยฉ 2020 Clark Lindsay. All rights reserved.
//
import Foundation
struct Forecast: Parsable {
let day: String
let conditions: String
let high: Int
let low: Int
var highLabel: String {
get {
return "High: \(high)ยบF"
}
}
var lowLabel: String {
get {
return "Low: \(low)ยบF"
}
}
static func parse(json: JSONMessage) throws -> Parsable {
guard let day = json["day"] as? String,
let high = json["high"] as? Int,
let low = json["low"] as? Int,
let conditions = json["conditions"] as? String else {
throw ParseResourceError.ParseError(message: "Missing fields")
}
return Forecast(day: day, conditions: conditions, high: high, low: low)
}
}
| true
|
28d93cbeb0016a8b6ddc9e80b21f5f6b6fb24aa8
|
Swift
|
DGonzilla/Baked-Potatoes
|
/Baked Potatoes/My Account Tabs/Watched.swift
|
UTF-8
| 6,054
| 3.203125
| 3
|
[] |
no_license
|
//
// Watched.swift
// Baked Potatoes
//
// Created by David Adrien Gonzalez on 1/31/20.
// Copyright ยฉ 2020 David Adrien Gonzalez. All rights reserved.
//
import SwiftUI
struct Watched: View {
var body: some View {
//ScrollView {
VStack (alignment: .leading){
// Movie 1
HStack{
Image("Joker Movie Poster")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(height: 225)
.cornerRadius(12.0)
VStack (alignment: .leading){
Text("Joker")
.font(.custom("Montserrat-Regular", size: 25))
Text("2h 2min")
.font(.custom("Montserrat-Light", size: 15))
Text("Placeholder, for, different, generes")
.font(.custom("Montserrat-Light", size: 10))
.foregroundColor(.gray)
.padding(.top, 10)
HStack{
Image("Star Icon")
.resizable()
.frame(width: 15, height: 15)
Text("9.5/10")
.font(.custom("Montserrat-Regular", size: 15))
}
Text("189 Reviews")
.font(.custom("Montserrat-Light", size: 15))
.foregroundColor(.gray)
Spacer()
} // Padding to top of Movie Title
.padding(.top)
}
// Movie 2
HStack{
Image("BadBoysForLifePoster")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(height: 225)
.cornerRadius(12.0)
VStack (alignment: .leading){
Text("Bad Boys For Life")
.font(.custom("Montserrat-Regular", size: 25))
Text("2h 4min")
.font(.custom("Montserrat-Light", size: 15))
Text("Placeholder, for, different, generes")
.font(.custom("Montserrat-Light", size: 10))
.foregroundColor(.gray)
.padding(.top, 10)
HStack{
Image("Star Icon")
.resizable()
.frame(width: 15, height: 15)
Text("9.6/10")
.font(.custom("Montserrat-Regular", size: 15))
}
Text("153 Reviews")
.font(.custom("Montserrat-Light", size: 15))
.foregroundColor(.gray)
Spacer()
} // Padding to top of Movie Title
.padding(.top)
} // Padding to top of Movie 2 Stack
.padding(.top)
// Movie 3
HStack{
Image("QueenAndSlimPoster")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(height: 225)
.cornerRadius(12.0)
VStack (alignment: .leading){
Text("Queen & Slim")
.font(.custom("Montserrat-Regular", size: 25))
.multilineTextAlignment(.leading)
Text("2h 12min")
.font(.custom("Montserrat-Light", size: 15))
Text("Placeholder, for, different, generes")
.font(.custom("Montserrat-Light", size: 10))
.foregroundColor(.gray)
.padding(.top, 10)
HStack{
Image("Star Icon")
.resizable()
.frame(width: 15, height: 15)
Text("8.7/10")
.font(.custom("Montserrat-Regular", size: 15))
}
Text("90 Reviews")
.font(.custom("Montserrat-Light", size: 15))
.foregroundColor(.gray)
Spacer()
} // Padding to top of Movie Title
.padding(.top)
} // Padding to top of Movie 3 Stack
.padding(.top)
}
//} // Padding to top of Scroll View
.padding(.top)
}
}
struct Watched_Previews: PreviewProvider {
static var previews: some View {
Watched()
}
}
| true
|
9acd842ee36dedd8dd170e628db921c832e0c260
|
Swift
|
si1991Van/SupportCustmersLand
|
/App-Spport-Customers-Land/Services/DgmResponse.swift
|
UTF-8
| 2,323
| 2.65625
| 3
|
[] |
no_license
|
//
// DgmResponse.swift
// App-Spport-Customers-Land
//
// Created by apple on 12/29/18.
// Copyright ยฉ 2018 haiphat. All rights reserved.
//
import Foundation
import SwiftyJSON
class DgmResponse {
var data: Data?
var error: Error?
var response: HTTPURLResponse?
var statusCode: Int? {
get {
return response?.statusCode
}
}
init(_ data: Data?, _ response: URLResponse? , _ error: Error?) {
self.data = data
self.error = error
if let httpResponse = response as? HTTPURLResponse {
self.response = httpResponse
}
}
var hasConnectionErrors: Bool {
if (error as? URLError) != nil {
return true
}
return false
}
var hasNoNetworkError: Bool {
if let error = error as? URLError {
if error.code == .notConnectedToInternet {
return true
}
}
return false
}
var hasNoResponseError: Bool {
if let error = error as? URLError {
if error.code != .notConnectedToInternet {
return true
}
}
return false
}
var errorMessage: String? {
if statusCode == 401 {
return nil
}
if hasConnectionErrors {
if self.hasNoNetworkError {
return Loc("no-internet-connection")
} else if self.hasNoResponseError {
return Loc("cannot-connect-to-server")
} else {
return Loc("cannot-connect-to-server")
}
}
let arrayError = json()?["message"].array
var errors: [String] = []
if arrayError != nil {
for item in (arrayError)!{
errors.append(item.string!)
}
}
return errors.joined(separator: "/")
}
func json() -> JSON?{
guard let data = data else {
return nil
}
return try! JSON(data: data)
}
func isSuccess() -> Bool {
return statusCode == 200
}
/*
logout when got 401 error
*/
func check401Error() {
if statusCode == 401 {
UserService.sharedInstance.logout()
}
}
}
| true
|
95bc1202acc8db73e099df41a36b2a31940cd47d
|
Swift
|
oolex2/RemindMe
|
/RemindMe/ViewModels/TabBarViewModel.swift
|
UTF-8
| 819
| 2.515625
| 3
|
[] |
no_license
|
//
// TabBarViewModel.swift
// RemindMe
//
// Created by Oleksandr Oleksyn on 19.07.2021.
//
import Foundation
import UIKit
final class TabBarViewModel: BaseViewModel {
let tabBarController: Box<UITabBarController> = Box(UITabBarController())
let dataSource = TabBarDataSource()
private struct Constants {
static let barTintColor = UIColor.red
}
func initTabBarController() {
tabBarController.value = UITabBarController()
tabBarController.value.modalPresentationStyle = .fullScreen;
tabBarController.value.tabBar.tintColor = Constants.barTintColor;
tabBarController.value.tabBar.barTintColor = .cyan
}
func initTabBar() {
tabBarController.value.setViewControllers(dataSource.getListOfControllers(), animated: true)
}
}
| true
|
d253931b2b61afc1cc56f06a2ab2ef8e85ce79a8
|
Swift
|
rahulmehndiratta/NYTimes
|
/NYTimes/Utilities/Extension/UIView+Extensions.swift
|
UTF-8
| 643
| 2.546875
| 3
|
[] |
no_license
|
//
// UIIMageView+Extension.swift
// NYTimes
//
// Created by Apple on 17/11/20.
// Copyright ยฉ 2020 Apple. All rights reserved.
//
import UIKit
extension UIView {
func getShadow(radius: CGFloat, color: UIColor = UIColor.black.withAlphaComponent(0.5)) {
layer.masksToBounds = false
layer.shadowColor = color.cgColor
layer.shadowOpacity = 0.2
layer.shadowOffset = CGSize(width: -5, height: 1)
layer.shadowRadius = radius
layer.shadowPath = UIBezierPath(rect: bounds).cgPath
layer.shouldRasterize = true
layer.rasterizationScale = true ? UIScreen.main.scale : 1
}
}
| true
|
64b85e451a699aaf3378e56f19b40eb35ece6c09
|
Swift
|
benjaminkimble/PixelCity
|
/Pixel City/Pixel City/Controllers/PopVC.swift
|
UTF-8
| 947
| 2.640625
| 3
|
[] |
no_license
|
//
// PopVC.swift
// Pixel City
//
// Created by Benjamin Kimble on 10/19/17.
// Copyright ยฉ 2017 Benjamin Kimble. All rights reserved.
//
import UIKit
class PopVC: UIViewController, UIGestureRecognizerDelegate {
//@IBOutlets
@IBOutlet weak var popImgView: UIImageView!
//Variables
var passedImg: UIImage!
//My Functions
func initData(forImage img: UIImage) {
self.passedImg = img
}
func addDoubleTap() {
let dblTap = UITapGestureRecognizer(target: self, action: #selector(screenWasDblTapped))
dblTap.numberOfTapsRequired = 2
dblTap.delegate = self
view.addGestureRecognizer(dblTap)
}
@objc func screenWasDblTapped() {
dismiss(animated: true, completion: nil)
}
//System Functions and Overrides
override func viewDidLoad() {
super.viewDidLoad()
popImgView.image = passedImg
addDoubleTap()
}
}
| true
|
c6add2dbbe7ef398a143dfe0dacffdc940bde6a2
|
Swift
|
tikeyc/TStudySwift
|
/TMyPlayground.playground/Pages/ๆณๅ.xcplaygroundpage/Contents.swift
|
UTF-8
| 5,161
| 4.28125
| 4
|
[] |
no_license
|
//: [Previous](@previous)
import Foundation
var str = "Hello, playground"
//: [Next](@next)
/*ไพๅฆ๏ผSwift ็ Array ๅ Dictionary ้ฝๆฏๆณๅ้ๅใ
ไฝ ๅฏไปฅๅๅปบไธไธช Int ๆฐ็ป๏ผไนๅฏๅๅปบไธไธช String ๆฐ็ป๏ผ็่ณๅฏไปฅๆฏไปปๆๅ
ถไป Swift ็ฑปๅ็ๆฐ็ปใ
ๅๆ ท็๏ผไฝ ไนๅฏไปฅๅๅปบๅญๅจไปปๆๆๅฎ็ฑปๅ็ๅญๅ
ธใ
*/
func swapTwoInts(_ a: inout Int, _ b: inout Int) {
let temporaryA = a
a = b
b = temporaryA
}
/*ๆณๅๅฝๆฐ
ๆณๅๅฝๆฐๅฏไปฅ้็จไบไปปไฝ็ฑปๅ๏ผไธ้ข็ swapTwoValues(_:_:) ๅฝๆฐๆฏไธ้ขไธไธชๅฝๆฐ็ๆณๅ็ๆฌ๏ผ
*/
func swapTwoValues<T>(_ a: inout T, _ b: inout T) {
let temporaryA = a
a = b
b = temporaryA
}
//ไธ้ขๅฑ็คบไบๅฆไฝ็ผๅไธไธช้ๆณๅ็ๆฌ็ๆ ๏ผไปฅ Int ๅ็ๆ ไธบไพ๏ผ
struct IntStack {
var items = [Int]()
mutating func push(_ item: Int) {
items.append(item)
}
mutating func pop() -> Int {
return items.removeLast()
}
}
//ไธ้ขๆฏ็ธๅไปฃ็ ็ๆณๅ็ๆฌ๏ผ
struct Stack<Element> {
var items = [Element]()
mutating func push(_ item: Element) {
items.append(item)
}
mutating func pop() -> Element {
return items.removeLast()
}
}
/*ๆฉๅฑไธไธชๆณๅ็ฑปๅ
ไธ้ข็ไพๅญๆฉๅฑไบๆณๅ็ฑปๅ Stack๏ผไธบๅ
ถๆทปๅ ไบไธไธชๅไธบ topItem ็ๅช่ฏป่ฎก็ฎๅๅฑๆง๏ผๅฎๅฐไผ่ฟๅๅฝๅๆ ้กถ็ซฏ็ๅ
็ด ่ไธไผๅฐๅ
ถไปๆ ไธญ็งป้ค๏ผ
*/
extension Stack {
var topItem: Element? {
return items.isEmpty ? nil : items[items.count - 1]
}
}
/*็ฑปๅ็บฆๆ่ฏญๆณ
ไฝ ๅฏไปฅๅจไธไธช็ฑปๅๅๆฐๅๅ้ขๆพ็ฝฎไธไธช็ฑปๅๆ่
ๅ่ฎฎๅ๏ผๅนถ็จๅๅท่ฟ่กๅ้๏ผๆฅๅฎไน็ฑปๅ็บฆๆ๏ผๅฎไปฌๅฐๆไธบ็ฑปๅๅๆฐๅ่กจ็ไธ้จๅใๅฏนๆณๅๅฝๆฐๆทปๅ ็ฑปๅ็บฆๆ็ๅบๆฌ่ฏญๆณๅฆไธๆ็คบ๏ผไฝ็จไบๆณๅ็ฑปๅๆถ็่ฏญๆณไธไน็ธๅ๏ผ๏ผ
*/
class SomeClass {
}
protocol SomeProtocol {
}
func someFunction<T: SomeClass, U: SomeProtocol>(someT: T, someU: U) {
// ่ฟ้ๆฏๆณๅๅฝๆฐ็ๅฝๆฐไฝ้จๅ
}
/*ไธ้ข่ฟไธชๅฝๆฐๆไธคไธช็ฑปๅๅๆฐใ็ฌฌไธไธช็ฑปๅๅๆฐ T๏ผๆไธไธช่ฆๆฑ T ๅฟ
้กปๆฏ SomeClass ๅญ็ฑป็็ฑปๅ็บฆๆ๏ผ็ฌฌไบไธช็ฑปๅๅๆฐ U๏ผๆไธไธช่ฆๆฑ U ๅฟ
้กป็ฌฆๅ SomeProtocol ๅ่ฎฎ็็ฑปๅ็บฆๆใ
*/
//ไปปไฝ Equatable ็ฑปๅ้ฝๅฏไปฅๅฎๅ
จๅฐไฝฟ็จๅจ findIndex(of:in:) ๅฝๆฐไธญ๏ผๅ ไธบๅ
ถไฟ่ฏๆฏๆ็ญๅผๆไฝ็ฌฆใไธบไบ่ฏดๆ่ฟไธชไบๅฎ๏ผๅฝไฝ ๅฎไนไธไธชๅฝๆฐๆถ๏ผไฝ ๅฏไปฅๅฎไนไธไธช Equatable ็ฑปๅ็บฆๆไฝไธบ็ฑปๅๅๆฐๅฎไน็ไธ้จๅ๏ผ
func findIndex<T: Equatable>(of valueToFind: T, in array:[T]) -> Int? {
for (index, value) in array.enumerated() {
if value == valueToFind {
return index
}
}
return nil
}
/*ๅ
ณ่็ฑปๅ
ๅฎไนไธไธชๅ่ฎฎๆถ๏ผๆ็ๆถๅๅฃฐๆไธไธชๆๅคไธชๅ
ณ่็ฑปๅไฝไธบๅ่ฎฎๅฎไน็ไธ้จๅๅฐไผ้ๅธธๆ็จใๅ
ณ่็ฑปๅไธบๅ่ฎฎไธญ็ๆไธช็ฑปๅๆไพไบไธไธชๅ ไฝๅ๏ผๆ่
่ฏดๅซๅ๏ผ๏ผๅ
ถไปฃ่กจ็ๅฎ้
็ฑปๅๅจๅ่ฎฎ่ขซ้็บณๆถๆไผ่ขซๆๅฎใไฝ ๅฏไปฅ้่ฟ associatedtype ๅ
ณ้ฎๅญๆฅๆๅฎๅ
ณ่็ฑปๅใ
ๅ
ณ่็ฑปๅๅฎ่ทต
ไธ้ขไพๅญๅฎไนไบไธไธช Container ๅ่ฎฎ๏ผ่ฏฅๅ่ฎฎๅฎไนไบไธไธชๅ
ณ่็ฑปๅ ItemType๏ผ
*/
protocol Container {
associatedtype ItemType
mutating func append(_ item: ItemType)
var count: Int { get }
subscript(i: Int) -> ItemType { get }
}
//่ฟไธๆฌก๏ผๅ ไฝ็ฑปๅๅๆฐ Element ่ขซ็จไฝ append(_:) ๆนๆณ็ item ๅๆฐๅไธๆ ็่ฟๅ็ฑปๅใ
//Swift ๅฏไปฅๆฎๆญคๆจๆญๅบ Element ็็ฑปๅๅณๆฏ ItemType ็็ฑปๅใ
struct Stack1<Element>: Container {
// Stack<Element> ็ๅๅงๅฎ็ฐ้จๅ
var items = [Element]()
mutating func push(_ item: Element) {
items.append(item)
}
mutating func pop() -> Element {
return items.removeLast()
}
// Container ๅ่ฎฎ็ๅฎ็ฐ้จๅ
mutating func append(_ item: Element) {
self.push(item)
}
var count: Int {
return items.count
}
subscript(i: Int) -> Element {
return items[i]
}
}
/*ไธ้ข็ไพๅญๅฎไนไบไธไธชๅไธบ allItemsMatch ็ๆณๅๅฝๆฐ๏ผ็จๆฅๆฃๆฅไธคไธช Container ๅฎไพๆฏๅฆๅ
ๅซ็ธๅ้กบๅบ็็ธๅๅ
็ด ใๅฆๆๆๆ็ๅ
็ด ่ฝๅคๅน้
๏ผ้ฃไน่ฟๅ true๏ผๅฆๅ่ฟๅ falseใ
่ขซๆฃๆฅ็ไธคไธช Container ๅฏไปฅไธๆฏ็ธๅ็ฑปๅ็ๅฎนๅจ๏ผ่ฝ็ถๅฎไปฌๅฏไปฅ็ธๅ๏ผ๏ผไฝๅฎไปฌๅฟ
้กปๆฅๆ็ธๅ็ฑปๅ็ๅ
็ด ใ่ฟไธช่ฆๆฑ้่ฟไธไธช็ฑปๅ็บฆๆไปฅๅไธไธช where ๅญๅฅๆฅ่กจ็คบ๏ผ
*/
func allItemsMatch<C1: Container, C2: Container>
(_ someContainer: C1, _ anotherContainer: C2) -> Bool
where C1.ItemType == C2.ItemType, C1.ItemType: Equatable {
// ๆฃๆฅไธคไธชๅฎนๅจๅซๆ็ธๅๆฐ้็ๅ
็ด
if someContainer.count != anotherContainer.count {
return false
}
// ๆฃๆฅๆฏไธๅฏนๅ
็ด ๆฏๅฆ็ธ็ญ
for i in 0..<someContainer.count {
if someContainer[i] != anotherContainer[i] {
return false
}
}
// ๆๆๅ
็ด ้ฝๅน้
๏ผ่ฟๅ true
return true
}
| true
|
fb7555b1b0791bec0531e179cc7202f5a82df70a
|
Swift
|
LqDeveloper/AppUtilsDemo
|
/AppUtilsDemo/Classes/Tools/AppAuthTool.swift
|
UTF-8
| 3,808
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
//
// AppAuthTool.swift
// AppUtils
//
// Created by Quan Li on 2019/9/24.
// Copyright ยฉ 2019 williamoneilchina. All rights reserved.
//
import UIKit
import LocalAuthentication
/// ้่ฆๅจinfo.plistไธญๆทปๅ Privacy - Face ID Usage Description
public enum LocalAuthStatus:Int{
case success
case failed //ๅคฑ่ดฅ
case passwordNotSet //ๆช่ฎพ็ฝฎๆๆบๅฏ็
case touchIdNotSet //ๆช่ฎพ็ฝฎๆ็บน
case touchIdNotAvailable //ไธๆฏๆๆ็บน
case systemCancle //็ณป็ปๅๆถ
case userCancle //็จๆทๅๆถ
case userFallback //่พๅ
ฅๅฏ็
case biometryNotAvailable //ๆฒกๆๆ้
case other //ๅ
ถไป
public static func initWithError(_ error: LAError) -> LocalAuthStatus {
switch Int32(error.errorCode) {
case kLAErrorAuthenticationFailed:
return failed
case kLAErrorUserCancel:
return userCancle
case kLAErrorUserFallback:
return userFallback
case kLAErrorSystemCancel:
return systemCancle
case kLAErrorPasscodeNotSet:
return passwordNotSet
case kLAErrorBiometryNotAvailable:
return biometryNotAvailable
case kLAErrorTouchIDNotEnrolled:
return touchIdNotSet
case kLAErrorTouchIDNotAvailable:
return touchIdNotAvailable
default:
return other
}
}
}
public enum AuthType:Int{
case none
case touchID
case faceID
}
public class AppAuthTool{
public static let shared = AppAuthTool()
public let authContext = LAContext()
public var canEvaluatePolicy:Bool{
return authContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil)
}
public var faceIDAvailable:Bool {
if #available(iOS 11.0, *) {
return (canEvaluatePolicy && authContext.biometryType == .faceID)
}
return false
}
public var touchIDAvailable:Bool {
if #available(iOS 11.0, *) {
return canEvaluatePolicy && authContext.biometryType == .touchID
}
return canEvaluatePolicy
}
public var getAuthType:AuthType{
if touchIDAvailable {
return .touchID
}else if faceIDAvailable{
return .faceID
}else{
return .none
}
}
public func userAuth(_ reason: String = "",_ fallbackTitle:String = "", _ cancelTitle: String = "",completion: @escaping (LocalAuthStatus) -> ()){
//ๅฆๆไธบ็ฉบไธๅฑ็คบ่พๅ
ฅๅฏ็ ็ๆ้ฎ
authContext.localizedFallbackTitle = fallbackTitle
if #available(iOS 10.0, *) {
authContext.localizedCancelTitle = cancelTitle
}
guard canEvaluatePolicy else{
completion(.biometryNotAvailable)
return
}
var reasonStr = reason
if reason == "" {
if getAuthType == .faceID{
reasonStr = "่ฏทๅผๅง้ข้จ่ฏๅซ"
}else{
reasonStr = "้่ฟHome้ฎ้ช่ฏๅทฒๆๆๆบๆ็บน"
}
}
evaluate(policy: .deviceOwnerAuthenticationWithBiometrics,reason: reasonStr, completion: completion)
}
private func evaluate(policy: LAPolicy, reason: String, completion: @escaping (LocalAuthStatus) -> ()) {
authContext.evaluatePolicy(policy, localizedReason: reason) { (success, err) in
DispatchQueue.main.async {
if success {
completion(.success)
}else {
let errorType = LocalAuthStatus.initWithError(err as! LAError)
completion(errorType)
}
}
}
}
}
| true
|
309bc8dc5ee202ccebe7cf74a5995728cee1fbd7
|
Swift
|
iOS-11/Swift-Playgrounds
|
/Dictionaries.playground/Contents.swift
|
UTF-8
| 1,014
| 3.96875
| 4
|
[] |
no_license
|
//: Dictionaries
import UIKit
// Name : Price
var apps = [String: Double]()
apps["FriendMe"] = 0.99
apps["Boggy"] = 1.99
apps["NoteRighter"] = 4.99
apps["ChittyPic"] = 9.99
apps // -> ["ChittyPic": 9.99, "Boggy": 1.99, "NoteRighter": 4.99, "FriendMe": 0.99]
apps["NoteRighter"] = nil // -> apps["ChittyPic": 9.99, "Boggy": 1.99, "FriendMe": 0.99]
for (name, price) in apps {
print("\(name) is $\(price) on the App Store")
}
// Complex Dictionary
var studentsRecords = [
"Jennifer": [
"age": 12,
"grade": 91
],
"Bobby": [
"age": 15,
"grade": 87
],
"Miya": [
"age": 9,
"grade": 74
],
"Nicholas": [
"age": 14,
"grade": 94
]
]
// loop into values
if let dict = studentsRecords as? Dictionary<String, AnyObject> {
if let miya = dict["Miya"] as? Dictionary<String, Int> {
if let grade = miya["grade"] as? Int {
print("Maya's Grade: \(grade)")
}
}
}
// print all grades
for (student, record) in studentsRecords {
for (age, grade) in record {
print("Grade: \(grade)")
}
}
| true
|
6bdf8ce2d5002bb9eed4f3c2d9bc51f0859de1cb
|
Swift
|
sasamario/capsule-toy
|
/capsule toy/NextViewController.swift
|
UTF-8
| 1,776
| 2.890625
| 3
|
[] |
no_license
|
//
// NextViewController.swift
// capsule toy
//
// Created by ็ฌน้ๅทง้ฆฌ on 2021/01/03.
//
import UIKit
class NextViewController: UIViewController {
let messageArray = [
"ไปๆฅใ1ๆฅใ็ฒใๆงใงใ๏ผๆฉใๅฏใพใใใใ",
"ใใคในใใกใคใ๏ผๆ้ซ๏ผ",
"ๆๆฅใฏใใฃใใไผใฟใพใใใ",
"ใใคใใใ๏ผ",
"ใใคใน๏ผ",
"่ฏใใงใใพใใ",
"่ฏใใใใฐใใพใใ",
"ๆๆฅใ้ ๅผตใใพใใใ",
"่ชๅใซใ่ค็พใใใใพใใใ",
"ๅๆฅใฏใใฃใใใใใ",
"ใ้ขจๅใซๆตธใใใ",
"ใ้
ใงใ้ฃฒใใ"
]
@IBOutlet weak var message: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
//ๆๅฎ็ฏๅฒๅ
ใงใฉใณใใ ใชๆดๆฐใ็ๆ
let randomInt = Int.random(in: 0..<12)
message.text = messageArray[randomInt]
//ใใใใใคในๅ
ใซใกใใปใผใธใไฟๅญใใใฆใใชใใฃใใไฟๅญใใ
if UserDefaults.standard.object(forKey: "\(randomInt)") == nil {
UserDefaults.standard.set(messageArray[randomInt], forKey: "\(randomInt)")
}
}
@IBAction func back(_ sender: Any) {
//ๅใฎ็ป้ขใซๆปใ
dismiss(animated: true, completion: nil)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
| true
|
fa8c6931a821a788b24cac267f5cd72c02dcf806
|
Swift
|
LiuSky/XBMusic
|
/XBMusic/Classes/Controller/Extensions/AudioPlayerController+PlayerModeCalculate.swift
|
UTF-8
| 2,910
| 3.359375
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
//
// AudioPlayerController+PlayerModeCalculate.swift
// XBMusic
//
// Created by xiaobin liu on 2019/3/19.
// Copyright ยฉ 2019 Sky. All rights reserved.
//
import Foundation
// MARK: - ๆญๆพๆจกๅผ็ฎๆณ
extension AudioPlayerController {
/// ่ฎก็ฎๆญๆพ็ดขๅผ
/// 1.ๅพช็ฏๆญๆพ(ๅฝๆญๆพๅฐๆๅไธไธช็ๆถๅไผ้็ฝฎๅ่กจ,็ถๅไป็ฌฌไธไธช้ๆฐๅผๅง)
/// 2.ๅๆฒๅพช็ฏ(ไธๆญ็้ๅคๆญๆพ)
/// 3.้ๆบๆญๆพ(ๆฏๆฌก่ขซๆญๆพ่ฟ็ๆญๆฒ็็ดขๅผไผ่ขซ็งป้ค,็ดๅฐ็งป้คๅฐๆๅไธไธชใ็ถๅ้ๆฐๅผๅง)
/// - Parameters:
/// - mode: ๆญๆพๆจกๅผ
/// - hasNextItem: ๆฏๅฆๆฏไธไธๆฒ
/// - Returns: Int
open func calculatePlayer(_ mode: AudioPlayerMode, _ hasNextItem: Bool) -> Int {
switch mode {
case .loop:
return calculateLoop(hasNextItem)
case .one:
return calculateOne()
case .random:
return calculateRandom(hasNextItem)
}
}
/// ่ฎก็ฎๅพช็ฏ
///
/// - Parameter hasNextItem: ๆฏๅฆๆฏไธไธๆฒ
/// - Returns: Int
private func calculateLoop(_ hasNextItem: Bool) -> Int {
if hasNextItem {
if currentPlaylistItemIndex + 1 == playlistItems.count {
/// ้็ฝฎๆญๆพๅ่กจไธบ0
return 0
} else {
return currentPlaylistItemIndex + 1
}
} else {
if currentPlaylistItemIndex == 0 {
/// ๆญๆพๆๅไธ้ฆๆญ
return playlistItems.count - 1
} else {
return currentPlaylistItemIndex - 1
}
}
}
/// ่ฎก็ฎๅๆฒๅพช็ฏ
///
/// - Returns: <#return value description#>
private func calculateOne() -> Int {
return currentPlaylistItemIndex
}
/// ่ฎก็ฎ้ๆบ(ๅพ
ไผๅ)
///
/// - Returns: <#return value description#>
private func calculateRandom(_ hasNextItem: Bool) -> Int {
/*
1.ๅฆๆๆด็็ๆฐ้ไธๆญๆพๅ่กจไธ็ธ็ญ
*/
if randomIndexs.count != playlistItems.count {
randomIndexs = (0..<playlistItems.count).shuffled()
}
/// ๆฅๆพๅฝๅๆญๆพ็็ดขๅผไฝ็ฝฎ
let idx = randomIndexs.firstIndex(of: currentPlaylistItemIndex)!
if hasNextItem {
let next = idx + 1
if next > playlistItems.count - 1 {
return randomIndexs[0]
} else {
return randomIndexs[next]
}
} else {
let previous = idx - 1
if previous < 0 {
return randomIndexs[randomIndexs.count-1]
} else {
return randomIndexs[previous]
}
}
}
}
| true
|
7ea6747f94f316c154894e1d58da560d0a2bfb07
|
Swift
|
mobile-academy/swift-tdd-workshop-krakow
|
/TDDWorkshop/Classes/Speakers/SpeakersViewControllerSpec.swift
|
UTF-8
| 3,170
| 2.703125
| 3
|
[] |
no_license
|
import Foundation
import Quick
import Nimble
@testable
import TDDWorkshop
class SpeakersViewControllerSpec: QuickSpec {
override func spec() {
describe("SpeakersViewController") {
var sut: SpeakersViewController!
beforeEach {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
sut = storyboard.instantiateViewControllerWithIdentifier("Speakers") as! SpeakersViewController
}
afterEach {
sut = nil
}
it("should have a title") {
expect(sut.title).to(equal("Speakers"))
}
describe("collection view") {
var view: UICollectionView?
beforeEach {
view = sut.collectionView
}
it("should always bounce vertically") {
expect(view?.alwaysBounceVertical).to(beTruthy())
}
describe("layout") {
var layout: UICollectionViewFlowLayout?
beforeEach {
layout = view?.collectionViewLayout as? UICollectionViewFlowLayout
}
//TODO: Just don't forget to implement test for layout before doing the workshop
describe("when the view lays itself out") {
beforeEach {
sut.view.bounds = CGRectMake(0, 0, 42, 120)
sut.view.layoutIfNeeded()
}
it("should set the item size on collection view layout") {
expect(layout?.itemSize).to(equal(CGSizeMake(42, 80)))
}
}
}
}
describe("speakers data source") {
var dataSource: SpeakersCollectionViewDataSource?
beforeEach {
dataSource = sut.dataSource
}
it("should be a speakers data source") {
expect(dataSource).notTo(beNil())
}
it("should be view controllers collection view data source") {
let dataSourceSet = sut.collectionView?.dataSource === dataSource
expect(dataSourceSet).to(beTruthy())
}
describe("speakers") {
var speakers: Array<Speaker>?
beforeEach {
speakers = dataSource?.speakers
}
it("should have four speakers") {
expect(speakers).to(haveCount(4))
}
describe("first speaker") {
var speaker: Speaker?
beforeEach {
speaker = speakers?[0]
}
it("should have a name") {
expect(speaker?.name).to(equal("Paweล Dudek"))
}
}
}
}
}
}
}
| true
|
d18b28b6fa09dbd8da729fef6ffbafa44421a714
|
Swift
|
cuba/MapCodableKit
|
/Tests/MapCodableKitTests/MapCodableKitTests.swift
|
UTF-8
| 1,374
| 2.984375
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//
// MapCodableKitTests.swift
// MapCodableKitTests
//
// Created by Jacob Sikorski on 2018-12-02.
//
import XCTest
import MapCodableKit
class MapCodableKitTests: XCTestCase {
func testGivenValidJson_GetsNestedObject() {
// Given
let jsonString = """
{
"profile": {
"id": "123",
"name": "Kevin Malone"
}
}
"""
do {
// When
let map = try Map(jsonString: jsonString)
let id: String = try map.value(from: [KeyPart.object(key: "profile"), KeyPart.object(key: "id")])
let name: String = try map.value(from: "profile.name")
// Then
XCTAssertEqual(id, "123")
XCTAssertEqual(name, "Kevin Malone")
} catch {
XCTFail("Should have succeeded to create JSON")
}
}
func testGivenInvalidJson_GetsNestedKey() {
// Given
let jsonString = """
{
"profile": {
"id": "123",
name": "Kevin Malone"
}
}
"""
do {
// When
let _ = try Map(jsonString: jsonString)
XCTFail("Should have failed to map JSON")
} catch {
// Success
}
}
}
| true
|
4ded63f65c6e0f6b7158d763a8781ac06e800a3d
|
Swift
|
jormungand/Marshroute
|
/Example/NavigationDemo/Common/Extensions/StringExtensions.swift
|
UTF-8
| 294
| 2.875
| 3
|
[
"MIT"
] |
permissive
|
import Foundation
extension String {
var localized: String {
return NSLocalizedString(self, comment: "")
}
func localizedWithArgument(arg: CVarArgType) -> String {
let format = self.localized
return NSString(format: format, arg) as String
}
}
| true
|
637b551fda976c76fb8c387efa3ed5b70a31fef4
|
Swift
|
lukesky79/Fun-e-SwiftUi
|
/Fun-e SwiftUI/AppFinal/HamidView.swift
|
UTF-8
| 2,019
| 2.578125
| 3
|
[] |
no_license
|
//
// ThemeDecksView.swift
// ListForm
//
// Created by HamidGACI on 07/07/2020.
// Copyright ยฉ 2020 HamidGACI. All rights reserved.
//
import SwiftUI
/*
struct ThemeDecksView: View {
@State var someTheme: ThemeMatiere
let matiereTheme: QCM = qcm1
@State private var showQCMSheet = false
var body: some View {
VStack {
// Text("Fun e")
// .font(.largeTitle)
// .fontWeight(.bold)
// .foregroundColor(Color.purple)
List {
ForEach(getQcmsFromTotalQCM(themeMatiere: self.someTheme)) { sujet in
NavigationLink(destination: RepondreView()) {
ListRowView(qcm: sujet)
}.buttonStyle(PlainButtonStyle())
}
}
}
.navigationBarTitle(Text(" \(matiereTheme.themeMatiere.rawValue)").font(.title).fontWeight(.bold))
.navigationBarItems(trailing:
Button(action: {
self.showQCMSheet.toggle()
}, label: {
Image(systemName: "plus.square.fill").accentColor(.red).font(.system(size: 30))
}))
.sheet(isPresented: $showQCMSheet, content: {
LeeRoyView2(qcmSheet: self.$showQCMSheet)
})
}
}
struct ListRowView: View {
var qcm : QCM
let backGroundColor = LinearGradient(gradient: Gradient(colors: [.blue, .white,]), startPoint: .top, endPoint: .bottom)
var body: some View {
VStack (alignment: .leading) {
Text("QCM numรฉro: \(qcm.id)")
Text(qcm.name).font(.title)
}.listRowBackground(backGroundColor)
}
}
struct ThemeDecksView_Previews: PreviewProvider {
static var previews: some View {
ThemeDecksView(someTheme: ThemeMatiere.algรจbre)
}
}
*/
| true
|
fe14891ea338804705802a40f45a197c7291ec48
|
Swift
|
XiaoChenYung/SwiftUI
|
/SwiftUI-P2/SwiftUI-P1/LandmarkDetail.swift
|
UTF-8
| 1,570
| 3.171875
| 3
|
[
"MIT"
] |
permissive
|
//
// ContentView.swift
// SwiftUI-P1
//
// Created by wanba on 2019/9/27.
// Copyright ยฉ 2019 yangxiaochen. All rights reserved.
//
import SwiftUI
struct LandmarkDetail: View {
var landmark: Landmark
var body: some View {
VStack {
// ๅๅงๅ mapView ๅฎไพ
MapView(coordinate: landmark.locationCoordinate)
.frame(height: 300)
CircleImage(image: landmark.image)
// ่ฟ้็ offset ็ฑปไผผไบ scrollView ็ offset offset ๅฏไปฅๅๆถๆๅฎ x,y ็ๅผ๏ผไนๅฏไปฅๅ็ฌๆๅฎๅ
ถไธญไธไธช
.offset(y: -130)
// ้่ฟ offset ๆๅฎไบๅไธๅ็งป็่ท็ฆปๅ้่ฆๅ่ฎพ็ฝฎไธไธ padding ็ bottom ๅฑๆง่ฟ่กไฟฎๆญฃ๏ผๅฆๅๅบ้จไผ็ไธ็ฉบ็ฝ
.padding(.bottom, -130)
// ๅๅปบไธไธชๅ็ดๅฎนๅจ, ๅทฆๅฏน้ฝ
VStack(alignment: .leading) {
// ่ฎพ็ฝฎไธไธช font ไธบ title ็ๆ ้ข0
Text(landmark.name)
.font(.title)
// ๅๅปบไธไธชๆฐดๅนณๅฎนๅจ
HStack {
// ่ฎพ็ฝฎไธไธช font ไธบ subheadline ็่ฏฆๆ
Text(landmark.park)
.font(.subheadline)
.foregroundColor(Color.red)
Spacer()
// ่ฎพ็ฝฎไธไธช font ไธบ subheadline ็่ฏฆๆ
Text(landmark.state)
.font(.subheadline)
}
}
// ่ฎพ็ฝฎ่ฏฅ VStack ่ท็ฆปๅทฆๅณ็่พน่ทๆฏ 10
.padding(EdgeInsets.init(top: 0, leading: 10, bottom: 0, trailing: 10))
Spacer()
}
.navigationBarTitle(Text(verbatim: landmark.name), displayMode: .inline)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
LandmarkDetail(landmark: landmarkData[0])
}
}
| true
|
fe342a7329a61a2a4c10ba788f3635ebaf87fcbc
|
Swift
|
pollini/LuMaxMan
|
/LuMaxMan/ContactNotifiableType.swift
|
UTF-8
| 428
| 2.75
| 3
|
[] |
no_license
|
/*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sampleโs licensing information
Abstract:
A protocol representing the ability of a `GKEntity` to respond to the start and end of a physics contact with another `GKEntity`.
*/
import GameplayKit
protocol ContactNotifiableType {
func contactWithEntityDidBegin(entity: GKEntity?)
func contactWithEntityDidEnd(entity: GKEntity?)
}
| true
|
209b32baf35d7eb4f2ec1efd797e0ef3eeb40827
|
Swift
|
lina0611/MoveMedicalCodeChallenge
|
/MoveMedicalCodeChallenge/ViewController/ViewController.DataProvider.swift
|
UTF-8
| 1,264
| 2.984375
| 3
|
[] |
no_license
|
//
// ViewController.DataProvider.swift
// MoveMedicalCodeChallenge
//
// Created by Lina Gao on 4/28/20.
// Copyright ยฉ 2020 Lina Gao. All rights reserved.
//
import Foundation
extension ViewController {
class DataProvider {
private var books: [Book] {
[Book(name: "Talk To Stranger", description: "Home book"),
Book(name: "Swift 5.0", description: "Programming Language"),
Book(name: "iOS Programming", description: "Programming Tool")]
}
private var phones: [Phone] {
[Phone(name: "iPhone 11", description: "Pro", version: "11"),
Phone(name: "iPhone SE", description: "2nd Generation", version: "SE")]
}
private var cars: [Car] {
[Car.init(name: "Mini Cooper", description: "Small Car", yearOfCar: "2016"),
Car.init(name: "Honda Civic", description: "Two doors", yearOfCar: "2019")]
}
func loadData() -> Snapshot {
let sectionComposer = SectionComposer(bookList: books,
phoneList: phones,
carList: cars)
let snapshot = sectionComposer.compose()
return snapshot
}
}
}
| true
|
428166825a2c0e97fac4db1d082b58668a4985db
|
Swift
|
Aalaizah/AngleGatorsiOS
|
/AngleGators/Utilities.swift
|
UTF-8
| 488
| 3.09375
| 3
|
[] |
no_license
|
//
// Utilities.swift
// AngleGators
//
// Created by Alexandria Mack on 10/6/15.
// Copyright ยฉ 2015 Alexandria Mack. All rights reserved.
//
import Foundation
import SpriteKit
extension Array {
func randomElement() -> Element {
let index = Int(arc4random_uniform(UInt32(self.count)))
return self[index]
}
}
extension CGPoint {
func length() -> CGFloat {
return sqrt(x*x + y*y)
}
func normalize() -> CGPoint {
return self / length()
}
}
| true
|
976113b9891c349a48120cee669620cead2776ea
|
Swift
|
michalek94/iOS_Local_Weather
|
/Local weather/Local weather/ConnectionManager/APIError.swift
|
UTF-8
| 913
| 3.078125
| 3
|
[] |
no_license
|
//
// APIError.swift
// Local weather
//
// Created by Michaล Pankowski on 29/11/2019.
// Copyright ยฉ 2019 Michaล Pankowski. All rights reserved.
//
import Foundation
enum APIError: LocalizedError {
case invalidData
case jsonDecodingFailure
case wrongAPIRequest
case tooManyCalls
case apiKey
case unknown
case customError(String)
var description: String {
switch self {
case .invalidData:
return "Invalid data"
case .jsonDecodingFailure:
return "JSON Decoding has failed"
case .wrongAPIRequest:
return "Wrong API request"
case .tooManyCalls:
return "Too many calls at this tariff"
case .apiKey:
return "Wrong API key"
case .unknown:
return "Uknown error has occurred"
case .customError(let description):
return description
}
}
}
| true
|
dbfd3729dc5cc26824c7dda41cb8b057473a2f9e
|
Swift
|
kyaing/KDYSample
|
/LeetCode/LeetCode/7_ReverseInteger.swift
|
UTF-8
| 516
| 3.140625
| 3
|
[
"MIT"
] |
permissive
|
//
// 7_ReverseInteger.swift
// LeetCode
//
// Created by Mac on 2018/4/16.
// Copyright ยฉ 2018ๅนด Mac. All rights reserved.
//
import Foundation
class ReverseInteger {
func reverse(_ x: Int) -> Int {
var result = 0
var x = x
while x != 0 {
result = x % 10 + result * 10
x /= 10
if result > Int(Int32.max) || result < Int(Int32.min) {
return 0
}
}
return result
}
}
| true
|
8cdc63947e7ae672cc96460f0ee6f36fb9f065e3
|
Swift
|
liudhzhyym/SwiftUI
|
/Basic/SwiftUI_Lecture_3_Image/SwiftUI_Lecture_3/ContentView.swift
|
UTF-8
| 1,258
| 2.765625
| 3
|
[] |
no_license
|
//
// ContentView.swift
// SwiftUI_Lecture_3
//
// Created by bakhaan on 2021/02/01.
//
import SwiftUI
struct ContentView: View {
var body: some View {
VStack(spacing: 0) {
Text("Hello")
.background(Color.green)
Text("Hello")
.background(Color.green)
Image("1")
.resizable()
.edgesIgnoringSafeArea(/*@START_MENU_TOKEN@*/.all/*@END_MENU_TOKEN@*/)
.aspectRatio(contentMode: .fit)
.padding(.bottom, 20)
Image("1")
.resizable()
.edgesIgnoringSafeArea(/*@START_MENU_TOKEN@*/.all/*@END_MENU_TOKEN@*/)
.aspectRatio(contentMode: .fit)
.mask(
// Circle()
// VStack(spacing: 0) {
// Circle()
// Circle()
// }
HStack(spacing: 0) {
Circle()
Circle()
}
)
.padding(.bottom, 20)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| true
|
ab2a3fc16a402a4d15bc9e06cc6ad267492b810f
|
Swift
|
franckclement/Netw
|
/NetwTests/GithubAPI/Mock/URLProtocolMock.swift
|
UTF-8
| 2,135
| 2.6875
| 3
|
[
"MIT"
] |
permissive
|
/**
* Netw
*
* Copyright (c) 2019 Franck Clement. Licensed under the MIT license, as follows:
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import Foundation
/// This class is used to mock network calls during unit testing.
/// Simply provide any URL you want to mock and its corresponding value
/// to the static testUrls Dictionary
class URLProtocolMock: URLProtocol {
static var testURLs = [URL?: Data]()
override class func canInit(with request: URLRequest) -> Bool {
return true
}
override class func canonicalRequest(for request: URLRequest) -> URLRequest {
return request
}
override func startLoading() {
if let url = request.url {
// if the url is contained in ou testURLs dictionnary
if let data = URLProtocolMock.testURLs[url] {
// then returns immediateli the corresponding data
self.client?.urlProtocol(self, didLoad: data)
}
}
self.client?.urlProtocolDidFinishLoading(self)
}
override func stopLoading() { }
}
| true
|
1f74b003e3ce2b0d4f61c3b09a8e8f1b63983c50
|
Swift
|
firebase/firebase-ios-sdk
|
/FirebaseFunctions/Sources/FunctionsError.swift
|
UTF-8
| 8,266
| 2.78125
| 3
|
[
"Apache-2.0",
"LicenseRef-scancode-proprietary-license"
] |
permissive
|
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
/// The error domain for codes in the `FunctionsErrorCode` enum.
public let FunctionsErrorDomain: String = "com.firebase.functions"
/// The key for finding error details in the `NSError` userInfo.
public let FunctionsErrorDetailsKey: String = "details"
/**
* The set of error status codes that can be returned from a Callable HTTPS tigger. These are the
* canonical error codes for Google APIs, as documented here:
* https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto#L26
*/
@objc(FIRFunctionsErrorCode) public enum FunctionsErrorCode: Int {
/** The operation completed successfully. */
case OK = 0
/** The operation was cancelled (typically by the caller). */
case cancelled = 1
/** Unknown error or an error from a different error domain. */
case unknown = 2
/**
* Client specified an invalid argument. Note that this differs from `FailedPrecondition`.
* `InvalidArgument` indicates arguments that are problematic regardless of the state of the
* system (e.g., an invalid field name).
*/
case invalidArgument = 3
/**
* Deadline expired before operation could complete. For operations that change the state of the
* system, this error may be returned even if the operation has completed successfully. For
* example, a successful response from a server could have been delayed long enough for the
* deadline to expire.
*/
case deadlineExceeded = 4
/** Some requested document was not found. */
case notFound = 5
/** Some document that we attempted to create already exists. */
case alreadyExists = 6
/** The caller does not have permission to execute the specified operation. */
case permissionDenied = 7
/**
* Some resource has been exhausted, perhaps a per-user quota, or perhaps the entire file system
* is out of space.
*/
case resourceExhausted = 8
/**
* Operation was rejected because the system is not in a state required for the operation's
* execution.
*/
case failedPrecondition = 9
/**
* The operation was aborted, typically due to a concurrency issue like transaction aborts, etc.
*/
case aborted = 10
/** Operation was attempted past the valid range. */
case outOfRange = 11
/** Operation is not implemented or not supported/enabled. */
case unimplemented = 12
/**
* Internal errors. Means some invariant expected by underlying system has been broken. If you
* see one of these errors, something is very broken.
*/
case `internal` = 13
/**
* The service is currently unavailable. This is a most likely a transient condition and may be
* corrected by retrying with a backoff.
*/
case unavailable = 14
/** Unrecoverable data loss or corruption. */
case dataLoss = 15
/** The request does not have valid authentication credentials for the operation. */
case unauthenticated = 16
}
/**
* Takes an HTTP status code and returns the corresponding `FIRFunctionsErrorCode` error code.
* This is the standard HTTP status code -> error mapping defined in:
* https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto
* - Parameter status An HTTP status code.
* - Returns: The corresponding error code, or `FIRFunctionsErrorCodeUnknown` if none.
*/
internal func FunctionsCodeForHTTPStatus(_ status: NSInteger) -> FunctionsErrorCode {
switch status {
case 200:
return .OK
case 400:
return .invalidArgument
case 401:
return .unauthenticated
case 403:
return .permissionDenied
case 404:
return .notFound
case 409:
return .alreadyExists
case 429:
return .resourceExhausted
case 499:
return .cancelled
case 500:
return .internal
case 501:
return .unimplemented
case 503:
return .unavailable
case 504:
return .deadlineExceeded
default:
return .internal
}
}
extension FunctionsErrorCode {
static func errorCode(forName name: String) -> FunctionsErrorCode {
switch name {
case "OK": return .OK
case "CANCELLED": return .cancelled
case "UNKNOWN": return .unknown
case "INVALID_ARGUMENT": return .invalidArgument
case "DEADLINE_EXCEEDED": return .deadlineExceeded
case "NOT_FOUND": return .notFound
case "ALREADY_EXISTS": return .alreadyExists
case "PERMISSION_DENIED": return .permissionDenied
case "RESOURCE_EXHAUSTED": return .resourceExhausted
case "FAILED_PRECONDITION": return .failedPrecondition
case "ABORTED": return .aborted
case "OUT_OF_RANGE": return .outOfRange
case "UNIMPLEMENTED": return .unimplemented
case "INTERNAL": return .internal
case "UNAVAILABLE": return .unavailable
case "DATA_LOSS": return .dataLoss
case "UNAUTHENTICATED": return .unauthenticated
default: return .internal
}
}
var descriptionForErrorCode: String {
switch self {
case .OK:
return "OK"
case .cancelled:
return "CANCELLED"
case .unknown:
return "UNKNOWN"
case .invalidArgument:
return "INVALID ARGUMENT"
case .deadlineExceeded:
return "DEADLINE EXCEEDED"
case .notFound:
return "NOT FOUND"
case .alreadyExists:
return "ALREADY EXISTS"
case .permissionDenied:
return "PERMISSION DENIED"
case .resourceExhausted:
return "RESOURCE EXHAUSTED"
case .failedPrecondition:
return "FAILED PRECONDITION"
case .aborted:
return "ABORTED"
case .outOfRange:
return "OUT OF RANGE"
case .unimplemented:
return "UNIMPLEMENTED"
case .internal:
return "INTERNAL"
case .unavailable:
return "UNAVAILABLE"
case .dataLoss:
return "DATA LOSS"
case .unauthenticated:
return "UNAUTHENTICATED"
}
}
func generatedError(userInfo: [String: Any]? = nil) -> NSError {
return NSError(domain: FunctionsErrorDomain,
code: rawValue,
userInfo: userInfo ?? [NSLocalizedDescriptionKey: descriptionForErrorCode])
}
}
internal func FunctionsErrorForResponse(status: NSInteger,
body: Data?,
serializer: FUNSerializer) -> NSError? {
// Start with reasonable defaults from the status code.
var code = FunctionsCodeForHTTPStatus(status)
var description = code.descriptionForErrorCode
var details: AnyObject?
// Then look through the body for explicit details.
if let body = body,
let json = try? JSONSerialization.jsonObject(with: body) as? NSDictionary,
let errorDetails = json["error"] as? NSDictionary {
if let status = errorDetails["status"] as? String {
code = FunctionsErrorCode.errorCode(forName: status)
// If the code in the body is invalid, treat the whole response as malformed.
guard code != .internal else {
return code.generatedError(userInfo: nil)
}
}
if let message = errorDetails["message"] as? String {
description = message
} else {
description = code.descriptionForErrorCode
}
details = errorDetails["details"] as AnyObject?
if let innerDetails = details {
// Just ignore the details if there an error decoding them.
details = try? serializer.decode(innerDetails)
}
}
if code == .OK {
// Technically, there's an edge case where a developer could explicitly return an error code of
// OK, and we will treat it as success, but that seems reasonable.
return nil
}
var userInfo = [String: Any]()
userInfo[NSLocalizedDescriptionKey] = description
if let details = details {
userInfo[FunctionsErrorDetailsKey] = details
}
return code.generatedError(userInfo: userInfo)
}
| true
|
fcf45bf93510600f52ba7fcbb8431fef3ef1588e
|
Swift
|
tessaSAC/Spottp-Calendar
|
/Calendar Mobile/Spottp Calendar/EventViewController.swift
|
UTF-8
| 2,771
| 2.78125
| 3
|
[] |
no_license
|
//
// EventViewController.swift
// Spottp Calendar
//
// Created by tessa on 6/28/18.
// Copyright ยฉ 2018 tessa. All rights reserved.
//
import UIKit
class EventViewController: UIViewController {
// UI
@IBOutlet weak var eventViewControllerTitle: UINavigationItem!
@IBOutlet weak var deleteButton: UIBarButtonItem!
@IBOutlet weak var addUpdateButton: UIButton!
// Data
@IBOutlet weak var eventTitleTextField: UITextField!
@IBOutlet weak var startTextField: UITextField!
@IBOutlet weak var endTextField: UITextField!
@IBOutlet weak var descriptionTextField: UITextField!
// For in case an event will be edited
var day: Day? = nil
var event: Event? = nil
var eid: String? = nil
override func viewDidLoad() {
super.viewDidLoad()
// If an event is passed in for editing
eventTitleTextField.text = event?.title
startTextField.text = event?.start
endTextField.text = event?.end
descriptionTextField.text = event?.desc
eid = event?.eid
// Update UI as necessary
if event != nil {
eventViewControllerTitle.title = "edit event"
addUpdateButton.setTitle("update", for: .normal)
day = event!.day
} else {
deleteButton.isEnabled = false
deleteButton.tintColor = UIColor.clear
}
}
@IBAction func cancelTapped(_ sender: Any) {
print("this works")
navigationController?.popViewController(animated: true)
}
@IBAction func deleteTapped(_ sender: Any) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
day?.removeFromEvents(event!)
context.delete(event!)
// Save and go back
appDelegate.saveContext()
navigationController?.popViewController(animated: true)
}
@IBAction func addUpdateEventTapped(_ sender: Any) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
// When creating a new event
if event == nil {
let context = appDelegate.persistentContainer.viewContext
event = Event(context: context)
eid = NSUUID().uuidString
}
event!.eid = eid
event!.title = eventTitleTextField.text
event!.start = startTextField.text
event!.end = endTextField.text
event!.desc = descriptionTextField.text
event!.day = day
// Save and go back
day?.addToEvents(event!)
appDelegate.saveContext()
navigationController?.popViewController(animated: true)
}
}
| true
|
2e0da1ed1c206e79c9112568c39810cc9ff528ca
|
Swift
|
NutPreuttipan/SwiftSelectedTableview
|
/SwiftSelectedTableView/TableViewCell.swift
|
UTF-8
| 2,167
| 2.734375
| 3
|
[] |
no_license
|
//
// TableViewCell.swift
// SwiftSelectedTableView
//
// Created by Preuttipan Janpen on 30/5/2562 BE.
// Copyright ยฉ 2562 Lphant Solutions. All rights reserved.
//
import UIKit
protocol TableViewDelegate {
func didSelectedChoice(indexPath:Int, choice:Int)
}
class TableViewCell: UITableViewCell {
@IBOutlet weak var button1: UIButton!
@IBOutlet weak var button2: UIButton!
var delegate: TableViewDelegate?
func ChoiceConfigure(indexPath:Int, selectedChoice:[Int:Int]) {
button1.tag = indexPath
button2.tag = indexPath
if let choice = selectedChoice[indexPath] {
if choice == 1 {
button1.backgroundColor = UIColor.blue
button1.tintColor = UIColor.white
button2.backgroundColor = UIColor.white
button2.tintColor = UIColor.blue
} else {
button1.backgroundColor = UIColor.white
button1.tintColor = UIColor.blue
button2.backgroundColor = UIColor.blue
button2.tintColor = UIColor.white
}
} else {
button1.backgroundColor = UIColor.white
button1.tintColor = UIColor.blue
button2.backgroundColor = UIColor.white
button2.tintColor = UIColor.blue
}
}
@IBAction func onClickSelectChoice(_ sender: Any) {
switch sender as! UIButton {
case button1:
button1.backgroundColor = UIColor.blue
button1.tintColor = UIColor.white
button2.backgroundColor = UIColor.white
button2.tintColor = UIColor.blue
delegate?.didSelectedChoice(indexPath: button1.tag, choice: 1)
case button2:
button1.backgroundColor = UIColor.white
button1.tintColor = UIColor.blue
button2.backgroundColor = UIColor.blue
button2.tintColor = UIColor.white
delegate?.didSelectedChoice(indexPath: button2.tag, choice: 2)
default:
break;
}
}
}
| true
|
da904c6f4896a25d8e4e6f2a2f72875b361c0ae3
|
Swift
|
wassermanm/twitterClient
|
/TwitterClient/TwitterClient/LoginViewController.swift
|
UTF-8
| 2,954
| 2.828125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// TwitterClient
//
// Created by Michael Wasserman on 2016-09-09.
// Copyright ยฉ 2016 Wasserman. All rights reserved.
//
import UIKit
class LoginViewController: UIViewController {
// MARK: - Lifecycle Methods
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
userNameField.text = ""
passwordField.text = ""
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Outlets
@IBOutlet weak var userNameField: UITextField!
@IBOutlet weak var passwordField: UITextField!
// MARK: - Action Methods
@IBAction func loginAction(sender: AnyObject) {
guard let userName = userNameField.text, let password = passwordField.text else {
//since I'm setting the username and password to empty strings in viewWillAppear
//these values will never be nil. This guard statement is here because I believe
//that forced unwrapping is bad form
return
}
if !Reachability.isConnectedToNetwork() {
let alertController = UIAlertController(title: "No Network", message: "It appears that you are not connected to a network. Please check your network settings and try again.", preferredStyle: .Alert)
let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
alertController.addAction(defaultAction)
presentViewController(alertController, animated: true, completion: nil)
}
var authKey = ""
do {
try authKey = DataManager.sharedInstance.login(userName, password: password)
} catch {
let alertController = UIAlertController(title: "Network Error", message: "A network error has occurred. Please check your network settings and try again.", preferredStyle: .Alert)
let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
alertController.addAction(defaultAction)
presentViewController(alertController, animated: true, completion: nil)
return
}
if authKey == "" {
let alertController = UIAlertController(title: "Invalid Login", message: "You have entered an invalid user name or password. Please try again.", preferredStyle: .Alert)
let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
alertController.addAction(defaultAction)
presentViewController(alertController, animated: true, completion: nil)
} else {
performSegueWithIdentifier("tweetsSegue", sender: nil)
}
}
}
| true
|
4ea4df3ab68a55ff2b3294b5c677fa228616be62
|
Swift
|
alvinmatthew12/HapticTest
|
/Haptic/BreathViewController.swift
|
UTF-8
| 6,660
| 2.609375
| 3
|
[] |
no_license
|
//
// BreathViewController.swift
// Haptic
//
// Created by Alvin Matthew Pratama on 15/10/20.
//
import UIKit
class BreathViewController: UIViewController {
@IBOutlet weak var instructionLabel: UILabel!
let touchPoint = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 50.0, height: 50.0))
let circle = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 80.0, height: 80.0))
var pulseTimer = Timer()
var hapticTimer = Timer()
var breathTimer = Timer()
// var inhaleTimer = Timer()
// var holdTimer = Timer()
// var exhaleTimer = Timer()
var breathCount = 0
var isBreathStart = false
override func viewDidLoad() {
super.viewDidLoad()
setup()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch: UITouch! = touches.first! as UITouch
let location = touch.location(in: self.view)
touchPoint.center = location
isBreathStart = true
breathSession()
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch: UITouch! = touches.first! as UITouch
let location = touch.location(in: self.view)
touchPoint.center = location
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
stop()
}
func setup() {
circle.layer.cornerRadius = circle.frame.width / 2
circle.center = touchPoint.center
circle.backgroundColor = UIColor.clear
circle.layer.borderWidth = 2
circle.layer.borderColor = UIColor.red.cgColor
touchPoint.layer.cornerRadius = touchPoint.frame.width / 2
touchPoint.backgroundColor = UIColor.systemTeal
touchPoint.addSubview(circle)
touchPoint.center = CGPoint(x: view.frame.size.width / 2, y: view.frame.size.height / 2)
view.addSubview(touchPoint)
}
func breathSession() {
if isBreathStart {
if breathCount < 4 {
breathFourSevenEight()
} else {
self.instructionLabel.text = "Well Done"
breathCount = 0
return
}
} else {
breathCount = 0
return
}
}
func breathFourSevenEight() {
haptic(style: 3, timeInterval: 1)
pulseGrowAnimation(object: circle)
self.instructionLabel.text = "Inhale"
breathTimer = Timer.scheduledTimer(withTimeInterval: 4, repeats: false) { (timer) in
self.instructionLabel.text = "Hold"
self.hapticTimer.invalidate()
self.pulseTimer.invalidate()
self.breathTimer = Timer.scheduledTimer(withTimeInterval: 7, repeats: false) { (timer) in
self.instructionLabel.text = "Exhale"
self.shrinkHaptic()
self.shrinkAnimation(object: self.circle, duration: 8)
self.breathTimer = Timer.scheduledTimer(withTimeInterval: 8, repeats: false) { (timer) in
self.hapticTimer.invalidate()
self.pulseTimer.invalidate()
self.breathCount += 1
self.instructionLabel.text = ""
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self.breathSession()
}
}
}
}
}
func stop() {
pulseTimer.invalidate()
hapticTimer.invalidate()
breathTimer.invalidate()
isBreathStart = false
instructionLabel.text = "Stopped"
}
func pulseGrowAnimation(object: UIView, timeInterval: TimeInterval = 1) {
var scaleXValue: CGFloat = 1.0
var yValue: CGFloat = 1.0
pulseTimer = Timer.scheduledTimer(withTimeInterval: timeInterval, repeats: true, block: { (timer) in
object.transform = CGAffineTransform(scaleX: scaleXValue + 0.9, y: yValue + 0.9)
scaleXValue += 0.5
yValue += 0.5
UIView.animate(
withDuration: 1, delay: 0, usingSpringWithDamping: 0.55, initialSpringVelocity: 3,
options: .curveEaseOut, animations: {
object.transform = CGAffineTransform(scaleX: scaleXValue, y: yValue)
}, completion: nil)
})
}
func shrinkAnimation(object: UIView, duration: TimeInterval) {
UIView.animate(
withDuration: duration, delay: 0,
options: .curveEaseOut, animations: {
object.transform = .identity
}, completion: nil)
}
func shrinkHaptic() {
self.haptic(style: 3, timeInterval: 0.03)
self.breathTimer = Timer.scheduledTimer(withTimeInterval: 2.5, repeats: false) { (timer) in
self.hapticTimer.invalidate()
self.haptic(style: 2, timeInterval: 0.03)
self.breathTimer = Timer.scheduledTimer(withTimeInterval: 2.5, repeats: false) { (timer) in
self.hapticTimer.invalidate()
self.haptic(style: 1, timeInterval: 0.03)
self.breathTimer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false) { (timer) in
self.hapticTimer.invalidate()
}
}
}
}
func haptic(style: Int, timeInterval: TimeInterval) {
hapticTimer.invalidate()
var impactFeedbackGenerator: UIImpactFeedbackGenerator
switch style {
case 1:
impactFeedbackGenerator = UIImpactFeedbackGenerator(style: .light)
case 2:
impactFeedbackGenerator = UIImpactFeedbackGenerator(style: .medium)
case 3:
impactFeedbackGenerator = UIImpactFeedbackGenerator(style: .heavy)
default:
impactFeedbackGenerator = UIImpactFeedbackGenerator(style: .light)
}
hapticTimer = Timer.scheduledTimer(withTimeInterval: timeInterval, repeats: true) { (timer) in
impactFeedbackGenerator.prepare()
impactFeedbackGenerator.impactOccurred()
}
}
}
| true
|
10647f2058c9e832bec7c84dbcf770f5e3fdca75
|
Swift
|
atsabitsoev/Habits
|
/Habits/DesignSystem/Cells/HabitItemCell.swift
|
UTF-8
| 1,649
| 2.578125
| 3
|
[] |
no_license
|
//
// HabitItemCell.swift
// Habits
//
// Created by ะัะฐะผะฐะท ะะธัะพะตะฒ on 15.10.2020.
//
import UIKit
final class HabitItemCell: UITableViewCell {
static let identifier = "HabitItemCell"
private let habitItemView: HabitItemView = {
let view = HabitItemView()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
configureCell()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func updateConstraints() {
setHabitItemViewConstraints()
super.updateConstraints()
}
func setItem(_ item: HabitItem, delegate: HabitItemViewDelegate? = nil) {
habitItemView.setItem(item, delegate: delegate)
}
private func configureCell() {
contentView.addSubview(habitItemView)
selectionStyle = .none
clipsToBounds = false
setNeedsUpdateConstraints()
}
private func setHabitItemViewConstraints() {
NSLayoutConstraint.activate([
habitItemView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 10),
habitItemView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -10),
habitItemView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16),
habitItemView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -16)
])
}
}
| true
|
f7064bb19f9b74b72fdc62b17d14d4be30808bce
|
Swift
|
patagoniacode/soto
|
/Sources/Soto/Services/MigrationHubConfig/MigrationHubConfig_Error.swift
|
UTF-8
| 3,024
| 2.5625
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"BSD-2-Clause"
] |
permissive
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2021 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import SotoCore
/// Error enum for MigrationHubConfig
public struct MigrationHubConfigErrorType: AWSErrorType {
enum Code: String {
case accessDeniedException = "AccessDeniedException"
case dryRunOperation = "DryRunOperation"
case internalServerError = "InternalServerError"
case invalidInputException = "InvalidInputException"
case serviceUnavailableException = "ServiceUnavailableException"
case throttlingException = "ThrottlingException"
}
private let error: Code
public let context: AWSErrorContext?
/// initialize MigrationHubConfig
public init?(errorCode: String, context: AWSErrorContext) {
guard let error = Code(rawValue: errorCode) else { return nil }
self.error = error
self.context = context
}
internal init(_ error: Code) {
self.error = error
self.context = nil
}
/// return error code string
public var errorCode: String { self.error.rawValue }
/// You do not have sufficient access to perform this action.
public static var accessDeniedException: Self { .init(.accessDeniedException) }
/// Exception raised to indicate that authorization of an action was successful, when the DryRun flag is set to true.
public static var dryRunOperation: Self { .init(.dryRunOperation) }
/// Exception raised when an internal, configuration, or dependency error is encountered.
public static var internalServerError: Self { .init(.internalServerError) }
/// Exception raised when the provided input violates a policy constraint or is entered in the wrong format or data type.
public static var invalidInputException: Self { .init(.invalidInputException) }
/// Exception raised when a request fails due to temporary unavailability of the service.
public static var serviceUnavailableException: Self { .init(.serviceUnavailableException) }
/// The request was denied due to request throttling.
public static var throttlingException: Self { .init(.throttlingException) }
}
extension MigrationHubConfigErrorType: Equatable {
public static func == (lhs: MigrationHubConfigErrorType, rhs: MigrationHubConfigErrorType) -> Bool {
lhs.error == rhs.error
}
}
extension MigrationHubConfigErrorType: CustomStringConvertible {
public var description: String {
return "\(self.error.rawValue): \(self.message ?? "")"
}
}
| true
|
e2fea2a2ec9e3ec9df2b26c8de5ec344bcce44cc
|
Swift
|
larryhou/swift
|
/TexasHoldem/TexasHoldem/ViewController.swift
|
UTF-8
| 5,532
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
//
// ViewController.swift
// TexasHoldem
//
// Created by larryhou on 6/3/2016.
// Copyright ยฉ 2016 larryhou. All rights reserved.
//
import UIKit
class ViewModel {
var data: [UniqueRound]
var stats: [Int: [HandPattern: Int]]
init(data: [UniqueRound], stats: [Int: [HandPattern: Int]]) {
self.data = data
self.stats = stats
}
init() {
self.data = []
self.stats = [:]
}
}
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var progressInfo: UILabel!
@IBOutlet weak var progressIndicator: UIProgressView!
@IBOutlet weak var peopleStepper: UIStepper!
@IBOutlet weak var peopleInput: UITextField!
@IBOutlet weak var roundStepper: UIStepper!
@IBOutlet weak var roundInput: UITextField!
@IBOutlet weak var simulateButton: UIButton!
private let background_queue = DispatchQueue(label: "TexasHoldem.background.simulate", attributes: DispatchQueueAttributes.concurrent)
private let model = ViewModel()
override func viewDidLoad() {
super.viewDidLoad()
print(HandV1HighCard.description)
print(HandV2OnePair.description)
print(HandV3TwoPair.description)
print(HandV4TreeOfKind.description)
print(HandV5Straight.description)
print(HandV6Flush.description)
print(HandV7FullHouse.description)
print(HandV8FourOfKind.description)
print(HandV9StraightFlush.description)
}
func generateGameRounds(_ roundCount: Int, personCount: Int) {
var digitCount = 0
var value = Double(roundCount)
while value >= 1 {
value /= 10
digitCount += 1
}
background_queue.async {
var stats: [Int: [HandPattern: Int]] = [:]
var data: [UniqueRound] = []
UIApplication.shared().isIdleTimerDisabled = true
self.simulateButton.isUserInteractionEnabled = false
let start = Date()
for n in 0..<roundCount {
let round = UniqueRound(index: n)
data.append(round)
let result = PokerDealer.deal(personCount)
for i in 0..<result.count {
result[i].evaluate()
round.list.append(RawPokerHand(index: n, id: UInt8(i), data: result[i].rawValue))
let hand = result[i]
if stats[i] == nil {
stats[i] = [:]
}
if stats[i]?[hand.pattern] == nil {
stats[i]?[hand.pattern] = 0
}
stats[i]?[hand.pattern]? += 1
}
DispatchQueue.main.async {
self.updateProgressIndicator(n + 1, total: roundCount, digitCount: digitCount, elapse: Date().timeIntervalSince(start))
}
}
UIApplication.shared().isIdleTimerDisabled = false
self.simulateButton.isUserInteractionEnabled = true
DispatchQueue.main.async {
self.setViewModel(data, stats: stats)
}
}
}
func setViewModel(_ data: [UniqueRound], stats: [Int: [HandPattern: Int]]) {
model.data = data
model.stats = stats
}
func updateProgressIndicator(_ count: Int, total: Int, digitCount: Int, elapse: TimeInterval) {
progressInfo.text = String(format: "%0\(digitCount)d/%d %5.2f%% %5.3fs", count, total, Double(count) * 100 / Double(total), elapse)
progressIndicator.progress = Float(count)/Float(total)
}
@IBAction func simulate(_ sender: AnyObject) {
let roundCount = roundInput.text != "" ? NSString(string: roundInput.text!).integerValue : Int(roundStepper.value)
let personCount = peopleInput.text != "" ? NSString(string: peopleInput.text!).integerValue : Int(peopleStepper.value)
generateGameRounds(roundCount, personCount: personCount)
}
// MARK: text input
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == peopleInput {
var value = NSString(string: peopleInput.text!).doubleValue
value = max(min(peopleStepper.maximumValue, value), peopleStepper.minimumValue)
peopleInput.text = String(format: "%.0f", value)
peopleStepper.value = value
} else
if textField == roundInput {
var value = NSString(string: roundInput.text!).doubleValue
value = max(min(roundStepper.maximumValue, value), roundStepper.minimumValue)
roundInput.text = String(format: "%.0f", value)
roundStepper.value = value
}
return true
}
@IBAction func setPeopleCount(_ sender: AnyObject) {
if sender is UIStepper {
peopleInput.text = String(format: "%.0f", peopleStepper.value)
}
}
@IBAction func setRoundCount(_ sender: AnyObject) {
if sender is UIStepper {
roundInput.text = String(format: "%.0f", roundStepper.value)
}
}
// MARK: segue
override func prepare(for segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "player" {
let dst = segue.destinationViewController as! PlayerTableViewController
dst.model = model
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| true
|
71b476c95c6fbfb7cc3b7dab946430889f2457d4
|
Swift
|
shumpei-nagata/PokemonSwiftUI
|
/PokemonSwiftUI/PokemonSwiftUI/Sources/Presentation/Modules/PokemonList/ViewModel/PokemonListViewModel.swift
|
UTF-8
| 928
| 2.875
| 3
|
[] |
no_license
|
import Combine
import Domain
@MainActor
final class PokemonListViewModel: ObservableObject {
private let pokemonListUseCase: PokemonListUseCaseContract
private var count = 0
@Published private(set) var pokemons = [Pokemon]()
var canFetchMore: Bool {
pokemons.count < count
}
init(pokemonListUseCase: PokemonListUseCaseContract) {
self.pokemonListUseCase = pokemonListUseCase
}
func fetchPokemons() async {
do {
let result = try await pokemonListUseCase.fetch(offset: 0)
pokemons = result.pokemons
count = result.count
} catch {
debugPrint(error)
}
}
func fetchMore() async {
do {
let result = try await pokemonListUseCase.fetch(offset: pokemons.count)
pokemons.append(contentsOf: result.pokemons)
} catch {
debugPrint(error)
}
}
}
| true
|
a32e34f7f94c46dad66fb484957e2a8c5967e4b4
|
Swift
|
28th-BE-SOPT-iOS-Part/KimHyeSoo
|
/KakaoTalk-Clone/KakaoTalk-Clone/LoginPage/UIViewController + makeAlert.swift
|
UTF-8
| 1,747
| 2.859375
| 3
|
[] |
no_license
|
import Foundation
import UIKit
extension UIViewController
{
func makeRequestAlert(title : String,
message : String,
okAction : ((UIAlertAction) -> Void)?,
cancelAction : ((UIAlertAction) -> Void)? = nil,
completion : (() -> Void)? = nil)
{
let generator = UIImpactFeedbackGenerator(style: .medium)
generator.impactOccurred()
let alertViewController = UIAlertController(title: title, message: message,
preferredStyle: .alert)
let okAction = UIAlertAction(title: "ํ์ธ", style: .default, handler: okAction)
alertViewController.addAction(okAction)
let cancelAction = UIAlertAction(title: "์ทจ์", style: .cancel, handler: cancelAction)
alertViewController.addAction(cancelAction)
self.present(alertViewController, animated: true, completion: completion)
}
func makeAlert(title : String,
message : String,
okAction : ((UIAlertAction) -> Void)? = nil,
completion : (() -> Void)? = nil)
{
let generator = UIImpactFeedbackGenerator(style: .medium)
generator.impactOccurred()
let alertViewController = UIAlertController(title: title, message: message,
preferredStyle: .alert)
let okAction = UIAlertAction(title: "ํ์ธ", style: .default, handler: okAction)
alertViewController.addAction(okAction)
self.present(alertViewController, animated: true, completion: completion)
}
}
| true
|
c3fece1ee18a7d1b10614c9820127c432d18cd66
|
Swift
|
itsdamslife/ELMTimer
|
/TEA/Framework/Elm.swift
|
UTF-8
| 3,528
| 2.765625
| 3
|
[] |
no_license
|
/// Imported from objc.io and reused with modification as per this app's requirement
import UIKit
// -----------------------------------------------
// A simple Elm implementation for Swift
// -----------------------------------------------
class Driver<State, Action> {
var state: State {
didSet {
updateForChangedState()
}
}
var disposeBag: DisposeBag
let update: (inout State, Action) -> Command<Action>?
let view: (State) -> [ElmView<Action>]
let subscriptions: (State) -> [Subscription<Action>]
let rootView: UIStackView
let model: TimerModel
var notifications: [NotificationSubscription<Action>] = []
init(_ initial: State,
update: @escaping (inout State, Action) -> Command<Action>?,
view: @escaping (State) -> [ElmView<Action>],
subscriptions: @escaping (State) -> [Subscription<Action>],
rootView: UIStackView,
model: TimerModel) {
self.disposeBag = DisposeBag()
self.state = initial
self.update = update
self.view = view
self.rootView = rootView
self.subscriptions = subscriptions
self.model = model
updateForChangedState()
}
func updateForChangedState() {
let d = DisposeBag()
rootView.updateSubviews(virtualViews: view(state), sendAction: { [unowned self] in
self.receive($0)
}, disposeBag: d)
self.disposeBag = d
self.updateSubscriptions()
}
func updateSubscriptions() {
let all = subscriptions(state)
if all.count != notifications.count {
notifications = []
for s in all {
switch s {
case let .notification(name: name, action):
notifications.append(NotificationSubscription(name, handle: action, send: { [unowned self] in
self.receive($0)
}))
}
}
} else {
for i in 0..<all.count {
switch all[i] {
case let .notification(name: name, action):
assert(notifications[i].name == name) // todo
notifications[i].action = action
}
}
}
}
func receive(_ action: Action) {
if let command = update(&state, action) {
command.execute(model) { [unowned self] in
self.receive($0)
}
}
}
}
enum Subscription<Action> {
case notification(name: Notification.Name, (Notification) -> Action)
}
final class NotificationSubscription<Action> {
let name: (Notification.Name)
var action: (Notification) -> Action
let send: (Action) -> ()
init(_ name: Notification.Name, handle: @escaping (Notification) -> Action, send: @escaping (Action) -> ()) {
self.name = name
self.action = handle
self.send = send
NotificationCenter.default.addObserver(forName: name, object: nil, queue: nil) { [unowned self] note in
self.send(self.action(note))
}
}
}
final class TargetAction: NSObject {
let execute: () -> ()
init(_ action: @escaping () -> ()) {
self.execute = action
}
@objc func action(_ sender: Any) {
self.execute()
}
}
// Autorelease
class DisposeBag {
var disposables: [Any] = []
func append(_ value: Any) {
disposables.append(value)
}
}
| true
|
705d89e85a705c9638f74059ebed3968a7a12eb8
|
Swift
|
kkserver/kk-ios-observer
|
/KKObserver/KKObserver/KKObject.swift
|
UTF-8
| 15,657
| 2.75
| 3
|
[
"MIT"
] |
permissive
|
//
// KKObject.swift
// KKObserver
//
// Created by zhanghailong on 2016/10/14.
// Copyright ยฉ 2016ๅนด kkserver.cn. All rights reserved.
//
import Foundation
open class KKObject : NSObject {
internal func valueOf() -> Any? {
return self
}
public func set(key:String,_ value:Any?) {
self.set([key],value)
}
public func set(_ keys:[String],_ value:Any?) {
KKObject.set(self.valueOf(),keys, value)
changeKeys(keys)
}
public func remove(key:String) {
self.remove(keys:[key]);
}
public func remove(keys:[String]) {
KKObject.remove(self.valueOf(),keys)
changeKeys(keys)
}
public func get(key:String) -> Any? {
return self.get([key])
}
public func get(_ keys:[String]) -> Any? {
return KKObject.get(self.valueOf(), keys)
}
public func stringValue(_ keys:[String],_ defaultValue:String?) -> String? {
return KKObject.stringValue(get(keys), defaultValue)
}
public func intValue(_ keys:[String],_ defaultValue:Int) -> Int {
return KKObject.intValue(get(keys), defaultValue)
}
public func int64Value(_ keys:[String],_ defaultValue:Int64) -> Int64 {
return KKObject.int64Value(get(keys), defaultValue)
}
public func floatValue(_ keys:[String],_ defaultValue:Float) -> Float {
return KKObject.floatValue(get(keys), defaultValue)
}
public func doubleValue(_ keys:[String],_ defaultValue:Double) -> Double {
return KKObject.doubleValue(get(keys), defaultValue)
}
public func booleanValue(_ keys:[String],_ defaultValue:Bool) -> Bool {
return KKObject.booleanValue(get(keys), defaultValue)
}
public func changeKeys(_ keys:[String]) {
}
public static func set(_ object:Any?,key:String,value:Any?) {
if object is Dictionary<String,Any> {
var v = (object as! Dictionary<String,Any>)
if value == nil {
v.removeValue(forKey: key)
}
else {
v[key] = value!
}
} else if(object is KKDictionary<String,Any> ) {
let v = (object as! KKDictionary<String,Any>)
if value == nil {
_ = v.removeValue(forKey: key)
}
else {
v[key] = value!
}
} else if(object is Array<Any>) {
var v = object as! Array<Any>
let i = intValue(key, 0);
if value == nil {
if(i>=0 && i < v.count) {
v.remove(at: i)
}
}
else {
if( i == v.count) {
v.append(value!)
}
else if(i >= 0 && i < v.count) {
v[i] = value!
}
}
} else if(object is KKArray<Any>) {
let v = object as! KKArray<Any>
let i = intValue(key, 0);
if value == nil {
if(i>=0 && i < v.count) {
_ = v.remove(at: i)
}
}
else {
if( i == v.count) {
v.append(value!)
}
else if(i >= 0 && i < v.count) {
v[i] = value!
}
}
} else if(object is NSMutableArray) {
let v = object as! NSMutableArray
let i = intValue(key, 0);
if value == nil {
if(i>=0 && i < v.count) {
v.removeObject(at: i)
}
}
else {
if( i == v.count) {
v.add(value!)
}
else if(i >= 0 && i < v.count) {
v.replaceObject(at: i, with: value!)
}
}
}
else if(object is NSObject) {
(object as! NSObject).setValue(value, forKey: key)
}
}
public static func set(_ object:Any?,_ keys:[String],_ value:Any?) {
KKObject.set(object,keys,0,value)
}
public static func set(_ object:Any?,_ keys:[String],_ idx:Int,_ value:Any?) {
if(idx < keys.count) {
let key = keys[idx]
if idx + 1 == keys.count {
KKObject.set(object,key:key,value:value)
} else {
var v = KKObject.get(object, key: key)
if v == nil {
v = KKDictionary<String,Any>.init()
KKObject.set(object, key: key, value: v)
}
KKObject.set(v,keys,idx + 1,value)
}
}
}
public static func remove(_ object:Any?,key:String) {
if object is Dictionary<String,Any> {
var v = object as! Dictionary<String,Any>
v.removeValue(forKey: key)
} else if object is NSMutableDictionary {
(object as! NSMutableDictionary).removeObject(forKey: key)
}
}
public static func remove(_ object:Any?,_ keys:[String]) {
KKObject.remove(object,keys, 0)
}
public static func remove(_ object:Any?,_ keys:[String],_ idx:Int) {
if idx < keys.count {
let key = keys[idx]
if idx + 1 == keys.count {
KKObject.remove(object,key:key)
} else {
let v = KKObject.get(object,key:key)
if v != nil {
KKObject.remove(v, keys, idx + 1)
}
}
}
}
public static func get(_ object:Any?,key:String) -> Any? {
if object is Dictionary<String,Any> {
let v = object as! Dictionary<String,Any>;
return v[key]
} else if object is KKDictionary<String,Any> {
let v = object as! KKDictionary<String,Any>;
return v[key]
} else if object is Array<Any> {
let v = object as! Array<Any>;
if key == "@last" {
if v.count > 0 {
return v.last
}
return nil
} else if key == "@first" {
if v.count > 0 {
return v.first
}
return nil
} else if key == "@length" {
return v.count
} else {
let i = intValue(key, 0)
if i >= 0 && i < v.count {
return v[i]
}
return nil
}
} else if object is KKArray<Any> {
let v = object as! KKArray<Any>;
if key == "@last" {
if v.count > 0 {
return v[v.count - 1]
}
return nil
} else if key == "@first" {
if v.count > 0 {
return v[0]
}
return nil
} else if key == "@length" {
return v.count
} else {
let i = intValue(key, 0)
if i >= 0 && i < v.count {
return v[i]
}
return nil
}
} else if object is NSArray {
let v = object as! NSArray;
if key == "@last" {
if v.count > 0 {
return v.lastObject
}
return nil
} else if key == "@first" {
if v.count > 0 {
return v.firstObject
}
return nil
} else if key == "@length" {
return v.count
} else {
let i = intValue(key, 0)
if i >= 0 && i < v.count {
return v[i]
}
return nil
}
} else if(object is NSObject) {
return (object as! NSObject).value(forKey: key)
}
return nil
}
public static func get(_ object:Any?,_ keys:[String]) -> Any? {
return KKObject.get(object,keys,0)
}
public static func get(_ object:Any?,_ keys:[String],_ idx:Int) -> Any? {
if idx < keys.count {
let key = keys[idx]
let v = KKObject.get(object,key:key)
if v != nil {
return KKObject.get(v,keys,idx + 1)
}
return v;
}
return object
}
public static func stringValue(_ object:Any?,_ defaultValue:String?) -> String? {
if(object == nil) {
return defaultValue;
}
if(object is String || object is NSString) {
return object as! String?;
}
if(object is Int) {
return String.init(object as! Int);
}
if(object is NSNumber) {
return (object as! NSNumber).stringValue;
}
if(object is Int64) {
return String.init(object as! Int64);
}
if(object is Float) {
return String.init(object as! Float);
}
if(object is Double) {
return String.init(object as! Double);
}
return defaultValue
}
public static func intValue(_ object:Any?,_ defaultValue:Int) -> Int {
if(object == nil) {
return defaultValue;
}
if(object is Int) {
return object as! Int;
}
if(object is NSNumber) {
return Int.init(object as! NSNumber);
}
if(object is Int64) {
return Int.init(object as! Int64);
}
if(object is Float) {
return Int.init(object as! Float);
}
if(object is Double) {
return Int.init(object as! Double);
}
if(object is String) {
return Int.init(object as! String)!;
}
if(object is NSString) {
return Int.init(object as! String)!;
}
return defaultValue;
}
public static func int64Value(_ object:Any?,_ defaultValue:Int64) -> Int64 {
if(object == nil) {
return defaultValue;
}
if(object is Int) {
return Int64.init(object as! Int);
}
if(object is NSNumber) {
return (object as! NSNumber).int64Value;
}
if(object is Int64) {
return object as! Int64;
}
if(object is Float) {
return Int64.init(object as! Float);
}
if(object is Double) {
return Int64.init(object as! Double);
}
if(object is String) {
return Int64.init(object as! String)!;
}
if(object is NSString) {
return Int64.init(object as! String)!;
}
return defaultValue;
}
public static func floatValue(_ object:Any?,_ defaultValue:Float) -> Float {
if(object == nil) {
return defaultValue;
}
if(object is Int) {
return Float.init(object as! Int);
}
if(object is NSNumber) {
return (object as! NSNumber).floatValue;
}
if(object is Int64) {
return Float.init(object as! Int64);
}
if(object is Float) {
return object as! Float;
}
if(object is Double) {
return Float.init(object as! Double);
}
if(object is String) {
return Float.init(object as! String)!;
}
if(object is NSString) {
return Float.init(object as! String)!;
}
return defaultValue;
}
public static func doubleValue(_ object:Any?,_ defaultValue:Double) -> Double {
if(object == nil) {
return defaultValue;
}
if(object is Int) {
return Double.init(object as! Int);
}
if(object is NSNumber) {
return (object as! NSNumber).doubleValue;
}
if(object is Int64) {
return Double.init(object as! Int64);
}
if(object is Float) {
return Double.init(object as! Float);
}
if(object is Double) {
return object as! Double;
}
if(object is String) {
return Double.init(object as! String)!;
}
if(object is NSString) {
return Double.init(object as! String)!;
}
return defaultValue;
}
public static func booleanValue(_ object:Any?,_ defaultValue:Bool) -> Bool {
if(object == nil) {
return defaultValue;
}
if(object is Int) {
return object as! Int != 0;
}
if(object is NSNumber) {
return (object as! NSNumber).boolValue;
}
if(object is Int64) {
return object as! Int64 != 0;
}
if(object is Float) {
return object as! Float != 0;
}
if(object is Double) {
return object as! Double != 0.0;
}
if(object is String) {
let v = object as! String;
return v == "true" || v == "yes";
}
if(object is NSString) {
let v = object as! String;
return v == "true" || v == "yes";
}
return defaultValue;
}
public typealias EachFunction = (Any?,Any?)->Void
public static func forEach(_ object:Any?,_ fn:EachFunction) -> Void {
if object == nil {
return
}
if object is KKArray<Any> {
let v = object! as! KKArray<Any>
var i = 0
v.forEach({ (value) in
fn(i,value)
i = i + 1
})
} else if object is KKDictionary<String,Any> {
let v = object! as! KKDictionary<String,Any>
v.forEach({ (key, value) in
fn(key,value)
})
} else if object is Array<Any> {
let v = object! as! Array<Any>
var i = 0
v.forEach({ (value) in
fn(i,value)
i = i + 1
})
} else if object is Dictionary<String,Any> {
let v = object! as! Dictionary<String,Any>
v.forEach({ (key, value) in
fn(key,value)
})
} else if object is NSArray {
let v = object! as! NSArray
var i = 0
v.forEach({ (value) in
fn(i,value)
i = i + 1
})
} else if object is NSDictionary {
let v = object! as! NSDictionary
v.forEach({ (key, value) in
fn(key,value)
})
}
}
}
| true
|
8d983daf17d9229d086a322948b5de3711538652
|
Swift
|
LucasXu0/learnopengl
|
/LearnOpenGL/Lesson 5/L5ViewController.swift
|
UTF-8
| 3,691
| 2.71875
| 3
|
[] |
no_license
|
//
// L5ViewController.swift
// LearnOpenGL
//
// Created by xurunkang on 2019/7/10.
//
import Foundation
import GLKit
class L5ViewController: BaseViewController {
// ๆณจๆ: effect ็ๅๅงๅ้่ฆๅจ่ฎพ็ฝฎ EAGLContext.setCurrent ๅ
private lazy var effect: L5BaseEffect = {
let effect = L5BaseEffect("l5vertex.vsh", "l5fragment.fsh")
effect.setTexture("L5.JPG")
return effect
}()
// vertex buffer object
private var VBO: GLuint = 0
// ้กถ็นๆฐ็ป
private let vertices: [L5Vertex] = [
L5Vertex(position: (-1, -1, 0), color: (1, 0, 0, 1), texCoord: (0, 0)),
L5Vertex(position: (1, -1, 0), color: (0, 1, 0, 1), texCoord: (1, 0)),
L5Vertex(position: (1, 1, 0), color: (0, 0, 1, 1), texCoord: (1, 1)),
L5Vertex(position: (1, 1, 0), color: (0, 0, 1, 1), texCoord: (1, 1)),
L5Vertex(position: (-1, 1, 0), color: (0, 1, 0, 1), texCoord: (0, 1)),
L5Vertex(position: (-1, -1, 0), color: (1, 0, 0, 1), texCoord: (0, 0))
]
override func viewDidLoad() {
super.viewDidLoad()
setupBuffer()
setupVertexAttributes()
}
override func glkView(_ view: GLKView, drawIn rect: CGRect) {
glClearColor(1, 1, 1, 1)
glClear(GLenum(GL_COLOR_BUFFER_BIT))
effect.prepareToDraw()
// ไผ ๅ
ฅๅๆข็ฉ้ต
effect.modelMatrix = modelMatrix()
glDrawArrays(GLenum(GL_TRIANGLES), 0, GLsizei(vertices.count))
}
}
private extension L5ViewController {
private func modelMatrix() -> GLKMatrix4 {
var modelMatrix = GLKMatrix4Identity
modelMatrix = GLKMatrix4Translate(modelMatrix, 0.5, -0.5, 0) // ๅนณ็งป
modelMatrix = GLKMatrix4Scale(modelMatrix, 0.5, 0.5, 1) // ็ผฉๆพ
let radians = linearRadians()
modelMatrix = GLKMatrix4Rotate(modelMatrix, radians, 0, 1, 0) // ๆ่ฝฌ, ๆฒฟ Y ่ฝดๆ่ฝฌ 45ยฐ
return modelMatrix
}
private func linearRadians() -> Float {
return sinf(Float(CACurrentMediaTime())/2.0) * Float.pi
}
private func setupBuffer() {
// ๅๆฌกไธ้จๆฒ
glGenBuffers(1, &VBO)
glBindBuffer(GLenum(GL_ARRAY_BUFFER), VBO)
glBufferData(
GLenum(GL_ARRAY_BUFFER),
vertices.elementsSize,
vertices,
GLenum(GL_STATIC_DRAW)
)
}
private func setupVertexAttributes() {
// ่ฟ้้่ฆๆณจๆ๏ผๅ ไธบๆไปฌๅทฒ็ปๅๆขไธบ่ชๅฎไน็ BaseEffect๏ผๆไปฅๅฏนๅบ็้กถ็นๅฑๆงๆไน่ฎฐๅพ่ฆไฟฎๆน
glEnableVertexAttribArray(VertexAttrib.position.rawValue)
// ไผ ่พๅๆ
glVertexAttribPointer(
VertexAttrib.position.rawValue,
3,
GLenum(GL_FLOAT),
GLboolean(GL_FALSE),
GLsizei(MemoryLayout<L5Vertex>.stride),
UnsafeRawPointer(bitPattern: 0)
)
glEnableVertexAttribArray(VertexAttrib.color.rawValue)
// ไผ ่พ้ข่ฒ
glVertexAttribPointer(
VertexAttrib.color.rawValue,
4,
GLenum(GL_FLOAT),
GLboolean(GL_FALSE),
GLsizei(MemoryLayout<L5Vertex>.stride),
UnsafeRawPointer(bitPattern: 3 * MemoryLayout<GLfloat>.size)
)
glEnableVertexAttribArray(VertexAttrib.textureCoordinate.rawValue)
// ไผ ่พ็บน็ๅๆ
glVertexAttribPointer(
VertexAttrib.textureCoordinate.rawValue,
2,
GLenum(GL_FLOAT),
GLboolean(GL_FALSE),
GLsizei(MemoryLayout<L5Vertex>.stride),
UnsafeRawPointer(bitPattern: (3 + 4) * MemoryLayout<GLfloat>.size)
)
}
}
| true
|
4c34b37b8dcaee454ec2aac025d7bf17b50e6728
|
Swift
|
hadukin/swift_course
|
/lesson_8/Lab - Collections.playground/Pages/3. Exercise - Dictionaries.xcplaygroundpage/Contents.swift
|
UTF-8
| 2,899
| 4.625
| 5
|
[] |
no_license
|
/*:
## ะฃะฟัะฐะถะฝะตะฝะธะต - ัะปะพะฒะฐัะธ
ะกะพะทะดะฐะนัะต ะฟะตัะตะผะตะฝะฝัั ัะธะฟะฐ ัะปะพะฒะฐัั `[String: Int]`, ะบะพัะพัะฐั ะฑัะดะตั ัะพะดะตัะถะฐัั ะบะพะปะธัะตััะฒะพ ะดะฝะตะน ะฒ ะบะฐะถะดะพะผ ะธะท ะผะตัััะตะฒ. ะัะฟะพะปัะทัั ะปะธัะตัะฐะปั, ะธะฝะธัะธะฐะปะธะทะธััะนัะต ะตั ะทะฝะฐัะตะฝะธัะผะธ ัะฝะฒะฐัั, ัะตะฒัะฐะปั ะธ ะผะฐััะฐ. ะ ัะฝะฒะฐัะต 31 ะดะตะฝั, ะฒ ัะตะฒัะฐะปะต 28, ะฒ ะผะฐััะต โย 31. ะัะฒะตะดะธัะต ัะพะดะตัะถะธะผะพะต ัะปะพะฒะฐัั ะฒ ะบะพะฝัะพะปั.
*/
var dict: [String: Int] = ["ะฏะฝะฒะฐัั": 31, "ะคะตะฒัะฐะปั": 28, "ะะฐัั": 31]
/*:
ะัะฟะพะปัะทัั ะธะฝะดะตะบัะฐัะธั, ะดะพะฑะฐะฒััะต ะฒ ะบะพะปะปะตะบัะธั ะฐะฟัะตะปั ัะพ ะทะฝะฐัะตะฝะธะตะผ 30. ะัะฒะตะดะธัะต ัะพะดะตัะถะธะผะพะต ัะปะพะฒะฐัั ะฒ ะบะพะฝัะพะปั.
*/
dict["ะะฟัะตะปั"] = 30
print(dict)
/*:
ะะฐัััะฟะธะป ะฒะธัะพะบะพัะฝัะน ะณะพะด. ะกะดะตะปะฐะนัะต ะบะพะปะธัะตััะฒะพ ะดะฝะตะน ะฒ ัะตะฒัะฐะปะต ัะฐะฒะฝัะผ 29 ั ะฟะพะผะพััั ะผะตัะพะดะฐ `updateValue(_:, forKey:)`. ะัะฒะตะดะธัะต ัะพะดะตัะถะธะผะพะต ัะปะพะฒะฐัั ะฒ ะบะพะฝัะพะปั.
*/
dict.updateValue(29, forKey: "ะคะตะฒัะฐะปั")
print(dict)
/*:
ะก ะฟะพะผะพััั if-let ะฟะพะปััะธัะต ะบะพะปะธัะตััะฒะพ ะดะฝะตะน ะดะปั ะบะปััะฐ "ัะฝะฒะฐัั". ะัะปะธ ัะปะพะฒะฐัั ัะพะดะตัะถะธั ะดะฐะฝะฝัะต, ะฒัะฒะตะดะธัะต "ะะพะปะธัะตััะฒะพ ะดะฝะตะน ะฒ ัะฝะฒะฐัะต: 31", ะณะดะต 31 โย ััะพ ะทะฝะฐัะตะฝะธะต, ะฟะพะปััะตะฝะฝะพะต ะธะท ัะปะพะฒะฐัั.
*/
if let januaryCount = dict["ะฏะฝะฒะฐัั"] {
print(januaryCount)
}
/*:
ะะฐะดะฐะฝั ัะปะตะดัััะธะต ะผะฐััะธะฒั. ะกะพะทะดะฐะนัะต ะฝะพะฒัะน ัะปะพะฒะฐัั [String : [String]]. `shapesArray` ะดะพะปะถะตะฝ ะธัะฟะพะปัะทะพะฒะฐัั ะบะปัั "ัะพัะผั", ะฐ `colorsArray` โ ะบะปัั "ัะฒะตัะฐ". ะัะฒะตะดะธัะต ัะพะดะตัะถะธะผะพะต ะฟะพะปััะธะฒัะตะณะพัั ัะปะพะฒะฐัั.
*/
let shapesArray = ["ะบััะณ", "ะบะฒะฐะดัะฐั", "ััะตัะณะพะปัะฝะธะบ"]
let colorsArray = ["ะบัะฐัะฝัะน", "ะทะตะปัะฝัะน", "ัะธะฝะธะน"]
var arr: [String : [String]] = [:]
var seq = zip(shapesArray, [colorsArray])
var dict1 = Dictionary(uniqueKeysWithValues:seq)
//for (key, value) in dict1 {
// print("\(key) - \(value)")
//}
print(dict1)
/*:
ะัะฒะตะดะธัะต ะฟะพัะปะตะดะฝะธะน ัะปะตะผะตะฝั `colorsArray`, ะฟะพะปััะธะฒ ะตะณะพ ั ะฟะพะผะพััั ัะพะทะดะฐะฝะฝะพะณะพ ะฒะฐะผะธ ัะปะพะฒะฐัั. ะะฐะผ ะฝัะถะฝะพ ะธัะฟะพะปัะทะพะฒะฐัั if-let, ะปะธะฑะพ ะพะฟะตัะฐัะพั ั ะฒะพัะบะปะธัะฐัะตะปัะฝัะผ ะทะฝะฐะบะพะผ, ััะพะฑั ะธัะฟะพะปัะทะพะฒะฐัั ะทะฝะฐัะตะฝะธะต, ะฒะพะทะฒัะฐััะฝะฝะพะต ะธะท ัะปะพะฒะฐัั, ะดะพ ัะพะณะพ, ะบะฐะบ ะฒั ัะผะพะถะตัะต ะฟะพะปััะธัั ะดะพัััะฟ ะบ ัะปะตะผะตะฝัั ะผะฐััะธะฒะฐ.
*/
//: [ะ ะฐะฝะตะต](@previous) | ัััะฐะฝะธัะฐ 3 ะธะท 4 | [ะะฐะปะตะต: ะฃะฟัะฐะถะฝะตะฝะธะต ะดะปั ะฟัะธะปะพะถะตะฝะธั - ัะตะผะฟ](@next)
| true
|
1778c9d867aa25304499a1aadd86d1b1a10d3ceb
|
Swift
|
cprime/WatsonSpeechToTextDemo
|
/WatsonSpeechToTextDemo/AudioManager.swift
|
UTF-8
| 10,975
| 2.5625
| 3
|
[] |
no_license
|
//
// VoiceRecorder.swift
// bose-scribe
//
// Created by Colden Prime on 8/12/16.
// Copyright ยฉ 2016 Intrepid Pursuits LLC. All rights reserved.
//
import AVFoundation
import Foundation
import Intrepid
protocol AudioManagerType {
func recordPermission() -> AVAudioSessionRecordPermission
func hasRequestedRecordPermission() -> Bool
func hasRecordPermission() -> Bool
func requestRecordingPermission(withCompletion completion: (Bool) -> Void)
func startRecording(tapBlock: AVAudioNodeTapBlock?, interruptedCallback: ((ErrorType?) -> Void)?) throws
func stopRecording() throws -> NSURL
func startPlayingAudio(fileURL: NSURL, completion: ((ErrorType?) -> Void)?) throws
func stopPlayingAudio()
func toggleSessionActive(active: Bool) throws
}
// MARK: AudioManager.State Equatable
func ==(lhs: AudioManager.State, rhs: AudioManager.State) -> Bool {
switch (lhs, rhs) {
case (.Idle, .Idle), (.Recording(_), .Recording(_)), (.Playing(_), .Playing(_)):
return true
default:
return false
}
}
class AudioManager: NSObject, AudioManagerType, AVAudioSessionDelegate, AVAudioPlayerDelegate {
static let audioBus = 0
typealias InterruptedCallback = (ErrorType?) -> Void
typealias PlaybackCompletion = (ErrorType?) -> Void
enum AudioError: ErrorType {
case Unauthorized
case Busy
case RecordingFailed
case RecordingInterrupted
case PlaybackFailed
case PlaybackInterrupted
}
enum State: Equatable {
case Idle
case PreparingToRecord(interruptedCallback: InterruptedCallback?)
case Recording(audioFile: AVAudioFile, interruptedCallback: InterruptedCallback?)
case Playing(playbackCompletion: PlaybackCompletion?)
var isIdle: Bool {
get {
switch self {
case Idle:
return true
default:
return false
}
}
}
var isPreparingToRecord: Bool {
get {
switch self {
case .PreparingToRecord:
return true
default:
return false
}
}
}
var isRecording: Bool {
get {
switch self {
case .Recording(_):
return true
default:
return false
}
}
}
var isPlaying: Bool {
get {
switch self {
case .Playing(_):
return true
default:
return false
}
}
}
var interruptedCallback: InterruptedCallback? {
switch self {
case .PreparingToRecord(let interruptedCallback):
return interruptedCallback
case .Recording(_, let interruptedCallback):
return interruptedCallback
default:
return nil
}
}
var playbackCompletion: PlaybackCompletion? {
get {
switch self {
case .Playing(let completion):
return completion
default:
return nil
}
}
}
}
private(set) var state = State.Idle {
didSet {
guard oldValue != state else { return }
_ = try? toggleSessionActive(state == .Idle ? false : true)
}
}
static let sharedInstance = AudioManager()
private var recordingFileURL: NSURL = NSURL(fileURLWithPath: "\(NSFileManager.documentPath)/Voice_Recording.caf")
private var audioEngine = AVAudioEngine()
private var audioPlayer: AVAudioPlayer?
private var tonePlayers = [AVAudioPlayer]()
private override init() {
super.init()
registerForNotifications()
}
deinit {
unregisterForNotifications()
}
private func generateUniqueFileURL() -> NSURL {
return NSURL(fileURLWithPath: "\(NSFileManager.documentPath)/Voice_Recording_\(NSUUID().UUIDString).caf")
}
func setupSession() {
do {
UIApplication.sharedApplication().beginReceivingRemoteControlEvents()
let session = AVAudioSession.sharedInstance()
try session.setCategory(AVAudioSessionCategoryPlayAndRecord,
withOptions: [.AllowBluetooth, .DefaultToSpeaker])
let bluetoothHFP = session.availableInputs?.filter({ $0.portType == AVAudioSessionPortBluetoothHFP }).first
try session.setPreferredInput(bluetoothHFP)
} catch let e {
print(e)
}
}
func toggleSessionActive(active: Bool) throws {
do {
try AVAudioSession.sharedInstance().setActive(active, withOptions: .NotifyOthersOnDeactivation)
} catch let e {
print(e)
throw e
}
}
// MARK: - Authorization
func recordPermission() -> AVAudioSessionRecordPermission {
return AVAudioSession.sharedInstance().recordPermission()
}
func hasRequestedRecordPermission() -> Bool {
return self.recordPermission() != .Undetermined
}
func hasRecordPermission() -> Bool {
return self.recordPermission() == .Granted
}
func requestRecordingPermission(withCompletion completion: (Bool) -> Void) {
AVAudioSession.sharedInstance().requestRecordPermission { recordPermissionGranted in
Qu.Main {
completion(recordPermissionGranted)
}
}
}
// MARK: - Controls
func startRecording(tapBlock: AVAudioNodeTapBlock?, interruptedCallback: InterruptedCallback?) throws {
guard AudioManager.sharedInstance.hasRecordPermission() else { throw AudioError.Unauthorized}
guard state.isIdle else { throw AudioError.Busy }
state = .PreparingToRecord(interruptedCallback: interruptedCallback)
do {
guard let inputNode = audioEngine.inputNode else { throw AudioError.RecordingFailed }
let audioFile = try AVAudioFile(forWriting: recordingFileURL, settings: inputNode.inputFormatForBus(AudioManager.audioBus).settings)
let recordingFormat = inputNode.inputFormatForBus(AudioManager.audioBus)
inputNode.installTapOnBus(AudioManager.audioBus, bufferSize: 1024, format: recordingFormat) { (buffer: AVAudioPCMBuffer, when: AVAudioTime) in
_ = try? audioFile.writeFromBuffer(buffer)
tapBlock?(buffer, when)
}
try audioEngine.start()
state = .Recording(audioFile: audioFile, interruptedCallback: interruptedCallback)
} catch let e {
print(e)
finishRecording()
throw AudioError.RecordingFailed
}
}
func stopRecording() throws -> NSURL {
guard AudioManager.sharedInstance.hasRecordPermission() else { throw AudioError.Unauthorized }
var tempFile: AVAudioFile?
switch state {
case .Recording(let file, _):
tempFile = file
default:
break
}
guard let audioFile = tempFile else { throw AudioError.Busy }
do {
finishRecording()
let fileManager = NSFileManager.defaultManager()
let finalFileURL = generateUniqueFileURL()
try fileManager.moveItemAtURL(audioFile.url, toURL: finalFileURL)
return finalFileURL
} catch let e {
print(e)
throw AudioError.RecordingFailed
}
}
func startPlayingAudio(fileURL: NSURL, completion: PlaybackCompletion?) throws {
guard state.isIdle else { throw AudioError.Busy }
state = .Playing(playbackCompletion: completion)
do {
audioPlayer = try AVAudioPlayer(contentsOfURL: fileURL)
audioPlayer?.delegate = self
audioPlayer?.play()
} catch {
state = .Idle
throw AudioError.PlaybackFailed
}
}
func stopPlayingAudio() {
guard state.isPlaying else { return }
audioPlayer?.stop()
state = .Idle
}
// MARK: - Cleanup
private func finishRecording() {
audioEngine.stop()
audioEngine.inputNode?.removeTapOnBus(AudioManager.audioBus)
audioEngine.reset()
After(1.0) {
// either recorder.stop() or playing the StopRecording tone seems to need a second to finish
self.state = .Idle
}
}
// MARK: - Notifications
private func registerForNotifications() {
NSNotificationCenter.defaultCenter().addObserver(self,
selector: #selector(AudioManager.handleAudioSessionInterruptionNotification),
name: AVAudioSessionInterruptionNotification,
object: AVAudioSession.sharedInstance())
}
private func unregisterForNotifications() {
NSNotificationCenter.defaultCenter().removeObserver(self,
name: AVAudioSessionInterruptionNotification,
object: AVAudioSession.sharedInstance())
}
@objc private func handleAudioSessionInterruptionNotification(notification: NSNotification) {
guard notification.name == AVAudioSessionInterruptionNotification else { return }
guard let value = notification.userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt,
let interruptionType = AVAudioSessionInterruptionType(rawValue: value) where interruptionType == .Began else { return }
switch state {
case .Idle:
break
case .PreparingToRecord(_), .Recording(_):
let interruptedCallback = state.interruptedCallback
finishRecording()
Qu.Main {
interruptedCallback?(AudioError.RecordingInterrupted)
}
case .Playing(let playbackCompletion):
audioPlayer?.stop()
audioPlayer = nil
state = .Idle
Qu.Main {
playbackCompletion?(AudioError.PlaybackInterrupted)
}
}
}
// MARK: - AVAudioPlayerDelegate
@objc func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool) {
if player == audioPlayer {
guard state.isPlaying else { return }
let completion = state.playbackCompletion
state = .Idle
audioPlayer = nil
completion?(nil)
} else if let i = tonePlayers.indexOf(player) {
tonePlayers.removeAtIndex(i)
}
}
}
| true
|
3eb5f2b58da3b027d9ec70e0aa87750c80ce35da
|
Swift
|
milomi/CV_APP
|
/OSOM_app/Screens/SignUp/Name/ViewController/SignUpNameViewController.swift
|
UTF-8
| 2,786
| 2.515625
| 3
|
[] |
no_license
|
//
// SignUpNameViewController.swift
// OSOM_app
//
// Created by Miลosz Bugla on 15.10.2017.
//
import Foundation
import UIKit
import SwiftValidator
final class SignUpNameViewController: UIViewController {
fileprivate let mainView: SignUpNameView
fileprivate var navigator: NavigationController?
fileprivate let validator = Validator()
init(mainView: SignUpNameView) {
self.mainView = mainView
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
setupView()
setupNavigation()
}
override func viewDidAppear(_ animated: Bool) {
DispatchQueue.main.async(execute: {
self.mainView.fadeIn()
})
}
fileprivate func setupNavigation() {
navigator = NavigationController(navigationView: mainView.navigation, navigationController: navigationController)
navigator?.delegate = self
}
private func setupView() {
view = mainView
mainView.setupView()
registerValidatableFields()
}
}
extension SignUpNameViewController: NavigationControllerDelegate {
func rightAction() {
validator.validate(self)
}
func backAction() {
mainView.animate(entry: false, completion: {
self.navigationController?.popViewController(animated: false)
})
}
}
extension SignUpNameViewController: ValidationDelegate {
func validationSuccessful() {
mainView.clearErrorLabels()
DispatchQueue.main.async(execute: {
self.mainView.animate(entry: true, completion: {
let user = User()
user.name = self.mainView.nameEditField.textField.text ?? ""
user.surname = self.mainView.surnameEditField.textField.text ?? ""
let vc = ViewControllerContainer.shared.getSignUpEmail(user: user)
self.navigationController?.pushViewController(vc, animated: false)
})
})
}
func validationFailed(_ errors: [(Validatable, ValidationError)]) {
mainView.clearErrorLabels()
for (field, error) in errors {
if let field = field as? UITextField {
error.errorLabel?.text = error.errorMessage
field.shake()
}
}
}
fileprivate func registerValidatableFields() {
validator.registerField(mainView.nameEditField.textField, errorLabel: mainView.nameEditField.errorLabel, rules: [RequiredRule()])
validator.registerField(mainView.surnameEditField.textField, errorLabel: mainView.surnameEditField.errorLabel, rules: [RequiredRule()])
}
}
| true
|
9b89a031c55e095f3e7291d22f2efce26aef8084
|
Swift
|
Shivam0911/IOS-Training-Projects
|
/HitList/HitList/DBhelper.swift
|
UTF-8
| 3,202
| 2.90625
| 3
|
[
"MIT"
] |
permissive
|
//
// DBhelper.swift
// HitList
//
// Created by MAC on 24/02/17.
// Copyright ยฉ 2017 Razeware. All rights reserved.
//
import Foundation
import CoreData
import UIKit
class DBhelper {
//MARK: Variables
//============
var people = [Person]()
var name : String
var age : Int
var email : String
var gender : String
//MARK: Initializers
//=============
init() {
name = ""
age = 0
email = ""
gender = ""
}
init(withName name : String , withAge age : Int , withEmail email : String , withGender gender : String) {
self.name = name
self.age = age
self.email = email
self.gender = gender
}
}
extension DBhelper {
//MARK: SaveData Method
//==================
func saveData() {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
let managedContext = appDelegate.persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "Person" , in: managedContext)!
let person = Person(entity: entity , insertInto: managedContext)
person.name = name
person.age = Int16(age)
person.email = email
person.gender = gender
do {
try managedContext.save()
people.append(person)
} catch let error as NSError {
print("Could not save. \(error), \(error.userInfo)")
}
}
//MARK: getData Method
//==================
func getData(){
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
fatalError("no Delegate !")
}
let managedContext = appDelegate.persistentContainer.viewContext
let fetchRequest : NSFetchRequest<Person> = Person.fetchRequest()
do {
people = try managedContext.fetch(fetchRequest)
}
catch let error as NSError {
print("Could not fetch. \(error), \(error.userInfo)")
}
}
//MARK: deleteData Method
//===================
func deleteData(_ deleteSpecificData : Person) {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
fatalError("no Delegate !")
}
let managedContext = appDelegate.persistentContainer.viewContext
managedContext.delete(deleteSpecificData)
do {
try managedContext.save()
}
catch _ {
}
}
//MARK: editAtPerson Method
//=====================
func editAtPerson(_ atPerson : Person , _ personIndex : Int) {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
fatalError("no Delegate !")
}
let managedContext = appDelegate.persistentContainer.viewContext
people[personIndex].name = atPerson.name
people[personIndex].email = atPerson.email
people[personIndex].age = atPerson.age
people[personIndex].gender = atPerson.gender
do{
try managedContext.save()
print("saved")
}catch let error as NSError {
print("Could not save \(error)")
}
}
}
| true
|
4ec59ce4fb49879a763f8ee3a998f572a8d8771d
|
Swift
|
aryaputras/DrugCounter2
|
/DrugCounter2/Helper.swift
|
UTF-8
| 1,146
| 3.3125
| 3
|
[] |
no_license
|
//
// Helper.swift
// DrugCounter2
//
// Created by Abigail Aryaputra Sudarman on 07/12/20.
//
import Foundation
import SwiftUI
func getColor(color: String) -> Color {
var result: Color
if color == "pink" {
result = .pink
} else if color == "blue" {
result = .blue
} else if color == "purple" {
result = .purple
} else if color == "green" {
result = .green
} else if color == "black" {
result = .black
} else {
result = .white
}
return result
}
func getDosage(drugs: Drug) -> String{
var result: String
if drugs.dosage > 0 {
result = "\(drugs.dosage) mg"
} else {
result = "1 Cap(s)"
}
return result
}
func dateToString(date: Date) -> String{
let df = DateFormatter()
df.dateFormat = "hh:mm:ss"
let string = df.string(from: date)
return string
}
func getShape(shape: String, color: String) -> some View {
return Image(shape + color).resizable()
.frame(width: 130, height: 130, alignment: .center)
.shadow(color: Color(hue: 0, saturation: 0, brightness: 0, opacity: 0.35), radius: 4, x: 0.0, y: 3)
}
| true
|
d2ed9b68339ec6c8be5d1a86a0e564912c7c5806
|
Swift
|
hamchapman/codesearch
|
/codesearch/Read.swift
|
UTF-8
| 18,780
| 3.078125
| 3
|
[] |
no_license
|
import Foundation
// Constants
let indexHeader = "csearch index 1\n"
let indexTrailer = "\ncsearch trailr\n"
let postEntrySize = 3 + 4 + 4
//// An mmapData is mmap'ed read-only data from a file.
//
////type mmapData struct {
//// f *os.File
//// d []byte
////}
//
struct MmapData {
let filePath: URL
let data: Data
}
// An Index implements read-only access to a trigram index.
struct Index {
let verbose: Bool
let data: MmapData
let pathData: UInt32
let nameData: UInt32
let postData: UInt32
let nameIndex: UInt32
let postIndex: UInt32
let numName: Int
let numPost: Int
}
func corrupt() {
fatalError("Corrupt index: remove \(indexPath())")
}
// mmap maps the given file into memory.
func mmap(filePath: String) -> MmapData {
// f, err := os.Open(file)
// if err != nil {
// log.Fatal(err)
// }
guard let filePathURL = URL(string: filePath) else {
fatalError("Couldn't create URL from string: \(filePath)")
}
return mmapFile(filePath: filePathURL)
}
func openIndex(atFilePath filePath: String) -> Index {
let mm = mmap(filePath: filePath)
let indexTrailerBytesLength = indexTrailer.lengthOfBytes(using: .utf8)
let afterTrailerOffset = mm.data.count - indexTrailer.count
// TODO: Is lengthOfBytes correct? Is utf8 correct?
guard mm.data.count >= 4 * 4 + indexTrailerBytesLength else {
corrupt()
}
// TODO: Should the range be ..< or ...
guard String(data: mm.data.subdata(in: afterTrailerOffset..<mm.data.endIndex), encoding: .utf8) != indexTrailer else {
corrupt()
}
let n = UInt32(mm.data.count - indexTrailerBytesLength - 5 * 4)
let index = Index(
verbose: false,
data: mm,
pathData: UInt32(n),
nameData: UInt32(n + 4),
postData: UInt32(n + 8),
nameIndex: UInt32(n + 12),
postIndex: UInt32(n + 16),
numName: Int((UInt32(n + 16) - UInt32(n + 12)) / 4) - 1,
numPost: Int((n - (n + 16))) / postEntrySize
)
return index
// ix := &Index{data: mm}
// ix.pathData = ix.uint32(n)
// ix.nameData = ix.uint32(n + 4)
// ix.postData = ix.uint32(n + 8)
// ix.nameIndex = ix.uint32(n + 12)
// ix.postIndex = ix.uint32(n + 16)
// ix.numName = int((ix.postIndex-ix.nameIndex)/4) - 1
// ix.numPost = int((n - ix.postIndex) / postEntrySize)
// return ix
}
// TODO: Does slice work with length -1 (e.g. from IndexByte)
// slice returns the slice of index data starting at the given byte offset.
// If length >= 0, the slice must have length at least length and is truncated
// to length length.
func slice(index: Index, offset: UInt32, length: Int) -> Data {
let o = Int(offset)
if UInt32(o) != offset || length >= 0 && o + length > index.data.data.count {
corrupt()
}
if length < 0 {
return index.data.data[o..<index.data.data.endIndex]
}
return index.data.data[o..<(o + length)]
}
///// Gets an unsigned int (32 bits => 4 bytes) from the given index.
/////
///// - parameter index: The index of the uint to be retrieved. Note that this should never be >= length -
///// 3.
/////
///// - returns: The unsigned int located at position `index`.
//func getUnsignedInteger(at index: Int, bigEndian: Bool = true) -> UInt32 {
// let data: UInt32 = self.subdata(in: index ..< (index + 4)).withUnsafeBytes { $0.pointee }
// return bigEndian ? data.bigEndian : data.littleEndian
//}
// uint32 returns the uint32 value at the given offset in the index data.
func valueOf(index: Index, atOffset offset: UInt32) -> UInt32 {
let data: UInt32 = slice(index: index, offset: offset, length: 4).withUnsafeBytes { $0.pointee }
return data.bigEndian
}
func uvarint(index: Index, offset: UInt32) -> UInt32 {
// v, n := binary.Uvarint(ix.slice(off, -1))
// if n <= 0 {
// corrupt()
// }
// return uint32(v)
//
//
// v, n := binary.Uvarint(ix.slice(off, -1))
let data: UInt32 = slice(index: index, offset: offset, length: -1).withUnsafeBytes { $0.pointee }
return data
}
// Paths returns the list of indexed paths.
//func (ix *Index) Paths() []string {
// off := ix.pathData
// var x []string
// for {
// s := ix.str(off)
// if len(s) == 0 {
// break
// }
// x = append(x, string(s))
// off += uint32(len(s) + 1)
// }
// return x
//}
func paths(fromIndex index: Index) -> [String] {
var offset = index.pathData
var paths: [String] = []
for {
let s = str(index: index, offset: offset)
if s.count == 0 {
break
}
paths.append(String(data: s, encoding: .utf8))
offset = offset + UInt32(s.count + 1)
}
return paths
}
func str(index: Index, offset: UInt32) -> Data {
let str = slice(index: index, offset: offset, length: -1)
guard let i = str.firstIndex(where: { $0 == 0x0 }) else { // TODO: does this check work or do I need to do String($0) == "\0"
corrupt()
}
return str[str.startIndex..<i]
}
// NameBytes returns the name corresponding to the given fileid.
func nameBytes(index: Index, fileID: UInt32) -> Data {
let offset = index.nameIndex + (4 * fileID)
return str(index: index, offset: index.nameData + offset)
}
func name(index: Index, fileID: UInt32) -> String {
// TODO: Should we bang here?
return String(data: nameBytes(index: index, fileID: fileID), encoding: .utf8)!
}
// TODO: This seems a bit mad
// TODO: Probs want to make a struct for the list
func listAt(index: Index, offset: UInt32) -> (trigram: UInt32, count: UInt32, offset: UInt32) {
let d = slice(index: index, offset: index.postIndex + offset, length: postEntrySize)
let trigram = UInt32(d[0]) << 16 | UInt32(d[1]) << 8 | UInt32(d[2])
let countData: UInt32 = d[3..<d.endIndex].withUnsafeBytes { $0.pointee }
let count = countData.bigEndian
let returnOffsetData: UInt32 = d[(3 + 4)..<d.endIndex].withUnsafeBytes { $0.pointee }
let offsetToReturn = returnOffsetData.bigEndian
return (trigram, count, offsetToReturn)
}
func dumpPosting(index: Index) {
let d = slice(index: index, offset: index.postIndex, length: postEntrySize * index.numPost)
(0...index.numPost).forEach { i in
let j = i * postEntrySize
let t = UInt32(d[j]) << 16 | UInt32(d[j+1]) << 8 | UInt32(d[j + 2])
let countData: UInt32 = d[(j + 3)..<d.endIndex].withUnsafeBytes { $0.pointee }
let count = countData.bigEndian
let offsetData: UInt32 = d[(j + 3 + 4)..<d.endIndex].withUnsafeBytes { $0.pointee }
let offset = offsetData.bigEndian
// log.Printf("%#x: %d at %d", t, count, offset)
print("Dump: ", t, count, offset)
}
}
func findList(index: Index, trigram: UInt32) -> (count: Int, offset: UInt32) {
// binary search
let d = slice(index: index, offset: index.postIndex, length: postEntrySize * index.numPost)
var i = sort.Search(index.numPost, { (i: Int) -> Bool in
i *= postEntrySize
let t = UInt32(d[i]) << 16 | UInt32(d[i + 1]) << 8 | UInt32(d[i + 2])
return t >= trigram
})
guard i < index.numPost else {
return (0, 0)
}
i *= postEntrySize
let t = UInt32(d[i]) << 16 | UInt32(d[i + 1]) << 8 | UInt32(d[i + 2])
guard t == trigram else {
return (0, 0)
}
let countData: UInt32 = d[(i + 3)..<d.endIndex].withUnsafeBytes { $0.pointee }
let count = countData.bigEndian
let offsetData: UInt32 = d[(i + 3 + 4)..<d.endIndex].withUnsafeBytes { $0.pointee }
let offset = offsetData.bigEndian
return (count, offset)
}
//func (ix *Index) str(off uint32) []byte {
// str := ix.slice(off, -1)
// i := bytes.IndexByte(str, '\x00')
// if i < 0 {
// corrupt()
// }
// return str[:i]
//}
// Name returns the name corresponding to the given fileid.
//func (ix *Index) Name(fileid uint32) string {
// return string(ix.NameBytes(fileid))
//}
// listAt returns the index list entry at the given offset.
//func (ix *Index) listAt(off uint32) (trigram, count, offset uint32) {
// d := ix.slice(ix.postIndex+off, postEntrySize)
// trigram = uint32(d[0])<<16 | uint32(d[1])<<8 | uint32(d[2])
// count = binary.BigEndian.Uint32(d[3:])
// offset = binary.BigEndian.Uint32(d[3+4:])
// return
//}
//func (ix *Index) dumpPosting() {
// d := ix.slice(ix.postIndex, postEntrySize*ix.numPost)
// for i := 0; i < ix.numPost; i++ {
// j := i * postEntrySize
// t := uint32(d[j])<<16 | uint32(d[j+1])<<8 | uint32(d[j+2])
// count := int(binary.BigEndian.Uint32(d[j+3:]))
// offset := binary.BigEndian.Uint32(d[j+3+4:])
// log.Printf("%#x: %d at %d", t, count, offset)
// }
//}
//func (ix *Index) findList(trigram uint32) (count int, offset uint32) {
// // binary search
// d := ix.slice(ix.postIndex, postEntrySize*ix.numPost)
// i := sort.Search(ix.numPost, func(i int) bool {
// i *= postEntrySize
// t := uint32(d[i])<<16 | uint32(d[i+1])<<8 | uint32(d[i+2])
// return t >= trigram
// })
// if i >= ix.numPost {
// return 0, 0
// }
// i *= postEntrySize
// t := uint32(d[i])<<16 | uint32(d[i+1])<<8 | uint32(d[i+2])
// if t != trigram {
// return 0, 0
// }
// count = int(binary.BigEndian.Uint32(d[i+3:]))
// offset = binary.BigEndian.Uint32(d[i+3+4:])
// return
//}
class PostReader {
let index: Index
var count: Int
let offset: UInt32
var fileID: UInt32
let data: Data
var restrict: [UInt32]?
init(index: Index, trigram: UInt32, restrict: [UInt32]? = nil) {
let (count, offset) = findList(index: index, trigram: trigram)
guard count != 0 else {
return // TOOD: Should this be a failable intializer?
}
self.index = index
self.count = count
self.offset = offset
self.fileID = ~UInt32(0)
self.data = slice(index: index, offset: index.postData + offset + 3, length: -1)
self.restrict = restrict
}
func max() -> Int {
return self.count
}
func next() -> Bool {
while self.count > 0 {
self.count -= 1
let delta: UInt32 = self.data.withUnsafeBytes { $0.pointee }
// delta64, n := binary.Uvarint(r.d)
if n <= 0 || delta == 0 {
corrupt()
}
self.data = self.data[n..<self.data.endIndex]
self.fileID += delta
if self.restrict != nil {
var i = 0
while i < self.restrict!.count && self.restrict![i] < self.fileID {
i += 1
}
self.restrict! = self.restrict![i..<self.restrict!.endIndex]
if self.restrict!.count == 0 || self.restrict![0] != self.fileID {
continue
}
}
return true
}
// list should end with terminating 0 delta
// TODO: Should data be optional?
if self.data != nil && (self.data.count == 0 || self.data[0] != 0) {
corrupt()
}
self.fileID = ~UInt32(0)
return false
}
}
//func (r *postReader) init(ix *Index, trigram uint32, restrict []uint32) {
// count, offset := ix.findList(trigram)
// if count == 0 {
// return
// }
// r.ix = ix
// r.count = count
// r.offset = offset
// r.fileid = ^uint32(0)
// r.d = ix.slice(ix.postData+offset+3, -1)
// r.restrict = restrict
//}
//func (r *postReader) max() int {
// return int(r.count)
//}
//
//func (r *postReader) next() bool {
// for r.count > 0 {
// r.count--
// delta64, n := binary.Uvarint(r.d)
// delta := uint32(delta64)
// if n <= 0 || delta == 0 {
// corrupt()
// }
// r.d = r.d[n:]
// r.fileid += delta
// if r.restrict != nil {
// i := 0
// for i < len(r.restrict) && r.restrict[i] < r.fileid {
// i++
// }
// r.restrict = r.restrict[i:]
// if len(r.restrict) == 0 || r.restrict[0] != r.fileid {
// continue
// }
// }
// return true
// }
// // list should end with terminating 0 delta
// if r.d != nil && (len(r.d) == 0 || r.d[0] != 0) {
// corrupt()
// }
// r.fileid = ^uint32(0)
// return false
//}
//func (ix *Index) PostingList(trigram uint32) []uint32 {
// return ix.postingList(trigram, nil)
//}
//func postingList(index: Index, trigram: UInt32) -> [UInt32] {
// return postingList(index: index, trigram: trigram, restrict: nil)
//}
func postingList(index: Index, trigram: UInt32, restrict: [UInt32]? = nil) -> [UInt32] {
let r = PostReader(index: index, trigram: trigram, restrict: restrict)
var x: [UInt32] = Array(repeating: 0, count: r.max())
while r.next() { x.append(r.fileID) }
return x
}
//func (ix *Index) postingList(trigram uint32, restrict []uint32) []uint32 {
// var r postReader
// r.init(ix, trigram, restrict)
// x := make([]uint32, 0, r.max())
// for r.next() {
// x = append(x, r.fileid)
// }
// return x
//}
//func (ix *Index) PostingAnd(list []uint32, trigram uint32) []uint32 {
// return ix.postingAnd(list, trigram, nil)
//}
//func postingAnd(index: Index, list: [UInt32], trigram: UInt32) -> [UInt32] {
// return postingAnd(list, trigram, nil)
//}
func postingAnd(index: Index, list: [UInt32], trigram: UInt32, restrict: [UInt32]? = nil) -> [UInt32] {
let r = PostReader(index: index, trigram: trigram, restrict: restrict)
var x = list[:0] // TOOD: wut?
var i = 0
while r.next() {
let fileID = r.fileID
while i < list.count && list[i] < fileID {
i += 1
}
if i < list.count && list[i] == fileID {
x.append(fileID)
i += 1
}
}
return x
}
//func (ix *Index) PostingOr(list []uint32, trigram uint32) []uint32 {
// return ix.postingOr(list, trigram, nil)
//}
func postingOr(index: Index, list: [UInt32], trigram: UInt32, restrict: [UInt32]? = nil) -> [UInt32] {
let r = PostReader(index: index, trigram: trigram, restrict: restrict)
var x: [UInt32] = Array(repeating: 0, count: list.count + r.max())
var i = 0
while r.next() {
let fileID = r.fileID
while i < list.count && list[i] < fileID {
x.append(list[i])
i += 1
}
x.append(fileID)
if i < list.count && list[i] == fileID {
i += 1
}
}
x.append(contentsOf: list[i..<list.endIndex])
return x
}
func postingQuery(index: Index, query: Query, restrict: [UInt32]? = nil) -> [UInt32] {
var list: [UInt32] = []
switch q.Op {
case QNone:
// nothing
case QAll:
if restrict != nil {
return restrict
}
list = make([]uint32, ix.numName)
for i := range list {
list[i] = uint32(i)
}
return list
case QAnd:
for _, t := range q.Trigram {
tri := uint32(t[0])<<16 | uint32(t[1])<<8 | uint32(t[2])
if list == nil {
list = ix.postingList(tri, restrict)
} else {
list = ix.postingAnd(list, tri, restrict)
}
if len(list) == 0 {
return nil
}
}
for _, sub := range q.Sub {
if list == nil {
list = restrict
}
list = ix.postingQuery(sub, list)
if len(list) == 0 {
return nil
}
}
case QOr:
for _, t := range q.Trigram {
tri := uint32(t[0])<<16 | uint32(t[1])<<8 | uint32(t[2])
if list == nil {
list = ix.postingList(tri, restrict)
} else {
list = ix.postingOr(list, tri, restrict)
}
}
for _, sub := range q.Sub {
list1 := ix.postingQuery(sub, restrict)
list = mergeOr(list, list1)
}
}
return list
}
//func (ix *Index) PostingQuery(q *Query) []uint32 {
// return ix.postingQuery(q, nil)
//}
//func (ix *Index) postingQuery(q *Query, restrict []uint32) (ret []uint32) {
// var list []uint32
// switch q.Op {
// case QNone:
// // nothing
// case QAll:
// if restrict != nil {
// return restrict
// }
// list = make([]uint32, ix.numName)
// for i := range list {
// list[i] = uint32(i)
// }
// return list
// case QAnd:
// for _, t := range q.Trigram {
// tri := uint32(t[0])<<16 | uint32(t[1])<<8 | uint32(t[2])
// if list == nil {
// list = ix.postingList(tri, restrict)
// } else {
// list = ix.postingAnd(list, tri, restrict)
// }
// if len(list) == 0 {
// return nil
// }
// }
// for _, sub := range q.Sub {
// if list == nil {
// list = restrict
// }
// list = ix.postingQuery(sub, list)
// if len(list) == 0 {
// return nil
// }
// }
// case QOr:
// for _, t := range q.Trigram {
// tri := uint32(t[0])<<16 | uint32(t[1])<<8 | uint32(t[2])
// if list == nil {
// list = ix.postingList(tri, restrict)
// } else {
// list = ix.postingOr(list, tri, restrict)
// }
// }
// for _, sub := range q.Sub {
// list1 := ix.postingQuery(sub, restrict)
// list = mergeOr(list, list1)
// }
// }
// return list
//}
func mergeOr(l1: [UInt32], l2: [UInt32]) -> [UInt32] {
var l: [UInt32] = []
var i = 0
var j = 0
while i < l1.count || j < l2.count {
switch {
case j == l2.count || (i < l1.count && l1[i] < l2[j]):
l.append(l1[i])
i += 1
case i == l1.count || (j < l2.count && l1[i] > l2[j]):
l.append(l2[j])
j += 1
case l1[i] == l2[j]:
l.append(l1[i])
i += 1
j += 1
}
}
return l
}
// Returns the name of the index file to use.
// It's either $CSEARCHINDEX or $HOME/.csearchindex.
func indexPath() -> String {
if let cSearchIndex = ProcessInfo.processInfo.environment["CSEARCHINDEX"] {
if !cSearchIndex.isEmpty {
return cSearchIndex
}
}
return FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".csearchindex").absoluteString
}
| true
|
c6361a1606e20cf7cac7d6f07778476426b15629
|
Swift
|
hopinxian/paintsplash
|
/paintsplash/Health/HealthComponent.swift
|
UTF-8
| 666
| 3.28125
| 3
|
[] |
no_license
|
//
// HealthComponent.swift
// paintsplash
//
// Created by Farrell Nah on 26/3/21.
//
class HealthComponent: Component {
var currentHealth: Int {
didSet {
if currentHealth > maxHealth {
currentHealth = maxHealth
}
if currentHealth < 0 {
currentHealth = 0
}
}
}
var maxHealth: Int
init(currentHealth: Int, maxHealth: Int) {
self.currentHealth = currentHealth
self.maxHealth = maxHealth
}
func heal(amount: Int) {
currentHealth += amount
}
func takeDamage(amount: Int) {
currentHealth -= amount
}
}
| true
|
6e223950436ecddb2b8184407a2f980bbe4add7f
|
Swift
|
ValeriiVV/OnlineToursTest
|
/OnlineToursTest/Modules/TourList/TourListDataSource.swift
|
UTF-8
| 1,182
| 2.65625
| 3
|
[] |
no_license
|
//
// TourListDataSource.swift
// OnlineToursTest
//
// Created by Valerii Korobov on 04.12.2020.
//
import UIKit
import AlamofireImage
protocol TourListDataSourceProtocol: UITableViewDataSource, UITableViewDelegate {
func update(with tours: [Tour]?)
}
final class TourListDataSource: NSObject, TourListDataSourceProtocol {
private var tourList: [Tour]? = []
func update(with tours: [Tour]?) {
self.tourList = tours
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
tourList?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: TourListTableViewCell.reuseIdentifier)
guard let tourCell = cell as? TourListTableViewCell,
let tourModel = tourList?[indexPath.row] else {
return UITableViewCell()
}
tourCell.set(forPost: tourModel)
guard let photoUrlString = tourModel.top?.cost?.hotel?.photos?.compactMap({$0}).first,
let photoUrl = URL(string: photoUrlString) else {
return tourCell
}
tourCell.tourImageView.af.setImage(withURL: photoUrl, placeholderImage: nil)
return tourCell
}
}
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.