hexsha
stringlengths 40
40
| size
int64 3
1.03M
| content
stringlengths 3
1.03M
| avg_line_length
float64 1.33
100
| max_line_length
int64 2
1k
| alphanum_fraction
float64 0.25
0.99
|
---|---|---|---|---|---|
4bd4fa991f5e13c05cf20b751335851046a6971b | 6,158 | Random Code:-
class func switchResponder<T:Countable>(textField:UITextField,arrTextFields:[UITextField],enumInstance:T.Type) {
let nextTag = (textField.tag + 1) % enumInstance.count()
let nextTextFieldTag = arrTextFields.filter({ (textField) -> Bool in
return textField.tag == nextTag
}).first
guard textField.tag != enumInstance.count() - 1, let reqdTextField = nextTextFieldTag else{
textField.resignFirstResponder()
return
}
reqdTextField.becomeFirstResponder()
}
class func stringMatches(text:String,regex:String) -> [NSTextCheckingResult]? {
guard let regExpression = try? NSRegularExpression(pattern: regex, options: NSRegularExpression.Options.caseInsensitive) else {
return nil
}
let matches = regExpression.matches(in: text, options: [], range: NSRange(location: 0, length: text.count))
let arrReqdmatches = matches.filter { (match) -> Bool in
return match.range.length > 0
}
return arrReqdmatches
}
enum APITypealias<Type> {
typealias apiCallBack = (Type?,ValidationError?) -> Void
typealias UploadImageCallBack = (Type?,Type?,ValidationError?) -> Void
}
eg:-
func validateForUniquePhoneNumber(callback:@escaping APITypealias<RegisterPhoneResponse>.apiCallBack) {
guard let service:DriverServicesDelegate = ServiceLocator.defaultLocator.service() else{
Logger.printValue(value: "could not hit service")
callback(nil, ValidationError(description: StringConstants.errorOccured))
return
}
service.checkForUniqueNumber(number: registrationModel.phone ?? "0", callBack: { (response, error) in
callback(response,error)
})
}
The most deadly multipart image upload (wink)(took a long time to make this work)
func uploadImage(image:UIImage,callBack:@escaping APITypealias<String>.UploadImageCallBack) {
PKHUD.sharedHUD.show()
guard let unwrappedData = UIImagePNGRepresentation(image) else{
callBack(nil,nil,ValidationError(description: StringConstants.errorOccured))
return
}
let request = UploadPhotoRequest(data:unwrappedData)
self.client.performMultipartUpload(request: request) {[weak self] (result) in
PKHUD.sharedHUD.hide(false)
self?.parseResponse(result: result){ (response,error) -> Void in
callBack(response?.name,response?.path, error)
}
}
}
public func performMultipartUpload<T:UploadRequestDelegate>(request:T,completion:@escaping ResultCallback<T.Response>) {
guard let url = URL(string: "\(baseEndpoint)\(request.resourceName)") else{
print("Could not perform multipart request")
completion(Result.failure(APIError.encoding))
return
}
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = RequestMethod.POST.rawValue
let boundary = "XXXXXX"
urlRequest.setValue("multipart/form-data; boundary=" + boundary,
forHTTPHeaderField: "Content-Type")
var tempData = Data()
guard let startBoundary = "--\(boundary)\r\n".data(using: String.Encoding.utf8),
let contentDispositionFile = "Content-Disposition: form-data; name=\"file\"; filename=\"image.png\"\r\n".data(using: String.Encoding.utf8),
let contentDispositionType = "Content-Disposition: form-data; name=\"type\"\r\n\r\nProfileImage\r\n".data(using: String.Encoding.utf8),
let contentType = "Content-Type: image/png\r\n\r\n".data(using: String.Encoding.utf8),let padding = "\r\n".data(using: String.Encoding.utf8),
let endBoundary = "--\(boundary)--\r\n".data(using: String.Encoding.utf8) else{
return
}
tempData.append(startBoundary)
tempData.append(contentDispositionType)
tempData.append(startBoundary)
tempData.append(contentDispositionFile)
tempData.append(contentType)
tempData.append(request.data!)
tempData.append(padding)
tempData.append(endBoundary)
urlRequest.httpBody = tempData
urlRequest.setValue(String(tempData.count), forHTTPHeaderField: "Content-Length")
self.session.dataTask(with: urlRequest) { (data, response, error) in
print(data?.count)
if let data = data {
do {
// Decode the top level response, and look up the decoded response to see
// if it's a success or a failure
let response = try JSONDecoder().decode(APIResponseBase<T.Response>.self, from: data)
if let data = response.data {
DispatchQueue.main.async {
completion(.success(data))
}
} else if let errors = response.errors {
DispatchQueue.main.async {
// one more condition in which you get data as nil for a successful reqeust so im checking if errors count is 0
print(errors.count)
guard errors.count == 0 else{
completion(.failure(APIError.server(messages: errors)))
return
}
completion(.success(nil))
}
} else {
DispatchQueue.main.async {
completion(.failure(APIError.decoding))
}
}
} catch {
DispatchQueue.main.async {
completion(.failure(error))
}
}
} else if let error = error {
DispatchQueue.main.async {
completion(.failure(error))
}
}
}.resume()
}
| 44.948905 | 149 | 0.583956 |
46de10305a1b298b93bd29c76ac78e2f35d18ab5 | 1,466 | //: ## MultiDelay Example
//: This is similar to the MultiDelay implemented in the Analog Synth X example project.
import AudioKitPlaygrounds
import AudioKit
let file = try AKAudioFile(readFileName: processingPlaygroundFiles[0],
baseDir: .resources)
var player = try AKAudioPlayer(file: file)
player.looping = true
var delays = [AKVariableDelay]()
var counter = 0
func multitapDelay(_ input: AKNode?, times: [Double], gains: [Double]) -> AKMixer {
let mix = AKMixer(input)
zip(times, gains).forEach { (time, gain) -> Void in
delays.append(AKVariableDelay(input, time: time))
mix.connect(AKBooster(delays[counter], gain: gain))
counter += 1
}
return mix
}
//: Delay Properties
var delayTime = 0.2 // Seconds
var delayMix = 0.4 // 0 (dry) - 1 (wet)
let gains = [0.5, 0.25, 0.15].map { gain -> Double in gain * delayMix }
let input = player
//: Delay Definition
let leftDelay = multitapDelay(input,
times: [1.5, 2.5, 3.5].map { t -> Double in t * delayTime },
gains: gains)
let rightDelay = multitapDelay(input,
times: [1.0, 2.0, 3.0].map { t -> Double in t * delayTime },
gains: gains)
let delayPannedLeft = AKPanner(leftDelay, pan: -1)
let delayPannedRight = AKPanner(rightDelay, pan: 1)
let mix = AKMixer(delayPannedLeft, delayPannedRight)
AudioKit.output = mix
AudioKit.start()
player.play()
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
| 29.32 | 88 | 0.685539 |
8f4ba4634223dcc8d6fd84044096f83586dd05d1 | 645 | //
// PFSettingTableViewCell.swift
// PuzzleFilterProduct
//
// Created by diantu on 2020/9/1.
// Copyright © 2020 diantus. All rights reserved.
//
import UIKit
class PFSettingTableViewCell: UITableViewCell {
@IBOutlet weak var leftImageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var rightLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 23.035714 | 65 | 0.686822 |
0e6ccbc269cce45a99d803e8a518429dda845b25 | 272 | class Solution {
func judgeSquareSum(_ c: Int) -> Bool {
for a in 0...Int(sqrt(Double(c))) {
let b = Int(sqrt(Double(c - a * a)))
if a * a + b * b == c {
return true
}
}
return false
}
}
| 20.923077 | 48 | 0.400735 |
891d64d162faf676e0c670f27bc683b92db0ab14 | 2,134 | //
// AppDelegate.swift
// Tipper
//
// Created by zach lee on 12/5/15.
// Copyright © 2015 zach lee. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 45.404255 | 285 | 0.752577 |
e0403fd4e16c717dc6995ce541568292e9ea5d83 | 2,963 | //
// Transitioner.swift
// KoalaTransitions
//
// Created by boulder on 5/13/19.
//
import Foundation
import UIKit
/// Tranisioner holds reference to the animator, and can be set as
/// the `transitioningDelegate` on any UIViewController
/// updates the 'playDirection' based on the presentation method called
open class Transitioner: NSObject, UIViewControllerTransitioningDelegate {
public let animator: Animator
/// foward the play direction to the backing animator
open var playDirection: AnimationDirection {
get {
return animator.playDirection
}
set {
animator.playDirection = newValue
}
}
open override var debugDescription: String {
return "[Transitioner] direction: \(playDirection) animator: \(animator.debugDescription ?? "")"
}
public init(animator: Animator) {
self.animator = animator
}
// MARK: - `UIViewControllerTransitioningDelegate` -
open func animationController(
forPresented _: UIViewController,
presenting _: UIViewController,
source _: UIViewController
) -> UIViewControllerAnimatedTransitioning? {
if animator.supportedPresentations.contains(.present) {
playDirection = .forward
return animator
} else {
return nil
}
}
open func animationController(forDismissed _: UIViewController) -> UIViewControllerAnimatedTransitioning? {
if animator.supportedPresentations.contains(.dismiss) {
playDirection = .backward
return animator
} else {
return nil
}
}
}
// MARK: - `UINavigationControllerDelegate` -
extension Transitioner: UINavigationControllerDelegate {
public func navigationController(
_: UINavigationController,
animationControllerFor operation: UINavigationController.Operation,
from _: UIViewController,
to _: UIViewController
) -> UIViewControllerAnimatedTransitioning? {
if animator.supportedPresentations.contains(.push), operation == .push {
playDirection = .forward
return animator
} else if animator.supportedPresentations.contains(.pop), operation == .pop {
playDirection = .backward
return animator
}
return nil
}
}
/// InOutTransitioner holds reference to two animators, a In and an Out
/// inAnimator will always be set to playDirection `.forward` and outAnimator to `.backward`
public class InOutTransitioner: Transitioner {
let outAnimator: Animator
public init(inAnimator: Animator, outAnimator: Animator) {
self.outAnimator = outAnimator
outAnimator.playDirection = .backward
super.init(animator: inAnimator)
}
public override func animationController(forDismissed _: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return outAnimator
}
}
| 31.521277 | 122 | 0.675667 |
ed3db61f3fa75b1daa579909830162771fef6944 | 1,462 | //
// OpenLibraryService.swift
// GoodQuotes
//
// Created by Kieran Bamford on 27/10/2021.
// Copyright © 2021 Protome. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
class OpenLibraryService {
static var sharedInstance = OpenLibraryService()
func searchForBook(title: String, author: String, completion: @escaping (Book?) -> ())
{
var titleQuery = title
if title.contains("(") {
let titleSplit = title.components(separatedBy: "(")
titleQuery = titleSplit.first ?? titleQuery
}
var components = URLComponents(string: "https://openlibrary.org/search.json")
components?.queryItems = [
URLQueryItem(name: "author", value: author),
URLQueryItem(name: "title", value: titleQuery)]
if let url = components?.url
{
Alamofire.request(url).responseJSON { response in
if let jsonResponse = response.result.value {
let json = JSON(jsonResponse)
let numFound = json["numFound"].intValue
if numFound == 0 { completion(nil) }
if numFound > 0, let bookJson = json["docs"].arrayValue.first {
let book = Book(json: bookJson)
completion(book)
}
}
}
}
}
}
| 31.782609 | 91 | 0.540356 |
f4aa122917f7f37a78e858db672d179b7efa1d38 | 3,340 | //
// Owl
// A declarative type-safe framework for building fast and flexible list with Tables & Collections
//
// Created by Daniele Margutti
// - Web: https://www.danielemargutti.com
// - Twitter: https://twitter.com/danielemargutti
// - Mail: [email protected]
//
// Copyright © 2019 Daniele Margutti. Licensed under Apache 2.0 License.
//
import UIKit
// MARK: - TableHeaderFooterAdapterProtocol -
public protocol TableHeaderFooterAdapterProtocol {
var modelCellType: Any.Type { get }
func registerHeaderFooterViewForDirector(_ director: TableDirector) -> String
func dequeueHeaderFooterForDirector(_ director: TableDirector) -> UITableViewHeaderFooterView?
@discardableResult
func dispatch(_ event: TableSectionEvents, isHeader: Bool, view: UIView?, section: Int) -> Any?
}
public extension TableHeaderFooterAdapterProtocol {
var modelCellIdentifier: String {
return String(describing: modelCellType)
}
}
// MARK: - TableHeaderFooterAdapter -
public class TableHeaderFooterAdapter<View: UITableViewHeaderFooterView>: TableHeaderFooterAdapterProtocol {
// MARK: - Public Properties -
public var modelCellType: Any.Type = View.self
// Events you can assign to monitor the header/footer of a section.
public var events = HeaderFooterEventsSubscriber()
// MARK: - Initialization -
public init(_ configuration: ((TableHeaderFooterAdapter) -> ())? = nil) {
configuration?(self)
}
// MARK: - Helper Function s-
public func registerHeaderFooterViewForDirector(_ director: TableDirector) -> String {
let id = View.reusableViewIdentifier
guard director.headerFooterReuseIdentifiers.contains(id) == false else {
return id
}
View.registerReusableView(inTable: director.table, as: .header) // or footer, it's the same for table
return id
}
public func dequeueHeaderFooterForDirector(_ director: TableDirector) -> UITableViewHeaderFooterView? {
let id = View.reusableViewIdentifier
return director.table?.dequeueReusableHeaderFooterView(withIdentifier: id)
}
@discardableResult
public func dispatch(_ event: TableSectionEvents, isHeader: Bool, view: UIView?, section: Int) -> Any? {
switch event {
case .dequeue:
events.dequeue?(HeaderFooterEvent(header: isHeader, view: view, at: section))
case .headerHeight:
return events.height?(HeaderFooterEvent(header: true, view: view, at: section))
case .footerHeight:
return events.height?(HeaderFooterEvent(header: false, view: view, at: section))
case .estHeaderHeight:
return events.estimatedHeight?(HeaderFooterEvent(header: true, view: view, at: section))
case .estFooterHeight:
return events.estimatedHeight?(HeaderFooterEvent(header: false, view: view, at: section))
case .endDisplay:
events.endDisplay?(HeaderFooterEvent(header: false, view: view, at: section))
case .willDisplay:
events.willDisplay?(HeaderFooterEvent(header: false, view: view, at: section))
}
return nil
}
}
| 34.43299 | 109 | 0.666467 |
756c3172a439d54c261fdfb3aa8f2f9474c05eb9 | 2,140 | //
// CatalogFactory.swift
// RSDCatalog
//
// Copyright © 2018 Sage Bionetworks. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder(s) nor the names of any contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission. No license is granted to the trademarks of
// the copyright holders even if such marks are included in this software.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
import Foundation
import ResearchStack2
/// Stub out a factory for this application. Any factory overrides that are used by the catalog
/// can be declared here. This stub is intentional so that unit tests will all use this rather
/// than risk adding it later and having unit tests fail to match the app logic b/c they do not
/// reference the preferred factory.
class CatalogFactory : RSDFactory {
}
| 48.636364 | 95 | 0.771495 |
398a345b6a82882a22bea78567ac79891c1319ec | 1,269 | //
// UIView+loading.swift
// Redwoods Insurance Project
//
// Created by Kevin Poorman on 11/26/18.
// Copyright © 2018 Salesforce. All rights reserved.
//
import Foundation
import UIKit
private var ActivityIndicatorViewAssociativeKey = "ActivityIndicatorViewAssociativeKey"
extension UIView {
var activityIndicatorView: UIActivityIndicatorView {
get {
if let activityIndicatorView = objc_getAssociatedObject(self, &ActivityIndicatorViewAssociativeKey) as? UIActivityIndicatorView {
return activityIndicatorView
} else {
let activityIndicatorView = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
activityIndicatorView.style = .whiteLarge
activityIndicatorView.color = .gray
activityIndicatorView.center = CGPoint(x: self.bounds.size.width/2, y: self.bounds.size.height/2) //center
activityIndicatorView.hidesWhenStopped = true
addSubview(activityIndicatorView)
objc_setAssociatedObject(self, &ActivityIndicatorViewAssociativeKey, activityIndicatorView, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return activityIndicatorView
}
}
set {
addSubview(newValue)
objc_setAssociatedObject(self, &ActivityIndicatorViewAssociativeKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
| 32.538462 | 132 | 0.784082 |
d77df92e691c0e26c84ac6656c863747889fc783 | 7,765 | //: Playground - noun: a place where people can play
import UIKit
//Mirror 都可以对其进行探索。强大的运行时特性,也意味着额外的开销。Mirror 的文档明确告诉我们,
//这个类型更多是用来在 Playground 和调试器中进行输出和观察用的。如果我们想要以高效的方式来处理字典转换问题,也许应该试试看其他思路
//
/*
let leaveWord = NSMutableAttributedString(string: "留言: 民地地 asdlfk 地 进kasjdfk al;sjf;lasd要工划顶起黑苹果机加工工要 工地工)")
let paraStyle = NSMutableParagraphStyle()
paraStyle.lineSpacing = 3
leaveWord.addAttributes([NSAttributedString.Key.paragraphStyle:paraStyle], range: NSMakeRange(0, leaveWord.length))
let size = leaveWord.size()
var zzz = [2,3,4,5,6,8]
for z in zzz {
if z % 2 == 0{
zzz.removeAll { (item) -> Bool in
return item == z
}
}
}
print(zzz)
let format = NumberFormatter()
format.numberStyle = .decimal
//format.maximumFractionDigits = 2
format.minimumFractionDigits = 2
var moneyStr = format.string(from: NSNumber(value: 100100.0/100.0))!
var a = 100
func testa(p:UnsafeMutableRawPointer){
print("a = ", p.load(as: Int.self))
p.storeBytes(of: 50, as: Int.self)
}
testa(p: &a)
print(a)
var p1 = withUnsafeMutablePointer(to: &a) { $0 }
p1.pointee = 200
print(p1.pointee)
let p2 = withUnsafePointer(to: &a){$0}
print(p1)
print(p2)
var p3 = withUnsafeMutablePointer(to: &a){UnsafeMutableRawPointer($0)}
print(p3.load(as: Int.self))
p3.storeBytes(of: 111, as: Int.self)
print(p3.load(as: Int.self))
var p4 = withUnsafePointer(to: &a){UnsafeRawPointer($0)}
print(p4.load(as: Int.self))
print(p3)
print(p4)
//获取指针的指针
var pp = withUnsafePointer(to: &p4){$0}
print(pp.pointee)
var p5 = malloc(16)
p5?.storeBytes(of: 10, as: Int.self)
p5?.storeBytes(of: 12, toByteOffset: 8, as: Int.self)
print(p5?.load(as: Int.self) ?? 0)
print(p5?.load(fromByteOffset: 8, as: Int.self) ?? 0)
free(p5)
print(Int.max)
var p6 = UnsafeMutableRawPointer.allocate(byteCount: 16, alignment: 1)
p6.storeBytes(of: 100, as: Int.self)
var p7 = p6.advanced(by: 8)
p7.storeBytes(of: 120, as: Int.self)
print(p6.load(as: Int.self))
print(p6.advanced(by: 8).load(as: Int.self))
p6.deallocate()
var p8 = UnsafeMutablePointer<Int>.allocate(capacity: 3)
p8.initialize(to: 123)
p8.initialize(repeating: 14, count: 2)
var p9 = p8.successor()
print(p9.pointee)
p9.successor().initialize(to: 15)
print(p9.successor().pointee)
p8.deinitialize(count: 3)
p8.deallocate()
var p10 = UnsafeMutableRawPointer(p8)
print(p10.load(as: Int.self))
print(p8)
print(p10)
print(p8.pointee)
var p11 = p10.assumingMemoryBound(to: Int.self)
print(p11.pointee)
print(p11)
p11.pointee = 1221
print(p8.pointee)
extension Array{
func isExistRepeatElement(condition:((_ item:Element)->Int)) -> Bool {
var m = [Int:Int]()
let res = self.map(condition)
for r in res {
if !m.keys.contains(r){
m[r] = 0
}
else{
m[r] = m[r]! + 1
return true
}
}
return false
}
}
struct arrayTest{
let id:Int
let name:String
}
let testArr = [arrayTest(id: 1, name: "123"),arrayTest(id: 1, name: "123"),arrayTest(id: 3, name: "123"),]
let res = testArr.isExistRepeatElement { (i) -> Int in
return i.id
}
print(res)
let arrInt = Array(0...100)
arrInt.forEach { (s) in
print(s)
}
for a in 0..<10 {
print(a)
}
let calendar = Calendar.current
let today = Date()
let day = calendar.dateComponents([.day], from: today).day!
print(day)
if day < 25 {
let preMonth = Date(timeInterval: -24 * 3600 * 25, since: today)
let range = calendar .range(of: .day, in: .month, for: preMonth)
for item in range!{
print(item)
}
}
func pre(x : Int){
print( (x - 1) % 12)
}
pre(x: 1)
pre(x: 2)
pre(x: 3)
pre(x: 12)
MemoryLayout<Int>.size
MemoryLayout<Int>.alignment
MemoryLayout<Int>.stride
MemoryLayout<Int?>.size
MemoryLayout<Int?>.alignment
MemoryLayout<Int?>.stride
MemoryLayout<Bool>.size
MemoryLayout<Bool>.alignment
MemoryLayout<Bool>.stride
MemoryLayout<String>.size
MemoryLayout<String>.alignment
MemoryLayout<String>.stride
MemoryLayout<String?>.size
MemoryLayout<String?>.alignment
MemoryLayout<String?>.stride
MemoryLayout<Data>.size
MemoryLayout<Data>.alignment
MemoryLayout<Data>.stride
MemoryLayout<UIColor>.size
MemoryLayout<CGPoint>.size
MemoryLayout<Double?>.size
MemoryLayout<Double?>.alignment
MemoryLayout<Double?>.stride
struct Me{
let age:Int? = 33
let height:Double? = 180
let name:String? = "xiaowang"
let haveF:Bool = true
}
MemoryLayout<Me>.size
MemoryLayout<Me>.alignment
MemoryLayout<Me>.stride
class MyClass{
func test() {
var me = Me()
print(me)
}
}
let myClass = MyClass()
myClass.test()
class MeClass{
let age:Int? = 33
let height:Double? = 180
let name:String? = "xiaowang"
let haveF:Bool = true
}
print("MeClass MemoryLayout")
MemoryLayout<MeClass>.size
MemoryLayout<MeClass>.alignment
MemoryLayout<MeClass>.stride
func heapTest(){
let m = MyClass()
print(m)
}
class Cat{
var name = "Cat"
func bark() {
print("Maow")
}
func headerPointOfClass() -> UnsafeMutableRawPointer {
return Unmanaged.passUnretained(self as AnyObject).toOpaque()
}
}
class Dog{
var name = "dog"
func bark() {
print("wang wang")
}
func headerPointerOfClass() -> UnsafeMutableRawPointer{
return Unmanaged.passUnretained(self as AnyObject).toOpaque()
}
}
func headTest(){
let cat = Cat()
let dog = Dog()
let catPointer = cat.headerPointOfClass()
let dogPointer = dog.headerPointerOfClass()
catPointer.advanced(by: 0).bindMemory(to: Dog.self, capacity: 1).initialize(to: dogPointer.assumingMemoryBound(to: Dog.self).pointee)
cat.bark()
}
//headTest()
struct MirrorObject {
let intValue = 256
let uint8Value: UInt8 = 15
let boolValue = false
let stringValue = "test"
}
Mirror(reflecting: MirrorObject()).children.forEach { (child) in
print(child.label!,child.value)
}
struct Person:Decodable,Encodable{
let age:Int
let sex:Int
let name:String
}
let person1 = Person(age: 12, sex: 1, name: "老王")
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let p1Data = try encoder.encode(person1)
String(data: p1Data, encoding: .utf8)
let newP1 = try JSONDecoder().decode(Person.self, from: p1Data)
print(newP1)
print("最大最小值", Int.max, Int.min, Int64.max, Int64.min, Int8.max, Int8.min)
print("大小端", 5.bigEndian, 5.littleEndian)
print("位宽", 5.bitWidth, Int64.bitWidth, Int8.bitWidth)
*/
protocol DefaultValue{
associatedtype Value:Decodable
static var defaultValue:Value{get}
}
@propertyWrapper
struct Default<T:DefaultValue>{
var wrappedValue:T.Value
}
extension Default:Decodable{
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
wrappedValue = (try? container.decode(T.Value.self)) ?? T.defaultValue
}
}
extension KeyedDecodingContainer{
func decode<T>(type:Default<T>.Type,forKey Key:Key) throws -> Default<T> where T : DefaultValue{
(try decodeIfPresent(type, forKey: Key)) ?? Default(wrappedValue:T.defaultValue)
}
}
extension Int:DefaultValue{
static var defaultValue = 0
}
extension String:DefaultValue{
static var defaultValue = "super"
}
struct Person:Decodable{
@Default<String> var name:String
@Default<Int> var age:Int
// @Default<String.Unknow> var hname:String
}
extension String{
struct Unknow :DefaultValue{
static var defaultValue = "Unknow"
}
struct UnNamed :DefaultValue{
static var defaultValue = "UnNamed"
}
}
let str = #"{"name":null,"age":null}"#
let p = try JSONDecoder().decode(Person.self, from: str.data(using: .utf8)!)
print(p.age)
print(p.name)
//print(p.hname)
| 20.596817 | 137 | 0.678171 |
11117bf0ce3a78f1a36e18574787a8d3fae93485 | 5,969 | //
// TileImprovementTests.swift
// SmartAILibraryTests
//
// Created by Michael Rommel on 06.10.21.
// Copyright © 2021 Michael Rommel. All rights reserved.
//
import XCTest
@testable import SmartAILibrary
// swiftlint:disable force_try
class TileImprovementTests: XCTestCase {
func testFishingBoatsCanBeBuilt() {
// GIVEN
let barbarianPlayer = Player(leader: .barbar, isHuman: false)
barbarianPlayer.initialize()
let aiPlayer = Player(leader: .victoria, isHuman: false)
aiPlayer.initialize()
let humanPlayer = Player(leader: .alexander, isHuman: true)
humanPlayer.initialize()
var mapModel = MapUtils.mapFilled(with: .grass, sized: .small)
mapModel.set(terrain: .plains, at: HexPoint(x: 2, y: 4))
mapModel.set(hills: true, at: HexPoint(x: 2, y: 4))
mapModel.set(resource: .wheat, at: HexPoint(x: 3, y: 4))
mapModel.set(terrain: .plains, at: HexPoint(x: 3, y: 4))
mapModel.set(resource: .iron, at: HexPoint(x: 3, y: 3))
mapModel.set(hills: true, at: HexPoint(x: 3, y: 3))
mapModel.set(feature: .forest, at: HexPoint(x: 4, y: 4))
mapModel.set(resource: .furs, at: HexPoint(x: 4, y: 4))
mapModel.set(hills: true, at: HexPoint(x: 4, y: 5))
mapModel.set(resource: .wine, at: HexPoint(x: 4, y: 5))
mapModel.set(terrain: .shore, at: HexPoint(x: 4, y: 3))
mapModel.set(resource: .fish, at: HexPoint(x: 4, y: 3))
let gameModel = GameModel(
victoryTypes: [.domination],
handicap: .king,
turnsElapsed: 0,
players: [barbarianPlayer, aiPlayer, humanPlayer],
on: mapModel
)
// AI
aiPlayer.found(at: HexPoint(x: 20, y: 8), named: "AI Capital", in: gameModel)
aiPlayer.found(at: HexPoint(x: 12, y: 10), named: "AI City", in: gameModel)
// Human
humanPlayer.found(at: HexPoint(x: 3, y: 5), named: "Human Capital", in: gameModel)
try! humanPlayer.techs?.discover(tech: .pottery)
try! humanPlayer.techs?.discover(tech: .bronzeWorking)
try! humanPlayer.techs?.discover(tech: .irrigation)
try! humanPlayer.techs?.discover(tech: .animalHusbandry)
try! humanPlayer.techs?.discover(tech: .sailing)
try! humanPlayer.techs?.setCurrent(tech: .archery, in: gameModel)
try! humanPlayer.civics?.discover(civic: .codeOfLaws)
try! humanPlayer.civics?.discover(civic: .foreignTrade)
try! humanPlayer.civics?.setCurrent(civic: .craftsmanship, in: gameModel)
if let humanCity = gameModel.city(at: HexPoint(x: 3, y: 5)) {
humanCity.buildQueue.add(item: BuildableItem(buildingType: .granary))
for pointToClaim in HexPoint(x: 3, y: 5).areaWith(radius: 2) {
if let tileToClaim = gameModel.tile(at: pointToClaim) {
if !tileToClaim.hasOwner() {
do {
try tileToClaim.set(owner: humanPlayer)
try tileToClaim.setWorkingCity(to: humanCity)
humanPlayer.addPlot(at: pointToClaim)
gameModel.userInterface?.refresh(tile: tileToClaim)
} catch {
fatalError("cant set owner")
}
}
}
}
}
MapUtils.discover(mapModel: &mapModel, by: humanPlayer, in: gameModel)
// WHEN
let builderUnit = Unit(at: HexPoint(x: 3, y: 4), type: .builder, owner: humanPlayer)
_ = builderUnit.doMove(on: HexPoint(x: 4, y: 3), in: gameModel)
gameModel.add(unit: builderUnit)
gameModel.userInterface?.show(unit: builderUnit)
let canBuildFishingBoats = builderUnit.canDo(command: .buildFishingBoats, in: gameModel)
// THEN
XCTAssertTrue(canBuildFishingBoats)
}
// Cannot build mine on resource in open terrain (not on hills) #129
func testMineCanBeBuiltOnResourceInOpenTerrain() {
// GIVEN
let barbarianPlayer = Player(leader: .barbar, isHuman: false)
barbarianPlayer.initialize()
let aiPlayer = Player(leader: .victoria, isHuman: false)
aiPlayer.initialize()
let humanPlayer = Player(leader: .alexander, isHuman: true)
humanPlayer.initialize()
let mapModel = MapUtils.mapFilled(with: .grass, sized: .small)
mapModel.set(terrain: .plains, at: HexPoint(x: 2, y: 4))
mapModel.set(hills: false, at: HexPoint(x: 2, y: 4))
mapModel.set(resource: .salt, at: HexPoint(x: 2, y: 4))
let gameModel = GameModel(
victoryTypes: [.domination],
handicap: .king,
turnsElapsed: 0,
players: [barbarianPlayer, aiPlayer, humanPlayer],
on: mapModel
)
// AI
aiPlayer.found(at: HexPoint(x: 20, y: 8), named: "AI Capital", in: gameModel)
// Human
humanPlayer.found(at: HexPoint(x: 3, y: 5), named: "Human Capital", in: gameModel)
try! humanPlayer.techs?.discover(tech: .pottery)
try! humanPlayer.techs?.discover(tech: .bronzeWorking)
try! humanPlayer.techs?.discover(tech: .irrigation)
try! humanPlayer.techs?.discover(tech: .animalHusbandry)
try! humanPlayer.techs?.discover(tech: .sailing)
try! humanPlayer.techs?.discover(tech: .mining)
try! humanPlayer.techs?.setCurrent(tech: .archery, in: gameModel)
try! humanPlayer.civics?.discover(civic: .codeOfLaws)
try! humanPlayer.civics?.discover(civic: .foreignTrade)
try! humanPlayer.civics?.setCurrent(civic: .craftsmanship, in: gameModel)
// WHEN
let canBuildMine = humanPlayer.canBuild(build: .mine, at: HexPoint(x: 2, y: 4), testGold: true, in: gameModel)
// THEN
XCTAssertTrue(canBuildMine)
}
}
| 38.019108 | 118 | 0.604456 |
c14f05fb56bce77e10d30d4744eaa6d816c0225e | 1,539 | //
// Date+String.swift
// SocialAppCleanSwift
//
// Created by Christian Slanzi on 10.12.20.
//
import Foundation
// MARK: - DATE TO STRING
public extension Date {
func toString(format: String = "MMMM dd yyyy", locale: Locale = Locale.current, timeZone: TimeZone = TimeZone.current) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
dateFormatter.timeZone = timeZone
dateFormatter.locale = locale
return dateFormatter.string(from: self)
}
}
public extension Date {
func toTimeString() -> String {
let dateTimeFormatter = DateFormatter()
dateTimeFormatter.dateFormat = "HH:mm:ss"
return dateTimeFormatter.string(from: self)
}
func toShortTimeString() -> String {
let dateTimeFormatter = DateFormatter()
dateTimeFormatter.dateFormat = "HH:mm"
return dateTimeFormatter.string(from: self)
}
func toDayMonthYearString() -> String {
let dateTimeFormatter = DateFormatter()
dateTimeFormatter.dateFormat = "dd.MM.yyyy"
return dateTimeFormatter.string(from: self)
}
func toDayMonthYearTimeString() -> String {
let dateTimeFormatter = DateFormatter()
dateTimeFormatter.dateFormat = "dd.MM.yyyy HH:mm"
return dateTimeFormatter.string(from: self)
}
func toMonthYearString() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM yyyy"
return dateFormatter.string(from: self)
}
}
| 32.0625 | 134 | 0.667316 |
5b4dc0235d9e9c9debbc4bf0887428ce0a8e0744 | 1,787 | //
// Copyright (c) 2015 Google Inc.
//
// 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.
//
//
// For more information on setting up and running this sample code, see
// https://firebase.google.com/docs/analytics/ios/start
//
import Foundation
import Firebase
@objc(FoodPickerViewController) // match the ObjC symbol name inside Storyboard
class FoodPickerViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
let foodStuffs = ["Hot Dogs", "Hamburger", "Pizza"]
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
let food = foodStuffs[row]
UserDefaults.standard.setValue(food, forKey: "favorite_food")
UserDefaults.standard.synchronize()
// [START user_property]
Analytics.setUserProperty(food, forName: "favorite_food")
// [END user_property]
performSegue(withIdentifier: "unwindToHome", sender: self)
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return foodStuffs.count
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return foodStuffs[row]
}
}
| 32.490909 | 109 | 0.738668 |
bf436f012bb5300c79bd8481fb97e4a23df4f7bd | 1,843 | /*
Copyright (c) 2016 NgeosOne LLC
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
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 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.
Engineered using http://www.generatron.com/
[GENERATRON]
Generator : System Templates
Filename: RepositoryMySQL.swift
Description: Repository MySQL class
Project: TodoList
Template: persistenceManagerSwift/RepositoryMySQL.swift.vmg
*/
import MySQL
enum RepositoryError : ErrorProtocol {
case Select(UInt32)
case Insert(UInt32)
case Update(UInt32)
case Delete(UInt32)
case CreateTable(UInt32)
case List(UInt32)
case Retrieve(UInt32)
}
class RepositoryMySQL : Repository {
var db: MySQL!
init(db: MySQL) {
super.init()
self.db = db
}
}
/*
[STATS]
It would take a person typing @ 100.0 cpm,
approximately 3.8100002 minutes to type the 381+ characters in this file.
*/
| 34.12963 | 148 | 0.744438 |
39442e14c5da033f549aa2689b88854b5d0c93c8 | 953 | //
// PostListViewModel.swift
// HealiosTest
//
// Created by Sergii Kutnii on 02.09.2021.
//
import Combine
class PostListViewModelImpl: PostListViewModel{
private let objectStore: ObjectStore
init(objectStore: ObjectStore) {
self.objectStore = objectStore
_ = (objectStore.getPosts() &&& objectStore.getUsers()).then({
[weak self] (res: ([Post], [User])) in
let (posts, users) = res
self?.posts = posts
var userIndex = [Int: User]()
for user in users {
userIndex[user.id] = user
}
self?.authors = userIndex
})
}
@Published private(set) var posts: [Post] = []
@Published private(set) var authors: [Int : User] = [:]
func details(for post: Post) -> PostDetailsViewModelImpl {
return PostDetailsViewModelImpl(post: post, objectStore: objectStore)
}
}
| 25.756757 | 77 | 0.56978 |
509e046438eb8c5d2638d1b9bf50dfb2b00cc51a | 4,125 | /**
* Copyright © 2019 Aga Khan Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**/
import UIKit
import NotificationCenter
extension NSNotification.Name {
static let teamChanged: NSNotification.Name =
NSNotification.Name(rawValue: "steps4impact.team-changed")
static let eventChanged: NSNotification.Name =
NSNotification.Name(rawValue: "steps4impact.event-changed")
static let commitmentChanged: NSNotification.Name =
NSNotification.Name(rawValue: "steps4impact.commitment-changed")
}
class DashboardViewController: TableViewController {
override func commonInit() {
super.commonInit()
title = Strings.Dashboard.title
dataSource = DashboardDataSource()
navigationItem.rightBarButtonItem = UIBarButtonItem(
image: Assets.gear.image,
style: .plain,
target: self,
action: #selector(settingsButtonTapped))
// setup event handlers
_ = NotificationCenter.default.addObserver(forName: .teamChanged,
object: nil, queue: nil) { [weak self] (_) in
self?.reload()
}
_ = NotificationCenter.default.addObserver(forName: .eventChanged,
object: nil, queue: nil) { [weak self] (_) in
self?.reload()
}
}
deinit {
NotificationCenter.default.removeObserver(self)
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
super.tableView(tableView, willDisplay: cell, forRowAt: indexPath)
if let cell = cell as? ProfileCardCell {
cell.delegate = self
}
if let cell = cell as? EmptyActivityCell {
cell.delegate = self
}
if let cell = cell as? DisclosureCell {
cell.delegate = self
}
}
// MARK: - Actions
@objc
func settingsButtonTapped() {
navigationController?.pushViewController(SettingsViewController(), animated: true)
}
}
extension DashboardViewController: ProfileCardCellDelegate {
func profileDisclosureTapped() {
navigationController?.pushViewController(BadgesViewController(), animated: true)
}
}
extension DashboardViewController: EmptyActivityCellDelegate {
func emptyActivityCellConnectTapped() {
navigationController?.pushViewController(ConnectSourceViewController(),
animated: true)
}
}
extension DashboardViewController: DisclosureCellDelegate {
func disclosureCellTapped(context: Context?) {
guard let context = context as? DashboardDataSource.DashboardContext else { return }
switch context {
case .inviteSupporters:
navigationController?.pushViewController(InviteSupportersViewController(), animated: true)
}
}
}
| 36.830357 | 119 | 0.721455 |
f90e59f1dfa1fb3ed080643602bb644211c5dc88 | 2,978 | //
// StackingFooterViewController.swift
// BrickKit
//
// Created by Ruben Cagnie on 9/23/16.
// Copyright © 2016 Wayfair LLC. All rights reserved.
//
import BrickKit
private let StickySection = "Sticky Section"
private let BuyButton = "BuyButton"
private let BuySection = "BuySection"
private let TotalLabel = "TotalLabel"
class StackingFooterViewController: BrickApp.BaseBrickController, HasTitle {
class var brickTitle: String {
return "Stacking Footers"
}
class var subTitle: String {
return "Example how to stack footers"
}
let numberOfLabels = 50
var repeatLabel: LabelBrick!
var titleLabelModel: LabelBrickCellModel!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .brickBackground
let layout = self.brickCollectionView.layout
layout.zIndexBehavior = .bottomUp
self.brickCollectionView.registerBrickClass(ButtonBrick.self)
self.brickCollectionView.registerBrickClass(LabelBrick.self)
let sticky = StickyFooterLayoutBehavior(dataSource: self)
sticky.canStackWithOtherSections = true
behavior = sticky
let buyButton = ButtonBrick(BuyButton, backgroundColor: .brickGray1, title: "BUY") { cell in
cell.configure()
}
let totalLabel = LabelBrick(TotalLabel, backgroundColor: .brickGray2, text: "TOTAL") { cell in
cell.configure()
}
let section = BrickSection(bricks: [
BrickSection(bricks: [
LabelBrick(BrickIdentifiers.repeatLabel, width: .ratio(ratio: 0.5), height: .auto(estimate: .fixed(size: 200)), backgroundColor: UIColor.lightGray, dataSource: self),
totalLabel
], inset: 10, edgeInsets: UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)),
BrickSection(BuySection, bricks: [
buyButton
])
])
section.repeatCountDataSource = self
self.setSection(section)
}
}
extension StackingFooterViewController: BrickRepeatCountDataSource {
func repeatCount(for identifier: String, with collectionIndex: Int, collectionIdentifier: String) -> Int {
if identifier == BrickIdentifiers.repeatLabel {
return numberOfLabels
} else {
return 1
}
}
}
extension StackingFooterViewController: LabelBrickCellDataSource {
func configureLabelBrickCell(_ cell: LabelBrickCell) {
cell.label.text = "BRICK \(cell.index + 1)"
cell.configure()
}
}
extension StackingFooterViewController: StickyLayoutBehaviorDataSource {
func stickyLayoutBehavior(_ stickyLayoutBehavior: StickyLayoutBehavior, shouldStickItemAtIndexPath indexPath: IndexPath, withIdentifier identifier: String, inCollectionViewLayout collectionViewLayout: UICollectionViewLayout) -> Bool {
return identifier == BuySection || identifier == TotalLabel
}
}
| 32.725275 | 238 | 0.68133 |
1e1c4dbc4a89145e977e99e37af1fe631960cde5 | 2,253 | //
// SearchTabViewController.swift
// Wordie
//
// Created by Lu Ao on 11/20/16.
// Copyright © 2016 Lu Ao. All rights reserved.
//
import UIKit
import Firebase
import AFNetworking
class SearchTabViewController: UITabBarController, UITabBarControllerDelegate, UINavigationControllerDelegate {
var word: Word?
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let tabBar = self.tabBar
tabBar.barTintColor = UIColor.clear
tabBar.tintColor = UIColor.white
tabBar.backgroundImage = UIImage()
tabBar.shadowImage = #imageLiteral(resourceName: "Line")
}
override func viewDidLoad() {
super.viewDidLoad()
// Set up the first View Controller
let storyboard = UIStoryboard(name: "Louis.Main", bundle: nil)
let vc1 = storyboard.instantiateViewController(withIdentifier: "HomeScreen") as! UINavigationController
vc1.delegate = self
vc1.tabBarItem.title = "Add Word"
vc1.tabBarItem = UITabBarItem.init(tabBarSystemItem: UITabBarSystemItem.bookmarks, tag: 0)
// Set up the second View Controller
let vc2 = storyboard.instantiateViewController(withIdentifier: "HomeScreen") as! UINavigationController
vc2.delegate = self
vc2.tabBarItem.title = "Word Set"
vc2.tabBarItem = UITabBarItem.init(tabBarSystemItem: UITabBarSystemItem.history, tag: 1)
let vc3 = storyboard.instantiateViewController(withIdentifier: "HomeScreen") as! UINavigationController
vc3.delegate = self
vc3.tabBarItem.title = "Media"
vc3.tabBarItem = UITabBarItem.init(tabBarSystemItem: UITabBarSystemItem.favorites, tag: 2)
let vc4 = storyboard.instantiateViewController(withIdentifier: "HomeScreen") as! UINavigationController
vc4.delegate = self
vc4.tabBarItem.title = "Personal"
vc4.tabBarItem = UITabBarItem.init(tabBarSystemItem: UITabBarSystemItem.more, tag: 3)
// Set up the Tab Bar Controller to have four tabs
self.viewControllers = [vc1, vc2, vc3, vc4]
}
}
| 32.185714 | 111 | 0.65779 |
4af8208cbeba0e88a664af56cbcb70755eb6dcf8 | 2,513 | //
// TextDataManager.swift
// Data Modeler for Power Calculations
//
// Created by Peyton Chen on 8/6/20.
// Copyright © 2020 Peyton Chen. All rights reserved.
//
import Foundation
class TextDataManager {
private var textString = ""
private var SASString = ""
func processArray(array: [[[String]]]) {
self.textString.removeAll()
for j in 0..<array.count {
for i in 0..<array[j].count {
textString.append(array[j][i].joined(separator: " "))
textString.append("\n")
}
textString.append("\n\n")
}
}
func multiSAS(array: [[[String]]], experimentName eName: String) {
self.SASString.removeAll()
for sub in array {
implementSAS(array: sub, experimentName: eName)
}
}
private func implementSAS(array: [[String]], experimentName eName: String) {
var data = ""
var blockNames = ""
let names = array[0]
for i in 2..<names.count - 1 {
let fName = " " + names[i]
blockNames += fName
}
for i in 1..<array.count {
data.append(array[i].joined(separator: " "))
data.append("\n")
}
SASString.append("DATA \(eName); INPUT \(names[0]) Treatment\(blockNames) \(names[names.count - 1]); Lines;\n\n\(data)\n;\nRUN;\n\nPROC MIXED ASYCOV NOBOUND DATA=\(eName) ALPHA=0.05;\nCLASS Treatment\(blockNames);\nMODEL \(names[names.count - 1]) = Treatment\(blockNames)\n/SOLUTION DDFM=KENWARDROGER;\nlsmeans Treatment / adjust=tukey;\nRUN;\n\n\n")
}
func writeToFile(SAS choice: Bool, url: URL) {
let fileURL = url
var outString = ""
if choice == false {
outString = textString
} else {
outString = SASString
}
do {
try outString.write(to: fileURL, atomically: true, encoding: .utf8)
} catch {
print("Failed writing to URL: \(fileURL), Error: " + error.localizedDescription)
}
}
}
//The following was for testing purposes
// var inString = ""
//
// do {
// inString = try String(contentsOf: fileURL)
// } catch {
// print("Failed reading from URL: \(fileURL), Error: " + error.localizedDescription)
// }
//
// print("Read from file: \(inString)")
// print(fileURL)
| 28.885057 | 358 | 0.532829 |
e914896e7cf48575388e0498a4cd562d543b8352 | 3,029 | //
// UIViewExtension.swift
// motoRoutes
//
// Created by Peter Pohlmann on 02.12.16.
// Copyright © 2016 Peter Pohlmann. All rights reserved.
//
import UIKit
import pop
extension UIView {
func scaleSize(_ delay: TimeInterval = 1.0, size: Int ) {
self.isHidden = true
DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: {
self.isHidden = false;
let scale = POPSpringAnimation(propertyNamed: kPOPViewScaleXY)
scale?.toValue = NSValue(cgSize: CGSize(width: size, height: size))
scale?.springBounciness = 15
scale?.springSpeed = 15
self.pop_add(scale, forKey: "scalePosition")
scale?.completionBlock = {(animation, finished) in
print("#### Animation completed scale size ###")
// NotificationCenter.default.post(name: Notification.Name(rawValue: completionFinishedNotificationKey), object: [self])
}
})
}
func scale(_ size: Int ) {
let scale = POPSpringAnimation(propertyNamed: kPOPViewScaleXY)
scale?.toValue = NSValue(cgSize: CGSize(width: size, height: size))
scale?.springBounciness = 8
scale?.springSpeed = 15
self.pop_add(scale, forKey: "scalePosition")
scale?.completionBlock = {(animation, finished) in
print("#### Animation completed ###")
}
}
func aniToX(_ delay: Double){
let when = DispatchTime.now() + delay
DispatchQueue.main.asyncAfter(deadline: when) {
AnimationEngine.animationToPositionX(self, x: Double(self.frame.width/2))
}
}
func aniToOff(_ delay: Double){
let when = DispatchTime.now() + delay
DispatchQueue.main.asyncAfter(deadline: when) {
AnimationEngine.animationToPositionX(self, x: Double(self.frame.width/2*3))
}
}
func aniOffToLeft(_ delay: Double){
let when = DispatchTime.now() + delay
DispatchQueue.main.asyncAfter(deadline: when) {
AnimationEngine.animationToPositionX(self, x: -Double(self.frame.width/2))
}
}
func aniToY(_ delay: Double, y: Double){
let when = DispatchTime.now() + delay
DispatchQueue.main.asyncAfter(deadline: when) {
AnimationEngine.animationToPositionY(self, y: Double(self.frame.origin.y) + y)
print(Double(self.frame.origin.y) + y)
}
}
func aniToYabsolute(_ delay: Double, y: Double){
let when = DispatchTime.now() + delay
DispatchQueue.main.asyncAfter(deadline: when) {
AnimationEngine.animationToPositionY(self, y: y)
print(Double(self.frame.origin.y) + y)
}
}
func aniToXabsolute(_ delay: Double, x: Double){
let when = DispatchTime.now() + delay
DispatchQueue.main.asyncAfter(deadline: when) {
AnimationEngine.animationToPositionX(self, x: x)
}
}
}
| 34.420455 | 137 | 0.6035 |
9cf060f4eb9788abec3d70238c876f77c97df88c | 3,437 | // RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s
func inoutWithDefaults(_ x: inout Int, y: Int = 0, z: Int = 0) {}
func inoutWithCallerSideDefaults(_ x: inout Int, y: Int = #line) {}
func scalarWithDefaults(_ x: Int, y: Int = 0, z: Int = 0) {}
func scalarWithCallerSideDefaults(_ x: Int, y: Int = #line) {}
func tupleWithDefaults(x x: (Int, Int), y: Int = 0, z: Int = 0) {}
func variadicFirst(_ x: Int...) {}
func variadicSecond(_ x: Int, _ y: Int...) {}
var x = 0
// CHECK: [[X_ADDR:%.*]] = global_addr @_Tv20scalar_to_tuple_args1xSi : $*Int
// CHECK: [[INOUT_WITH_DEFAULTS:%.*]] = function_ref @_TF20scalar_to_tuple_args17inoutWithDefaultsFTRSi1ySi1zSi_T_
// CHECK: [[DEFAULT_Y:%.*]] = apply {{.*}} : $@convention(thin) () -> Int
// CHECK: [[DEFAULT_Z:%.*]] = apply {{.*}} : $@convention(thin) () -> Int
// CHECK: apply [[INOUT_WITH_DEFAULTS]]([[X_ADDR]], [[DEFAULT_Y]], [[DEFAULT_Z]])
inoutWithDefaults(&x)
// CHECK: [[INOUT_WITH_CALLER_DEFAULTS:%.*]] = function_ref @_TF20scalar_to_tuple_args27inoutWithCallerSideDefaultsFTRSi1ySi_T_
// CHECK: [[LINE_VAL:%.*]] = integer_literal
// CHECK: [[LINE:%.*]] = apply {{.*}}([[LINE_VAL]]
// CHECK: apply [[INOUT_WITH_CALLER_DEFAULTS]]([[X_ADDR]], [[LINE]])
inoutWithCallerSideDefaults(&x)
// CHECK: [[SCALAR_WITH_DEFAULTS:%.*]] = function_ref @_TF20scalar_to_tuple_args18scalarWithDefaultsFTSi1ySi1zSi_T_
// CHECK: [[X:%.*]] = load [trivial] [[X_ADDR]]
// CHECK: [[DEFAULT_Y:%.*]] = apply {{.*}} : $@convention(thin) () -> Int
// CHECK: [[DEFAULT_Z:%.*]] = apply {{.*}} : $@convention(thin) () -> Int
// CHECK: apply [[SCALAR_WITH_DEFAULTS]]([[X]], [[DEFAULT_Y]], [[DEFAULT_Z]])
scalarWithDefaults(x)
// CHECK: [[SCALAR_WITH_CALLER_DEFAULTS:%.*]] = function_ref @_TF20scalar_to_tuple_args28scalarWithCallerSideDefaultsFTSi1ySi_T_
// CHECK: [[X:%.*]] = load [trivial] [[X_ADDR]]
// CHECK: [[LINE_VAL:%.*]] = integer_literal
// CHECK: [[LINE:%.*]] = apply {{.*}}([[LINE_VAL]]
// CHECK: apply [[SCALAR_WITH_CALLER_DEFAULTS]]([[X]], [[LINE]])
scalarWithCallerSideDefaults(x)
// CHECK: [[TUPLE_WITH_DEFAULTS:%.*]] = function_ref @_TF20scalar_to_tuple_args17tupleWithDefaultsFT1xTSiSi_1ySi1zSi_T_
// CHECK: [[X1:%.*]] = load [trivial] [[X_ADDR]]
// CHECK: [[X2:%.*]] = load [trivial] [[X_ADDR]]
// CHECK: [[DEFAULT_Y:%.*]] = apply {{.*}} : $@convention(thin) () -> Int
// CHECK: [[DEFAULT_Z:%.*]] = apply {{.*}} : $@convention(thin) () -> Int
// CHECK: apply [[TUPLE_WITH_DEFAULTS]]([[X1]], [[X2]], [[DEFAULT_Y]], [[DEFAULT_Z]])
tupleWithDefaults(x: (x,x))
// CHECK: [[VARIADIC_FIRST:%.*]] = function_ref @_TF20scalar_to_tuple_args13variadicFirstFtGSaSi__T_
// CHECK: [[ALLOC_ARRAY:%.*]] = apply {{.*}} -> (@owned Array<τ_0_0>, Builtin.RawPointer)
// CHECK: [[ARRAY:%.*]] = tuple_extract [[ALLOC_ARRAY]] {{.*}}, 0
// CHECK: [[MEMORY:%.*]] = tuple_extract [[ALLOC_ARRAY]] {{.*}}, 1
// CHECK: [[ADDR:%.*]] = pointer_to_address [[MEMORY]]
// CHECK: [[X:%.*]] = load [trivial] [[X_ADDR]]
// CHECK: store [[X]] to [trivial] [[ADDR]]
// CHECK: apply [[VARIADIC_FIRST]]([[ARRAY]])
variadicFirst(x)
// CHECK: [[VARIADIC_SECOND:%.*]] = function_ref @_TF20scalar_to_tuple_args14variadicSecondFtSiGSaSi__T_
// CHECK: [[ALLOC_ARRAY:%.*]] = apply {{.*}} -> (@owned Array<τ_0_0>, Builtin.RawPointer)
// CHECK: [[ARRAY:%.*]] = tuple_extract [[ALLOC_ARRAY]] {{.*}}, 0
// CHECK: [[X:%.*]] = load [trivial] [[X_ADDR]]
// CHECK: apply [[VARIADIC_SECOND]]([[X]], [[ARRAY]])
variadicSecond(x)
| 52.075758 | 128 | 0.643875 |
392efd3bff76c1ec79010d1956c11cb5f953c82a | 838 | //
// Logbook+Output.swift
//
//
// Created by Rayhan Nabi on 12/10/21.
//
import Foundation
public extension Logbook {
/// The log output destination
enum Output {
/// Logs to Xcode console
///
/// If console kind is ``Logbook/Logbook/Console/unified``,
/// also outputs to Unified Logging System.
case console(_ kind: Console)
}
/// The console output destination
enum Console {
/// Outputs to Xcode console only
///
/// Uses `print(:)` function for output
case xcode
/// Outputs to the Unified Logging System
///
/// Uses `OSLog` for logging, outputs are visible
/// in both Xcode and Console app.
case unified
}
}
// MARK: - Logbook.Output + Equatable
extension Logbook.Output: Equatable {}
| 22.648649 | 67 | 0.585919 |
cc5403c46d160353cbecb3d76491e2cd86bb5f81 | 4,491 | /// The type that can be embedded as a subquery.
public struct SQLSubquery {
private var impl: Impl
private enum Impl {
/// A literal SQL query
case literal(SQLLiteral)
/// A query interface relation
case relation(SQLRelation)
}
static func literal(_ sqlLiteral: SQLLiteral) -> Self {
self.init(impl: .literal(sqlLiteral))
}
static func relation(_ relation: SQLRelation) -> Self {
self.init(impl: .relation(relation))
}
}
extension SQLSubquery {
/// The number of columns selected by the subquery.
///
/// This method makes it possible to find the columns of a CTE in a request
/// that includes a CTE association:
///
/// // WITH cte AS (SELECT 1 AS a, 2 AS b)
/// // SELECT player.*, cte.*
/// // FROM player
/// // JOIN cte
/// let cte = CommonTableExpression(named: "cte", sql: "SELECT 1 AS a, 2 AS b")
/// let request = Player
/// .with(cte)
/// .including(required: Player.association(to: cte))
/// let row = try Row.fetchOne(db, request)!
///
/// // We know that "SELECT 1 AS a, 2 AS b" selects two columns,
/// // so we can find cte columns in the row:
/// row.scopes["cte"] // [a:1, b:2]
func columnsCount(_ db: Database) throws -> Int {
switch impl {
case let .literal(sqlLiteral):
// Compile request. We can freely use the statement cache because we
// do not execute the statement or modify its arguments.
let context = SQLGenerationContext(db)
let sql = try sqlLiteral.sql(context)
let statement = try db.cachedSelectStatement(sql: sql)
return statement.columnCount
case let .relation(relation):
return try SQLQueryGenerator(relation: relation).columnsCount(db)
}
}
}
extension SQLSubquery {
/// Returns the subquery SQL.
///
/// For example:
///
/// // SELECT *
/// // FROM "player"
/// // WHERE "score" = (SELECT MAX("score") FROM "player")
/// let maxScore = Player.select(max(Column("score")))
/// let players = try Player
/// .filter(Column("score") == maxScore)
/// .fetchAll(db)
///
/// - parameter context: An SQL generation context.
/// - parameter singleResult: A hint that a single result row will be
/// consumed. Implementations can optionally use it to optimize the
/// generated SQL, for example by adding a `LIMIT 1` SQL clause.
/// - returns: An SQL string.
func sql(_ context: SQLGenerationContext) throws -> String {
switch impl {
case let .literal(sqlLiteral):
return try sqlLiteral.sql(context)
case let .relation(relation):
return try SQLQueryGenerator(relation: relation).requestSQL(context)
}
}
}
// MARK: - SQLSubqueryable
/// The protocol for types that can be embedded as a subquery.
public protocol SQLSubqueryable: SQLSpecificExpressible {
var sqlSubquery: SQLSubquery { get }
}
extension SQLSubquery: SQLSubqueryable {
// Not a real deprecation, just a usage warning
@available(*, deprecated, message: "Already SQLSubquery")
public var sqlSubquery: SQLSubquery { self }
}
extension SQLSubqueryable {
/// Returns a subquery expression.
public var sqlExpression: SQLExpression {
.subquery(sqlSubquery)
}
}
extension SQLSubqueryable {
/// Returns an expression that checks the inclusion of the expression in
/// the subquery.
///
/// // 1000 IN (SELECT score FROM player)
/// let request = Player.select(Column("score"), as: Int.self)
/// let condition = request.contains(1000)
public func contains(_ element: SQLExpressible) -> SQLExpression {
SQLCollection.subquery(sqlSubquery).contains(element.sqlExpression)
}
/// Returns an expression that checks the inclusion of the expression in
/// the subquery.
///
/// // name COLLATE NOCASE IN (SELECT name FROM player)
/// let request = Player.select(Column("name"), as: String.self)
/// let condition = request.contains(Column("name").collating(.nocase))
public func contains(_ element: SQLCollatedExpression) -> SQLExpression {
SQLCollection.subquery(sqlSubquery).contains(element.sqlExpression)
}
}
| 35.362205 | 87 | 0.610332 |
69698c192ef66adaf1d4b3dfa6e84d7e817abdcb | 8,074 | //
// CameraController.swift
// Phimpme
//
// Created by JOGENDRA on 01/04/18.
// Copyright © 2018 Jogendra Singh. All rights reserved.
//
import UIKit
import AVFoundation
class CameraController: NSObject {
var captureSession: AVCaptureSession?
var currentCameraPosition: CameraPosition?
var frontCamera: AVCaptureDevice?
var frontCameraInput: AVCaptureDeviceInput?
var photoOutput: AVCapturePhotoOutput?
var rearCamera: AVCaptureDevice?
var rearCameraInput: AVCaptureDeviceInput?
var previewLayer: AVCaptureVideoPreviewLayer?
var flashMode = AVCaptureDevice.FlashMode.off
var photoCaptureCompletionBlock: ((UIImage?, Error?) -> Void)?
}
extension CameraController {
func prepare(completionHandler: @escaping (Error?) -> Void) {
func createCaptureSession() {
self.captureSession = AVCaptureSession()
}
func configureCaptureDevices() throws {
let session = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera], mediaType: AVMediaType.video, position: .unspecified)
let cameras = (session.devices.flatMap { $0 })
if !cameras.isEmpty {
for camera in cameras {
if camera.position == .front {
self.frontCamera = camera
}
if camera.position == .back {
self.rearCamera = camera
try camera.lockForConfiguration()
camera.focusMode = .continuousAutoFocus
camera.unlockForConfiguration()
}
}
} else { throw CameraControllerError.noCamerasAvailable }
}
func configureDeviceInputs() throws {
guard let captureSession = self.captureSession else { throw CameraControllerError.captureSessionIsMissing }
if let rearCamera = self.rearCamera {
self.rearCameraInput = try AVCaptureDeviceInput(device: rearCamera)
if captureSession.canAddInput(self.rearCameraInput!) { captureSession.addInput(self.rearCameraInput!) }
self.currentCameraPosition = .rear
} else if let frontCamera = self.frontCamera {
self.frontCameraInput = try AVCaptureDeviceInput(device: frontCamera)
if captureSession.canAddInput(self.frontCameraInput!) {
captureSession.addInput(self.frontCameraInput!)
} else {
throw CameraControllerError.inputsAreInvalid
}
self.currentCameraPosition = .front
} else { throw CameraControllerError.noCamerasAvailable }
}
func configurePhotoOutput() throws {
guard let captureSession = self.captureSession else { throw CameraControllerError.captureSessionIsMissing }
self.photoOutput = AVCapturePhotoOutput()
self.photoOutput!.setPreparedPhotoSettingsArray([AVCapturePhotoSettings(format: [AVVideoCodecKey : AVVideoCodecJPEG])], completionHandler: nil)
if captureSession.canAddOutput(self.photoOutput!) { captureSession.addOutput(self.photoOutput!) }
captureSession.startRunning()
}
DispatchQueue(label: "prepare").async {
do {
createCaptureSession()
try configureCaptureDevices()
try configureDeviceInputs()
try configurePhotoOutput()
} catch {
DispatchQueue.main.async {
completionHandler(error)
}
return
}
DispatchQueue.main.async {
completionHandler(nil)
}
}
}
func displayPreview(on view: UIView, darkLayerView: UIView) throws {
guard let captureSession = self.captureSession, captureSession.isRunning else { throw CameraControllerError.captureSessionIsMissing }
self.previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
self.previewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
self.previewLayer?.connection?.videoOrientation = .portrait
view.layer.insertSublayer(self.previewLayer!, at: 0)
self.previewLayer?.frame = view.frame
view.insertSubview(darkLayerView, at: 1)
}
func switchCameras() throws {
guard let currentCameraPosition = currentCameraPosition, let captureSession = self.captureSession, captureSession.isRunning else { throw CameraControllerError.captureSessionIsMissing }
captureSession.beginConfiguration()
func switchToFrontCamera() throws {
guard let inputs = captureSession.inputs as? [AVCaptureInput], let rearCameraInput = self.rearCameraInput, inputs.contains(rearCameraInput),
let frontCamera = self.frontCamera else { throw CameraControllerError.invalidOperation }
self.frontCameraInput = try AVCaptureDeviceInput(device: frontCamera)
captureSession.removeInput(rearCameraInput)
if captureSession.canAddInput(self.frontCameraInput!) {
captureSession.addInput(self.frontCameraInput!)
self.currentCameraPosition = .front
} else {
throw CameraControllerError.invalidOperation
}
}
func switchToRearCamera() throws {
guard let inputs = captureSession.inputs as? [AVCaptureInput], let frontCameraInput = self.frontCameraInput, inputs.contains(frontCameraInput),
let rearCamera = self.rearCamera else { throw CameraControllerError.invalidOperation }
self.rearCameraInput = try AVCaptureDeviceInput(device: rearCamera)
captureSession.removeInput(frontCameraInput)
if captureSession.canAddInput(self.rearCameraInput!) {
captureSession.addInput(self.rearCameraInput!)
self.currentCameraPosition = .rear
} else {
throw CameraControllerError.invalidOperation
}
}
switch currentCameraPosition {
case .front:
try switchToRearCamera()
case .rear:
try switchToFrontCamera()
}
captureSession.commitConfiguration()
}
func captureImage(completion: @escaping (UIImage?, Error?) -> Void) {
guard let captureSession = captureSession, captureSession.isRunning else { completion(nil, CameraControllerError.captureSessionIsMissing); return }
let settings = AVCapturePhotoSettings()
settings.flashMode = self.flashMode
self.photoOutput?.capturePhoto(with: settings, delegate: self)
self.photoCaptureCompletionBlock = completion
}
}
extension CameraController: AVCapturePhotoCaptureDelegate {
public func photoOutput(_ captureOutput: AVCapturePhotoOutput, didFinishProcessingPhoto photoSampleBuffer: CMSampleBuffer?, previewPhoto previewPhotoSampleBuffer: CMSampleBuffer?,
resolvedSettings: AVCaptureResolvedPhotoSettings, bracketSettings: AVCaptureBracketedStillImageSettings?, error: Swift.Error?) {
if let error = error {
self.photoCaptureCompletionBlock?(nil, error) } else if let buffer = photoSampleBuffer, let data = AVCapturePhotoOutput.jpegPhotoDataRepresentation(forJPEGSampleBuffer: buffer, previewPhotoSampleBuffer: nil),
let image = UIImage(data: data) {
self.photoCaptureCompletionBlock?(image, nil)
} else {
self.photoCaptureCompletionBlock?(nil, CameraControllerError.unknown)
}
}
}
extension CameraController {
enum CameraControllerError: Swift.Error {
case captureSessionAlreadyRunning
case captureSessionIsMissing
case inputsAreInvalid
case invalidOperation
case noCamerasAvailable
case unknown
}
public enum CameraPosition {
case front
case rear
}
}
| 37.728972 | 220 | 0.655685 |
7a77352adeb03f0aaf30e0c28b5ef7897979452e | 3,909 | //
// PieView.swift
// dayu
//
// Created by 王毅东 on 15/9/10.
// Copyright (c) 2015年 Xinger. All rights reserved.
//
import UIKit
class PieView: UIView , UITableViewDataSource, UITabBarDelegate {
var currencys = Array<Comb.Currency>()
var comb : Comb!
@IBOutlet weak var utvUnderPie: UITableView!
@IBOutlet weak var pieView: PieView!
var itemNum = 0
var app = UIApplication.sharedApplication().delegate as! AppDelegate
func createMagicPie(comb:Comb) {
self.comb = comb
currencys = comb.currencys
let cell = UINib(nibName: "UnderPieItem", bundle: nil)
self.utvUnderPie.registerNib(cell, forCellReuseIdentifier: "Cell")
self.utvUnderPie.reloadData()
itemNum = currencys.count % 2 == 0 ? (currencys.count/2) : (currencys.count/2 + 1)
self.utvUnderPie.frame = CGRectMake(10+(app.ScreenWidth-320)/2, 230*app.autoSizeScaleY, 320, CGFloat(45 * itemNum)*app.autoSizeScaleY)
if currencys.count > 0 {
let pieLayer = PieLayer()
pieLayer.frame = CGRectMake(0, 0, 180, 180)
pieView.frame = CGRectMake(80+(app.ScreenWidth-320)/2, 42*app.autoSizeScaleY, 180, 180)
var i = 0
// var startOffset = 160 + (4 - dic.count) * 20
for c in currencys {
let str = Colors.currencyColor[c.key]!
let color = StringUtil.colorWithHexString(str)
pieLayer.addValues([PieElement(value: (c.buyRate), color: color)], animated: true)
// var offset = startOffset + (i * 40)
// var view = UIView(frame: CGRectMake(CGFloat(offset), 250, 5, 5))
// view.backgroundColor = colorArr[i]
// var label = UILabel(frame: CGRectMake(CGFloat(offset + 5), 250, 30, 5))
// label.font = UIFont(name: "Arial", size: 7.0)
// label.text = c.key as? String
// addSubview(view)
// addSubview(label)
i++
}
pieView.layer.cornerRadius = 90
pieView.clipsToBounds = true
pieView.layer.addSublayer(pieLayer)
}
// else {
// noLabel.hidden = false
// }
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print(currencys.count % 2 == 0 ? (currencys.count/2) : (currencys.count/2 + 1))
return itemNum
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
print("cellForRowAtIndexPath")
var cs = Array<Comb.Currency>()
let c1 = currencys[indexPath.row * 2] as Comb.Currency
cs.append(c1)
var c2 : Comb.Currency!
if (currencys.count > indexPath.row * 2 + 1) {
c2 = currencys[indexPath.row * 2 + 1] as Comb.Currency
cs.append(c2)
}
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
var i = 0;
for c in cs {
let color = StringUtil.colorWithHexString(Colors.currencyColor[c.key]!)
let dot = cell.viewWithTag(10 + i) as! UILabel
dot.backgroundColor = color
dot.layer.cornerRadius = 5
dot.clipsToBounds = true
if c.value != "可用保证金" {
dot.text = c.operation == "SELL" ? "空" : "多"
let pro = cell.viewWithTag(13 + i) as! UILabel
pro.text = "当前盈亏$\(StringUtil.formatFloat(c.earning))"
}
let name = cell.viewWithTag(11 + i) as! UILabel
name.text = c.value
let percent = cell.viewWithTag(12 + i) as! UILabel
percent.text = StringUtil.formatFloat(c.buyRate * 100) + "%"
percent.textColor = color
i = 10
}
return cell
}
} | 41.147368 | 142 | 0.57406 |
8fd3ee7147a61473c7eef61b5d4e9d40711f50af | 2,179 | //
// AppDelegate.swift
// LinkSDK
//
// Created by devildriver666 on 09/07/2020.
// Copyright (c) 2020 devildriver666. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.361702 | 285 | 0.755392 |
291b7a017632f93cf4ed3cbf4132343231acc837 | 2,193 | //
// AppDelegate.swift
// IOSCocoapodsTutorial
//
// Created by Arthur Knopper on 27/11/2018.
// Copyright © 2018 Arthur Knopper. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.659574 | 285 | 0.756954 |
621beced6dac58db1ce6a22eecd097db44c41b8f | 116 | import XCTest
import BigMathTests
var tests = [XCTestCaseEntry]()
tests += BigMathTests.allTests()
XCTMain(tests)
| 14.5 | 32 | 0.775862 |
719a5ca0fdc1a0ab6774526dadf00060567b7df8 | 288 | //
// BaseCollectionViewCtr.swift
// SYBasicTools
//
// Created by Yunis on 2022/5/12.
//
import UIKit
class BaseCollectionViewCtr: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
| 15.157895 | 58 | 0.666667 |
89dfac9b415fa4270b2802d5b9d1bb47e395fdfd | 989 | //
// UIView+Blink.swift
// Tempura
//
// Copyright © 2021 Bending Spoons.
// Distributed under the MIT License.
// See the LICENSE file for more information.
import UIKit
extension UIView {
func blink() {
UIView.animate(
withDuration: 0.1,
delay: 0.0,
options: [.curveEaseIn],
animations: {
self.transform = CGAffineTransform(scaleX: 1.3, y: 1.3)
},
completion: { _ in
UIView.animate(
withDuration: 0.1,
delay: 0.0,
options: [.curveLinear],
animations: {
self.transform = CGAffineTransform(scaleX: 0.9, y: 0.9)
},
completion: { _ in
UIView.animate(
withDuration: 0.1,
delay: 0.0,
options: [.curveEaseOut],
animations: {
self.transform = CGAffineTransform.identity
},
completion: nil
)
}
)
}
)
}
}
| 22.477273 | 67 | 0.499494 |
38aec957785e11f902b184d18df04e48835a5bab | 3,215 | //
// File.swift
//
//
// Created by Jesulonimi on 3/5/21.
//
import Foundation
public class TxGroup : Encodable {
private static var TG_PREFIX:[Int8]=[84,71,];
public static var MAX_TX_GROUP_SIZE:Int=16
private var txGroupHashes:[Digest]?;
enum CodingKeys:String,CodingKey{
case txGroupHashes="txlist"
}
init(txGroupHashes:[Digest]) {
self.txGroupHashes=txGroupHashes
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
var arrayOfData=Array(repeating: Data(), count: self.txGroupHashes!.count);
for i in 0..<self.txGroupHashes!.count{
arrayOfData[i]=Data(CustomEncoder.convertToUInt8Array(input:self.txGroupHashes![i].getBytes()!))
}
try! container.encode(arrayOfData, forKey: .txGroupHashes)
}
public static func computeGroupID(txns:[Transaction])throws -> Digest {
if (txns.count != 0) {
if (txns.count > MAX_TX_GROUP_SIZE) {
throw Errors.illegalArgumentError("max group size is \(MAX_TX_GROUP_SIZE)");
} else {
var txIDs:[Digest] = Array(repeating: Digest(), count: txns.count);
for i in 0..<txns.count {
txIDs[i] = txns[i].rawTxID();
}
var txgroup:TxGroup = TxGroup(txGroupHashes: txIDs);
var gid:[Int8] = try! SHA512_256().hash(txgroup.bytesToSign())
return Digest(gid);
}
}else {
throw Errors.illegalArgumentError("empty transaction list");
}
}
public static func assignGroupID(txns:[Transaction]) throws -> [Transaction] {
return try! assignGroupID(txns, nil);
}
public static func assignGroupID(_ address:Address, _ txns:[Transaction]) throws -> [Transaction] {
return try! assignGroupID(txns, address);
}
public static func assignGroupID(_ txns:[Transaction], _ address:Address?) throws -> [Transaction] {
var gid:Digest = try! self.computeGroupID(txns:txns);
var result:[Transaction] = Array();
var var4 = txns;
var var5 = txns.count;
for i in 0..<var5{
var tx = var4[i]
tx.assignGroupID(gid: gid)
result.append(tx)
}
return result
}
private func bytesToSign() throws ->[Int8]{
var encodedTx:[Int8] = CustomEncoder.encodeToMsgPack(self);
// print("Digest hash")
// print(encodedTx)
// var total:Int64=0//Int64(encodedTx.reduce(0, +))
// for number in encodedTx{
// total += Int64(number)
// }
// print(total)
//
var prefixEncodedTx:[Int8] = Array(repeating: 0, count: TxGroup.TG_PREFIX.count+encodedTx.count)
for i in 0..<TxGroup.TG_PREFIX.count{
prefixEncodedTx[i]=TxGroup.TG_PREFIX[i]
}
var counter=0;
for i in TxGroup.TG_PREFIX.count..<prefixEncodedTx.count{
prefixEncodedTx[i]=encodedTx[counter]
counter=counter+1
}
return prefixEncodedTx;
}
}
| 28.705357 | 108 | 0.583826 |
5bf5af9573a194e402b143357a26447fbb116f90 | 1,276 | import Foundation
import TuistCore
import TuistSupport
import XCTest
@testable import TuistGenerator
class SchemeLinterTests: XCTestCase {
var subject: SchemeLinter!
override func setUp() {
super.setUp()
subject = SchemeLinter()
}
override func tearDown() {
subject = nil
super.tearDown()
}
func test_lint_missingConfigurations() {
// Given
let settings = Settings(configurations: [
.release("Beta"): .test(),
])
let scheme = Scheme(name: "CustomScheme",
testAction: .test(configurationName: "Alpha"),
runAction: .test(configurationName: "CustomDebug"))
let project = Project.test(settings: settings, schemes: [scheme])
// When
let got = subject.lint(project: project)
// Then
XCTAssertEqual(got.first?.severity, .error)
XCTAssertEqual(got.last?.severity, .error)
XCTAssertEqual(got.first?.reason, "The build configuration 'CustomDebug' specified in the scheme's run action isn't defined in the project.")
XCTAssertEqual(got.last?.reason, "The build configuration 'Alpha' specified in the scheme's test action isn't defined in the project.")
}
}
| 31.9 | 149 | 0.631661 |
d9c9b7b57e78e1dd406ca8d3e2a679615f9242f1 | 3,864 | @testable import App
import Foundation
import XCTest
class StringExtensionTests: XCTestCase {
func test_pathToFileName_givenFileNameOnly_expectSameResult() {
let given = "FileName.png"
let actual = given.pathToFileName()
XCTAssertEqual(actual.count, given.count)
}
func test_pathToFileName_givenPath_expectGetFileName() {
let given = "/Users/Path/To/FileName.png"
let actual = given.pathToFileName()
XCTAssertEqual(actual, "FileName.png")
}
func test_capitalizingFirstLetter_givenNoCaps_expectCapitalizeFirstLetter() {
let given = "given"
let expected = "Given"
let actual = given.capitalizingFirstLetter()
XCTAssertEqual(actual, expected)
}
func test_capitalizingFirstLetter_givenAllCaps_expectCapitalizeFirstLetter() {
let given = "GIVEN"
let expected = "Given"
let actual = given.capitalizingFirstLetter()
XCTAssertEqual(actual, expected)
}
func test_capitalizingFirstLetter_givenAlreadyCapsFirstLetter_expectEqual() {
let given = "Given"
let expected = "Given"
let actual = given.capitalizingFirstLetter()
XCTAssertEqual(actual, expected)
}
func test_capitalizeFirstLetter_expectMutate() {
var given = "GIVEN"
let expected = "Given"
given.capitalizeFirstLetter()
XCTAssertEqual(expected, given)
}
func test_percentUrlEncode_givenhttpslink_expectEncodeCorrectly() {
let given = "https://foo.com?file=name of file.jpg"
let expected = "https://foo.com?file=name%20of%20file.jpg"
let actual = given.percentUrlEncode()!
XCTAssertEqual(actual, expected)
}
// MARK: isValidEmail
func test_isValidEmail_givenEmptyString_expectFalse() {
let given = ""
let actual = given.isValidEmail()
XCTAssertFalse(actual)
}
func test_isValidEmail_givenInvalidEmailAddress_expectFalse() {
let given = "@you.com"
let actual = given.isValidEmail()
XCTAssertFalse(actual)
}
func test_isValidEmail_givenValidEmailAddress_expectFalse() {
let given = "[email protected]"
let actual = given.isValidEmail()
XCTAssertTrue(actual)
}
// MARK: fromStringRepeated
func test_fromStringRepeated_givenRepeatTimes0_expectEmptyString() {
XCTAssertEqual(String.fromStringRepeated(string: ".", repeatTimes: 0), "")
}
func test_fromStringRepeated_givenSingleCharacter_expectString() {
XCTAssertEqual(String.fromStringRepeated(string: ".", repeatTimes: 5), ".....")
}
func test_fromStringRepeated_givenMultipleCharacters_expectString() {
XCTAssertEqual(String.fromStringRepeated(string: "ABC", repeatTimes: 3), "ABCABCABC")
}
func test_fromStringRepeated_givenRepeatTimes1_expectString() {
XCTAssertEqual(String.fromStringRepeated(string: ".", repeatTimes: 1), ".")
}
func test_fromStringRepeated_givenRepeatTimesX_expectString() {
XCTAssertEqual(String.fromStringRepeated(string: ".", repeatTimes: 10), "..........")
}
// MARK: ellipsis
func test_ellipsis_givenStringBelowMaxLength_expectNoEllipsis() {
let actual = "test".ellipsis(maxLengthOfString: 10)
XCTAssertEqual(actual, "test")
}
func test_ellipsis_givenStringEqualMaxLength_expectNoEllipsis() {
let actual = "test".ellipsis(maxLengthOfString: 4)
XCTAssertEqual(actual, "test")
}
func test_ellipsis_givenStringOverMaxLength_expectEllipsis_expectMaxLengthString() {
let given = "1234567890"
let maxLength = given.count - 1
let actual = given.ellipsis(maxLengthOfString: maxLength)
XCTAssertEqual(actual, "123456...")
XCTAssertEqual(actual.count, maxLength)
}
}
| 28 | 93 | 0.684524 |
f419e14a4b9f7026ea65f6ed7c175ace7a7d2cc9 | 1,763 | // The MIT License (MIT)
// Copyright © 2022 Ivan Vorobei ([email protected])
//
// 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.
extension SFSymbol {
public static var rupeesign: Rupeesign { .init(name: "rupeesign") }
open class Rupeesign: SFSymbol {
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
open var circle: SFSymbol { ext(.start.circle) }
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
open var circleFill: SFSymbol { ext(.start.circle.fill) }
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
open var square: SFSymbol { ext(.start.square) }
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
open var squareFill: SFSymbol { ext(.start.square.fill) }
}
} | 46.394737 | 81 | 0.733409 |
fb7d3001acef6d66879659614503cfee86aee607 | 1,456 | //
// ForceTransitionCoordinator.swift
// PracticeApp
//
// Created by Atsushi Miyake on 2019/02/10.
// Copyright © 2019年 Atsushi Miyake. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
import CoordinatorKit
import Connectable
import Data
final class ForceTransitionCoordinator: Coordinator, Inputable {
static let shared = ForceTransitionCoordinator()
var viewController: UIViewController? = nil
typealias Route = ForceTransitionRoute
func transition(to route: Route) {
switch route {
case .logout:
// transition to login view.
break
case .updateRequired:
// let forceUpdateViewController = ForceUpdateViewController.instantiate()
// UIApplication.shared.keyWindow?.rootViewController = forceUpdateViewController
break
case .ban:
// let banViewController = BanViewController.instantiate()
// UIApplication.shared.keyWindow?.rootViewController = banViewController
break
}
}
}
// MARK: - Input
extension InputSpace where Definer: ForceTransitionCoordinator {
var transition: AnyObserver<ForceTransitionCoordinator.Route> {
return AnyObserver<ForceTransitionCoordinator.Route> { event in
if case .next(let forceTransitionRoute) = event {
self.definer.transition(to: forceTransitionRoute)
}
}
}
}
| 29.12 | 93 | 0.676511 |
6a71588be602f34465312a23f02fe5218b5dfc0b | 789 | import UIKit
extension UIFont {
public convenience init? (_ identifier: FontIdentifier, size: CGFloat) {
self.init(name: identifier.fontName, size: size)
}
}
public protocol FontIdentifierable {
var fontName: String { get }
}
public struct FontIdentifier: FontIdentifierable {
public let fontName: String
public init (_ fontName: String) {
self.fontName = fontName
}
}
/** Usage example
extension FontIdentifier {
public static var sfProBold = FontIdentifier("SFProDisplay-Bold")
public static var sfProRegular = FontIdentifier("SFProDisplay-Regular")
public static var sfProMedium = FontIdentifier("SFProDisplay-Medium")
}
And then somewhere
Label("hello world").font(.sfProRegular, 16)
TextField().font(.sfProRegular, 16)
*/
| 23.909091 | 76 | 0.719899 |
f7d6ca3ca719a79290eac35031035785d30f548e | 3,326 | /*
Copyright © 2016 Toboggan Apps LLC. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import UIKit
/// View with a black, semi-transparent overlay that can have subtracted "holes" to view behind the overlay.
/// Optionally add ``subtractedPaths`` to initialize the overlay with holes. More paths can be subtracted later using ``subtractFromView``.
public class TAOverlayView: UIView {
/// The paths that have been subtracted from the view.
fileprivate var subtractions: [UIBezierPath] = []
/// Use to init the overlay.
///
/// - parameter frame: The frame to use for the semi-transparent overlay.
/// - parameter subtractedPaths: The paths to subtract from the overlay initially. These are optional (not adding them creates a plain overlay). More paths can be subtracted later using ``subtractFromView``.
///
public init(frame: CGRect, subtractedPaths: [TABaseSubtractionPath]? = nil) {
super.init(frame: frame)
// Set a semi-transparent, black background.
self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.85)
// Create the initial layer from the view bounds.
let maskLayer = CAShapeLayer()
maskLayer.frame = self.bounds
maskLayer.fillColor = UIColor.black.cgColor
let path = UIBezierPath(rect: self.bounds)
maskLayer.path = path.cgPath
maskLayer.fillRule = CAShapeLayerFillRule.evenOdd
// Set the mask of the view.
self.layer.mask = maskLayer
if let paths = subtractedPaths {
// Subtract any given paths.
self.subtractFromView(paths: paths)
}
}
override public func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
// Allow touches in "holes" of the overlay to be sent to the views behind it.
for path in self.subtractions {
if path.contains(point) {
return false
}
}
return true
}
/// Subtracts the given ``paths`` from the view.
public func subtractFromView(paths: [TABaseSubtractionPath]) {
if let layer = self.layer.mask as? CAShapeLayer, let oldPath = layer.path {
// Start off with the old/current path.
let newPath = UIBezierPath(cgPath: oldPath)
// Subtract each of the new paths.
for path in paths {
self.subtractions.append(path.bezierPath)
newPath.append(path.bezierPath)
}
// Update the layer.
layer.path = newPath.cgPath
self.layer.mask = layer
}
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 36.955556 | 211 | 0.642213 |
61acd63def13b2d6be4c815e84f7e87348809b98 | 3,465 | //
// MigrationStep.swift
// PersistentStoreMigrationKit
//
// Created by Georg C. Brückmann on 26.08.15.
// Copyright (c) 2015 Georg C. Brückmann. All rights reserved.
//
import Foundation
import CoreData
/// A `MigrationStep` instance encapsulates the migration from one `NSManagedObjectModel` to another without any intermediate models.
/// Migration is performed via an `NSMigrationManager` using an `NSMappingModel`.
final class MigrationStep: NSObject {
/// Specifies how to from `sourceModel` to `destinationModel`.
let mappingModel: NSMappingModel
/// The model to migrate from.
let sourceModel: NSManagedObjectModel
/// The model to migrate to.
let destinationModel: NSManagedObjectModel
private var keyValueObservingContext = NSUUID().UUIDString
/// Initializes a migration step for a source model, destination model, and a mapping model.
///
/// - Parameters:
/// - sourceModel: The model to migrate from.
/// - destinationModel: The model to migrate to.
/// - mappingModel: Specifies how to from `sourceModel` to `destinationModel`.
init(sourceModel: NSManagedObjectModel, destinationModel: NSManagedObjectModel, mappingModel: NSMappingModel) {
self.sourceModel = sourceModel
self.destinationModel = destinationModel
self.mappingModel = mappingModel
}
private var progress: NSProgress?
/// Performs the migration from the persistent store identified by `sourceURL` and using `sourceModel` to `destinationModel`, saving the result in the persistent store identified by `destinationURL`.
///
/// Inserts an `NSProgress` instance into the current progress tree.
///
/// - Parameters:
/// - sourceURL: Identifies the persistent store to migrate from.
/// - sourceStoreType: A string constant (such as `NSSQLiteStoreType`) that specifies the source store type.
/// - destinationURL: Identifies the persistent store to migrate to. May be identical to `sourceURL`.
/// - destinationStoreType: A string constant (such as `NSSQLiteStoreType`) that specifies the destination store type.
func executeForStoreAtURL(sourceURL: NSURL, type sourceStoreType: String, destinationURL: NSURL, storeType destinationStoreType: String) throws {
progress = NSProgress(totalUnitCount: 100)
defer { progress = nil }
let migrationManager = NSMigrationManager(sourceModel: sourceModel, destinationModel: destinationModel)
migrationManager.addObserver(self, forKeyPath: "migrationProgress", options: .New, context: &keyValueObservingContext)
defer { migrationManager.removeObserver(self, forKeyPath: "migrationProgress", context: &keyValueObservingContext) }
try migrationManager.migrateStoreFromURL(sourceURL, type: sourceStoreType, options: nil, withMappingModel: mappingModel, toDestinationURL: destinationURL, destinationType: destinationStoreType, destinationOptions: nil)
}
// MARK: NSKeyValueObserving
override func observeValueForKeyPath(keyPath: String!, ofObject object: AnyObject!, change: [String : AnyObject]!, context: UnsafeMutablePointer<Void>) {
if context != &keyValueObservingContext {
super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
return
}
if let _ = object as? NSMigrationManager {
switch keyPath {
case "migrationProgress":
let newMigrationProgress = (change[NSKeyValueChangeNewKey] as! NSNumber).floatValue
progress?.completedUnitCount = Int64(newMigrationProgress * 100)
default:
break
}
}
}
}
| 47.465753 | 220 | 0.768254 |
16c620efab5c0f719394cc87cfa297bb971b6437 | 229 | //
// AppKeys.swift
// RTM-CollaboratAR
//
// Created by Max Cobb on 21/06/2021.
//
import Foundation
struct AppKeys {
static var appID: String = <#Agora App ID#>
static var appToken: String? = <#Agora App Token#>
}
| 16.357143 | 54 | 0.646288 |
ac836c33cd694e317fecd3d737c849a9309193f8 | 4,369 | //
// UIDevice+JHDevice.swift
// Ray
//
// Created by Ray on 2018/4/2.
// Copyright © 2018年 Ray. All rights reserved.
//
import UIKit
extension UIDevice {
public static func info(version: String) -> String {
return "\(UIDevice.modelName),iOS \(UIDevice.current.systemVersion),V \(version),\(UIDevice.current.name)"
}
public static var isiPhoneX: Bool {
switch deviceIdentifier {
case "iPhone10,3", "iPhone10,6": return true
case "iPhone11,2", "iPhone11,6", "iPhone11,8": return true
default: break
}
if #available(iOS 11.0, *) {
return (UIApplication.shared.keyWindow?.safeAreaInsets.bottom ?? 0) > 0
}
return false
}
public static var modelName: String {
let identifier = deviceIdentifier
switch identifier {
case "iPhone3,1", "iPhone3,2", "iPhone3,3": return "iPhone 4"
case "iPhone4,1": return "iPhone 4s"
case "iPhone5,1", "iPhone5,2": return "iPhone 5"
case "iPhone5,3", "iPhone5,4": return "iPhone 5c"
case "iPhone6,1", "iPhone6,2": return "iPhone 5s"
case "iPhone7,1": return "iPhone 6 Plus"
case "iPhone7,2": return "iPhone 6"
case "iPhone8,1": return "iPhone 6s"
case "iPhone8,2": return "iPhone 6s Plus"
case "iPhone8,4": return "iPhone SE"
case "iPhone9,1", "iPhone9,3": return "iPhone 7"
case "iPhone9,2", "iPhone9,4": return "iPhone 7 Plus"
case "iPhone10,1","iPhone10,4": return "iPhone 8"
case "iPhone10,2","iPhone10,5": return "iPhone 8 Plus"
case "iPhone10,3","iPhone10,6": return "iPhone X"
case "iPhone11,2": return "iPhone XS"
case "iPhone11,6": return "iPhone XS Max"
case "iPhone11,8": return "iPhone XR"
case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return "iPad 2"
case "iPad2,5", "iPad2,6", "iPad2,7": return "iPad Mini"
case "iPad3,1", "iPad3,2", "iPad3,3": return "iPad 3"
case "iPad3,4", "iPad3,5", "iPad3,6": return "iPad 4"
case "iPad4,1", "iPad4,2", "iPad4,3": return "iPad Air"
case "iPad4,4", "iPad4,5", "iPad4,6": return "iPad Mini 2"
case "iPad4,7", "iPad4,8", "iPad4,9": return "iPad Mini 3"
case "iPad5,3", "iPad5,4": return "iPad Air 2"
case "iPad5,1", "iPad5,2": return "iPad Mini 4"
case "iPad6,3", "iPad6,4": return "iPad Pro 9.7 inch"
case "iPad6,7", "iPad6,8": return "iPad Pro 12.9 inch"
case "iPad6,11","iPad6,12": return "iPad 5"
case "iPad7,1", "iPad7,2": return "iPad Pro 12.9 inch(2nd Gen)"
case "iPad7,3", "iPad7,4": return "iPad Pro 10.5 inch"
case "iPad7,5", "iPad7,6": return "iPad 6"
case "iPod5,1": return "iPod Touch 5"
case "iPod7,1": return "iPod Touch 6"
case "AppleTV5,3": return "Apple TV"
case "i386", "x86_64": return "iPhone Simulator"
default: return identifier.replacingOccurrences(of: ",", with: ".")
}
}
// MARK: - Private
private static var deviceIdentifier: String {
var systemInfo = utsname()
uname(&systemInfo)
let machineMirror = Mirror(reflecting: systemInfo.machine)
return machineMirror.children.reduce("") { identifier, element in
guard let value = element.value as? Int8, value != 0 else { return identifier }
return identifier + String(UnicodeScalar(UInt8(value)))
}
}
}
| 48.010989 | 114 | 0.469673 |
ab4973d3a55cdf59c76f9be4ecbcd6ab0735f924 | 649 |
//
// SinglePicTableViewCell.swift
// XW
//
// Created by shying li on 2017/9/7.
// Copyright © 2017年 浙江聚有财金融服务外包有限公司. All rights reserved.
//
import UIKit
import Kingfisher
class SinglePicTableViewCell: GenericTableViewCell, ConfigureCell {
@IBOutlet weak var titlelabel: UILabel!
@IBOutlet weak var timelabel: UILabel!
@IBOutlet weak var imageview: UIImageView!
func configureCell(datas: NewsModel) {
titlelabel.text = datas.title
timelabel.text = datas.date + " " + datas.author_name
imageview.kf.setImage(with: URL(string: datas.thumbnail_pic_s))
}
}
| 21.633333 | 71 | 0.662558 |
084c4d36f46c4326f3d74542c3c73a85be1cdd25 | 7,560 | //
// ColumnStringPickerPopoverViewController.swift
// SwiftyPickerPopover
//
// Created by Ken Torimaru on 2016/09/29.
// Copyright © 2016 Ken Torimaru.
//
//
/* 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.
*/
public class ColumnStringPickerPopoverViewController: AbstractPickerPopoverViewController {
// MARK: Types
/// Popover type
typealias PopoverType = ColumnStringPickerPopover
// MARK: Properties
/// Popover
private var popover: PopoverType! { return anyPopover as? PopoverType }
@IBOutlet weak private var cancelButton: UIBarButtonItem!
@IBOutlet weak private var doneButton: UIBarButtonItem!
@IBOutlet weak private var picker: UIPickerView!
@IBOutlet weak private var clearButton: UIButton!
override public func viewDidLoad() {
super.viewDidLoad()
picker.delegate = self
picker.dataSource = self
}
/// Make the popover properties reflect on this view controller
override func refrectPopoverProperties(){
super.refrectPopoverProperties()
// Set up cancel button
if #available(iOS 11.0, *) {}
else {
navigationItem.leftBarButtonItem = nil
navigationItem.rightBarButtonItem = nil
}
// Select rows if needed
popover.selectedRows.enumerated().forEach {
picker.selectRow($0.element, inComponent: $0.offset, animated: true)
}
cancelButton.title = popover.cancelButton.title
cancelButton.tintColor = popover.cancelButton.color ?? popover.tintColor
navigationItem.setLeftBarButton(cancelButton, animated: false)
doneButton.title = popover.doneButton.title
doneButton.tintColor = popover.doneButton.color ?? popover.tintColor
navigationItem.setRightBarButton(doneButton, animated: false)
clearButton.setTitle(popover.clearButton.title, for: .normal)
if let font = popover.clearButton.font {
clearButton.titleLabel?.font = font
}
clearButton.tintColor = popover.clearButton.color ?? popover.tintColor
clearButton.isHidden = popover.clearButton.action == nil
enableClearButtonIfNeeded()
}
/// Action when tapping done button
///
/// - Parameter sender: Done button
@IBAction func tappedDone(_ sender: AnyObject? = nil) {
tapped(button: popover.doneButton)
}
/// Action when tapping cancel button
///
/// - Parameter sender: Cancel button
@IBAction func tappedCancel(_ sender: AnyObject? = nil) {
tapped(button: popover.cancelButton)
}
private func tapped(button: ColumnStringPickerPopover.ButtonParameterType?) {
let selectedRows = popover.selectedRows
let selectedChoices = selectedValues()
button?.action?(popover, selectedRows, selectedChoices)
popover.removeDimmedView()
dismiss(animated: false)
}
@IBAction func tappedClear(_ sender: AnyObject? = nil) {
// Select row 0 in each componet
for componet in 0..<picker.numberOfComponents {
picker.selectRow(0, inComponent: componet, animated: true)
}
enableClearButtonIfNeeded()
popover.clearButton.action?(popover, popover.selectedRows, selectedValues())
popover.redoDisappearAutomatically()
}
private func enableClearButtonIfNeeded() {
guard !clearButton.isHidden else {
return
}
clearButton.isEnabled = selectedValues().filter({ $0 != popover.kValueForCleared}).count > 0
}
/// Action to be executed after the popover disappears
///
/// - Parameter popoverPresentationController: UIPopoverPresentationController
public func popoverPresentationControllerDidDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) {
tappedCancel()
}
}
// MARK: - UIPickerViewDataSource
extension ColumnStringPickerPopoverViewController: UIPickerViewDataSource {
public func numberOfComponents(in pickerView: UIPickerView) -> Int {
return popover.choices.count
}
public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return popover.choices[component].count
}
public func pickerView(_ pickerView: UIPickerView,
widthForComponent component: Int) -> CGFloat {
return pickerView.frame.size.width * CGFloat(popover.columnPercents[component])
}
private func selectedValue(component: Int, row: Int) -> ColumnStringPickerPopover.ItemType? {
guard let items = popover.choices[safe: component],
let selectedValue = items[safe: row] else {
return nil
}
return popover.displayStringFor?(selectedValue) ?? selectedValue
}
private func selectedValues() -> [ColumnStringPickerPopover.ItemType] {
var result = [ColumnStringPickerPopover.ItemType]()
popover.selectedRows.enumerated().forEach {
if let value = selectedValue(component: $0.offset, row: $0.element){
result.append(value)
}
}
return result
}
}
extension ColumnStringPickerPopoverViewController: UIPickerViewDelegate {
public func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
let value: String = popover.choices[component][row]
let adjustedValue: String = popover.displayStringFor?(value) ?? value
let label: UILabel = view as? UILabel ?? UILabel()
label.text = adjustedValue
label.attributedText = getAttributedText(adjustedValue, component: component)
label.textAlignment = .center
return label
}
private func getAttributedText(_ text: String?, component: Int) -> NSAttributedString? {
guard let text = text else {
return nil
}
let font: UIFont = {
if let f = popover.fonts?[component] {
if let size = popover.fontSizes?[component] {
return UIFont(name: f.fontName, size: size)!
}
return UIFont(name: f.fontName, size: f.pointSize)!
}
let size = popover.fontSizes?[component] ?? popover.kDefaultFontSize
return UIFont.systemFont(ofSize: size)
}()
let color: UIColor = popover.fontColors?[component] ?? popover.kDefaultFontColor
return NSAttributedString(string: text, attributes: [.font: font, .foregroundColor: color])
}
public func pickerView(_ pickerView: UIPickerView,
didSelectRow row: Int,
inComponent component: Int){
popover.selectedRows[component] = row
enableClearButtonIfNeeded()
popover.valueChangeAction?(popover, popover.selectedRows, selectedValues())
popover.redoDisappearAutomatically()
}
}
| 40 | 436 | 0.66918 |
6a582a0dab3f7df06a42e27ce3a3dcd44477092c | 596 | //
// FavoriteDataManager.swift
// thanos menu
//
// Created by Lucas Moreton on 24/07/20.
// Copyright © 2020 Lucas Moreton. All rights reserved.
//
import Foundation
struct FavoriteDataManager: FavoriteDataManagerProtocol {
let kFavoriteKey: String = "is-character-favorite"
func setFavorite(to bool: Bool, for characterId: Int) {
UserDefaults.standard.set(bool, forKey: "\(kFavoriteKey)-\(characterId)")
}
func isCharacterFavorite(_ characterId: Int) -> Bool {
return UserDefaults.standard.bool(forKey: "\(kFavoriteKey)-\(characterId)")
}
}
| 27.090909 | 83 | 0.691275 |
7534243886cc1765a558ed6a0899cb03aba8d931 | 246 | //
// Assignments.swift
// CourseTracker
//
// Created by Diego Bustamante on 12/4/17.
// Copyright © 2017 Diego Bustamante. All rights reserved.
//
import UIKit
class Assignments: NSObject {
var name: String?;
var due: String?;
}
| 16.4 | 59 | 0.670732 |
d96ccadbcf0af86bd72441c25465b098a78e182e | 2,102 | class Solution {
// Solution @ Sergey Leschev, Belarusian State University
// 1839. Longest Substring Of All Vowels in Order
// A string is considered beautiful if it satisfies the following conditions:
// Each of the 5 English vowels ('a', 'e', 'i', 'o', 'u') must appear at least once in it.
// The letters must be sorted in alphabetical order (i.e. all 'a's before 'e's, all 'e's before 'i's, etc.).
// For example, strings "aeiou" and "aaaaaaeiiiioou" are considered beautiful, but "uaeio", "aeoiu", and "aaaeeeooo" are not beautiful.
// Given a string word consisting of English vowels, return the length of the longest beautiful substring of word. If no such substring exists, return 0.
// A substring is a contiguous sequence of characters in a string.
// Example 1:
// Input: word = "aeiaaioaaaaeiiiiouuuooaauuaeiu"
// Output: 13
// Explanation: The longest beautiful substring in word is "aaaaeiiiiouuu" of length 13.
// Example 2:
// Input: word = "aeeeiiiioooauuuaeiou"
// Output: 5
// Explanation: The longest beautiful substring in word is "aeiou" of length 5.
// Example 3:
// Input: word = "a"
// Output: 0
// Explanation: There is no beautiful substring, so return 0.
// Constraints:
// 1 <= word.length <= 5 * 10^5
// word consists of characters 'a', 'e', 'i', 'o', and 'u'.
func longestBeautifulSubstring(_ word: String) -> Int {
var ans = Int.min
var l = word.startIndex
var visited = Set<Character>()
while l < word.endIndex {
visited.insert(word[l])
var r = word.index(after: l)
var last = l
while r < word.endIndex && word[r].asciiValue! >= word[last].asciiValue! {
if !visited.contains(word[r]) { visited.insert(word[r]) }
last = r
r = word.index(after: r)
}
if visited.count == 5 { ans = max(ans, word.distance(from: l, to: r)) }
l = r
visited = []
}
return max(ans, 0)
}
} | 39.660377 | 157 | 0.597526 |
abedad165138fe5fbf2a78bd92966fee1a3b8a60 | 194 | // Copyright (c) 2014 to present, Quick contributors
public class Ocean {
public class var sharedOcean: Ocean {
get {
return Ocean()
}
}
public func add(object: Any) {}
} | 17.636364 | 52 | 0.628866 |
8acc4ad669360612f67caeacf7a49aa621a64d16 | 337 | //
// EventDetailCell.swift
// ConferenceApp
//
// Created by Ryan McCracken on 4/6/15.
// Copyright (c) 2015 GR OpenSource. All rights reserved.
//
import Foundation
import UIKit
class EventDetailCell: UITableViewCell {
@IBOutlet weak var detailLabel: UILabel!
@IBOutlet weak var scheduleButton: UIButton!
} | 18.722222 | 58 | 0.700297 |
e0370706908f8be5549ed5b6174baa88a4e8a7a1 | 1,009 | import SwiftAST
public enum UIViewControllerCompoundType {
private static var singleton = makeType(from: typeString(), typeName: "UIViewController")
public static func create() -> CompoundedMappingType {
singleton
}
private static func typeString() -> String {
let type = """
class UIViewController: UIResponder, NSCoding, UIAppearanceContainer, UITraitEnvironment, UIContentContainer, UIFocusEnvironment {
var view: UIView
init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?)
func viewDidLoad()
func viewWillAppear(_ animated: Bool)
func viewDidAppear(_ animated: Bool)
func viewWillDisappear(_ animated: Bool)
func viewDidDisappear(_ animated: Bool)
func viewWillLayoutSubviews()
func viewDidLayoutSubviews()
}
"""
return type
}
}
| 34.793103 | 142 | 0.59663 |
d776ff7cde9ac8b1471993d474fb80639e055635 | 4,319 | //
// CourseViewController.swift
// Bonday
//
// Created by bonday012 on 2017/5/17.
// Copyright © 2017年 bonday012. All rights reserved.
//
import UIKit
import Alamofire
import AlamofireObjectMapper
import SVProgressHUD
import Moya
import RxSwift
let tableViews = UITableView()
let courceCellID = "courceCellID"
class CourseViewController: BaseViewController,UITableViewDelegate,UITableViewDataSource {
var type = Int()
//数据
var items = [LGOCLatestModel]()
var dataArr = NSMutableArray()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = kCommenColor_whiteColor
createTableView()
_ = self.addDownLoadTask()
// Do any additional setup after loading the view.
}
func addDownLoadTask() {
let provider = MoyaProvider<ApiManager>()
SVProgressHUD.show(withStatus: "正在加载...")
provider.rx.request(.KHot_OpenCourse_latest)
.mapJSON()
.subscribe { event in
switch event{
case .success(let response):
print(response)
case .error(let error):
print(error)
SVProgressHUD.showError(withStatus: "加载失败....")
}
}
let url = KBonDay + KHot_OpenCourse_latest
// let params = ["gender":1]
let headers:HTTPHeaders = [
"Authorization":"",
"Accept":"application/json"
]
Alamofire.request(url, method: .get, parameters: nil, encoding: URLEncoding.default, headers: headers)
.responseObject { (response:DataResponse<DataObjectModel>) in
guard response.result.isSuccess else{
return
}
let dataModel = response.result.value
let code = dataModel?.code
if code == 200{
if let data = dataModel?.datas{
for model in data{
self.dataArr.add(model)
}
tableViews.reloadData()
}
SVProgressHUD.dismiss()
}
}
}
func createTableView() {
tableViews.frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight-kNavBarHeight)
tableViews.rowHeight = 160
tableViews.separatorStyle = .none
tableViews.dataSource = self
tableViews.delegate = self
tableViews.backgroundColor = kCommenColor_whiteColor
tableViews.register(LGOCLatestTableViewCell.self, forCellReuseIdentifier: courceCellID)
tableViews.register(LGOCListTableViewCell.self, forCellReuseIdentifier: "LGOCListTableViewCell")
self.view.addSubview(tableViews)
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dataArr.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.row == 0 {
return 183-36
}
return 106+(kScreenWidth-20)/2
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 {
let listCell = tableView.dequeueReusableCell(withIdentifier: "LGOCListTableViewCell", for: indexPath) as!LGOCListTableViewCell
listCell.selectionStyle = .none
return listCell
}
let courceCell = tableView.dequeueReusableCell(withIdentifier: courceCellID) as! LGOCLatestTableViewCell
courceCell.selectionStyle = .none
courceCell.dataDic = self.dataArr[indexPath.row] as? LGOCLatestModel
return courceCell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 33.48062 | 138 | 0.627692 |
2095ac05f4b116287d6d781e1aebcc79dec90660 | 319 | //
// StudyQueueOperation.swift
// Pods
//
// Created by Andriy K. on 12/10/15.
//
//
import Foundation
public class DownloadStudyQueueOperation: DownloadOperation {
override init(url: NSURL, cacheFile: NSURL) {
super.init(url: url, cacheFile: cacheFile)
name = "Download Study Queue data"
}
}
| 16.789474 | 61 | 0.677116 |
cc40bd399621464c9b170de37387824b5bb1fca7 | 7,836 | //
// HoshiTextField.swift
// TextFieldEffects
//
// Created by Raúl Riera on 24/01/2015.
// Copyright (c) 2015 Raul Riera. All rights reserved.
//
import UIKit
/**
An HoshiTextField is a subclass of the TextFieldEffects object, is a control that displays an UITextField with a customizable visual effect around the lower edge of the control.
*/
@IBDesignable open class HoshiTextField: TextFieldEffects {
/**
The color of the border when it has no content.
This property applies a color to the lower edge of the control. The default value for this property is a clear color.
*/
@IBInspectable dynamic open var borderInactiveColor: UIColor? {
didSet {
updateBorder()
}
}
/**
The color of the border when it has content.
This property applies a color to the lower edge of the control. The default value for this property is a clear color.
*/
@IBInspectable dynamic open var borderActiveColor: UIColor? {
didSet {
updateBorder()
}
}
/**
The color of the placeholder text.
This property applies a color to the complete placeholder string. The default value for this property is a black color.
*/
@IBInspectable dynamic open var placeholderColor: UIColor = .black {
didSet {
updatePlaceholder()
}
}
/**
The scale of the placeholder font.
This property determines the size of the placeholder label relative to the font size of the text field.
*/
@IBInspectable dynamic open var placeholderFontScale: CGFloat = 0.65 {
didSet {
updatePlaceholder()
}
}
override open var placeholder: String? {
didSet {
updatePlaceholder()
}
}
override open var bounds: CGRect {
didSet {
updateBorder()
updatePlaceholder()
}
}
private let borderThickness: (active: CGFloat, inactive: CGFloat) = (active: 2, inactive: 0.5)
private let placeholderInsets = CGPoint(x: 0, y: 6)
private let textFieldInsets = CGPoint(x: 0, y: 12)
private let inactiveBorderLayer = CALayer()
private let activeBorderLayer = CALayer()
private var activePlaceholderPoint: CGPoint = CGPoint.zero
// MARK: - TextFieldEffects
override open func drawViewsForRect(_ rect: CGRect) {
let frame = CGRect(origin: CGPoint.zero, size: CGSize(width: rect.size.width, height: rect.size.height))
placeholderLabel.frame = frame.insetBy(dx: placeholderInsets.x, dy: placeholderInsets.y)
placeholderLabel.font = placeholderFontFromFont(font!)
updateBorder()
updatePlaceholder()
layer.addSublayer(inactiveBorderLayer)
layer.addSublayer(activeBorderLayer)
addSubview(placeholderLabel)
}
override open func didMoveToWindow() {
updateBorder()
updatePlaceholder()
layer.addSublayer(inactiveBorderLayer)
addSubview(placeholderLabel)
}
override open func animateViewsForTextEntry() {
if text!.isEmpty {
UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 1.0, options: .beginFromCurrentState, animations: ({
self.placeholderLabel.frame.origin = CGPoint(x: 10, y: self.placeholderLabel.frame.origin.y)
self.placeholderLabel.alpha = 0
}), completion: { _ in
self.animationCompletionHandler?(.textEntry)
})
}
layoutPlaceholderInTextRect()
placeholderLabel.frame.origin = activePlaceholderPoint
UIView.animate(withDuration: 0.4, animations: {
self.placeholderLabel.alpha = 1.0
})
activeBorderLayer.frame = rectForBorder(borderThickness.active, isFilled: true)
}
override open func animateViewsForTextDisplay() {
if text!.isEmpty {
UIView.animate(withDuration: 0.35, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 2.0, options: .beginFromCurrentState, animations: ({
self.layoutPlaceholderInTextRect()
self.placeholderLabel.alpha = 1
}), completion: { _ in
self.animationCompletionHandler?(.textDisplay)
})
activeBorderLayer.frame = self.rectForBorder(self.borderThickness.active, isFilled: false)
} else {
activeBorderLayer.frame = self.rectForBorder(self.borderThickness.active, isFilled: false)
}
}
// MARK: - Private
private func updateBorder() {
inactiveBorderLayer.frame = rectForBorder(borderThickness.inactive, isFilled: !isFirstResponder)
inactiveBorderLayer.backgroundColor = borderInactiveColor?.cgColor
activeBorderLayer.frame = rectForBorder(borderThickness.active, isFilled: isFirstResponder)
activeBorderLayer.backgroundColor = borderActiveColor?.cgColor
}
private func updatePlaceholder() {
placeholderLabel.text = placeholder
placeholderLabel.textColor = placeholderColor
placeholderLabel.sizeToFit()
layoutPlaceholderInTextRect()
if isFirstResponder { //|| text!.isNotEmpty {
animateViewsForTextEntry()
}
if text!.isNotEmpty {
/* UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 1.0, options: .beginFromCurrentState, animations: ({
self.placeholderLabel.frame.origin = CGPoint(x: 10, y: self.placeholderLabel.frame.origin.y)
self.placeholderLabel.alpha = 0
}), completion: { _ in
self.animationCompletionHandler?(.textEntry)
})
*/
layoutPlaceholderInTextRect()
placeholderLabel.frame.origin = activePlaceholderPoint
/*
UIView.animate(withDuration: 0.4, animations: {
self.placeholderLabel.alpha = 1.0
})*/
}
}
private func placeholderFontFromFont(_ font: UIFont) -> UIFont! {
let smallerFont = UIFont(name: font.fontName, size: font.pointSize * placeholderFontScale)
return smallerFont
}
private func rectForBorder(_ thickness: CGFloat, isFilled: Bool) -> CGRect {
if isFilled {
return CGRect(origin: CGPoint(x: 0, y: frame.height-thickness), size: CGSize(width: frame.width, height: thickness))
} else {
return CGRect(origin: CGPoint(x: 0, y: frame.height-thickness), size: CGSize(width: 0, height: thickness))
}
}
private func layoutPlaceholderInTextRect() {
let textRect = self.textRect(forBounds: bounds)
var originX = textRect.origin.x
switch self.textAlignment {
case .center:
originX += textRect.size.width/2 - placeholderLabel.bounds.width/2
case .right:
originX += textRect.size.width - placeholderLabel.bounds.width
default:
break
}
placeholderLabel.frame = CGRect(x: originX, y: textRect.height/2,
width: placeholderLabel.bounds.width, height: placeholderLabel.bounds.height)
activePlaceholderPoint = CGPoint(x: placeholderLabel.frame.origin.x, y: placeholderLabel.frame.origin.y - placeholderLabel.frame.size.height - placeholderInsets.y)
}
// MARK: - Overrides
override open func editingRect(forBounds bounds: CGRect) -> CGRect {
return bounds.offsetBy(dx: textFieldInsets.x, dy: textFieldInsets.y)
}
override open func textRect(forBounds bounds: CGRect) -> CGRect {
return bounds.offsetBy(dx: textFieldInsets.x, dy: textFieldInsets.y)
}
}
| 36.446512 | 178 | 0.643951 |
092348f7c2ff17c16f9152b0db3467c1f3207183 | 697 | //
// CartCoffeeCell.swift
// CoffeeShop
//
// Created by Göktuğ Gümüş on 25.09.2018.
// Copyright © 2018 Göktuğ Gümüş. All rights reserved.
//
import UIKit
class CartCoffeeCell: UITableViewCell {
@IBOutlet weak var iconImageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var countLabel: UILabel!
@IBOutlet weak var totalPriceLabel: UILabel!
func configure(with cartItem: CartItem) {
iconImageView.image = UIImage(named: cartItem.coffee.icon)
nameLabel.text = cartItem.coffee.name
countLabel.text = "\(cartItem.count) cup of coffee"
totalPriceLabel.text = CurrencyFormatter.turkishLirasFormatter.string(from: cartItem.totalPrice)
}
}
| 29.041667 | 100 | 0.74462 |
5bf85475bb0851308a5fe6d850d12653af5452b7 | 316 | //
// User.swift
// Builder pattern example
//
// Created by Gabrielle Earnshaw on 05/08/2018.
// Copyright © 2018 Gabrielle Earnshaw. All rights reserved.
//
import Foundation
struct User {
let firstName: String
let surname: String
let age: Int
let location: String
let account: Account
}
| 17.555556 | 61 | 0.683544 |
7af27444725f7dc90f6c1ee7f7822f01b2509c07 | 2,068 | //
// inputViewController.swift
// Vouched_Example
//
// Created by David Woo on 8/3/20.
// Copyright © 2020 CocoaPods. All rights reserved.
//
import UIKit
class InputViewController: UIViewController {
@IBOutlet private weak var inputFirstName: UITextField!
@IBOutlet private weak var inputLastName: UITextField!
@IBOutlet private weak var barcodeSwitch: UISwitch!
@IBOutlet private weak var helperSwitch: UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.isHidden = false
self.navigationItem.title = "Input Name"
self.setupHideKeyboardOnTap()
}
override func prepare(for segue: UIStoryboardSegue, sender:Any?) {
switch segue.destination {
case let destVC as IdViewController:
destVC.inputFirstName = self.inputFirstName.text!
destVC.inputLastName = self.inputLastName.text!
destVC.includeBarcode = self.barcodeSwitch.isOn
case let destVC as IdViewControllerV2:
destVC.inputFirstName = self.inputFirstName.text!
destVC.inputLastName = self.inputLastName.text!
destVC.includeBarcode = self.barcodeSwitch.isOn
default:
break
}
}
@IBAction func onContinue(_ sender: Any) {
if self.helperSwitch.isOn {
performSegue(withIdentifier: "ToInputNamesWithHelper", sender: self)
} else {
performSegue(withIdentifier: "ToInputNames", sender: self)
}
}
func setupHideKeyboardOnTap() {
self.view.addGestureRecognizer(self.endEditingRecognizer())
self.navigationController?.navigationBar.addGestureRecognizer(self.endEditingRecognizer())
}
/// Dismisses the keyboard from self.view
private func endEditingRecognizer() -> UIGestureRecognizer {
let tap = UITapGestureRecognizer(target: self.view, action: #selector(self.view.endEditing(_:)))
tap.cancelsTouchesInView = false
return tap
}
}
| 33.901639 | 104 | 0.672631 |
62f92d4395baee5e167b44686b5d32289c505b61 | 1,384 | /**
* https://leetcode.com/problems/count-vowels-permutation/
*
*
*/
// Date: Sun Jul 4 08:55:22 PDT 2021
class Solution {
func countVowelPermutation(_ n: Int) -> Int {
// a, e, i, o, u
let mod = 1000000007
var count = Array(repeating: Array(repeating: 0, count: 5), count: n)
for index in 0 ..< n {
for v in 0 ..< 5 {
if index == 0 {
count[index][v] = 1
} else {
switch v {
case 0:
count[index][v] += (((count[index - 1][1] + count[index - 1][2]) % mod) + count[index - 1][4]) % mod
case 1:
count[index][v] += (count[index - 1][0] + count[index - 1][2]) % mod
case 2:
count[index][v] += (count[index - 1][1] + count[index - 1][3]) % mod
case 3:
count[index][v] += (count[index - 1][2]) % mod
case 4:
count[index][v] += (count[index - 1][2] + count[index - 1][3]) % mod
default: break
}
}
}
}
var result = 0
for v in 0 ..< 5 {
result = (result + count[n - 1][v]) % mod
}
return result
}
} | 35.487179 | 124 | 0.375723 |
4a3153be1eac668d67a9f750d35946e2cab1e154 | 2,519 | //
// ColorsCell.swift
// Demo
//
// Created by mac on 2018/2/26.
// Copyright © 2018年 程维. All rights reserved.
//
import UIKit
import UIKitExtSwift
class ColorsCell: UITableViewCell {
static let cellHeight: CGFloat = 70
let textFont: UIFont = UIFont.systemFont(ofSize: 16)
lazy var itemHeight: CGFloat = textFont.lineHeight
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupUI() {
self.selectionStyle = .none
let count: CGFloat = CGFloat(floor((ColorsCell.cellHeight - 20) / itemHeight))
let spec: CGFloat = (ColorsCell.cellHeight - 20 - itemHeight * count) / (count + 1)
for i in 0..<Int(count) {
let v = createItem(with: (arc4random() % 0xFFFFFF).ex.color)
self.addSubview(v)
v.frame = CGRect(x: 0, y: 10 + (itemHeight + spec) * CGFloat(i), width: kScreenWidth, height: itemHeight)
}
}
func createItem(with color:UIColor) -> UIView {
let size: CGSize = CGSize(width: itemHeight, height: itemHeight)
let img: UIImage = UIImage.ex.color(with: color, size: size, radius: itemHeight * 0.5)
let view = UIView(frame: CGRect(origin: .zero, size: CGSize(width: kScreenWidth, height: itemHeight)))
self.contentView.addSubview(view)
let imageView = UIImageView(image: img)
view.addSubview(imageView)
imageView.frame = CGRect(x: 20, y: 0, width: itemHeight, height: itemHeight)
if let hex: String = color.ex.hexString {
let label = UILabel.init(hex, textColor: .darkGray)
label.font = textFont
view.addSubview(label)
let line: UIView = UIView()
line.backgroundColor = .lightGray
view.addSubview(line)
let labelW: CGFloat = hex.contentWidth(maxHeight: itemHeight, font: textFont)
let lineW: CGFloat = kScreenWidth - 40 - labelW - 10 - itemHeight
line.frame = CGRect(x: imageView.maxX + 5, y: imageView.midY - 0.25, width: lineW, height: 1)
label.frame = CGRect(x: line.maxX + 5, y: 0, width: labelW, height: itemHeight)
}
return view
}
}
| 34.506849 | 117 | 0.595474 |
d9f35ddd40cbab4c8c7da0780ba04fe32ad6853c | 4,615 | //
// Copyright 2011 - 2020 Schibsted Products & Technology AS.
// Licensed under the terms of the MIT license. See LICENSE in the project root.
//
import Foundation
/// Represents a phone number string
public struct PhoneNumber: IdentifierProtocol {
let phoneNumber: String
let normalizedPhoneNumber: String
let numberOfDigitsInNormalizedCountryCode: Int?
/// The string that is provided during initialization
public var originalString: String {
return phoneNumber
}
/// The normalized form used internally (may or may not be different)
public var normalizedString: String {
return normalizedPhoneNumber
}
/// Represents the components of a full phone number, i.e. dialing code and number
public struct Components {
let countryCode: String
let number: String
}
/**
Create a PhoneNumber.Components object out of this PhoneNumber.
This will only work if you have used the initializer that allows seperation of code and parts
*/
public func components() throws -> Components {
guard let numberOfDigits = numberOfDigitsInNormalizedCountryCode else {
throw ClientError.invalidPhoneNumber
}
let startIndexOfNumberPart = normalizedPhoneNumber.index(
normalizedPhoneNumber.startIndex,
offsetBy: numberOfDigits
)
return Components(
countryCode: String(normalizedPhoneNumber[..<startIndexOfNumberPart]),
number: String(normalizedPhoneNumber[startIndexOfNumberPart...])
)
}
/**
Initialize PhoneNumber identifier
The input strings are only allowed to have digits or spaces, with the exception of '+' that may be present in the country code. There must be at least one
digit in each string. The country code is normalized by removing '00' in the front (if present) and adding '+' as the first char.
- parameter countryCode: a phone number's country code as a string to parse
- parameter identifier: a phone number as a string to parse
- returns: PhoneNumber or nil if parsing fails
*/
public init?(countryCode: String, number: String) {
guard let normalizedCountryCode = PhoneNumber.normalizeCountryCode(countryCode),
let normalizedNumber = PhoneNumber.normalizeNumberComponent(number)
else {
return nil
}
phoneNumber = countryCode + number
normalizedPhoneNumber = normalizedCountryCode + normalizedNumber
numberOfDigitsInNormalizedCountryCode = normalizedCountryCode.count
}
/**
Initialize PhoneNumber identifier
Assumes the values passed in is a full phone number including the internal dialing code. The number is normalized by removing '00' in the
front (if present) and adding '+' as the first char.
- parameter fullNumber: a phone number including full country code
- returns: PhoneNumber or nil if parsing fails
*/
public init?(fullNumber: String?) {
guard let fullNumber = fullNumber else { return nil }
guard let normalizedPhoneNumber = PhoneNumber.normalizeFullNumber(fullNumber) else { return nil }
phoneNumber = fullNumber
self.normalizedPhoneNumber = normalizedPhoneNumber
numberOfDigitsInNormalizedCountryCode = nil
}
private static func normalizeFullNumber(_ value: String) -> String? {
var string = value.filter { $0 != " " }
if string.hasPrefix("+") {
string.remove(at: string.startIndex)
} else if string.hasPrefix("00") {
string.removeFirst(2)
} else {
return nil
}
guard string.count > 0, string.rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) == nil else {
return nil
}
return "+" + string
}
private static func normalizeCountryCode(_ value: String) -> String? {
if !value.hasPrefix("+"), !value.hasPrefix("00") {
return normalizeFullNumber("+" + value)
} else {
return normalizeFullNumber(value)
}
}
private static func normalizeNumberComponent(_ value: String) -> String? {
let digits = value.filter { $0 != " " }
guard digits.count > 0, digits.rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) == nil else {
return nil
}
return digits
}
}
extension PhoneNumber: Equatable {
public static func == (lhs: PhoneNumber, rhs: PhoneNumber) -> Bool {
return lhs.normalizedString == rhs.normalizedString
}
}
| 36.338583 | 159 | 0.669989 |
d576c7b0d0ac7bcdecea0b24ea8e6da9e3a5ea92 | 554 | //
// CountryFrom.swift
// Kiwi
//
// Created by Muhammad Zahid Imran on 1/18/20.
// Copyright © 2020 Zahid Imran. All rights reserved.
//
import Foundation
struct CountryFrom : Codable {
let code : String?
let name : String?
enum CodingKeys: String, CodingKey {
case code = "code"
case name = "name"
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
code = try values.decodeIfPresent(String.self, forKey: .code)
name = try values.decodeIfPresent(String.self, forKey: .name)
}
}
| 20.518519 | 63 | 0.696751 |
eb37095123f573f15f6d9005ebcc6e84592c8e79 | 654 | //
// RootVCRoutingOption.swift
// VISPER-Wireframe
//
// Created by bartel on 08.12.17.
//
import Foundation
import VISPER_Wireframe_Core
public protocol RootVCRoutingOption : AnimatedRoutingOption{
}
public struct DefaultRootVCRoutingOption: RootVCRoutingOption{
public let animated: Bool
public init(animated: Bool = true) {
self.animated = animated
}
public func isEqual(otherOption: RoutingOption?) -> Bool {
guard let otherOption = otherOption as? RootVCRoutingOption else {
return false
}
return self.animated == otherOption.animated
}
}
| 19.818182 | 74 | 0.659021 |
50f1573f79e74dd9a25630ac808900a769b4e01d | 477 | //
// ProductModel.swift
// E-Commerce
//
// Created by Christopher Hicks on 5/14/21.
//
import Foundation
struct Product: Codable, Identifiable {
let id: Int
let name: String
let image: String
let price: Int
let description: String
let color: [Double]
var red: Double { return color[0] }
var green: Double { return color [1] }
var blue: Double { return color[2] }
var formattedPrice: String { return "$\(price)" }
}
| 19.08 | 53 | 0.618449 |
e996de76d0051c07169fb52708cd8c4b45300385 | 4,782 | //
// NROptionDemo.swift
// NRFunctionSwiftDemo
//
// Created by 王文涛 on 2021/2/27.
//
import Foundation
/***************可选值****************/
let citiesMap = ["Pairs": 2241, "Madrid": 3165, "Amsterdam": 827, "Berlin": 3562]
// 可选绑定
fileprivate func test() {
if let madridPopulation = citiesMap["Madrid"] {
print("The population of Madrid is \(madridPopulation)")
} else {
print("Unknown city: Madrid")
}
}
// 自定一个??操作符
// 这里的定义有一个问题:
// 如果 defaultValue 的值是通过某个函数或者表达式得到的,那么无论可选值是否为nil,
// defaultValue 都会被求值,这是不合理的,通常只有可选参数值为nil的时候 defaultValue才进行求值
infix operator ??!
func ??!<T>(optional: T?, defaultValue: T) -> T {
if let x = optional {
return x
}
return defaultValue
}
// 改进方案
// 能够结果可选值为不为nil的时候 defaultValue 如果是函数或者表达式时被计算的问题,
// 但是使用起来不方便,如:test1
infix operator ??!!
func ??!!<T>(optional: T?, defaultValue: () -> T) -> T {
if let x = optional {
return x
} else {
return defaultValue()
}
}
fileprivate func text1() {
let cache = ["test.swift": 1000]
let defaultValue = 2000;
_ = cache["hello.swift"] ??!! { defaultValue }
}
// 最终方案
// Swift 标准库中的定义通过使用 Swift 的 aotoclosure 类型标签来避开显式闭包的需求
// 它会在所需要的闭包中隐式的将参数封装到 ?? 运算符
infix operator ??!!!
fileprivate func ??!!!<T>(optional: T?, defaultValue:@autoclosure () throws -> T) rethrows -> T {
if let x = optional {
return x
}
return try defaultValue()
}
/***************可选链****************/
fileprivate struct NROrder {
let orderNum: Int
let person: NRPerson?
}
fileprivate struct NRPerson {
let name: String
let address: NRAddress?
}
fileprivate struct NRAddress {
let streetName: String
let city: String
let state: String?
}
fileprivate func test2() {
let order = NROrder(orderNum: 42, person: nil)
// 可选绑定
if let person = order.person {
if let address = person.address {
if let state = address.state {
print("Got a state: \(state)")
}
}
}
// 可选链
if let state = order.person?.address?.state {
print("Got a state: \(state)")
} else {
print("Unkonwn person, adress, or state")
}
}
/***************分支上的可选值****************/
fileprivate func test3() {
let madridPopulation = citiesMap["Madrid"]
switch madridPopulation {
case 0?:
print("Nobody in Madrid")
case (1..<1000)?:
print("Less than a millon in Madrid")
case let x?:
print("\(x) pepple in Madrid")
case nil:
print("We don't knw about Madrid")
}
}
/*************** guard ****************/
fileprivate func test4() {
// 必须return
guard let madridPopulation = citiesMap["Madrid"] else {
print("We don't knw about Madrid")
return
}
print("The population of Madrid is \(madridPopulation)")
}
/*************** 可选映射 ****************/
fileprivate extension Optional {
func nr_map<U>(_ transform: (Wrapped) -> U) -> U? {
guard let x = self else { return nil }
return transform(x)
}
}
/*************** flatmap ****************/
fileprivate func add1(_ optionalX: Int?, _ optioalY: Int?) -> Int? {
if let x = optionalX {
if let y = optioalY {
return x + y
}
}
return nil
}
fileprivate func add2(_ optionalX: Int?, _ optioalY: Int?) -> Int? {
if let x = optionalX, let y = optioalY {
return x + y
}
return nil
}
fileprivate func add3(_ optionalX: Int?, _ optioalY: Int?) -> Int? {
guard let x = optionalX, let y = optioalY else { return nil }
return x + y
}
let captialsMap = [
"France": "Paris",
"Spain": "Madrid",
"The Netherlands": "Amsterddam",
"Belguim": "Brussels"
]
fileprivate func populationOfCapital1(country: String) -> Int? {
guard let captial = captialsMap[country], let population = citiesMap[captial] else { return nil }
return population * 1000
}
// flatMap自定义实现
fileprivate extension Optional {
func nr_flatMap<U>(_ transform: (Wrapped) throws -> U?) rethrows -> U? {
guard let x = self else { return nil }
return try transform(x)
}
}
fileprivate func add4(_ optionalX: Int?, _ optioalY: Int?) -> Int? {
return optionalX.flatMap { x in
optioalY.flatMap { y in
return x + y
}
}
}
fileprivate func populationOfCapital2(country: String) -> Int? {
return captialsMap[country].flatMap { captial in
return citiesMap[captial].flatMap { population in
return population * 1000
}
}
}
fileprivate func populationOfCapital3(country: String) -> Int? {
captialsMap[country].flatMap { captial in
citiesMap[captial]
}.flatMap { population in
return population * 1000
}
}
| 23.101449 | 101 | 0.585111 |
03a5b7f0e6b37862f248115a21cd77ace08b5ac7 | 2,669 | //
// ProductDetailViewController.swift
// MoltinSwiftExample
//
// Created by Dylan McKee on 16/08/2015.
// Copyright (c) 2015 Moltin. All rights reserved.
//
import UIKit
import Moltin
import SwiftSpinner
class ProductDetailViewController: UIViewController {
var productDict:NSDictionary?
@IBOutlet weak var descriptionTextView:UITextView?
@IBOutlet weak var productImageView:UIImageView?
@IBOutlet weak var buyButton:UIButton?
override func viewDidLoad() {
super.viewDidLoad()
buyButton?.backgroundColor = MOLTIN_COLOR
// Do any additional setup after loading the view.
if let description = productDict!.valueForKey("description") as? String {
self.descriptionTextView?.text = description
}
if let price = productDict!.valueForKeyPath("price.data.formatted.with_tax") as? String {
let buyButtonTitle = String(format: "Buy Now (%@)", price)
self.buyButton?.setTitle(buyButtonTitle, forState: UIControlState.Normal)
}
var imageUrl = ""
if let images = productDict!.objectForKey("images") as? NSArray {
if (images.firstObject != nil) {
imageUrl = images.firstObject?.valueForKeyPath("url.https") as! String
}
}
productImageView?.sd_setImageWithURL(NSURL(string: imageUrl))
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func buyProduct(sender: AnyObject) {
// Add the current product to the cart
let productId:String = productDict!.objectForKey("id") as! String
SwiftSpinner.show("Updating cart")
Moltin.sharedInstance().cart.insertItemWithId(productId, quantity: 1, andModifiersOrNil: nil, success: { (response) -> Void in
// Done.
// Switch to cart...
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.switchToCartTab()
// and hide loading UI
SwiftSpinner.hide()
}) { (response, error) -> Void in
// Something went wrong.
// Hide loading UI and display an error to the user.
SwiftSpinner.hide()
AlertDialog.showAlert("Error", message: "Couldn't add product to the cart", viewController: self)
print("Something went wrong...")
print(error)
}
}
}
| 30.678161 | 134 | 0.602473 |
22bf1badfe5350fb2ed2f753ce71b3a23a2c9ac0 | 1,932 | //
// Copyright (c) Vatsal Manot
//
import Swift
import SwiftUI
/// An internal structure used to manage cell preferences for `CocoaList` and `CollectionView`.
@usableFromInline
struct _ListRowPreferences: Equatable {
var estimatedCellSize: CGSize? = nil
var isHighlightable = true
var onSelect: Action?
var onDeselect: Action?
}
/// An internal preference key that defines a list row's preferences.
struct _ListRowPreferencesKey: PreferenceKey {
static let defaultValue = _ListRowPreferences()
static func reduce(value: inout _ListRowPreferences, nextValue: () -> _ListRowPreferences) {
value = nextValue()
}
}
// MARK: - API -
extension View {
/// Sets the estimated size for the list row.
public func estimatedListRowSize(_ estimatedCellSize: CGSize) -> some View {
transformPreference(_ListRowPreferencesKey.self) { preferences in
preferences.estimatedCellSize = estimatedCellSize
}
}
/// Sets whether the list row is highlightable or not.
public func listRowHighlightable(_ isHighlightable: Bool) -> some View {
transformPreference(_ListRowPreferencesKey.self) { preferences in
preferences.isHighlightable = isHighlightable
}
}
/// Returns a version of `self` that will invoke `action` after
/// recognizing a selection.
public func onListRowSelect(perform action: @escaping () -> Void) -> some View {
transformPreference(_ListRowPreferencesKey.self) { preferences in
preferences.onSelect = .init(action)
}
}
/// Returns a version of `self` that will invoke `action` after
/// recognizing a deselection.
public func onListRowDeselect(perform action: @escaping () -> Void) -> some View {
transformPreference(_ListRowPreferencesKey.self) { preferences in
preferences.onDeselect = .init(action)
}
}
}
| 32.745763 | 96 | 0.685818 |
01f01a3abf4d30ee9a6546badb83f55b0d3d5790 | 2,004 | //
// PresetAppearanceConfigs.swift
// Tabman-Example
//
// Created by Merrick Sapsford on 10/03/2017.
// Copyright © 2018 UI At Six. All rights reserved.
//
import Foundation
import Tabman
class PresetAppearanceConfigs: Any {
static func forStyle(_ style: TabmanBar.Style, currentAppearance: TabmanBar.Appearance?) -> TabmanBar.Appearance? {
let appearance = currentAppearance ?? TabmanBar.Appearance.defaultAppearance
appearance.indicator.bounces = false
appearance.indicator.compresses = false
appearance.style.background = .blur(style: .dark)
appearance.state.color = UIColor.white.withAlphaComponent(0.4)
appearance.state.selectedColor = UIColor.white.withAlphaComponent(0.8)
appearance.indicator.color = UIColor.white.withAlphaComponent(0.8)
switch style {
case .bar:
appearance.indicator.lineWeight = .thick
case .scrollingButtonBar:
appearance.layout.itemVerticalPadding = 16.0
appearance.indicator.bounces = true
appearance.indicator.lineWeight = .normal
appearance.layout.edgeInset = 16.0
appearance.layout.interItemSpacing = 20.0
appearance.style.showEdgeFade = true
case .buttonBar:
appearance.indicator.lineWeight = .thin
appearance.indicator.compresses = true
appearance.layout.edgeInset = 8.0
appearance.layout.interItemSpacing = 0.0
case .blockTabBar:
appearance.indicator.color = UIColor.white.withAlphaComponent(0.3)
appearance.layout.edgeInset = 0.0
appearance.layout.interItemSpacing = 0.0
appearance.indicator.bounces = true
default:
appearance.style.background = .blur(style: .light)
}
appearance.text.font = UIFont.systemFont(ofSize: 16.0, weight: .bold)
return appearance
}
}
| 34.551724 | 119 | 0.643214 |
acc458309a81173411aeebe36240c937ba6e72a9 | 978 | import UIKit
#if !os(tvOS)
final public class ScreenEdgePanGestureRecognizer: UIScreenEdgePanGestureRecognizer, _GestureTrackable, _GestureDelegatorable {
var _tracker = _GestureTracker()
var _delegator = _GestureDelegator()
public init(edges: UIRectEdge) {
super.init(target: _tracker, action: #selector(_tracker.handle))
self.edges = edges
delegate = _delegator
}
@discardableResult
public func edges(_ v: UIRectEdge) -> Self {
edges = v
return self
}
@discardableResult
public func edges(_ state: UIKitPlus.UState<UIRectEdge>) -> Self {
state.listen { self.edges = $0 }
return self
}
@discardableResult
public func edges<V>(_ expressable: ExpressableState<V, UIRectEdge>) -> Self {
edges(expressable.unwrap())
}
var _tag: Int = 0
public override var tag: Int {
get { _tag }
set { _tag = newValue }
}
}
#endif
| 25.736842 | 127 | 0.633947 |
9b50d58efd7b6d92887e8f389f6096ae78e9fe24 | 965 | //
// Solution11.swift
// leetcode
//
// Created by youzhuo wang on 2020/3/25.
// Copyright © 2020 youzhuo wang. All rights reserved.
//
import Foundation
// 1. 双指针移动
class Solution11 {
func maxArea(_ height: [Int]) -> Int {
if height.count == 0 {
return 0
}
if height.count == 1 {
return height[0]
}
var left = 0
var right = height.count-1
var maxValue = (right - left) * min(height[left], height[right])
while(left < right) {
if height[left] < height[right] {
left = left + 1
}else {
right = right - 1
}
let value = (right - left) * min(height[left], height[right])
if value > maxValue {
maxValue = value
}
}
return maxValue
}
func test() {
print(maxArea([1,8,6,2,5,4,8,3,7]))
}
}
| 21.931818 | 73 | 0.463212 |
bfcfc9c9485496c9426b761450441beb7e5ce227 | 2,645 | //
// ViewController.swift
// ZipCheckout-iOS
//
// Created by Scott Murray on 6/04/21.
//
import UIKit
import WebKit
class ZipWebViewController: UIViewController, WKNavigationDelegate {
var webView: WKWebView!
var checkoutUrl: String = "sandbox.zip.co/nz/api"
var successRedirect: String = ""
var failureRedirect: String = ""
weak var webviewProtocol: ZipWebViewRedirectProtocol?
private var _loadingAnimationService: LoadingAnimationService = LoadingAnimationService()
private var _loaderObservation: NSKeyValueObservation?
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: checkoutUrl)!
webView.load(URLRequest(url: url))
webView.allowsBackForwardNavigationGestures = true
}
override func loadView() {
webView = WKWebView()
webView.navigationDelegate = self
_loaderObservation = self.closeSpinnerOnCompletion()
view = webView
}
override func viewDidAppear(_ animated: Bool) {
_loadingAnimationService.addCurrentView(self)
_loadingAnimationService.animate(true)
}
public func webView(
_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction,
decisionHandler: @escaping (WKNavigationActionPolicy) -> Swift.Void
) {
if navigationAction.request.url != nil {
if navigationAction.request.url!.absoluteString.contains(self.successRedirect) {
print("Successful order")
dismissWithStatus("Success!")
}
if navigationAction.request.url!.absoluteString.contains(self.failureRedirect) {
print("Failed order")
dismissWithStatus("Failure")
}
}
decisionHandler(.allow)
}
private func closeSpinnerOnCompletion() -> NSKeyValueObservation {
return self.webView.observe(
\.isLoading,
changeHandler: { (webView, _) in
if webView.isLoading {
self._loadingAnimationService.animate(true)
} else {
self._loadingAnimationService.animate(false)
}
})
}
private func dismissWithStatus(_ status: String) {
if let presenter = presentingViewController as? CheckoutController {
presenter.completionStatus = status
self._loadingAnimationService.animate(false)
dismiss(animated: true, completion: nil)
}
}
private func isIframeRequest(_ navAction: WKNavigationAction) -> Bool {
guard let isMainFrameRequest = navAction.targetFrame?.isMainFrame else {
return false
}
return !isMainFrameRequest
}
override func viewDidDisappear(_ animated: Bool) {
self.webviewProtocol?.onCompletion()
}
deinit {
self._loaderObservation = nil
}
}
| 26.717172 | 91 | 0.712287 |
72187bd87af066286509c4781c86766a2b725fa0 | 315 | //
// AdvancedHelp-Sharing.swift
// IOS Helper
//
// Created by Andrew Apperley on 2016-11-30.
// Copyright © 2016 Humber College. All rights reserved.
//
import UIKit
class AdvancedHelp_Sharing: HelperViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Sharing"
}
} | 17.5 | 57 | 0.698413 |
efcd714eab712d7a4ef226ec495580e277c8cf02 | 2,460 | //
// ReachabilityService.swift
// RxExample
//
// Created by Vodovozov Gleb on 10/22/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import RxSwift
import Dispatch
public enum ReachabilityStatus {
case reachable(viaWiFi: Bool)
case unreachable
}
extension ReachabilityStatus {
var reachable: Bool {
switch self {
case .reachable:
return true
case .unreachable:
return false
}
}
}
protocol ReachabilityService {
var reachability: Observable<ReachabilityStatus> { get }
}
enum ReachabilityServiceError: Error {
case failedToCreate
}
class DefaultReachabilityService
: ReachabilityService {
private let _reachabilitySubject: BehaviorSubject<ReachabilityStatus>
var reachability: Observable<ReachabilityStatus> {
_reachabilitySubject.asObservable()
}
let _reachability: Reachability
init() throws {
guard let reachabilityRef = Reachability() else { throw ReachabilityServiceError.failedToCreate }
let reachabilitySubject = BehaviorSubject<ReachabilityStatus>(value: .unreachable)
// so main thread isn't blocked when reachability via WiFi is checked
let backgroundQueue = DispatchQueue(label: "reachability.wificheck")
reachabilityRef.whenReachable = { reachability in
backgroundQueue.async {
reachabilitySubject.on(.next(.reachable(viaWiFi: reachabilityRef.isReachableViaWiFi)))
}
}
reachabilityRef.whenUnreachable = { reachability in
backgroundQueue.async {
reachabilitySubject.on(.next(.unreachable))
}
}
try reachabilityRef.startNotifier()
_reachability = reachabilityRef
_reachabilitySubject = reachabilitySubject
}
deinit {
_reachability.stopNotifier()
}
}
extension ObservableConvertibleType {
func retryOnBecomesReachable(_ valueOnFailure:Element, reachabilityService: ReachabilityService) -> Observable<Element> {
return self.asObservable()
.catch { e -> Observable<Element> in
reachabilityService.reachability
.skip(1)
.filter { $0.reachable }
.flatMap { _ in
Observable.error(e)
}
.startWith(valueOnFailure)
}
.retry()
}
}
| 27.032967 | 125 | 0.639837 |
2901d453b1fb3e7b9fce25ade3a9d6589fe6ecc4 | 360 | //
// WindowController.swift
// Trivia Swift
//
// Created by Gordon on 2/19/18.
// Copyright © 2018 Gordon Jacobs. All rights reserved.
//
import Cocoa
class WindowController: NSWindowController {
override func windowDidLoad() {
super.windowDidLoad()
window?.appearance = NSAppearance(named: NSAppearance.Name.vibrantDark)
}
}
| 18.947368 | 79 | 0.691667 |
ddec33aeb5b4a4afe1bef32a204ed50bcb3f008b | 9,393 | // Copyright (c) 2015 Rob Rix. All rights reserved.
#if swift(>=4.2)
#if compiler(>=5)
// Use Swift.Result
extension Result {
// ResultProtocol
public typealias Value = Success
public typealias Error = Failure
}
#else
/// An enum representing either a failure with an explanatory error, or a success with a result value.
public enum Result<Value, Error: Swift.Error> {
case success(Value)
case failure(Error)
}
#endif
#else
/// An enum representing either a failure with an explanatory error, or a success with a result value.
public enum Result<Value, Error: Swift.Error> {
case success(Value)
case failure(Error)
}
#endif
extension Result {
/// The compatibility alias for the Swift 5's `Result` in the standard library.
///
/// See https://github.com/apple/swift-evolution/blob/master/proposals/0235-add-result.md
/// and https://forums.swift.org/t/accepted-with-modifications-se-0235-add-result-to-the-standard-library/18603
/// for the details.
public typealias Success = Value
/// The compatibility alias for the Swift 5's `Result` in the standard library.
///
/// See https://github.com/apple/swift-evolution/blob/master/proposals/0235-add-result.md
/// and https://forums.swift.org/t/accepted-with-modifications-se-0235-add-result-to-the-standard-library/18603
/// for the details.
public typealias Failure = Error
}
extension Result {
// MARK: Constructors
/// Constructs a result from an `Optional`, failing with `Error` if `nil`.
public init(_ value: Value?, failWith: @autoclosure () -> Error) {
self = value.map(Result.success) ?? .failure(failWith())
}
/// Constructs a result from a function that uses `throw`, failing with `Error` if throws.
public init(_ f: @autoclosure () throws -> Value) {
self.init(catching: f)
}
/// Constructs a result from a function that uses `throw`, failing with `Error` if throws.
@available(*, deprecated, renamed: "init(catching:)")
public init(attempt f: () throws -> Value) {
self.init(catching: f)
}
/// The same as `init(attempt:)` aiming for the compatibility with the Swift 5's `Result` in the standard library.
///
/// See https://github.com/apple/swift-evolution/blob/master/proposals/0235-add-result.md
/// and https://forums.swift.org/t/accepted-with-modifications-se-0235-add-result-to-the-standard-library/18603
/// for the details.
public init(catching body: () throws -> Success) {
do {
self = .success(try body())
} catch var error {
if Error.self == AnyError.self {
error = AnyError(error)
}
self = .failure(error as! Error)
}
}
// MARK: Deconstruction
/// Returns the value from `success` Results or `throw`s the error.
@available(*, deprecated, renamed: "get()")
public func dematerialize() throws -> Value {
return try get()
}
/// The same as `dematerialize()` aiming for the compatibility with the Swift 5's `Result` in the standard library.
///
/// See https://github.com/apple/swift-evolution/blob/master/proposals/0235-add-result.md
/// and https://forums.swift.org/t/accepted-with-modifications-se-0235-add-result-to-the-standard-library/18603
/// for the details.
public func get() throws -> Success {
switch self {
case let .success(value):
return value
case let .failure(error):
throw error
}
}
/// Case analysis for Result.
///
/// Returns the value produced by applying `ifFailure` to `failure` Results, or `ifSuccess` to `success` Results.
public func analysis<Result>(ifSuccess: (Value) -> Result, ifFailure: (Error) -> Result) -> Result {
switch self {
case let .success(value):
return ifSuccess(value)
case let .failure(value):
return ifFailure(value)
}
}
// MARK: Errors
/// The domain for errors constructed by Result.
public static var errorDomain: String { return "com.antitypical.Result" }
/// The userInfo key for source functions in errors constructed by Result.
public static var functionKey: String { return "\(errorDomain).function" }
/// The userInfo key for source file paths in errors constructed by Result.
public static var fileKey: String { return "\(errorDomain).file" }
/// The userInfo key for source file line numbers in errors constructed by Result.
public static var lineKey: String { return "\(errorDomain).line" }
/// Constructs an error.
public static func error(_ message: String? = nil, function: String = #function, file: String = #file, line: Int = #line) -> NSError {
var userInfo: [String: Any] = [
functionKey: function,
fileKey: file,
lineKey: line,
]
if let message = message {
userInfo[NSLocalizedDescriptionKey] = message
}
return NSError(domain: errorDomain, code: 0, userInfo: userInfo)
}
}
extension Result: CustomStringConvertible {
public var description: String {
switch self {
case let .success(value): return ".success(\(value))"
case let .failure(error): return ".failure(\(error))"
}
}
}
extension Result: CustomDebugStringConvertible {
public var debugDescription: String {
return description
}
}
extension Result: ResultProtocol {
/// Constructs a success wrapping a `value`.
public init(value: Value) {
self = .success(value)
}
/// Constructs a failure wrapping an `error`.
public init(error: Error) {
self = .failure(error)
}
public var result: Result<Value, Error> {
return self
}
}
extension Result where Result.Failure == AnyError {
/// Constructs a result from an expression that uses `throw`, failing with `AnyError` if throws.
public init(_ f: @autoclosure () throws -> Value) {
self.init(attempt: f)
}
/// Constructs a result from a closure that uses `throw`, failing with `AnyError` if throws.
public init(attempt f: () throws -> Value) {
do {
self = .success(try f())
} catch {
self = .failure(AnyError(error))
}
}
}
// MARK: - Equatable
#if swift(>=4.2)
#if !compiler(>=5)
extension Result: Equatable where Result.Success: Equatable, Result.Failure: Equatable {}
#endif
#elseif swift(>=4.1)
extension Result: Equatable where Result.Success: Equatable, Result.Failure: Equatable {}
#endif
#if swift(>=4.2)
// Conformance to `Equatable` will be automatically synthesized.
#else
extension Result where Result.Success: Equatable, Result.Failure: Equatable {
/// Returns `true` if `left` and `right` are both `Success`es and their values are equal, or if `left` and `right` are both `Failure`s and their errors are equal.
public static func ==(left: Result<Value, Error>, right: Result<Value, Error>) -> Bool {
if let left = left.value, let right = right.value {
return left == right
} else if let left = left.error, let right = right.error {
return left == right
}
return false
}
}
extension Result where Result.Success: Equatable, Result.Failure: Equatable {
/// Returns `true` if `left` and `right` represent different cases, or if they represent the same case but different values.
public static func !=(left: Result<Value, Error>, right: Result<Value, Error>) -> Bool {
return !(left == right)
}
}
#endif
// MARK: - Derive result from failable closure
@available(*, deprecated, renamed: "Result.init(attempt:)")
public func materialize<T>(_ f: () throws -> T) -> Result<T, AnyError> {
return Result(attempt: f)
}
@available(*, deprecated, renamed: "Result.init(_:)")
public func materialize<T>(_ f: @autoclosure () throws -> T) -> Result<T, AnyError> {
return Result(try f())
}
// MARK: - ErrorConvertible conformance
extension NSError: ErrorConvertible {
public static func error(from error: Swift.Error) -> Self {
func cast<T: NSError>(_ error: Swift.Error) -> T {
return error as! T
}
return cast(error)
}
}
// MARK: - migration support
@available(*, unavailable, message: "Use the overload which returns `Result<T, AnyError>` instead")
public func materialize<T>(_ f: () throws -> T) -> Result<T, NSError> {
fatalError()
}
@available(*, unavailable, message: "Use the overload which returns `Result<T, AnyError>` instead")
public func materialize<T>(_ f: @autoclosure () throws -> T) -> Result<T, NSError> {
fatalError()
}
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
/// Constructs a `Result` with the result of calling `try` with an error pointer.
///
/// This is convenient for wrapping Cocoa API which returns an object or `nil` + an error, by reference. e.g.:
///
/// Result.try { NSData(contentsOfURL: URL, options: .dataReadingMapped, error: $0) }
@available(*, unavailable, message: "This has been removed. Use `Result.init(attempt:)` instead. See https://github.com/antitypical/Result/issues/85 for the details.")
public func `try`<T>(_ function: String = #function, file: String = #file, line: Int = #line, `try`: (NSErrorPointer) -> T?) -> Result<T, NSError> {
fatalError()
}
/// Constructs a `Result` with the result of calling `try` with an error pointer.
///
/// This is convenient for wrapping Cocoa API which returns a `Bool` + an error, by reference. e.g.:
///
/// Result.try { NSFileManager.defaultManager().removeItemAtURL(URL, error: $0) }
@available(*, unavailable, message: "This has been removed. Use `Result.init(attempt:)` instead. See https://github.com/antitypical/Result/issues/85 for the details.")
public func `try`(_ function: String = #function, file: String = #file, line: Int = #line, `try`: (NSErrorPointer) -> Bool) -> Result<(), NSError> {
fatalError()
}
#endif
// MARK: -
import Foundation
| 32.50173 | 167 | 0.697115 |
87f5b6fc4bc10d4649fc017e340dc82bd062d845 | 308 | //
// Sotry.swift
// Destini-iOS13
//
// Created by Angela Yu on 08/08/2019.
// Copyright © 2019 The App Brewery. All rights reserved.
//
import Foundation
struct Story {
let title:String
let choice1:String
let choice1Destination:Int
let choice2:String
let choice2Destination:Int
}
| 17.111111 | 58 | 0.691558 |
c1fee597ad24b6fcfdf8eaf06d782d96d9c2d21e | 2,931 | import Foundation
extension Array where Element == Cell {
func printContents() {
var str = ""
for i in self {
switch i {
case .occupied:
str += "#"
case .available:
str += "L"
case .floor:
str += "."
}
}
print(str)
}
}
extension Array where Element == [Cell] {
func printContents() {
for i in self {
i.printContents()
}
}
}
enum Cell: Equatable {
case occupied
case available
case floor
}
func findFirstNonFloor(state: [[Cell]], i: Int, deltaI: Int, j: Int, deltaJ: Int) -> (i: Int, j: Int)? {
var iTest = i
var jTest = j
while iTest >= 0, iTest < state.count, jTest >= 0, jTest < state[iTest].count {
switch state[iTest][jTest] {
case .occupied, .available:
return (i: iTest, j: jTest)
case .floor:
break
}
iTest += deltaI
jTest += deltaJ
}
return nil
}
func adjacentCells(state: [[Cell]], i: Int, j: Int) -> [(i: Int, j: Int)] {
var ret = [(i: Int, j: Int)]()
for iIter in -1...1 {
for jIter in -1...1 {
guard iIter != 0 || jIter != 0 else { continue }
guard let adj = findFirstNonFloor(state: state, i: i + iIter, deltaI: iIter, j: j + jIter, deltaJ: jIter) else { continue }
ret += [adj]
}
}
return ret
}
func iterate(state: [[Cell]]) -> [[Cell]] {
return state.enumerated().map { (i, row) -> [Cell] in
row.enumerated().map { (j, col) -> Cell in
guard state[i][j] != .floor else { return .floor }
var adjacentOccupied = 0
for adj in adjacentCells(state: state, i: i, j: j) {
if state[adj.i][adj.j] == .occupied {
adjacentOccupied += 1
}
}
switch state[i][j] {
case .available:
if adjacentOccupied == 0 {
return .occupied
}
case .occupied:
if adjacentOccupied >= 5 {
return .available
}
case .floor:
fatalError()
}
return state[i][j]
}
}
}
var state = [[Cell]]()
var lineIdx = 0
while let line = readLine() {
let row = line.map({ c -> Cell in
switch c {
case "L":
return .available
case ".":
return .floor
default:
fatalError()
}
})
state.append(row)
lineIdx += 1
}
var old = [[Cell]]()
var new = state
while old != new {
old = new
new = iterate(state: old)
}
let numOccupied = new.reduce(0) { r, row -> Int in
return r + row.reduce(0) { $0 + ($1 == .occupied ? 1 : 0) }
}
print(numOccupied)
| 24.425 | 135 | 0.455476 |
082ea8dac805431ccf0c9e0a4caa794f1c31efcc | 32,713 | //
// ConfigureWifiViewController.swift
// AferoLab
//
// Created by Justin Middleton on 12/10/17.
// Copyright © 2017 Afero, Inc. All rights reserved.
//
import UIKit
import CocoaLumberjack
import ReactiveSwift
import Afero
import SVProgressHUD
@IBDesignable @objcMembers class ScanWifiTableView: UITableView {
var headerStackView: UIStackView!
@IBInspectable var headerSpacing: CGFloat {
get { return headerStackView?.spacing ?? 0 }
set { headerStackView?.spacing = newValue }
}
var headerTitleLabel: UILabel!
@IBInspectable var headerTitle: String? {
get { return headerTitleLabel?.text }
set { headerTitleLabel?.text = newValue }
}
var headerBodyLabel: UILabel!
@IBInspectable var headerBody: String? {
get { return headerBodyLabel?.text }
set { headerBodyLabel?.text = newValue }
}
override init(frame: CGRect, style: UITableView.Style) {
super.init(frame: frame, style: style)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func commonInit() {
let headerContainerView = UIView()
headerContainerView.autoresizingMask = [ .flexibleWidth, .flexibleHeight ]
headerContainerView.layoutMargins = UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16)
headerStackView = UIStackView()
headerStackView.alignment = .fill
headerStackView.distribution = .fill
headerStackView.axis = .vertical
headerStackView.spacing = 8
headerStackView.translatesAutoresizingMaskIntoConstraints = false
headerContainerView.addSubview(headerStackView)
let views: [String: Any] = [ "v": headerStackView! ]
let vfl: [String] = [ "H:|-[v]-|", "V:|-[v]-|", ]
let constraints = vfl.flatMap {
NSLayoutConstraint.constraints(
withVisualFormat: $0,
options: [],
metrics: nil,
views: views
)
}
NSLayoutConstraint.activate(constraints)
headerTitleLabel = UILabel()
headerTitleLabel.font = UIFont.preferredFont(forTextStyle: .title1)
headerTitleLabel.lineBreakMode = .byWordWrapping
headerTitleLabel.numberOfLines = 0
headerStackView.addArrangedSubview(headerTitleLabel)
headerBodyLabel = UILabel()
headerBodyLabel.font = UIFont.preferredFont(forTextStyle: .body)
headerBodyLabel.lineBreakMode = .byWordWrapping
headerBodyLabel.numberOfLines = 0
headerStackView.addArrangedSubview(headerBodyLabel)
tableHeaderView = headerContainerView
}
}
// MARK: - ScanWifiViewController -
/// A UITableViewController responsible for scanning for available wifi SSID.
class ScanWifiViewController: WifiSetupAwareTableViewController, AferoWifiPasswordPromptDelegate {
// MARK: Reuse Identifiers
enum TableViewHeaderFooterViewReuse {
case sectionHeader
var reuseClass: AnyClass {
switch self {
case .sectionHeader: return SectionHeaderTableViewHeaderFooterView.self
}
}
var reuseIdentifier: String {
switch self {
case .sectionHeader: return "SectionHeaderTableViewHeaderFooterView"
}
}
static var allCases: Set<TableViewHeaderFooterViewReuse> {
return [ .sectionHeader ]
}
}
enum CellReuse {
case networkCell
case customNetworkCell
var reuseIdentifier: String {
switch self {
case .networkCell: return "WifiNetworkCell"
case .customNetworkCell: return "CustomSSIDWifiNetworkCell"
}
}
}
enum Section: Int {
case current = 0
case visible
var title: String {
switch self {
case .current: return NSLocalizedString("Current Network", comment: "ConfigureWifiViewController current network section title")
case .visible: return NSLocalizedString("Visible Networks", comment: "ConfigureWifiViewController visible network section title")
}
}
var caption: String? {
switch self {
case .current: return NSLocalizedString("Your device is currently configured for the following network. Swipe to remove it, or tap to reconfigure it.", comment: "ConfigureWifiViewController current network section caption")
case .visible: return NSLocalizedString("The following networks are currently visible to your device. Select one to connect to it.", comment: "ConfigureWifiViewController current network section caption")
}
}
var reuse: TableViewHeaderFooterViewReuse {
return .sectionHeader
}
static var allCases: Set<Section> {
return [.current, .visible]
}
static var count: Int { return allCases.count }
}
// MARK: Convenience Accessors
var headerTitle: String? {
get { return (tableView as! ScanWifiTableView).headerTitle }
set { (tableView as! ScanWifiTableView).headerTitle = newValue }
}
var headerBody: String? {
get { return (tableView as! ScanWifiTableView).headerBody }
set { (tableView as! ScanWifiTableView).headerBody = newValue }
}
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
TableViewHeaderFooterViewReuse.allCases.forEach {
tableView.register(
$0.reuseClass,
forHeaderFooterViewReuseIdentifier: $0.reuseIdentifier
)
}
tableView.estimatedSectionHeaderHeight = 31
tableView.sectionHeaderHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 55
tableView.rowHeight = UITableView.automaticDimension
refreshControl = UIRefreshControl()
refreshControl?.addTarget(self, action: #selector(refreshTapped(_:)), for: .valueChanged)
}
override var deviceModel: DeviceModel? {
didSet {
currentNetwork = deviceModel?.steadyStateWifiNetwork
}
}
// Turn the idle timer off when we're in front, so that
// we don't turn off the softhub.
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
UIApplication.shared.isIdleTimerDisabled = true
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
UIApplication.shared.isIdleTimerDisabled = false
}
// MARK: - Actions -
func startAnimatingRefreshIndicators() {
if !(refreshControl?.isRefreshing ?? false) {
refreshControl?.beginRefreshing()
}
}
func stopAnimatingRefreshIndicators() {
refreshControl?.endRefreshing()
}
@IBOutlet weak var refreshButton: UIBarButtonItem!
@IBAction func refreshTapped(_ sender: Any) {
scan()
}
@IBOutlet weak var doneButton: UIBarButtonItem!
@IBAction func doneButtonTapped(_ sender: Any) {
presentingViewController?.dismiss(animated: true, completion: nil)
}
// MARK: - General UI Updates -
func updateUI() {
updateDeviceInfo()
tableView.reloadData()
}
func updateDeviceInfo() {
if modelIsWifiConfigurable {
headerBody = NSLocalizedString("This device supports Afero Cloud connections via Wi-Fi. Select a network below to connect to it.", comment: "Scan wifi model is configurable header body")
} else {
headerBody = NSLocalizedString("This device does not support connections via Wi-Fi", comment: "Scan wifi model is configurable header body")
}
}
// MARK: - Model -
var modelIsWifiConfigurable: Bool {
return deviceModel?.isWifiConfigurable ?? false
}
typealias WifiNetwork = WifiSetupManaging.WifiNetwork
typealias WifiNetworkList = [WifiNetwork]
/// The current network for which the device is connectred, if any.
var currentNetwork: WifiNetwork? {
didSet {
guard oldValue != currentNetwork else {
return
}
if oldValue?.ssid == currentNetwork?.ssid {
guard
let indexPath = currentNetworkIndexPath,
let cell = tableView.cellForRow(at: indexPath) else {
return
}
self.configure(cell: cell, for: indexPath)
return
}
tableView.reloadSections(IndexSet(integer: 0), with: .automatic)
}
}
var currentNetworkIndexPath: IndexPath? {
guard currentNetwork != nil else { return nil }
return IndexPath(row: 0, section: Section.current.rawValue)
}
/// Networks that have been returned from a scan operation.
var visibleNetworks: WifiNetworkList = [] {
didSet {
let deltas = oldValue.deltasProducing(visibleNetworks)
tableView.beginUpdates()
tableView.deleteRows(
at: deltas.deletions.indexes().map {
IndexPath(row: $0, section: Section.visible.rawValue)
},
with: .automatic
)
tableView.insertRows(at: deltas.insertions.indexes().map {
IndexPath(row: $0, section: Section.visible.rawValue)
}, with: .automatic)
tableView.endUpdates()
}
}
// ========================================================================
// MARK: - Model Accessors
/// Replace existing SSID entries with new ones, and animate.
/// - parameter entries: The entries to set
/// - parameter anmated: Whether or not to animate changes (defaults to `true`)
/// - parameter completion: A block to execute upon completion of the change and any animations. Defaults to noop.
///
/// - note: `completion` is a `(Bool)->Void`. In this case, the `Bool` refers to whether or not the completion
/// should be animated, NOT to whether or not the changes completed.
fileprivate func setVisibleNetworks(_ entries: WifiNetworkList) {
startAnimatingRefreshIndicators()
visibleNetworks = entries.filter({ (entry) -> Bool in
!entry.ssid.trimmingCharacters(in: .whitespaces).isEmpty
})
stopAnimatingRefreshIndicators()
scanningState = .scanned
}
/// Translate a model index to an indexPath.
func indexPathForVisibleNetworksIndex(_ index: Int) -> IndexPath {
return IndexPath(row: index, section: Section.visible.rawValue)
}
/// Translate a `WifiNetwork` entry into an indexPath.
func indexPathForVisibleNetwork(_ entry: WifiNetwork?) -> IndexPath? {
guard let entry = entry else { return nil }
#if !compiler(>=5)
guard let entryIndex = visibleNetworks.index(of: entry) else { return nil }
#endif
#if compiler(>=5)
guard let entryIndex = visibleNetworks.firstIndex(of: entry) else { return nil }
#endif
return indexPathForVisibleNetworksIndex(entryIndex)
}
/// Translate an `SSID` into an indexPath.
func indexPathForVisibleNetworkSSID(_ ssid: String?) -> IndexPath? {
guard let ssid = ssid else { return nil }
let maybeEntryIndex: Int?
#if !compiler(>=5)
maybeEntryIndex = visibleNetworks.index(where: { (entry: WifiNetwork) -> Bool in
return entry.ssid == ssid
})
#endif
#if compiler(>=5)
maybeEntryIndex = visibleNetworks.firstIndex(where: { (entry: WifiNetwork) -> Bool in
return entry.ssid == ssid
})
#endif
guard let entryIndex = maybeEntryIndex else { return nil }
let ret = indexPathForVisibleNetworksIndex(entryIndex)
return ret
}
func cellForVisibleNetwork(_ entry: WifiNetwork?) -> UITableViewCell? {
guard let indexPath = indexPathForVisibleNetwork(entry) else { return nil }
return tableView.cellForRow(at: indexPath)
}
func cellForSSID(_ SSID: String?) -> UITableViewCell? {
guard let indexPath = indexPathForVisibleNetworkSSID(SSID) else { return nil }
return tableView.cellForRow(at: indexPath)
}
/// Translate an indexPath to a model index.
fileprivate func visibleNetworkIndexForIndexPath(_ indexPath: IndexPath) -> Int? {
return indexPath.row
}
/// Get a model value for the given indexPath.
fileprivate func visibleNetworkForIndexPath(_ indexPath: IndexPath) -> WifiNetwork? {
guard let entryIndex = visibleNetworkIndexForIndexPath(indexPath) else { return nil }
return visibleNetworks[entryIndex]
}
// MARK: - <UITableViewDatasource> -
override func numberOfSections(in tableView: UITableView) -> Int {
return Section.count
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
guard let sectionCase = Section(rawValue: section) else {
return nil
}
guard
let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: sectionCase.reuse.reuseIdentifier) else {
return nil
}
configure(headerView: headerView, for: sectionCase)
return headerView
}
func configure(headerView: UITableViewHeaderFooterView, for section: Section) {
if let sectionHeaderView = headerView as? SectionHeaderTableViewHeaderFooterView {
sectionHeaderView.headerText = section.title
sectionHeaderView.captionText = section.caption
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let sectionCase = Section(rawValue: section) else {
fatalError("Unrecognized section")
}
switch sectionCase {
case .current: return currentNetwork == nil ? 0 : 1
// disabling custom network config for now.
// case .visible: return visibleNetworks.count + 1
case .visible: return visibleNetworks.count
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let sectionCase = Section(rawValue: indexPath.section) else {
fatalError("Unrecognized section")
}
let cell: UITableViewCell
switch sectionCase {
case .current:
cell = tableView.dequeueReusableCell(withIdentifier: CellReuse.networkCell.reuseIdentifier, for: indexPath)
case .visible:
guard indexPath.row < visibleNetworks.count else {
cell = tableView.dequeueReusableCell(withIdentifier: CellReuse.customNetworkCell.reuseIdentifier, for: indexPath)
break
}
cell = tableView.dequeueReusableCell(withIdentifier: CellReuse.networkCell.reuseIdentifier, for: indexPath)
}
configure(cell: cell, for: indexPath)
return cell
}
func configure(cell: UITableViewCell, for indexPath: IndexPath) {
cell.selectionStyle = .none
if let networkCell = cell as? AferoWifiNetworkTableViewCell {
configure(networkCell: networkCell, for: indexPath)
return
}
}
func configure(networkCell cell: AferoWifiNetworkTableViewCell, for indexPath: IndexPath) {
guard let sectionCase = Section(rawValue: indexPath.section) else {
fatalError("Unrecognized section")
}
switch sectionCase {
case .current:
guard let currentNetwork = currentNetwork else {
fatalError("No currentNetwork to configure.")
}
cell.configure(with: currentNetwork)
case .visible:
let network = visibleNetworks[indexPath.row]
(cell as? AferoAssociatingWifiNetworkTableViewCell)?.passwordPromptDelegate = self
cell.configure(with: network)
}
}
func configureCell(forWifiNetwork wifiNetwork: WifiNetwork?) {
guard
let indexPath = indexPathForVisibleNetwork(wifiNetwork),
let cell = tableView.cellForRow(at: indexPath) else { return }
configure(cell: cell, for: indexPath)
}
func configureCell(forSSID SSID: String?) {
guard
let indexPath = indexPathForVisibleNetworkSSID(SSID),
let cell = tableView.cellForRow(at: indexPath) else { return }
configure(cell: cell, for: indexPath)
}
// MARK: - <UITableViewDelegate> -
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard
let cell = tableView.cellForRow(at: indexPath),
let networkCell = cell as? AferoAssociatingWifiNetworkTableViewCell else {
return
}
tableView.beginUpdates()
networkCell.passwordPromptIsHidden = false
networkCell.passwordPromptView.passwordTextField.becomeFirstResponder()
tableView.endUpdates()
}
override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
guard
let cell = tableView.cellForRow(at: indexPath),
let networkCell = cell as? AferoAssociatingWifiNetworkTableViewCell else {
return
}
tableView.beginUpdates()
networkCell.passwordPromptIsHidden = true
tableView.endUpdates()
}
override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
guard indexPath == currentNetworkIndexPath else {
return nil
}
var ret: [UITableViewRowAction] = []
ret.append(
UITableViewRowAction(
style: .destructive,
title: NSLocalizedString("Disconnect", comment: "Scan wifi disconnect from network action title"),
handler: {
(_, _) in
// [weak self] (action, path) in
// self?.disconnectFromCurrentNetwork()
}
)
)
return ret
}
// ========================================================================
// MARK: - UI State managemnt
// ========================================================================
/// Whether we've enver scanned, are currently scanning, or have scanned.
///
/// - **`.Unscanned`**: We've never attempted a scan.
/// - **`.Scanning`**: We're currently scanning.
/// - **`.Scanned`**: We've scanned at least once.
fileprivate enum ScanningState {
/// We're waiting to be able to transition to scanning state.
case waiting
/// We've never attempted a scan.
case unscanned
/// We're currently scanning.
case scanning
/// We've scanned at least once.
case scanned
/// Simple state machine: That which has been scanned cannot be unscanned,
/// but we can toggle between scanning and scanned states.
var nextState: ScanningState {
switch self {
case .waiting: return .unscanned
case .unscanned: return .scanning
case .scanning: return .scanned
case .scanned: return .scanning
}
}
func canTransition(_ toState: ScanningState) -> Bool {
switch (self, toState) {
case (.waiting, .unscanned): fallthrough
case (.waiting, .scanning): fallthrough
case (.scanning, .waiting): fallthrough
case (.unscanned, .scanning): fallthrough
case (.unscanned, .waiting): fallthrough
case (.scanning, .scanned): fallthrough
case (.scanned, .scanning):
return true
default:
return false
}
}
}
fileprivate func transitionToScanningState(_ toState: ScanningState) {
guard scanningState.canTransition(toState) else {
fatalError("Invalid state transition from \(scanningState) to \(toState)")
}
scanningState = toState
}
/// Our current scanning state. Changes result in an `updateUI()`
fileprivate var scanningState: ScanningState = .waiting {
didSet {
if oldValue == scanningState { return }
updateUI()
switch scanningState {
case .scanning:
scan()
case .waiting:
cancelScan()
case .scanned: fallthrough
case .unscanned:
break
}
}
}
// MARK: - WifiSetupManager State Change Handling -
// ========================================================================
// MARK: - Wifi setup attribute observation
// ========================================================================
override func handleManagerStateChanged(_ newState: WifiSetupManagerState) {
DDLogInfo("Got new wifi setup manager state: \(newState)", tag: TAG)
switch newState {
case .ready:
transitionToScanningState(.scanning)
case .notReady:
transitionToScanningState(.waiting)
case .managing:
break
case .completed:
break
}
}
func handleWifiSetupError(_ error: Error) {
let completion: ()->Void = {
let msg = String(
format: NSLocalizedString("Unable to complete wifi setup: %@",
comment: "wifi setup error template"
),
error.localizedDescription
)
SVProgressHUD.showError(withStatus: msg)
}
if let _ = presentedViewController {
dismiss(animated: true, completion: completion)
return
}
completion()
}
// MARK: - Wifi Config -
override func handleWifiCurrentSSIDChanged(_ newSSID: String) {
DDLogInfo("Current SSID changed to \(newSSID)", tag: TAG)
self.currentNetwork = deviceModel?.steadyStateWifiNetwork
}
override func handleWifiRSSIChanged(_ newRSSI: Int) {
DDLogInfo("Current WIFI RSSI changed to \(newRSSI)", tag: TAG)
self.currentNetwork = deviceModel?.steadyStateWifiNetwork
}
override func handleWifiRSSIBarsChanged(_ newRSSIBars: Int) {
DDLogInfo("Current WIFI RSSI bars changed to \(newRSSIBars)", tag: TAG)
self.currentNetwork = deviceModel?.steadyStateWifiNetwork
}
// MARK: SSID Scanning
/// Start a scan for SSIDs (In the sim, this just causes us to reload some sample SSIDs.)
fileprivate func scan() {
do {
try wifiSetupManager?.scan()
startAnimatingRefreshIndicators()
} catch {
DDLogError("Error thrown attempting to scan for wifi SSIDs: \(String(describing: error))", tag: TAG)
handleWifiSetupError(error)
}
}
/// Cancel a previous scan request.
func cancelScan() {
do {
try wifiSetupManager?.cancelScan()
stopAnimatingRefreshIndicators()
} catch {
DDLogError("Error thrown attempting to cancel scan for wifi SSIDs: \(String(describing: error))", tag: TAG)
handleWifiSetupError(error)
}
}
/// Handle receipt of scan results.
override func handleSSIDListChanged(_ newList: WifiSetupManaging.WifiNetworkList) {
DDLogInfo("Device \(deviceModel!.deviceId) got new SSID list: \(String(describing: newList))", tag: TAG)
setVisibleNetworks(newList)
}
// MARK: Association/Authentication
/// Forward an SSID/password pair to Hubby to attempt association.
typealias AssociationAttempt = (ssid: String, password: String)
var currentAssociationAttempt: AssociationAttempt?
func attemptAssociate(to ssid: String, with password: String) {
do {
try wifiSetupManager?.cancelAttemptAssociate()
try wifiSetupManager?.attemptAssociate(ssid, password: password)
if let indexPath = indexPathForVisibleNetworkSSID(ssid) {
tableView.deselectRow(at: indexPath, animated: true)
if let cell = tableView.cellForRow(at: indexPath),
let networkCell = cell as? AferoAssociatingWifiNetworkTableViewCell {
tableView.beginUpdates()
networkCell.password = nil
networkCell.passwordIsHidden = true
tableView.endUpdates()
}
}
currentAssociationAttempt = (ssid: ssid, password: password)
SVProgressHUD.show(
withStatus: NSLocalizedString("Connecting to \(ssid)…", comment: "ScanWifiViewcontroller association succeeded status message"),
maskType: SVProgressHUDMaskType.gradient
)
} catch {
let tmpl = NSLocalizedString(
"Unable to associate with %@: %@", comment: "ScanWifiViewController associate error template"
)
let msg = String(format: tmpl, ssid, error.localizedDescription)
DDLogError(msg, tag: TAG)
SVProgressHUD.showError(
withStatus: msg,
maskType: SVProgressHUDMaskType.gradient
)
}
}
/// Cancel a previous association request.
func cancelAttemptAssociate() {
do {
try wifiSetupManager?.cancelAttemptAssociate()
currentAssociationAttempt = nil
} catch {
DDLogError("Error thrown attempting cancel SSID association: \(String(describing: error))", tag: TAG)
}
}
/// Association with the wifi network failed. This is likely unrecoverable.
override func handleAssociateFailed() {
currentAssociationAttempt = nil
DDLogError("Device \(deviceModel!.deviceId) associate failed (default impl)", tag: TAG)
SVProgressHUD.showError(
withStatus: NSLocalizedString(
"Association failed. Verify that this network is properly configured.",
comment: "ScanWifiViewcontroller handshake failed status message"),
maskType: SVProgressHUDMaskType.gradient
)
}
/// Handshake failed. The *may* be due to a bad password, and so may be recoverable through a retry.
override func handleHandshakeFailed() {
DDLogError("Device \(deviceModel!.deviceId) handshake failed (default impl)", tag: TAG)
SVProgressHUD.showError(
withStatus: NSLocalizedString(
"Handshake failed. Verify that your password is correct.",
comment: "ScanWifiViewcontroller handshake failed status message"),
maskType: SVProgressHUDMaskType.gradient
)
if
let currentAssociationAttempt = currentAssociationAttempt,
let indexPath = indexPathForVisibleNetworkSSID(currentAssociationAttempt.ssid),
let cell = tableView.cellForRow(at: indexPath),
let networkCell = cell as? AferoAssociatingWifiNetworkTableViewCell {
tableView.beginUpdates()
tableView.selectRow(at: indexPath, animated: true, scrollPosition: .middle)
networkCell.passwordIsHidden = false
networkCell.password = currentAssociationAttempt.password
networkCell.passwordPromptView.passwordTextField.becomeFirstResponder()
tableView.endUpdates()
}
currentAssociationAttempt = nil
}
/// We were able to connect to the network and get an IP address, but we were unable to see the
/// Afero cloud from this network. This is likely due to a configuration or connectivity issue
/// with the network itself.
override func handleEchoFailed() {
currentAssociationAttempt = nil
DDLogError("Device \(deviceModel!.deviceId) echo failed (unable to ping Afero cloud) (default impl)", tag: TAG)
SVProgressHUD.showError(
withStatus: NSLocalizedString(
"Unable to connect to Afero cloud; verify that your network is correctly configured. Note that captive portal networks are not supported.",
comment: "ScanWifiViewcontroller handshake failed status message"),
maskType: SVProgressHUDMaskType.gradient
)
}
/// We were successfully able to connect to the Afero cloud over the given network.
override func handleWifiConnected() {
guard currentAssociationAttempt != nil else {
// This is related to connecting to the steady-state network,
// so we won't show anything.
return
}
currentAssociationAttempt = nil
DDLogInfo("Device \(deviceModel!.deviceId) connected to cloud!", tag: TAG)
SVProgressHUD.showSuccess(
withStatus: NSLocalizedString("Connected!", comment: "ScanWifiViewcontroller connected status message"),
maskType: SVProgressHUDMaskType.gradient
)
if let currentNetworkIndexPath = currentNetworkIndexPath {
tableView.scrollToRow(at: currentNetworkIndexPath, at: .top, animated: true)
}
}
/// We were unable to find a network with the given SSID.
override func handleSSIDNotFound() {
currentAssociationAttempt = nil
DDLogError("Device \(deviceModel!.deviceId) SSID not found (default impl)", tag: TAG)
SVProgressHUD.showError(
withStatus: NSLocalizedString(
"Unable to find network.",
comment: "ScanWifiViewcontroller handshake failed status message"),
maskType: .gradient
)
}
override func handleWifiCommandError(_ error: Error) {
stopAnimatingRefreshIndicators()
let message = String(format: NSLocalizedString("Wifi command error: %@", comment: "Wifi command error status template"), error.localizedDescription)
DDLogError("Error executing wifi command for device \(deviceModel!.deviceId): \(message)", tag: TAG)
SVProgressHUD.showError(withStatus: message, maskType: .gradient)
}
// MARK: - <AferoWifiPasswordPromptViewDelegate> -
func wifiPasswordPromptView(_ promptView: AferoWifiPasswordPromptView, attemptAssociateWith ssid: String, usingPassword password: String?, connectionStatusChangeHandler: @escaping (WifiSetupManaging.WifiState) -> Void) {
print("should attempt associate with '\(ssid)' using password '\(password ?? "<empty>")'")
promptView.passwordTextField.resignFirstResponder()
attemptAssociate(to: ssid, with: password ?? "")
}
func cancelAttemptAssociation(for promptView: AferoWifiPasswordPromptView) {
print("cancel attempt association.")
}
}
| 34.507384 | 235 | 0.595237 |
1c9116e234311c4727cac9d64004adad9d151f9d | 311 | //
// Created by Kasper T on 09/11/2017.
// Copyright (c) 2017 commonsense. All rights reserved.
//
import Foundation
public extension CGFloat {
/**
*
*/
public func isEqual(to: CGFloat, withStrife: Float) -> Bool {
return abs(distance(to: to)) <= CGFloat(abs(withStrife))
}
}
| 18.294118 | 65 | 0.617363 |
b9da9696e0449b5dd76d2f6f8844701f863a83ae | 21,005 | //
// APPDelegate.swift
// NetKnot
//
// Created by Harry on 2020/11/3.
// Copyright © 2020 Harry. All rights reserved.
//
import UIKit
import Reachability
import MMWormhole
import IDEAAdapter
import TunnelServices
@UIApplicationMain
class APPDelegate: UIResponder, UIApplicationDelegate {
internal var window : UIWindow? = nil;
internal var rootViewController : RootViewController? = nil;
internal var splashViewController : SplashViewController? = nil;
internal var certTrustType : TrustResultType = TrustResultType.none;
internal let reachability : Reachability = try! Reachability();
internal var IP : String = "Local IP address".localized;
internal var wifiIsOpen : Bool = false {
didSet {
if wifiIsOpen {
objc_sync_enter(self);
self.IP = NetworkInfo.LocalWifiIPv4();
if self.IP == "" {
self.IP = "Local IP address".localized;
} /* End if () */
} /* End if () */
else {
self.IP = "Local IP address".localized;
} /* End else */
objc_sync_exit(self);
} /* didSet */
};
internal var vpnStatus : NEVPNStatus = NEVPNStatus.disconnected {
didSet {
}
};
internal var tunnelProviderManager : NETunnelProviderManager? = nil;
internal var SPLASH_DONE : Bool = false;
#if DEBUG
static var WORMHOLE_DEBUG : MMWormhole? = nil;
#endif /* DEBUG */
// Image Literal
func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
TunnelService.initDDLog(isExtension: false);
if TunnelService.DEBUG { TunnelService.Debug("APPDelegate::application(_:willFinishLaunchingWithOptions:)"); }
/******************************************************************************************/
// https://www.jianshu.com/p/a02be724b7ec
// 动态注册字体
#if DEBUG
if TunnelService.DEBUG { print("----------------------------------------------------"); };
for szFamilyName in UIFont.familyNames {
if TunnelService.DEBUG { print("family : ", szFamilyName); }
for szName in UIFont.fontNames(forFamilyName: szFamilyName) {
if TunnelService.DEBUG { print("\tfont : ", szName); } // ╟
} /* End for () */
} /* End for () */
if TunnelService.DEBUG { print("----------------------------------------------------"); };
// let decrem = calcDecrement(forDecrement: 30)
// if TunnelService.DEBUG { print("decrem : \(decrem())"); };
var stFont : UIFont = UIFont.systemFont(ofSize: 10);
if TunnelService.DEBUG { print("family : ", stFont.familyName); }
if TunnelService.DEBUG { print("family : ", stFont.fontName); }
for szName in UIFont.fontNames(forFamilyName: stFont.familyName) {
if TunnelService.DEBUG { print("\tfont : ", szName); } // ╟
} /* End for () */
stFont = UIFont.boldSystemFont(ofSize: 10);
if TunnelService.DEBUG { print("family : ", stFont.familyName); }
if TunnelService.DEBUG { print("family : ", stFont.fontName); }
for szName in UIFont.fontNames(forFamilyName: stFont.familyName) {
if TunnelService.DEBUG { print("\tfont : ", szName); } // ╟
} /* End for () */
if TunnelService.DEBUG { print("----------------------------------------------------"); };
#endif /* DEBUG */
#if DEBUG
// NSLog("%d, %d, %@", 1, 2, "3");
// var stNotification : String = idea_make_notification("");
// print("APPDelegate::application(_:willFinishLaunchingWithOptions:) : Notification : \(stNotification)");
print("APPDelegate::application(_:willFinishLaunchingWithOptions:) : \(#function)");
print("APPDelegate::application(_:willFinishLaunchingWithOptions:) : ROOT : " + UIApplication.shared.appPath);
print("APPDelegate::application(_:willFinishLaunchingWithOptions:) : documents : " + UIApplication.shared.documentsPath);
print("APPDelegate::application(_:willFinishLaunchingWithOptions:) : DKNightVersionThemeChanging : \(NSNotification.Name.DKNightVersionThemeChanging.rawValue)");
#endif /* DEBUG */
/******************************************************************************************/
#if DEBUG
ASConfigration.logLevel = .debug;
#else
ASConfigration.logLevel = .error;
#endif
ASConfigration.setDefaultDB(path: MitmService.getDBPath(), name: "Session");
if nil == APPDelegate.isFirst() {
let stDefaultRule = Rule.defaultRule();
try? stDefaultRule.saveToDB();
UserDefaults.set("\(stDefaultRule.id ?? -1)", forKey: TunnelService.CURRENT_RULE_ID);
APPDelegate.setIsFirst(first: "no first");
} /* End if () */
if TunnelService.DEBUG { TunnelService.Debug("APPDelegate::application(_:willFinishLaunchingWithOptions:) : NEVPNStatusDidChange : \(NSNotification.Name.NEVPNStatusDidChange)"); }
if TunnelService.DEBUG { TunnelService.Debug("APPDelegate::application(_:willFinishLaunchingWithOptions:) : NEVPNStatusDidChange : \(NSNotification.Name.NEVPNStatusDidChange.rawValue)"); }
// self.onNotification(IDEAAdapter.makeNotification("Setting", "TABBAR", "ANIMATE"), self.onAnimate);
//
// self.registNotification({ (aNotification) -> NSObject? in
//
// });
let onAnimate : @convention(block) (_ aNotification:Notification) -> () = { (notification) -> () in
if TunnelService.DEBUG { TunnelService.Debug("APPDelegate::onAnimate : " + notification.name.rawValue); }
if TunnelService.DEBUG { TunnelService.Debug("APPDelegate::onAnimate : \(String(describing: notification.object))"); }
APPDelegate.setTabbarAnimation(notification.object as! Bool);
};
self.onNotification(IDEAAdapter.makeNotification("Setting", "TABBAR", "ANIMATE"), onAnimate);
return true
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
if TunnelService.DEBUG { TunnelService.Debug("APPDelegate::application(_ application:, didFinishLaunchingWithOptions launchOptions:)"); }
// #if DEBUG
// Bundle(path: "/Applications/InjectionIII.app/Contents/Resources/iOSInjection.bundle")?.load()
// #endif /* DEBUG */
let stAttributes : Dictionary<NSAttributedString.Key, Any> = [NSAttributedString.Key.foregroundColor:UIColor.clear];
UIBarButtonItem.appearance().setTitleTextAttributes(stAttributes, for: UIControl.State.normal);
UIBarButtonItem.appearance().setTitleTextAttributes(stAttributes, for: UIControl.State.highlighted);
UINavigationBar.appearance().backIndicatorImage = UIImage(named: "UIButtonBarArrowLeft");
UINavigationBar.appearance().backIndicatorTransitionMaskImage = UIImage.init();
UINavigationBar.appearance().tintColor = UIColor.clear;
if true == self.window!.rootViewController?.isKind(of: RootViewController.self) {
self.rootViewController = self.window?.rootViewController as? RootViewController;
} /* End if () */
self.window?.makeKeyAndVisible();
self.splash();
self.addNotificationName(SplashViewController.preSplashDone(), selector: #selector(__ON_PRE_SPLASH_DONE(notification:)), object: nil);
self.addNotificationName(Notification.Name.reachabilityChanged.rawValue, selector: #selector(__ON_REACHABILITY_CHANGED(notification:)), object: self.reachability);
do {
try reachability.startNotifier();
} /* End do-try */
catch {
if TunnelService.DEBUG { TunnelService.Error("APPDelegate::didFinishLaunchingWithOptions(_ application:, didFinishLaunchingWithOptions launchOptions:) : could not start reachability notifier"); }
} /* End catch */
if TunnelService.DEBUG { TunnelService.Error("APPDelegate::didFinishLaunchingWithOptions(_ application:, didFinishLaunchingWithOptions launchOptions:) : SettingHeader.reuseIdentifier() : " + SettingHeader.reuseIdentifier()); }
#if DEBUG
APPDelegate.WORMHOLE_DEBUG = MMWormhole.init(applicationGroupIdentifier: GROUPNAME, optionalDirectory: "DEBUG");
APPDelegate.WORMHOLE_DEBUG?.listenForMessage(withIdentifier: TunnelService.MM_WORMHOLE_DEBUG, listener: { /* [weak self]*/ (aDebug) in
if let szDebug = aDebug as? String {
NSLog("TunnelService:: %@", szDebug);
}
});
#endif /* DEBUG */
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
if TunnelService.DEBUG { TunnelService.Debug("APPDelegate::applicationWillResignActive(_ application)"); }
return;
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
// TunnelService.pauseLog();
if TunnelService.DEBUG { TunnelService.Debug("APPDelegate::applicationDidEnterBackground(_ application)"); }
return;
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
if TunnelService.DEBUG { TunnelService.Debug("APPDelegate::applicationWillEnterForeground(_ application)"); }
// TunnelService.beginLog();
return;
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
// TunnelService.beginLog();
if TunnelService.DEBUG { TunnelService.Debug("APPDelegate::applicationDidBecomeActive(_ application)"); }
return;
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
if TunnelService.DEBUG { TunnelService.Debug("APPDelegate::applicationWillTerminate(_ application)"); }
// TunnelService.endLog();
return;
}
func application(_ app: UIApplication, open aURL: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
var bOpen : Bool = false;
if TunnelService.DEBUG { TunnelService.Debug("APPDelegate::splash(_: url: options:)"); }
if TunnelService.DEBUG { TunnelService.Debug("APPDelegate::splash(_: url: options:) : URL : \(aURL)"); }
bOpen = APPDelegate.isAppScheme(aURL: aURL);
if bOpen {
// Do Something
if "open" == aURL.host {
if "setting" == aURL.query {
UIApplication.shared.open(URL.init(string: "App-Prefs:root=General")!);
} /* End if () */
} /* End if () */
} /* End if () */
else {
// Do Nothing.
} /* End else */
return bOpen;
}
func splash() -> Void {
if TunnelService.DEBUG { TunnelService.Debug("APPDelegate::splash()"); }
self.splashViewController = (UIStoryboard.load(SplashViewController.storyboard, viewController: SplashViewController.self) as! SplashViewController);
self.window!.addSubview(self.splashViewController!.view);
self.rootViewController?.setNeedsStatusBarAppearanceUpdate();
self.postNotificationName(SplashViewController.splash(), object: nil);
self.performSelector(inBackground: #selector(loadData), with: nil);
return;
}
@objc func loadData() -> Void {
sleep(UInt32(1.5));
let stCert : URL = TunnelService.certPath();
if TunnelService.DEBUG { TunnelService.Debug("APPDelegate::loadData() : Cert : " + stCert.path); }
let stCacertPath = stCert.appendingPathComponent("cacert.pem", isDirectory: false);
if TunnelService.DEBUG { TunnelService.Debug("APPDelegate::loadData() : CacertPath : " + stCacertPath.path); }
if !FileManager.fileExists(url: stCacertPath) {
let stCC = TunnelService.NAN_CC1 + TunnelService.NAN_CC2 + TunnelService.NAN_CC3;
try? stCC.write(to: stCacertPath, atomically: true, encoding: .utf8);
} /* End if () */
let stCacertDerPath = stCert.appendingPathComponent("cacert.der", isDirectory: false);
if TunnelService.DEBUG { TunnelService.Debug("APPDelegate::loadData() : CacertDer : " + stCacertDerPath.path); }
if !FileManager.fileExists(url: stCacertDerPath) {
let stDerData = Data(base64Encoded: TunnelService.NAN_CC_DER_BASE64);
try? stDerData?.write(to: stCacertDerPath, options: Data.WritingOptions.atomic);
} /* End if () */
let stCakeyPath = stCert.appendingPathComponent("cakey.pem", isDirectory: false);
if TunnelService.DEBUG { TunnelService.Debug("APPDelegate::loadData() : CakeyPath : " + stCakeyPath.path); }
if !FileManager.fileExists(url: stCakeyPath) {
let stCK = TunnelService.NAN_CK1 + TunnelService.NAN_CK2 + TunnelService.NAN_CK3;
try? stCK.write(to: stCakeyPath, atomically: true, encoding: .utf8);
} /* End if () */
let stRsakeyPath = stCert.appendingPathComponent("rsakey.pem", isDirectory: false);
if TunnelService.DEBUG { TunnelService.Debug("APPDelegate::loadData() : RsakeyPath : " + stRsakeyPath.path); }
if !FileManager.fileExists(url: stRsakeyPath) {
let stRK = TunnelService.NAN_RK1 + TunnelService.NAN_RK2 + TunnelService.NAN_RK3;
try? stRK.write(to: stRsakeyPath, atomically: true, encoding: .utf8);
} /* End if () */
let stBlackListPath = TunnelService.certPath()?.appendingPathComponent("DefaultBlackLisk.conf");
if TunnelService.DEBUG { TunnelService.Debug("APPDelegate::loadData() : DefaultBlackLisk : " + stBlackListPath!.path); }
if !FileManager.fileExists(url: stBlackListPath) {
let szBundlePath : String? = Bundle.main.path(forResource: "DefaultBlackLisk", ofType: "conf", inDirectory: "CERT");
if TunnelService.DEBUG { TunnelService.Debug("APPDelegate::loadData() : BundlePath : " + szBundlePath!); }
FileManager.copyItem(atPath: szBundlePath!, toPath: stBlackListPath!.path);
} /* End if () */
var stPath = TunnelService.httpPath().appendingPathComponent("index.html");
if TunnelService.DEBUG { TunnelService.Debug("APPDelegate::loadData() : HTML : " + stPath.path); }
if !FileManager.fileExists(url: stPath) {
let szBundlePath : String? = Bundle.main.path(forResource: "index", ofType: "html", inDirectory: "HTTP");
if TunnelService.DEBUG { TunnelService.Debug("APPDelegate::loadData() : BundlePath : " + szBundlePath!); }
FileManager.copyItem(atPath: szBundlePath!, toPath: stPath.path);
} /* End if () */
/**
供下载的证书
*/
stPath = TunnelService.httpPath().appendingPathComponent("cacert.pem");
if !FileManager.fileExists(url: stPath) {
let stCC = TunnelService.NAN_CC1 + TunnelService.NAN_CC2 + TunnelService.NAN_CC3;
try? stCC.write(to: stPath, atomically: true, encoding: .utf8);
} /* End if () */
/**
检查证书
*/
CheckCert.checkPermissions { (aCertTrustStatus : TrustResultType) in
if TunnelService.DEBUG { TunnelService.Debug("APPDelegate::loadData() : TrustResultType : \(aCertTrustStatus)"); }
APPDelegate.setCertTrustType(aCertTrustStatus);
};
if let stCache = YYWebImageManager.shared().cache {
stCache.diskCache.removeAllObjects();
} /* End if () */
/**
检查 VPN
*/
// if true == APPDelegate.isAgree() {
//
// } /* End if () */
self.SPLASH_DONE = true;
self.performSelector(onMainThread: #selector(splashDone), with: nil, waitUntilDone: false);
return;
}
@objc func splashDone() -> Void {
if TunnelService.DEBUG { TunnelService.Debug("APPDelegate::splashDone()"); }
UIView.animate(withDuration: SplashViewController.duration()) {
self.splashViewController?.view.alpha = 0;
} completion: { (Bool) in
self.splashViewController?.view.removeFromSuperview();
self.splashViewController = nil;
};
self.postNotificationName(SplashViewController.splashDone(), object: nil);
return;
}
// MARK: - NSNotification
@objc func __ON_PRE_SPLASH_DONE(notification : NSNotification) -> Void {
if TunnelService.DEBUG { TunnelService.Debug("APPDelegate::__ON_PRE_SPLASH_DONE(notification:)"); }
if true == self.SPLASH_DONE {
self.performSelector(onMainThread: #selector(splashDone), with: nil, waitUntilDone: false);
} /* End if () */
return;
}
@objc func __ON_REACHABILITY_CHANGED(notification : NSNotification) -> Void {
if TunnelService.DEBUG { TunnelService.Debug("APPDelegate::__ON_REACHABILITY_CHANGED(notification:)"); }
let stReachability = notification.object as! Reachability
switch stReachability.connection {
case .wifi:
if TunnelService.DEBUG { TunnelService.Debug("APPDelegate::__ON_REACHABILITY_CHANGED(notification:) : wifi"); }
APPDelegate.setWifiIsOpen(open: true);
if TunnelService.DEBUG { TunnelService.Debug("APPDelegate::__ON_REACHABILITY_CHANGED(notification:) : IP : " + self.IP); }
case .cellular:
if TunnelService.DEBUG { TunnelService.Debug("APPDelegate::__ON_REACHABILITY_CHANGED(notification:) : cellular"); }
APPDelegate.setWifiIsOpen(open: false);
case .none:
if TunnelService.DEBUG { TunnelService.Debug("APPDelegate::__ON_REACHABILITY_CHANGED(notification:) : none"); }
APPDelegate.setWifiIsOpen(open: false);
default: break;
}
return;
}
// func calcDecrement(forDecrement total: Int) ->() ->Int {
// var overallDecrement = 0
// func decrementer() -> Int {
// overallDecrement -= total
//
// return overallDecrement
// }
//
// return decrementer
// }
}
// MARK: - IDEAAppletNotification
extension APPDelegate {
@objc func onAnimate(_ notification : NSNotification) -> Void {
if TunnelService.DEBUG { TunnelService.Debug("APPDelegate::onAnimate(notification:)"); }
return;
}
}
| 39.557439 | 283 | 0.610759 |
ab38bfd3e7b23a347cdedf50abab5ea117b568b8 | 476 | //
// Post
// Legacy
//
// Copyright (c) 2018 Eugene Egorov.
// License: MIT, https://github.com/eugeneego/legacy/blob/master/LICENSE
//
// sourcery: transformer
// sourcery: lightTransformer
struct Post: Codable {
var userId: Int64
var id: Int64
var title: String
var body: String
}
// sourcery: transformer
// sourcery: lightTransformer
struct PartialPost: Codable {
var userId: Int64?
var id: Int64?
var title: String?
var body: String?
}
| 18.307692 | 72 | 0.67437 |
8af40880849abcd8a372e3f0318796ab103ed40f | 276 | //
// View+NavigationStyle.swift
//
// Created on 24/06/2020.
// Copyright © 2020 WildAid. All rights reserved.
//
import SwiftUI
extension View {
func stackNavigationView() -> some View {
AnyView(self.navigationViewStyle(StackNavigationViewStyle()))
}
}
| 18.4 | 69 | 0.684783 |
db78bba585c3c6b5ca3723604ff2e0d8a9138340 | 317 | //
// ResponseApi.swift
// GitWood
//
// Created by Nour on 23/02/2019.
// Copyright © 2019 Nour Saffaf. All rights reserved.
//
import Foundation
enum ResponseType {
case Trending
case Invalid
}
enum ResponseStatus:Equatable {
case Success
case More
case Empty
case Failure(String)
}
| 13.782609 | 54 | 0.671924 |
7a45469dc187a8928c619cf86bdcf08ec6d6dc38 | 320 | //
// UIViewController+.swift
// InvestScopio_Example
//
// Created by Joao Medeiros Pereira on 17/05/19.
// Copyright © 2019 CocoaPods. All rights reserved.
//
import Foundation
import UIKit
extension UIViewController {
static func toString() -> String {
return String(describing: self.self)
}
}
| 17.777778 | 52 | 0.69375 |
e9c0a8de5d46d66f0bec7575556d99c9f33ae95d | 624 | //
// SharedLoginApp.swift
// Shared
//
// Created by Balaji on 11/01/21.
//
import SwiftUI
@main
struct SharedLoginApp: App {
var body: some Scene {
// Hiding Title Bar For Only macOS...
#if os(iOS)
WindowGroup {
ContentView()
}
#else
WindowGroup {
ContentView()
}
.windowStyle(HiddenTitleBarWindowStyle())
#endif
}
}
// CHecking Only For MacOS And Disabling FOcus Ring....
#if !os(iOS)
extension NSTextField{
open override var focusRingType: NSFocusRingType{
get{.none}
set{}
}
}
#endif
| 16.864865 | 55 | 0.564103 |
87e319d1ebf93c2cd401f5ec3e9ffa11d38aea40 | 1,398 | //
// StdTx.swift
// Cosmostation
//
// Created by yongjoo on 25/03/2019.
// Copyright © 2019 wannabit. All rights reserved.
//
import Foundation
public class StdTx: Codable {
var type: String = ""
var value: Value = Value.init()
init() {}
init(_ dictionary: [String: Any]) {
self.type = dictionary["type"] as? String ?? ""
self.value = Value.init(dictionary["value"] as! [String : Any])
}
public class Value: Codable {
var msg: Array<Msg> = Array<Msg>()
var fee: Fee = Fee.init()
var signatures: Array<Signature> = Array<Signature>()
var memo: String = ""
init() {}
init(_ dictionary: [String: Any]) {
self.msg.removeAll()
let rawMsgs = dictionary["msg"] as! Array<NSDictionary>
for rawMsg in rawMsgs {
self.msg.append(Msg(rawMsg as! [String : Any]))
}
self.fee = Fee.init(dictionary["fee"] as! [String : Any])
self.signatures.removeAll()
let rawSignatures = dictionary["signatures"] as! Array<NSDictionary>
for rawSignature in rawSignatures {
self.signatures.append(Signature(rawSignature as! [String : Any]))
}
self.memo = dictionary["memo"] as? String ?? ""
}
}
}
| 28.530612 | 82 | 0.530758 |
50ed0a6f830e3d27263dab1a85ad5c08fdb71770 | 2,456 | //
// AppDelegate.swift
// HYaoQi
//
// Created by hwq on 2018/5/9.
// Copyright © 2018年 hwq. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
UIApplication.shared.statusBarStyle = .lightContent
createTabbarController()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
//MARK: -
func createTabbarController() {
window = UIWindow(frame: UIScreen.main.bounds)
window?.backgroundColor = UIColor.white
window?.rootViewController = HTabbarController()
window?.makeKeyAndVisible()
}
}
| 43.087719 | 285 | 0.734935 |
621e9277c097e52bf96e98580de79ce8a40ff268 | 32,082 | //
// DataExportModel.swift
// ECAB
//
// The class will create CSV from CoreData
//
// Creates CSV strings
// Use this as example "Visual S,,,,,,,\n,,,,,,,,\nID,aaaaa,,,,,,,\nbirth,dd/mm/yy,,,\n"
//
// Created by Boris Yurkevich on 21/12/2015.
// Copyright © 2015 Oliver Braddick and Jan Atkinson. All rights reserved.
//
import Foundation
import CoreGraphics
private enum MoveType {
case moveTypeMotorOne
case moveTypeMotorTwo
case moveTypeMotorThree
case moveTypeSearchOne
case moveTypeSearchTwo
case moveTypeSearchThree
case moveTypeUnknown
}
final class DataExportModel {
var pickedVisualSearchSession: Session? = nil
var pickedCounterpointingSession: CounterpointingSession? = nil
private let model = Model.sharedInstance
private let msInOneSec = 1000.0 // Milliseconds in one second
private let gameName: String
private let birth: String
private let age: String
private let dateFormatter = DateFormatter()
private let timeFormatter = DateFormatter()
private var returnValue = "empty line\n"
init() {
gameName = model.games[model.data.selectedGame.intValue]
birth = "dd/MM/yy"
age = "yy/mm"
dateFormatter.dateStyle = DateFormatter.Style.short
timeFormatter.dateFormat = "HH:mm:ss:SSS"
}
func export() -> String? {
var returnValue: String? = nil
switch model.data.selectedGame {
case GamesIndex.visualSearch.rawValue:
returnValue = createVisualSearchTable()
case GamesIndex.counterpointing.rawValue:
returnValue = createCounterpointingTable()
case GamesIndex.flanker.rawValue:
if pickedCounterpointingSession?.type.intValue == SessionType.flanker.rawValue {
returnValue = createFlankerTable(isRandom: false)
} else if pickedCounterpointingSession?.type.intValue == SessionType.flankerRandomized.rawValue {
returnValue = createFlankerTable(isRandom: true)
}
case GamesIndex.visualSust.rawValue:
returnValue = createVisualSustainedTable()
default:
break
}
return returnValue
}
func createVisualSearchTable() -> String {
if let visualSearchSession: Session = pickedVisualSearchSession {
let playerName = visualSearchSession.player.name
let dateStart: String = dateFormatter.string(from: visualSearchSession.dateStart as Date)
let timeStart = timeFormatter.string(from: visualSearchSession.dateStart as Date)
var difficulty = "easy"
if visualSearchSession.difficulty == Difficulty.hard.rawValue {
difficulty = "hard"
}
let speed = visualSearchSession.speed.doubleValue
let comments = visualSearchSession.comment
let screenComm = "*screen 3 should be blank throughout for 'hard' condition"
let durationComm = "**set this to screen duration if it doesn't finish early"
let header = "log of indivudual responces"
// Create dynamic lines
let dynamicLines = createDynamicLinesForVSSession(visualSearchSession)
let t = ECABLogCalculator.getVisualSearchTotals(visualSearchSession)
let avg = t.average
let mht = t.motorHits1 + t.motorHits2 + t.motorHits3
let mfpt = t.motorFalse1 + t.motorFalse2 + t.motorFalse3
// Motor time total
let mtt = t.motorOneTotal + t.motorTwoTotal + t.motorThreeTotal
// Search time total
let stt = t.searchOneTotal + t.searchTwoTotal + t.searchThreeTotal
// Search total hits
let sht = t.searchHits1 + t.searchHits2 + t.searchHits3
// Search false positives
let sfpt = t.searchFalse1 + t.searchFalse2 + t.searchFalse3
let searchDiff1 = t.searchHits1 - t.searchFalse1
let searchDiff2 = t.searchHits2 - t.searchFalse2
let searchDiff3 = t.searchHits3 - t.searchFalse3
let avgMotor = "Time per target found [motor]"
let avgSearch = "Time per target found [search]"
let avgDiff = "Search time - motor time per target"
let avgDiffVal = avg.search - avg.motor
returnValue = """
\(gameName) , , , , , ,
, , , , , ,
ID ,\(playerName) , , , , ,
date of birth ,\(birth) ,age at test ,\(age) , , ,
date/time of test start ,\(dateStart) ,\(timeStart) , , , ,
, , , , , ,
parameters ,\(difficulty) , , ,\(speed) s , ,
comments ,\(comments) , , , , ,
, , , , , ,
, , , , , ,
, ,motor 1 ,motor 2 ,motor 3 ,TOTAL ,*
no of hits , ,\(t.motorHits1) ,\(t.motorHits2) ,\(t.motorHits3) ,\(mht) ,
no of false positives , ,\(t.motorFalse1) ,\(t.motorFalse2) ,\(t.motorFalse3) ,\(mfpt) ,
total time , ,\(r(t.motorOneTotal)) ,\(r(t.motorTwoTotal)) ,\(r(t.motorThreeTotal)),\(r(mtt)) ,**
, , , , , ,
, , , , , ,
, ,search 1 ,search 2 ,search 3 , ,
no of hits , ,\(t.searchHits1) ,\(t.searchHits2) ,\(t.searchHits3) ,\(sht) ,
no of false positives , ,\(t.searchFalse1) ,\(t.searchFalse2) ,\(t.searchFalse3) ,\(sfpt) ,
total time , ,\(r(t.searchOneTotal)) ,\(r(t.searchTwoTotal)),\(r(t.searchThreeTotal)),\(r(stt)) ,**
hits - false positives , ,\(searchDiff1) ,\(searchDiff2) ,\(searchDiff3) ,\(sht-sfpt) ,
,\(screenComm) , , , , ,
,\(durationComm), , , , ,
, , , , , ,
\(avgMotor) ,\(avg.motor) , , , , ,
\(avgSearch) ,\(avg.search) , , , , ,
\(avgDiff) ,\(avgDiffVal) , , , , ,
, , , , , ,
\(header) , , , , , ,
, ,target row ,target col ,time , ,
"""
// Append dynamic rows: headers and moves
for line in dynamicLines {
returnValue += line
}
}
return returnValue
}
func createCounterpointingTable() -> String {
if let session: CounterpointingSession = pickedCounterpointingSession {
let playerName = session.player.name
let dateStart: String = dateFormatter.string(from: session.dateStart as Date)
let timeStart = timeFormatter.string(from: session.dateStart as Date)
let comments = session.comment
let rows = createCounterpointinLines(session)
let data = ECABLogCalculator.getCounterpointingResult(session)
guard let t = data.result else {
return "Critical Error \(data.error ?? "")"
}
let meanRatio = t.conflictTimeMean / t.nonConflictTimeMean
let medianRatio = t.conflictTimeMedian / t.nonConflictTimeMedian
let timeRatio = t.timeBlockConflict / t.timeBlockNonConflict
returnValue = """
ECAB Test ,\(gameName) , , ,
, , , ,
ID ,\(playerName) , , ,
date of birth ,\(birth) ,age at test ,\(age) ,
date/time of test start ,\(dateStart) ,\(timeStart) , ,
, , , ,
comments ,\(comments) , , ,
, , , ,
non-conflict (blocks 1) , , , ,
total time 1 = ,\(r(t.timeBlockNonConflict)),s. , ,
mean response time 1 = ,\(r(t.nonConflictTimeMean)),s. , ,
median response time 1 = ,\(r(t.nonConflictTimeMedian)),s. , ,
, , , ,
conflict (blocks 2) , , , ,
total time 2 = ,\(r(t.timeBlockConflict)),s. , ,
mean response time 2 = ,\(r(t.conflictTimeMean)),s. , ,
median response time 2 = ,\(r(t.conflictTimeMedian)),s. , ,
, , , ,
mean ratio (con / non c) ,\(r(meanRatio)), , ,
median ratio ,\(r(medianRatio)), , ,
time ratio ,\(r(timeRatio)), , ,
, , , ,
log of individual responses , , , ,
"""
// Append dynamic rows: headers and moves
for line in rows {
returnValue += line
}
}
return returnValue;
}
func createFlankerTable(isRandom: Bool) -> String {
if let session: CounterpointingSession = pickedCounterpointingSession {
let playerName = session.player.name
let dateStart: String = dateFormatter.string(from: session.dateStart as Date)
let timeStart = timeFormatter.string(from: session.dateStart as Date)
let comments = session.comment
var imageInfo = "unknown image size"
if let definedImageInfo = session.imageSizeComment as String? {
imageInfo = definedImageInfo
}
let rows = createFlankerLines(session)
let output = ECABLogCalculator.getFlankerResult(session)
guard let t = output.result else {
return "Couldn't create file. \(output.error ?? "")"
}
let meanRatio = t.conflictTimeMean / t.nonConflictTimeMean
let medianRatio = t.conflictTimeMedian / t.nonConflictTimeMedian
let timeRatio = t.conflictTime / t.nonConflictTime
let random: String
if isRandom {
random = "Randomised"
} else {
random = "Not randomised"
}
returnValue = """
ECAB Test ,\(gameName) \(random) , , ,
, , , ,
ID ,\(playerName) , , ,
date of birth ,\(birth) ,age at test ,\(age) ,
date/time of test start ,\(dateStart) ,\(timeStart), ,
, , , ,
parameters ,\(imageInfo) , , ,
comments ,\(comments) , , ,
, , , ,
non-conflict (block 1+4), , , ,
total time block 1 ,\(r(t.timeBlock1)) ,s. , ,
total time block 4 ,\(r(t.timeBlock4)) ,s. , ,
total time blocks 1+4 ,\(r(t.nonConflictTime)) ,s. , ,
, , , ,
mean response time 1+4 ,\(r(t.nonConflictTimeMean)) ,s. , ,
median response time 1+4,\(r(t.nonConflictTimeMedian)),s. , ,
, , , ,
conflicts (blocks 2+3) , , , ,
total time block 2 ,\(r(t.timeBlock2)) ,s. , ,
total time block 3 ,\(r(t.timeBlock3)) ,s. , ,
total time blocks 2+3 ,\(r(t.conflictTime)) ,s. , ,
, , , ,
mean response time 2+3 ,\(r(t.conflictTimeMean)) ,s. , ,
median response time 2+3,\(r(t.conflictTimeMedian)) ,s. , ,
, , , ,
mean ratio (con / non c),\(r(meanRatio)) , , ,
median ratio ,\(r(medianRatio)) , , ,
time ratio ,\(r(timeRatio)) , , ,
, , , ,
log of ind. responses , , , ,
"""
// Append dynamic rows: headers and moves
for line in rows {
returnValue += line
}
}
return returnValue;
}
func createVisualSustainedTable() -> String {
if let session: CounterpointingSession = pickedCounterpointingSession {
let playerName = session.player.name
let dateStart: String = dateFormatter.string(from: session.dateStart as Date)
let timeStart = timeFormatter.string(from: session.dateStart as Date)
let comments = session.comment
let rows = createVisualSustainedLines(session)
let t = ECABLogCalculator.getVisualSustainResult(session)
returnValue = """
ECAB Test ,\(gameName) , , , , ,
, , , , , ,
ID ,\(playerName) , , , , ,
date of birth ,\(birth) ,age at test ,\(age) , , ,
date/time of test start ,\(dateStart) ,\(timeStart) , , , ,
, , , , , ,
parameters , , , , , ,
total period ,\(t.totalPeriod),exposure ,\(t.totalExposure) ,max delay ,\(t.maxDelay),
, , , , , ,
comments ,\(comments) , , , , ,
, , , , , ,
total pictures displayed,\(t.totalPicturesDisplayd),of which ,\(t.totalAnimalsDisplayed),animals, ,
, , , , , ,
total hits = ,\(t.totalHits) , , , , ,
total misses = ,\(t.totalMisses), , , , ,
total false +ves ,\(t.totalFalseAndVE), , , , ,
, , , , , ,
log of individual responses, , , , , ,
"""
// Append dynamic rows: headers and moves
for line in rows {
returnValue += line
}
}
return returnValue;
}
fileprivate func createDynamicLinesForVSSession(_ visualSearchSession: Session) -> Array<String> {
var collectionOfTableRows: Array<String> = Array()
for move in visualSearchSession.moves {
let gameMove = move as! Move
let screenNumber = gameMove.screenNumber.intValue
var ignoreThisMove = false
switch screenNumber {
case 0 ... 2, 11 ... 13:
ignoreThisMove = true // Training
default:
break
}
if !ignoreThisMove {
if gameMove.empty.boolValue == false {
// Success or failure
var sof = ""
if gameMove.success.boolValue == true {
sof = "hit"
} else {
sof = "false"
}
// ve / repeat
var veor = ""
if gameMove.`repeat`.boolValue == true {
veor = "repeat"
} else {
veor = "ve"
}
let moveTimestamp = timeFormatter.string(from: gameMove.date as Date)
let targetRow = gameMove.row
let targetColumn = gameMove.column
// CSV line
let line = ",\(sof) \(veor), \(targetRow), \(targetColumn), \(moveTimestamp)\n"
collectionOfTableRows.append(line)
} else {
var header = "header unknown"
switch screenNumber {
case VisualSearchEasyModeView.motorOne.rawValue:
header = "motor screen 1"
case VisualSearchEasyModeView.motorTwo.rawValue:
header = "motor screen 2"
case VisualSearchEasyModeView.motorThree.rawValue:
header = "motor screen 3"
case VisualSearchHardModeView.motorOne.rawValue:
header = "motor screen 1"
case VisualSearchHardModeView.motorTwo.rawValue:
header = "motor screen 2"
case VisualSearchEasyModeView.one.rawValue:
header = "search screen 1"
case VisualSearchEasyModeView.two.rawValue:
header = "search screen 2"
case VisualSearchEasyModeView.three.rawValue:
header = "search screen 3"
case VisualSearchHardModeView.one.rawValue:
header = "search screen 1"
case VisualSearchHardModeView.two.rawValue:
header = "search screen 2"
default:
header = "wrong header number"
}
// Time
let headerTime = timeFormatter.string(from: gameMove.date as Date)
// CSV line
let headerLine = "\(header),screen onset, , ,\(headerTime)\n"
collectionOfTableRows.append(headerLine)
}
}
}
return collectionOfTableRows
}
fileprivate func createCounterpointinLines(_ session: CounterpointingSession) -> Array<String> {
var collectionOfTableRows: Array<String> = Array()
var headerCount = 0
var needHeader = true
var realScreen = 1
var previous = 0
for move in session.moves {
let gameMove = move as! CounterpointingMove
let isSuccess = gameMove.success.boolValue
if (gameMove.poitionX.intValue >= 4 && gameMove.poitionX.intValue <= 23)
|| (gameMove.poitionX.intValue >= 29 && gameMove.poitionX.intValue <= 48) {
// Success or failure
var sof = ""
if isSuccess {
sof = "correct"
} else {
sof = "incorrect"
}
var time: Double
if let newInterval = gameMove.intervalDouble as? Double {
time = r(newInterval)
} else {
// Because I defined old interval as Integer I am chaning it to Double
// This condition is to keep old data working.
time = gameMove.interval.doubleValue
}
// CSV line
let line: String
if realScreen == previous {
line = ",,\(sof), \(time), s.,\(gameMove.poitionX.intValue),\n"
} else {
line = ",\(realScreen),\(sof), \(time), s.,\(gameMove.poitionX.intValue),\n"
}
collectionOfTableRows.append(line)
needHeader = true
previous = realScreen
if isSuccess {
realScreen += 1
}
let startScreen = Model.testStartScreen(gameType: .counterpointing)
if gameMove.poitionX.intValue == startScreen {
// Reset
realScreen = 1
}
} else {
if needHeader {
var header = "header unknown"
switch headerCount {
case 0:
header = "non-conflict block 1"
case 1:
header = "conflict block 2"
default:
header = "header error"
}
headerCount += 1
// CSV line
let headerLine = "\(header),screen,response,time,,index\n"
collectionOfTableRows.append(headerLine)
// Prevents duplicate headers
needHeader = false
}
}
}
return collectionOfTableRows
}
fileprivate func createFlankerLines(_ session: CounterpointingSession) -> Array<String> {
var collectionOfTableRows: Array<String> = Array()
var headerCount = 1
var realScreen = 1
var previous = 0
// First header
let headerLine = "\(FlankerBlock.example.title),screen,response,time, ,\n"
collectionOfTableRows.append(headerLine)
for move in session.moves {
let gameMove = move as! CounterpointingMove
let isSuccess = gameMove.success.boolValue
let positionX: CGFloat = CGFloat(gameMove.poitionX.doubleValue)
if positionX != blankSpaceTag {
// Success or failure
var sof = ""
if isSuccess {
sof = "correct"
} else {
sof = "incorrect"
}
var time: Double
if let newInterval = gameMove.intervalDouble as? Double {
time = r(newInterval)
} else {
// Because I defined old interval as Integer I am chaning it to Double
// This condition is to keep old data working.
time = gameMove.interval.doubleValue
}
// CSV line
let line: String
if realScreen == previous {
line = ",,\(sof), \(time), s.,\(gameMove.poitionX.intValue),\n"
} else {
line = ",\(realScreen),\(sof), \(time), s.,\(gameMove.poitionX.intValue),\n"
}
collectionOfTableRows.append(line)
previous = realScreen
if isSuccess {
realScreen += 1
}
let startScreen = Model.testStartScreen(gameType: .flanker)
if gameMove.poitionX.intValue == startScreen {
// Reset
realScreen = 1
}
} else {
let header: String
if let aHeader = FlankerBlock(rawValue: headerCount) {
header = aHeader.title
} else {
header = "Header Error"
}
headerCount += 1
// CSV line
let headerLine = "\(header),screen,response,time,,index,\n"
collectionOfTableRows.append(headerLine)
}
}
return collectionOfTableRows
}
fileprivate func createFlankerRandomLines(_ session: CounterpointingSession) -> Array<String> {
var collectionOfTableRows: Array<String> = Array()
var screenCount = 1
collectionOfTableRows.append("Randmised,screen,response,time,,inversed ,case ,\n")
for move in session.moves {
let gameMove = move as! CounterpointingMove
if gameMove.poitionX.doubleValue != Double(blankSpaceTag) {
// Success or failure
var sof = ""
if gameMove.success.boolValue == true {
sof = "correct"
} else {
sof = "incorrect"
}
var time: Double
if let newInterval = gameMove.intervalDouble as? Double {
time = r(newInterval)
} else {
// Because I defined old interval as Integer I am chaning it to Double
// This condition is to keep old data working.
time = gameMove.interval.doubleValue
}
var inv = "normal"
if let sc = gameMove.poitionX.intValue as Int? {
switch sc {
// TODO: Replace with the correct numers from Oliver.
case 24, 25, 27, 29, 30, 31, 32, 35, 36, 41, 42, 46, 47, 49, 50, 54, 55:
inv = "inversed"
default:
inv = "unknown"
}
}
// CSV line
let line = ",\(screenCount),\(sof), \(time), s.,\(inv),\(gameMove.poitionX.stringValue),\n"
collectionOfTableRows.append(line)
screenCount += 1
}
}
return collectionOfTableRows
}
fileprivate func createVisualSustainedLines(_ session: CounterpointingSession) -> Array<String> {
var collectionOfTableRows: Array<String> = Array()
var spacePrinted = false
for move in session.moves {
let gameMove = move as! CounterpointingMove
var line = ""
var fourMistakes = ""
let poitionY = CGFloat(gameMove.poitionY.floatValue)
if poitionY == VisualSustainSkip.fourSkips.rawValue {
fourMistakes = "[4 mistaken taps in a row]"
}
if gameMove.success.boolValue {
let formattedDelay = String(format: "%.02f", gameMove.delay!.doubleValue)
line = "picture \(gameMove.poitionX), Success, delay:,\(formattedDelay) s., \(fourMistakes)\n"
} else {
// Two mistakes type
if (gameMove.interval.doubleValue == VisualSustainMistakeType.falsePositive.rawValue) {
line = "picture \(gameMove.poitionX), False Positive, \(fourMistakes)\n"
} else if (gameMove.interval.doubleValue == VisualSustainMistakeType.miss.rawValue) {
line = "picture \(gameMove.poitionX), Miss, \(fourMistakes)\n"
}
}
if !spacePrinted && !gameMove.inverted.boolValue { // Not training
line = "\n" + line
spacePrinted = true
}
collectionOfTableRows.append(line)
}
return collectionOfTableRows
}
}
| 49.281106 | 142 | 0.395611 |
f915b80de6bf60e6c22c6f18cfe6ed426161a3aa | 1,273 | //: [Previous](@previous)
import Foundation
//: - - -
//: # Parsing JSON
//: - - -
// http://open-notify.org/Open-Notify-API/
let astronauts = "http://api.open-notify.org/astros.json" // 우주비행사 정보
let apiURL = URL(string: astronauts)!
let dataTask = URLSession.shared.dataTask(with: apiURL) { (data, response, error) in
guard error == nil else { return print(error!) }
guard let response = response as? HTTPURLResponse, // 헤더정보
// ~= 는 범위 사이에 있는지 없는지를 체크하는 키워드 // (200..<400).contains(response.statusCode) 로 사용해도 됨
200..<400 ~= response.statusCode
else { return print("StatusCode 가 적절하지 않습니다.") }
guard let data = data, // body 정보
let jsonObject = try? JSONSerialization.jsonObject(with: data) as? [String: Any]
else { return print("데이터가 없습니다.") }
print("jsonObject :", jsonObject)
guard (jsonObject["message"] as? String) == "success",
let people = jsonObject["people"] as? [[String: String]],
let peopleCount = jsonObject["number"] as? Int
else { return print("Parsing Error") }
print("\n---------- [ Parsing Success ] ----------\n")
print("총 \(peopleCount)명의 우주비행사가 탑승 중입니다.")
print("= 우주비행사 명단 =")
people
.compactMap { $0["name"] }
.forEach { print($0) }
}
dataTask.resume()
//: [Next](@next)
| 28.931818 | 90 | 0.627651 |
d71465fae6d77bdc9a290cbce7c3fc83d29b1e12 | 3,459 | //
// TodayInteractor.swift
// Weather
//
// Created by Ricardo Casanova on 01/12/2018.
// Copyright © 2018 Pijp. All rights reserved.
//
import UIKit
import CoreLocation
class TodayInteractor {
private let requestManager = RequestManager()
private var lastRefreshDate: Date?
}
// MARK: - Private section
extension TodayInteractor {
private func getWeatherWith(latitude: CGFloat, longitude: CGFloat, completion: @escaping getWeatherCompletionBlock) {
var getWeatherRequest = WeatherRequest(latitude: latitude, longitude: longitude)
getWeatherRequest.completion = completion
requestManager.send(request: getWeatherRequest)
}
private func addInformationWithWeatherResponse(_ weatherResponse: WeatherResponse, location: CLLocationCoordinate2D) {
guard let weather = weatherResponse.list.first, let userId = getCurrenUserId() else {
return
}
RemoteDabaBaseManager.shared.addInformation(userId: userId, lastTemperature: weather.main.temp, latitude: location.latitude, longitude: location.longitude, countryCode: weatherResponse.city.country)
}
private func getCurrenUserId() -> String? {
return LocalWeatherManager.shared.getCurrentUserId()
}
}
// MARK: - TodayInteractorDelegate
extension TodayInteractor: TodayInteractorDelegate {
func requestLocationAuthorizationIfNeeded() {
LocationManager.shared.requestAuthorizationIfNeeded()
}
func getCurrentWeather(completion: @escaping getWeatherInteractorCompletionBlock) {
guard let currenLocation = LocationManager.shared.getCurrentLocation() else {
completion(nil, false, nil)
return
}
let latitude = CGFloat(currenLocation.latitude)
let longitude = CGFloat(currenLocation.longitude)
getWeatherWith(latitude: latitude, longitude: longitude) { [weak self] (response) in
guard let `self` = self else { return }
switch response {
case .success(let weather):
guard let weather = weather else {
completion(nil, false, nil)
return
}
self.addInformationWithWeatherResponse(weather, location: currenLocation)
LocalWeatherManager.shared.saveLocalWeather(weather)
let viewModel = TodayViewModel.getViewModelWith(weatherResponse: weather)
self.lastRefreshDate = Date()
completion(viewModel, true, nil)
break
case .failure(let error):
completion(nil, false, error)
break
}
}
}
func getLocalWeatherInformation() -> TodayViewModel? {
guard let weatherResponse = LocalWeatherManager.shared.getLocalWeather() else {
return nil
}
return TodayViewModel.getViewModelWith(weatherResponse: weatherResponse)
}
func shouldGetLocalWeatherInformation() -> Bool {
return LocalWeatherManager.shared.localWeatherExists()
}
func shouldGetRemoteWeatherInformation() -> Bool {
guard let lastRefreshDate = lastRefreshDate else {
return true
}
let currentDate = Date()
if currentDate.minutes(from: lastRefreshDate) >= 20 {
return true
}
return false
}
}
| 33.911765 | 206 | 0.648742 |
5b3deb52466b026d797bdd738008aeadf2ee8265 | 2,753 | // autogenerated
// swiftlint:disable all
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
extension V1.BetaBuildLocalizations.ById {
public struct PATCH: Endpoint {
public typealias Parameters = BetaBuildLocalizationUpdateRequest
public typealias Response = BetaBuildLocalizationResponse
public var path: String {
"/v1/betaBuildLocalizations/\(id)"
}
/// the id of the requested resource
public var id: String
/// BetaBuildLocalization representation
public var parameters: Parameters
public init(
id: String,
parameters: Parameters
) {
self.id = id
self.parameters = parameters
}
public func request(with baseURL: URL) throws -> URLRequest? {
var components = URLComponents(url: baseURL, resolvingAgainstBaseURL: true)
components?.path = path
var urlRequest = components?.url.map { URLRequest(url: $0) }
urlRequest?.httpMethod = "PATCH"
var jsonEncoder: JSONEncoder {
let encoder = JSONEncoder()
return encoder
}
urlRequest?.httpBody = try jsonEncoder.encode(parameters)
urlRequest?.setValue("application/json", forHTTPHeaderField: "Content-Type")
return urlRequest
}
/// - Returns: **200**, Single BetaBuildLocalization as `BetaBuildLocalizationResponse`
/// - Throws: **400**, Parameter error(s) as `ErrorResponse`
/// - Throws: **403**, Forbidden error as `ErrorResponse`
/// - Throws: **404**, Not found error as `ErrorResponse`
/// - Throws: **409**, Request entity error(s) as `ErrorResponse`
public static func response(from data: Data, urlResponse: HTTPURLResponse) throws -> Response {
var jsonDecoder: JSONDecoder {
let decoder = JSONDecoder()
return decoder
}
switch urlResponse.statusCode {
case 200:
return try jsonDecoder.decode(BetaBuildLocalizationResponse.self, from: data)
case 400:
throw try jsonDecoder.decode(ErrorResponse.self, from: data)
case 403:
throw try jsonDecoder.decode(ErrorResponse.self, from: data)
case 404:
throw try jsonDecoder.decode(ErrorResponse.self, from: data)
case 409:
throw try jsonDecoder.decode(ErrorResponse.self, from: data)
default:
throw try jsonDecoder.decode(ErrorResponse.self, from: data)
}
}
}
}
// swiftlint:enable all
| 32.77381 | 103 | 0.599709 |
384cdf2b34d6058e73a9dfcca6121c8911486e8e | 262 | //
// DecodableResponse.swift
// OAuthAPIKit
//
// Created by David on 2019/11/20.
//
import Foundation
/// Response that can be decoded by Swift's standard Decodable procotol
public protocol DecodableResponse {
associatedtype ResponseType: Decodable
}
| 18.714286 | 71 | 0.748092 |
6ae64de197378ad2059761a4e7c6ecff1263158a | 5,580 | //
// CesaroFractal.swift
// CesaroFractal
//
// Created by Jeff_Terry on 1/19/22.
//
import Foundation
import SwiftUI
class CesaroFractal: NSObject, ObservableObject {
@MainActor @Published var cesaroVerticesForPath = [(xPoint: Double, yPoint: Double)]() ///Array of tuples
@Published var timeString = ""
@Published var enableButton = true
@Published var iterationsFromParent: Int?
@Published var angleFromParent: Int?
/// Class Parameters Necessary for Drawing
var x: CGFloat = 75
var y: CGFloat = 100
let pi = CGFloat(Float.pi)
var piDivisorForAngle = 0.0
var angle: CGFloat = 0.0
@MainActor init(withData data: Bool){
super.init()
cesaroVerticesForPath = []
}
/// calculateCesaro
///
/// This function ensures that the program will not crash if non-valid input is applied.
///
/// - Parameters:
/// - iterations: number of iterations in the fractal
/// - piAngleDivisor: integer that sets the angle as pi/piAngleDivisor so if 2, then the angle is π/2
///
func calculateCesaro(iterations: Int?, piAngleDivisor: Int?) async {
var newIterations :Int? = 0
var newPiAngleDivisor :Int? = 2
// Test to make sure the input is valid
if (iterations != nil) && (piAngleDivisor != nil) {
newIterations = iterations
newPiAngleDivisor = piAngleDivisor
} else {
newIterations = 0
newPiAngleDivisor = 2
}
print("Start Time of \(newIterations!) \(Date())\n")
await calculateCesaroFractalVertices(iterations: newIterations!, piAngleDivisor: newPiAngleDivisor!)
print("End Time of \(newIterations!) \(Date())\n")
}
/// calculateCesaroFractalVertices
///
/// - Parameters:
/// - iterations: number of iterations in the fractal
/// - piAngleDivisor: integer that sets the angle as pi/piAngleDivisor so if 2, then the angle is π/2
///
func calculateCesaroFractalVertices(iterations: Int, piAngleDivisor: Int) async {
var CesaroPoints: [(xPoint: Double, yPoint: Double)] = [] ///Array of tuples
var x: CGFloat = 0
var y: CGFloat = 0
let size: Double = 550
let width :CGFloat = 600.0
let height :CGFloat = 600.0
// draw from the center of our rectangle
let center = CGPoint(x: width / 2, y: height / 2)
// Offset from center in y-direction for Cesaro Fractal
let yoffset = size/(2.0*tan(45.0/180.0*Double.pi))
x = center.x - CGFloat(size/2.0)
y = height/2.0 - CGFloat(yoffset)
guard iterations >= 0 else { await updateData(pathData: CesaroPoints)
return }
guard iterations <= 15 else { await updateData(pathData: CesaroPoints)
return }
guard piAngleDivisor > 0 else { await updateData(pathData: CesaroPoints)
return }
guard piAngleDivisor <= 50 else { await updateData(pathData: CesaroPoints)
return }
CesaroPoints = CesaroFractalCalculator(fractalnum: iterations, x: x, y: y, size: size, angleDivisor: piAngleDivisor)
await updateData(pathData: CesaroPoints)
return
}
/// updateData
///
/// The function runs on the main thread so it can update the GUI
///
/// - Parameters:
/// - pathData: array of tuples containing the calculated Cesaro Vertices
///
@MainActor func updateData(pathData: [(xPoint: Double, yPoint: Double)]){
cesaroVerticesForPath.append(contentsOf: pathData)
}
/// eraseData
///
/// This function erases the cesaroVertices on the main thread so the drawing can be cleared
///
@MainActor func eraseData(){
Task.init {
await MainActor.run {
self.cesaroVerticesForPath.removeAll()
}
}
}
/// updateTimeString
/// The function runs on the main thread so it can update the GUI
/// - Parameter text: contains the string containing the current value of Pi
@MainActor func updateTimeString(text:String){
self.timeString = text
}
/// setButton Enable
///
/// Toggles the state of the Enable Button on the Main Thread
///
/// - Parameter state: Boolean describing whether the button should be enabled.
///
@MainActor func setButtonEnable(state: Bool){
if state {
Task.init {
await MainActor.run {
self.enableButton = true
}
}
}
else{
Task.init {
await MainActor.run {
self.enableButton = false
}
}
}
}
}
| 27.219512 | 124 | 0.515591 |
72d1b6876253ef2edcf47e2b476d49423a88cd5b | 4,141 | //
// MapTabViewController.swift
// YelpIt
//
// Created by Sudipta Bhowmik on 8/6/18.
// Copyright © 2018 Sudipta Bhowmik. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
class MapTabViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var tableView: UITableView!
/*override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.tableView.contentInset = UIEdgeInsetsMake(self.mapView.frame.size.height - 100, 0, 0, 0);
}*/
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if (scrollView.contentOffset.y < self.mapView.frame.size.height * -1 ) {
scrollView.setContentOffset(CGPoint(x: scrollView.contentOffset.x, y: self.mapView.frame.size.height * -1), animated: false)
}
}
override func viewDidLoad() {
super.viewDidLoad()
let footerHeight = 700
let dummyView = UIView(frame: CGRect(x: 0, y: 0, width: Int(self.tableView.bounds.size.width), height: footerHeight))
dummyView.backgroundColor = UIColor.white
self.tableView.tableFooterView = dummyView;
//Set the content offset of the table view to be the inverse of that footer view's height:
let footerHt = dummyView.bounds.height;
self.tableView.contentOffset = CGPoint(x: 0, y: -footerHt)
//Set the content inset of your table view to offset the footer view.
self.tableView.contentInset = UIEdgeInsets(top: footerHt, left: 0, bottom: -footerHt, right: 0)
//Adjust the scrollbar position, again, based on the footer's height.
self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(footerHt, 0, 0, 0);
tableView.backgroundColor = UIColor(named: "clear")
tableView.dataSource = self
tableView.delegate = self
tableView.rowHeight = 30.0
let centerLocation = CLLocation(latitude: 37.7833, longitude: -122.4167)
goToLocation(location : centerLocation)
//tableView.isHidden = true
// Do any additional setup after loading the view.
}
func goToLocation(location: CLLocation) {
let span = MKCoordinateSpanMake(0.1, 0.1)
let region = MKCoordinateRegionMake(location.coordinate, span)
mapView.setRegion(region, animated: false)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/* func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return ""
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let vw : UIView = UIView()
//let m : MKMapView = MKMapView()
vw.backgroundColor = UIColor(named: "clear")
return vw
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 300.0
}*/
/*override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.tableView.contentInset = UIEdgeInsetsMake(self.mapView.frame.size.height - 400, 0, 0, 0);
}*/
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "maptabcell") as! MapTableViewCell
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 30
}
/*
// 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.
}
*/
}
| 33.395161 | 136 | 0.647428 |
ab3162fc96a60789088479605b575ab894b857a3 | 1,169 | //
// User.swift
// twitter_alamofire_demo
//
// Created by Charles Hieger on 6/17/17.
// Copyright © 2017 Charles Hieger. All rights reserved.
//
import Foundation
class User {
var name: String
var screenName: String
var profileImageURL: String
var id: Int64
var followers_count: Int
var friends_count: Int
var favorites_count: Int
var profile_banner_url: String
var statuses_count: Int
static var current: User?
init(dictionary: [String: Any]) {
name = dictionary["name"] as! String
screenName = dictionary["screen_name"] as! String
profileImageURL = dictionary["profile_image_url_https"] as! String
id = dictionary["id"] as! Int64
followers_count = dictionary["followers_count"] as! Int
friends_count = dictionary["friends_count"] as! Int
favorites_count = dictionary["favourites_count"] as! Int
if let bannerURL = dictionary["profile_banner_url"] {
profile_banner_url = bannerURL as! String
} else {
profile_banner_url = ""
}
statuses_count = dictionary["statuses_count"] as! Int
}
}
| 28.512195 | 74 | 0.650984 |
1d1b81b17cfab2c112cfbb17b0270e5b9957f7f0 | 2,335 | //
// settingScene.swift
// Big2
//
// Created by Tsznok Wong on 4/11/2016.
// Copyright © 2016 Tsznok Wong. All rights reserved.
//
import Foundation
import SpriteKit
class SettingScene: SKScene {
override func didMove(to view: SKView) {
/// Called when the scene is transited to SettingScene
/// Initialize setting view
print("Moved to SettingScene")
clearScene()
graphicsController.initSettingView(self)
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
/// Called when a touch ends
for touch in touches {
let location = touch.location(in: self)
/// Confirm button pushed
if graphicsController.Back.contains(location) {
/// Save setting changed
audioController.saveSetting()
transitToMenuScene()
} else if graphicsController.vibrateToggle.contains(location) {
vibrate.toggle()
graphicsController.vibrateToggle.texture = vibrate ? graphicsController.vibrateTrue : graphicsController.vibrateFalse
audioController.vibrator()
}
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
/// Called when a touch moves
for touch in touches {
let location = touch.location(in: self)
let touchedSprite = atPoint(location)
/// Confirm slider movement
if touchedSprite.name == "slider" {
/// Change volume
let volumeBarHalfWidth = Float(graphicsController.volumeBar.frame.width) / 2
let halfViewWidth = Float(ViewWidth / 2)
var moveTo = Float(location.x)
if moveTo > halfViewWidth + volumeBarHalfWidth {
moveTo = halfViewWidth + volumeBarHalfWidth
} else if moveTo < halfViewWidth - volumeBarHalfWidth {
moveTo = halfViewWidth - volumeBarHalfWidth
}
touchedSprite.position.x = CGFloat(moveTo)
audioController.changeVolume(to: (moveTo - halfViewWidth + volumeBarHalfWidth) / (volumeBarHalfWidth * 2))
}
}
}
}
| 33.84058 | 133 | 0.581585 |
725328b4210aa4dc05d1f4ba0682b2a2dcff1e29 | 2,255 | import Vapor
import VaporPostgreSQL
let drop = Droplet()
try drop.addProvider(VaporPostgreSQL.Provider)
drop.preparations += Acronym.self
(drop.view as? LeafRenderer)?.stem.cache = nil
// clear View cache
let controller = TILController()
controller.addRoutes(drop: drop)
let basic = BasicController()
basic.addRoutes(drop: drop)
let acronym = AcronymController()
drop.resource("acronyms", acronym)
//===================Simple Get request================================//
//let drop = Droplet()
//drop.get { req in
// return try drop.view.make("welcome", [
// "message": drop.localization[req.lang, "welcome", "title"]
// ])
//}
//
//drop.get("hello") { request in
// return ("Hello world")
//}
////hello/vapor
//drop.get("hello","vapor") { request in
// return try JSON(node: ["Greeting":"Hello vapor"])
//}
////chat/1
//drop.get("chat", Int.self) { request, chat in
// return try JSON(node: ["person","person-\(chat)"])
//}
//
//drop.post("post") { request in
// guard let name = request.data["name"]?.string else {
// throw Abort.badRequest
// }
// return try JSON(node: ["message":"Hello \(name)"])
//}
////hello-template
//drop.get("hello-template") { request in
// return try drop.view.make("hello", Node(node:["name":"willie"]))
//}
////hello-template2/willie
//drop.get("hello-template2", String.self) { request, name in
// return try drop.view.make("hello", Node(node:["name":name]))
//
//}
////hello-template3
//drop.get("hello-template3") { request in
// let users = try [
// ["name":"willie", "email":"[email protected]"].makeNode(),
// ["name":"vickie", "email":"[email protected]"].makeNode(),
// ["name":"arthour", "email":"[email protected]"].makeNode()].makeNode()
// return try drop.view.make("hello3", Node(node: ["users":users]))
//}
//
////hello-template4?sayHello=true
//drop.get("hello-template4") { request in
// guard let sayHello = request.data["sayHello"]?.bool else {
// throw Abort.badRequest
// }
// return try drop.view.make("ifelse", Node(node:["sayHello":sayHello.makeNode()]))
//
//}
//drop.resource("posts", PostController())
//===========================================================================//
drop.run()
| 28.544304 | 86 | 0.596896 |
1edba6e005f21cbcb48c37d94072cf75761ab366 | 1,464 | //
// todoUITests.swift
// todoUITests
//
// Created by Swamita on 15/08/20.
// Copyright © 2020 Swamita Gupta. All rights reserved.
//
import XCTest
class todoUITests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// UI tests must launch the application that they test.
let app = XCUIApplication()
app.launch()
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testLaunchPerformance() throws {
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) {
// This measures how long it takes to launch your application.
measure(metrics: [XCTOSSignpostMetric.applicationLaunch]) {
XCUIApplication().launch()
}
}
}
}
| 33.272727 | 182 | 0.65847 |
6184b0a0d873d3f71b61c635b51cce69c872748b | 2,760 | /*
See LICENSE folder for this sample’s licensing information.
Abstract:
A view that wraps a UIPageViewController.
*/
import SwiftUI
import UIKit
struct PageViewController: UIViewControllerRepresentable {
var controllers: [UIViewController]
let loops: Bool = false
@Binding var currentPage: Int
@Binding var forwardAnimation: Bool
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func makeUIViewController(context: Context) -> UIPageViewController {
let pageViewController = UIPageViewController(
transitionStyle: .scroll,
navigationOrientation: .horizontal)
pageViewController.dataSource = context.coordinator
pageViewController.delegate = context.coordinator
return pageViewController
}
func updateUIViewController(_ pageViewController: UIPageViewController, context: Context) {
pageViewController.setViewControllers(
[controllers[currentPage]], direction: forwardAnimation ? .forward : .reverse, animated: true)
}
class Coordinator: NSObject, UIPageViewControllerDataSource, UIPageViewControllerDelegate {
var parent: PageViewController
init(_ pageViewController: PageViewController) {
self.parent = pageViewController
}
func pageViewController(
_ pageViewController: UIPageViewController,
viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard let index = parent.controllers.firstIndex(of: viewController) else {
return nil
}
if index == 0 {
return parent.loops ? parent.controllers.last : nil
}
return parent.controllers[index - 1]
}
func pageViewController(
_ pageViewController: UIPageViewController,
viewControllerAfter viewController: UIViewController) -> UIViewController? {
guard let index = parent.controllers.firstIndex(of: viewController) else {
return nil
}
if index + 1 == parent.controllers.count {
return parent.loops ? parent.controllers.first : nil
}
return parent.controllers[index + 1]
}
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
if completed,
let visibleViewController = pageViewController.viewControllers?.first,
let index = parent.controllers.firstIndex(of: visibleViewController) {
parent.currentPage = index
}
}
}
}
| 36.315789 | 194 | 0.663768 |
46c052c70ba05b7f6bd313daf537ccb03ac84368 | 1,178 | //
// CustomDatePickerTests.swift
// xDripTests
//
// Created by Ivan Skoryk on 21.04.2020.
// Copyright © 2020 Faifly. All rights reserved.
//
import XCTest
@testable import xDrip
// swiftlint:disable implicitly_unwrapped_optional
final class CustomDatePickerTests: XCTestCase {
var sut: CustomDatePicker!
var valueChangedHandlerCalled = false
var formattedString = ""
var date = Date()
override func setUp() {
super.setUp()
sut = CustomDatePicker()
sut.formatDate = { date in
self.date = date
return DateFormatter.localizedString(from: date, dateStyle: .short, timeStyle: .short)
}
sut.onValueChanged = { str in
self.valueChangedHandlerCalled = true
self.formattedString = str ?? ""
}
}
func testValueChanged() {
// When
sut.sendActions(for: .valueChanged)
// Then
XCTAssertTrue(valueChangedHandlerCalled)
let strDate = DateFormatter.localizedString(from: date, dateStyle: .short, timeStyle: .short)
XCTAssert(strDate == formattedString)
}
}
| 25.06383 | 101 | 0.616299 |
75c5994742a1153b9c321d0505faebfc8a94534c | 1,036 | //
// CursorInfoUSRTests.swift
// SourceKittenFrameworkTests
//
// Created by Timofey Solonin on 14/05/19.
// Copyright © 2019 SourceKitten. All rights reserved.
//
import Foundation
import SourceKittenFramework
import XCTest
class CursorInfoUSRTests: XCTestCase {
/// Validates that cursorInfo is parsed correctly.
func testCursorInfoUSRRequest() throws {
let path = fixturesDirectory + "DocInfo.swift"
let info = toNSDictionary(
try Request.cursorInfoUSR(
file: path,
usr: "s:7DocInfo22multiLineCommentedFuncyyF",
arguments: ["-sdk", sdkPath(), path],
cancelOnSubsequentRequest: false
).send()
)
compareJSONString(withFixtureNamed: "CursorInfoUSR", jsonString: toJSON(info))
}
}
extension CursorInfoUSRTests {
static var allTests: [(String, (CursorInfoUSRTests) -> () throws -> Void)] {
return [
("testCursorInfoUSRRequest", testCursorInfoUSRRequest)
]
}
}
| 27.263158 | 86 | 0.642857 |
d6c1c6b81c53a88d1676d3221e2a064aea58335b | 612 | //
// MovieCell.swift
// Flicks
//
// Created by Sara Hender on 10/12/16.
// Copyright © 2016 Sara Hender. All rights reserved.
//
import UIKit
class MovieCell: UITableViewCell {
@IBOutlet weak var posterView: UIImageView!
@IBOutlet weak var overviewLabel: UILabel!
@IBOutlet weak var titleLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 21.857143 | 65 | 0.673203 |
decf7420919bae767f13bb587ec5ce9f8d88e01f | 544 | //
// GOTviewCell.swift
// GameOfThrones
//
// Created by Joshua Viera on 11/19/18.
// Copyright © 2018 Alex Paul. All rights reserved.
//
import UIKit
class GOTviewCell: UITableViewCell {
@IBOutlet weak var GOTimage: UIImageView!
@IBOutlet weak var seasonAndEpisode: UILabel!
@IBOutlet weak var episodeName: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
| 20.923077 | 65 | 0.681985 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.