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
|
---|---|---|---|---|---|
9caf8f0efcec4eac023e643ecf8c536ac48dfb44 | 2,132 | //
// AppDelegate.swift
// bongloy-demo-ios
//
// Created by khomsovon on 9/3/18.
//
import UIKit
import Bongloy
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
Stripe.setDefaultPublishableKey(BONGLOY_PUBLISHABLE_KEY)
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:.
}
}
| 45.361702 | 285 | 0.758912 |
11d8be475971e977d7ef4f5cd0166a088a76e3b4 | 637 | //
// DurationDelayedRequest.swift
// LeagueAPI
//
// Created by Antoine Clop on 8/27/18.
// Copyright © 2018 Antoine Clop. All rights reserved.
//
import Foundation
internal class DurationDelayedRequest: DelayedRequest {
public var delay: Duration
public init(identifier: Int, delay: Duration, request: @escaping () -> Void) {
self.delay = delay
super.init(identifier: identifier, request: request)
}
public func start() {
let delayedTask: DelayedTask = DelayedTask(taskName: "DelayedRequest", task: { self.execute() })
delayedTask.execute(after: self.delay)
}
}
| 25.48 | 104 | 0.66405 |
14b0220a910bf6f641eecb6be61b821ebe74bd0b | 3,194 | // The MIT License (MIT)
// Copyright © 2017 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.
import UIKit
class SPStorkIndicatorView: UIView {
var style: Style = .line {
didSet {
switch self.style {
case .line:
SPAnimationSpring.animate(0.5, animations: {
self.leftView.transform = .identity
self.rightView.transform = .identity
}, options: .curveEaseOut)
case .arrow:
SPAnimationSpring.animate(0.5, animations: {
let angle = CGFloat(20 * Float.pi / 180)
self.leftView.transform = CGAffineTransform.init(rotationAngle: angle)
self.rightView.transform = CGAffineTransform.init(rotationAngle: -angle)
}, options: .curveEaseOut)
}
}
}
private var leftView: UIView = UIView()
private var rightView: UIView = UIView()
init() {
super.init(frame: .zero)
self.backgroundColor = UIColor.clear
self.addSubview(self.leftView)
self.addSubview(self.rightView)
self.leftView.backgroundColor = UIColor.init(hex: "CAC9CF")
self.rightView.backgroundColor = UIColor.init(hex: "CAC9CF")
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func sizeToFit() {
super.sizeToFit()
self.setWidth(36)
self.setHeight(13)
let height: CGFloat = 5
let correction = height / 2
self.leftView.frame = CGRect.init(x: 0, y: 0, width: self.frame.width / 2 + correction, height: height)
self.leftView.center.y = self.frame.height / 2
self.leftView.round()
self.rightView.frame = CGRect.init(x: self.frame.width / 2 - correction, y: 0, width: self.frame.width / 2 + correction, height: height)
self.rightView.center.y = self.frame.height / 2
self.rightView.round()
}
enum Style {
case arrow
case line
}
}
| 38.02381 | 144 | 0.637445 |
23ec1aeeea24a04ac2e39ab184f6329212ab4450 | 516 | //
// ViewController.swift
// StringChineseTests
//
// Created by Niklas Berglund on 2017-02-01.
// Copyright © 2017 Klurig. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 19.846154 | 80 | 0.676357 |
1c2c79132ce2ee477878fcd9f18059efc59cce9f | 2,148 | //
// Common.swift
// SearchTwitterWithOauth
//
// Created by Larry on 16/5/14.
// Copyright © 2016年 Larry. All rights reserved.
//
import Foundation
public var queryHeader = ""
public var onlySearchNearByTweets = false
public var longitude = ""
public var latitude = ""
public var radius = "1000km"
public var language = "en"
//获取Twitter数据有关‘page’的参数,默认获取15条推
public var sinceID = 0
public var maxID = 0
public var settedRadius:Float = 100//默认的搜索距离,单位km
struct Constants {
struct TwitterApi {
static let BaseUrl = "https://api.twitter.com/"
static let Oauth2 = "https://api.twitter.com/oauth2/token"
static let SearchUrl = "https://api.twitter.com/1.1/search/tweets.json"
}
struct TwitterOauthKeys {
static let ConsumerKey = "你的ConsumerKey"
static let ConsumerSecret = "你的ConsumerSecret"
static func encodeConsumerKey() -> String {
let ConsumerKeyAndConsumerSecret = ConsumerKey + ":" + ConsumerSecret
let encodedConsumerKeyAndConsumerSecret = Tools.base64(ConsumerKeyAndConsumerSecret)
return encodedConsumerKeyAndConsumerSecret
}
}
struct GetIPAdress {
static let BaseUrl = "http://ipof.in/json"//返回经常超时
static let BaseUrlBak1 = "http://geoip.nekudo.com/api" //备用,和BaseUrl解析ip地址的顺序一致
}
struct GetCountryCode {
static let BaseUrl = "http://ip.taobao.com/service/getIpInfo.php"
}
static func setUserDefaults() {
let onlySearchNearByDefault = false
let useLocalLanguage = true
let defaultRadius:Float = 100
NSUserDefaults.standardUserDefaults().setBool(onlySearchNearByDefault, forKey: "onlySearchNearBy")
NSUserDefaults.standardUserDefaults().setFloat(defaultRadius, forKey: "settedRadius")
NSUserDefaults.standardUserDefaults().setBool(useLocalLanguage, forKey: "shouldUseLocalLanguage")
}
struct AlertMessages {
static let noMoreData = "没有更多数据"
}
}
| 27.189873 | 106 | 0.641061 |
38f5dbaf290dbf1d7053f38136a79fdf458e6314 | 2,448 | //
// Player.swift
// PodcastApp
//
// Created by Rafael Schmitt on 29/11/20.
//
import AVFoundation
import Foundation
class Player: NSObject, AVAudioPlayerDelegate {
enum Activity {
case stopped
case playing
case paused
}
struct State {
var currentTime: TimeInterval
var duration: TimeInterval
var activity: Activity
}
private var audioPlayer: AVAudioPlayer
private var timer: Timer?
private var update: (State?) -> Void
init?(url: URL, update: @escaping (State?) -> Void) {
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback)
try AVAudioSession.sharedInstance().setActive(true)
} catch {
return nil
}
if let player = try? AVAudioPlayer(contentsOf: url) {
audioPlayer = player
self.update = update
} else {
return nil
}
super.init()
audioPlayer.delegate = self
}
func togglePlay() {
if audioPlayer.isPlaying {
audioPlayer.pause()
timer?.invalidate()
timer = nil
notify()
} else {
audioPlayer.play()
if let t = timer {
t.invalidate()
}
timer = Timer.scheduledTimer(withTimeInterval: 0.05, repeats: true) { [weak self] _ in
guard let s = self else { return }
s.notify()
}
}
}
var state: Player.State {
State(currentTime: audioPlayer.currentTime, duration: audioPlayer.duration, activity: activity)
}
func notify() {
update(state)
}
func setProgress(_ time: TimeInterval) {
audioPlayer.currentTime = time
notify()
}
func audioPlayerDidFinishPlaying(_: AVAudioPlayer, successfully flag: Bool) {
timer?.invalidate()
timer = nil
if flag {
notify()
} else {
update(nil)
}
}
var duration: TimeInterval {
audioPlayer.duration
}
var activity: Activity {
audioPlayer.isPlaying ? .playing : isPaused ? .paused : .stopped
}
var isPaused: Bool {
!audioPlayer.isPlaying && audioPlayer.currentTime > 0
}
func cancel() {
audioPlayer.stop()
timer?.invalidate()
}
deinit {
cancel()
}
}
| 22.254545 | 103 | 0.54902 |
d95403c96df3a97d764974c4ae614c0c58b249b2 | 1,991 | // Copyright (c) 2019 Spotify AB.
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
import Foundation
import MobiusCore
public class ConsoleLogger<T: LoopTypes>: MobiusLogger {
public typealias Model = T.Model
public typealias Event = T.Event
public typealias Effect = T.Effect
private let prefix: String
public init(tag: String = "Mobius") {
prefix = tag + ": "
}
public func willInitiate(model: T.Model) {
print(prefix + "Initializing loop")
}
public func didInitiate(model: T.Model, first: First<T.Model, T.Effect>) {
print(prefix + "Loop initialized, starting from model: \(first.model)")
first.effects.forEach { (effect: T.Effect) in
print(prefix + "Effect dispatched: \(effect)")
}
}
public func willUpdate(model: T.Model, event: T.Event) {
print(prefix + "Event received: \(event)")
}
public func didUpdate(model: T.Model, event: T.Event, next: Next<T.Model, T.Effect>) {
if let nextModel = next.model {
print(prefix + "Model updated: \(nextModel)")
}
next.effects.forEach { (effect: T.Effect) in
print(prefix + "Effect dispatched: \(effect)")
}
}
}
| 33.183333 | 90 | 0.669513 |
019d69c21600246a87ef38f72c22f3e3f1db05ca | 2,408 | //
// SceneDelegate.swift
// ExpandingTableViewCell + Programiticially
//
// Created by Muhammad Abdullah Al Mamun on 13/7/20.
// Copyright © 2020 Muhammad Abdullah Al Mamun. All rights reserved.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 44.592593 | 147 | 0.717608 |
62ce7fa9b4378aca2520ea0c12547e2f7eced150 | 876 | // Please keep this file in alphabetical order!
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -enable-source-import -emit-module -emit-module-path %t/comments.swiftmodule -emit-module-doc -emit-module-doc-path %t/comments.swiftdoc -module-name comments %S/../Inputs/comment_to_something_conversion.swift -disable-objc-attr-requires-foundation-module
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -parse-as-library %t/comments.swiftmodule -typecheck -emit-objc-header-path %t/comments.h -import-objc-header %S/../Inputs/empty.h -disable-objc-attr-requires-foundation-module
// RUN: awk '/A000/,0' %t/comments.h > %t/comments.h-cleaned
// RUN: diff -u %t/comments.h-cleaned %S/Inputs/comments-expected-output.h
// RUN: %check-in-clang -Wno-documentation %t/comments.h
// REQUIRES: objc_interop
// REQUIRES: no_asan
| 73 | 317 | 0.755708 |
e536fbea9e9709fd705e42a82f5ce280d041baa3 | 115 | import UIKit
public protocol IBaseCell {
associatedtype DataType
func setData(data:DataType?)
}
| 12.777778 | 32 | 0.686957 |
214f7dd3b86b0e4421319113bdbe9527525567da | 2,036 | //
// URL+Utilities.swift
// Compute
//
// Copyright (c) 2020 Jason Morley
//
// 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.
//
enum URLAccessError: Error {
case bookmarkCreationFailure
case notReadable
}
extension URL {
static func resolveBookmark(at url: URL) throws -> URL {
var isStale = false
let bookmarkData = try URL.bookmarkData(withContentsOf: url)
let url = try URL(resolvingBookmarkData: bookmarkData, bookmarkDataIsStale: &isStale)
try url.prepareForSecureAccess()
return url
}
func prepareForSecureAccess() throws {
guard startAccessingSecurityScopedResource() else {
throw URLAccessError.bookmarkCreationFailure
}
guard FileManager.default.isReadableFile(atPath: path) else {
throw URLAccessError.notReadable
}
}
public var lastPathComponent: String {
assert(self.isFileURL)
return (self.path as NSString).lastPathComponent
}
}
| 36.357143 | 93 | 0.716601 |
4656068c5c7786f63700f86abff38ff3713c22e3 | 2,503 | // Copyright (c) 2015 - 2019 Jann Schafranek
//
// 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.
#if os(OSX)
import AppKit
#else
import UIKit
#endif
/// A color representation containing 8-bit representations of the `red`, `blue`, `green` and `alpha` values.
public struct OK8BitRGBARepresentation : Equatable {
public let red : UInt8
public let green : UInt8
public let blue : UInt8
public let alpha : UInt8
/// Initializes and returns a `UIColor` object using the specified `OK8BitRGBARepresentation`.
public var color : UIColor {
return UIColor(representation: self)
}
/// Initializes and returns a `OK8BitRGBARepresentation` object.
public init(red : UInt8, green : UInt8, blue : UInt8, alpha : UInt8 = 255) {
self.red = red
self.green = green
self.blue = blue
self.alpha = alpha
}
/// Initializes and returns a `OK8BitRGBARepresentation` object.
public init(representation : OKRGBARepresentation) {
self.red = UInt8(representation.red * 255)
self.green = UInt8(representation.green * 255)
self.blue = UInt8(representation.blue * 255)
self.alpha = UInt8(representation.alpha * 255)
}
public static func ==(left : OK8BitRGBARepresentation, right : OK8BitRGBARepresentation) -> Bool {
return OKRGBARepresentation(bitRepresentation: left) == OKRGBARepresentation(bitRepresentation: right)
}
}
| 42.423729 | 110 | 0.709149 |
f92525ba124e6bff05e1608af0ede13c2be68506 | 4,908 | //
// ProcedureKit
//
// Copyright © 2015-2018 ProcedureKit. All rights reserved.
//
import Foundation
import Dispatch
/// `PendingEvent` encapsulates a reference to a future `Procedure` event, and can be used
/// to ensure that asynchronous tasks are executed to completion *before* the future event.
///
/// While a reference to the `PendingEvent` exists, the event will not occur.
///
/// You cannot instantiate your own `PendingEvent` instances - only the framework
/// itself creates and provides (in certain circumstances) PendingEvents.
///
/// A common use-case is when handling a WillExecute or WillFinish observer callback.
/// ProcedureKit will provide your observer with a `PendingExecuteEvent` or a `PendingFinishEvent`.
///
/// If you must dispatch an asynchronous task from within your observer, but want to
/// ensure that the observed `Procedure` does not execute / finish until your asynchronous task
/// completes, you can use the Pending(Execute/Finish)Event like so:
///
/// ```swift
/// procedure.addWillFinishObserver { procedure, errors, pendingFinish in
/// DispatchQueue.global().async {
/// pendingFinish.doBeforeEvent {
/// // do something asynchronous
/// // this block is guaranteed to complete before the procedure finishes
/// }
// }
/// }
/// ```
///
/// Some of the built-in `Procedure` functions take an optional "before:" parameter,
/// to which a `PendingEvent` can be directly passed. For example:
///
/// ```swift
/// procedure.addWillFinishObserver { procedure, errors, pendingFinish in
/// // produce a new operation before the procedure finishes
/// procedure.produce(BlockOperation { /* do something */ }, before: pendingFinish)
/// }
/// ```
///
final public class PendingEvent: CustomStringConvertible {
public enum Kind: CustomStringConvertible {
case postDidAttach
case addOperation
case postDidAddOperation
case execute
case postDidExecute
case postDidCancel
case finish
case postDidFinish
public var description: String {
switch self {
case .postDidAttach: return "PostDidAttach"
case .addOperation: return "AddOperation"
case .postDidAddOperation: return "PostAddOperation"
case .execute: return "Execute"
case .postDidExecute: return "PostExecute"
case .postDidCancel: return "PostDidCancel"
case .finish: return "Finish"
case .postDidFinish: return "PostFinish"
}
}
}
internal let event: Kind
internal let group: DispatchGroup
fileprivate let procedure: ProcedureProtocol
private let isDerivedEvent: Bool
internal init(forProcedure procedure: ProcedureProtocol, withGroup group: DispatchGroup = DispatchGroup(), withEvent event: Kind) {
self.group = group
self.procedure = procedure
self.event = event
self.isDerivedEvent = false
group.enter()
}
// Ensures that a block is executed prior to the event described by the `PendingEvent`
public func doBeforeEvent(block: () -> Void) {
group.enter()
block()
group.leave()
}
// Ensures that the call to this function will occur prior to the event described by the `PendingEvent`
public func doThisBeforeEvent() {
group.enter()
group.leave()
}
deinit {
debugProceed()
group.leave()
}
private func debugProceed() {
(procedure as? Procedure)?.system.verbose.message("(\(self)) is ready to proceed")
}
public var description: String {
return "Pending\(event.description) for: \(procedure.procedureName)"
}
}
internal extension PendingEvent {
static let postDidAttach: (Procedure) -> PendingEvent = { PendingEvent(forProcedure: $0, withEvent: .postDidAttach) }
static let addOperation: (Procedure) -> PendingEvent = { PendingEvent(forProcedure: $0, withEvent: .addOperation) }
static let postDidAdd: (Procedure) -> PendingEvent = { PendingEvent(forProcedure: $0, withEvent: .postDidAddOperation) }
static let execute: (Procedure) -> PendingEvent = { PendingEvent(forProcedure: $0, withEvent: .execute) }
static let postDidExecute: (Procedure) -> PendingEvent = { PendingEvent(forProcedure: $0, withEvent: .postDidExecute) }
static let postDidCancel: (Procedure) -> PendingEvent = { PendingEvent(forProcedure: $0, withEvent: .postDidCancel) }
static let finish: (Procedure) -> PendingEvent = { PendingEvent(forProcedure: $0, withEvent: .finish) }
static let postFinish: (Procedure) -> PendingEvent = { PendingEvent(forProcedure: $0, withEvent: .postDidFinish) }
}
public typealias PendingExecuteEvent = PendingEvent
public typealias PendingFinishEvent = PendingEvent
public typealias PendingAddOperationEvent = PendingEvent
| 39.264 | 135 | 0.685615 |
acbaa09e7d91ea58f8ab740a889d00bb22a670fc | 15,600 | //
// DocumentsTableViewController.swift
// ImageGallery
//
// Created by Ruben on 1/20/18.
// Copyright © 2018 Ruben. All rights reserved.
//
import UIKit
///
/// Controller that allows the user to navigate through the list of documents (galleries),
/// rename them, delete them and/or create new ones.
///
class DocumentsTableViewController: UITableViewController {
///
/// User pressed the add ("+") document button
///
@IBAction func AddDocumentPressed(_ sender: Any) {
newDocumentPrompt()
}
///
/// Types of section the tableView displays
///
private enum Section {
///
/// Regular galleries. The ones the user can view and select.
///
case regularDocuments
///
/// Deleted galleries. When user swipes to delete a gallery from the
/// regularDocuments section, it goes into this "deleted" section
///
case deletedDocuments
///
/// Unknown section. The provided sectionIndex was not valid.
///
case unknown
///
/// Create a `Section` object from the given section index.
///
init(_ sectionIndex: Int) {
switch sectionIndex {
case 0: self = .regularDocuments
case 1: self = .deletedDocuments
default: self = .unknown
}
}
///
/// Get the section-index value for the current case
///
var index: Int {
switch self {
case .regularDocuments: return 0
case .deletedDocuments: return 1
case .unknown: return 2
}
}
}
///
/// Get the `ImageGallery` for the given indexPath
///
private func gallery(at indexPath: IndexPath) -> ImageGallery {
return Database.documents[indexPath.section][indexPath.row]
}
///
/// Get the `Section` for the given indexPath
///
private func section(at indexPath: IndexPath) -> Section {
return Section(indexPath.section)
}
///
/// Get the `Section` for the given section index
///
private func section(at sectionIndex: Int) -> Section {
return Section(sectionIndex)
}
///
/// Move gallery from the given `indexPath` into the given `section`
///
private func moveGallery(from indexPath: IndexPath, to section: Section) {
// Delete from model
guard let deletedGallery = Database.deleteDocument(section: indexPath.section, row: indexPath.row) else {
return
}
// Update view
tableView.deleteRows(at: [indexPath], with: .automatic)
// Insert the deleted gallery into the "deleted" section
// Insert into model
let insertIndex = IndexPath(row: 0, section: section.index)
Database.insert(deletedGallery, section: insertIndex.section, row: insertIndex.row)
// Insert into view
tableView.insertRows(at: [insertIndex], with: .automatic)
}
///
/// Delete the gallery at the given `indexPath`
///
private func deleteGallery(at indexPath: IndexPath) {
// Update model
Database.deleteDocument(section: indexPath.section, row: indexPath.row)
// Update view
tableView.deleteRows(at: [indexPath], with: .automatic)
}
}
//
// DataSource methods
//
extension DocumentsTableViewController {
///
/// Number of sections available
///
override func numberOfSections(in tableView: UITableView) -> Int {
// How many documents do we have?
return Database.documents.count
}
///
/// Get cell for the given indexPath
///
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Deque cell from given identifier
let cell = tableView.dequeueReusableCell(withIdentifier: Settings.StoryboardIdentifiers.DocumentCell, for: indexPath)
// Setup cell's name and style
cell.textLabel?.text = gallery(at: indexPath).name
cell.selectionStyle = selectionStyle(forRowAt: indexPath)
// Return it
return cell
}
///
/// Determine the cell's selection-style for the given indexPath. For instance, cells in the "deleted"
/// section should not be selectable.
///
private func selectionStyle(forRowAt indexPath: IndexPath) -> UITableViewCellSelectionStyle {
switch section(at: indexPath) {
// Regular documents: allow for selecetion
case .regularDocuments:
return .default
// Other(s): not selectable
case .deletedDocuments,
.unknown:
return .none
}
}
///
/// Number of rows in given section
///
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// How many elements the section has?
return Database.documents[section].count
}
///
/// Get the title for the given section
///
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return headerTitle(for: self.section(at: section))
}
///
/// Get a header title for the given section
///
private func headerTitle(for section: Section) -> String {
switch section {
case .regularDocuments:
return "My Galleries"
case .deletedDocuments:
return "Deleted Galleries"
case .unknown:
return "?"
}
}
}
//
// SWIPE:
// - Left: delte
// - Right: undelete (if gallery is deleted)
//
extension DocumentsTableViewController {
///
/// Is the given row editable?
///
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// All cells can be edited (i.e. to delete/undelete them)
return true
}
///
/// Swipe to delete
///
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Process a "swipeToDelete" action
processSwipeToDelete(at: indexPath)
}
}
///
/// Process a "swipe-to-delete" action. This might be:
/// - Move gallery to "deleted" documents, or...
/// - Permanently delete the gallery
///
private func processSwipeToDelete(at indexPath: IndexPath) {
switch section(at: indexPath) {
// Documents in "regular" section are moved to the "deleted" section
case .regularDocuments:
moveGallery(from: indexPath, to: .deletedDocuments)
// Documents in "deleted" section are permanently deleted
case .deletedDocuments:
deleteGallery(at: indexPath)
// Ignore other(s)
case .unknown:
break
}
}
///
/// Leading swipe (left to right)
///
override func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
// Determine swipe actions based on indexPath
return leadingSwipeActionsConfiguration(forRowAt: indexPath)
}
///
/// What to do for leadingSwipe gestures
///
private func leadingSwipeActionsConfiguration(forRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration {
// Actions vary based on indexPath
let actions = leadingSwipeActions(at: indexPath)
return UISwipeActionsConfiguration(actions: actions)
}
///
/// What to do for leadingSwipe gestures based on indexPath
///
private func leadingSwipeActions(at indexPath: IndexPath) -> [UIContextualAction] {
switch section(at: indexPath) {
// Deleted documents can swipe to "undelete"
case .deletedDocuments:
return leadingSwipeToUndeleteActions(at: indexPath)
// Ignore other(s)
default:
return []
}
}
///
/// User swiped to undelete gallery at indexPath
///
private func leadingSwipeToUndeleteActions(at indexPath: IndexPath) -> [UIContextualAction] {
// Setup action
let undeleteAction = UIContextualAction(style: .normal, title: "Recover") { (action, view, completion) in
// Move gallery to "regularDocuments" section
self.moveGallery(from: indexPath, to: .regularDocuments)
completion(true)
}
// Configure action
undeleteAction.backgroundColor = #colorLiteral(red: 0.2392156869, green: 0.6745098233, blue: 0.9686274529, alpha: 1)
// Return it
return [undeleteAction]
}
}
//
// NAVIGATION
//
extension DocumentsTableViewController {
///
/// Determine if segueing is allowed
///
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
switch identifier {
// Only supported segue (from this controller) is `ShowGallery`
case Settings.StoryboardSegues.ShowGallery:
// Determine if the selected cell should be allowed to segue
let cell = sender as! UITableViewCell
return shouldShowGallery(for: cell)
default:
return false
}
}
///
/// Whether or not the given `cell` should be allowed to segue
///
private func shouldShowGallery(for cell: UITableViewCell) -> Bool {
// Make sure there's an indexPath for the given cell
guard let indexPath = tableView.indexPath(for: cell) else {
return false
}
switch section(at: indexPath) {
// Cells from "regularDocuments" section can segue to show the actual gallery
case .regularDocuments:
return true
// Other(s) (i.e. deleted galleries) cannot segue
default:
return false
}
}
///
/// Prepare for segue
///
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// All segues must contain an identifier
guard let identifier = segue.identifier else {
return
}
switch identifier {
// `ShowGallery`
case Settings.StoryboardSegues.ShowGallery:
// Sender must be a table view cell
let cell = sender as! UITableViewCell
// Do `ShowGallery` segue for the given cell
showGallery(segue: segue, cell: cell)
default:
break
}
}
///
/// Do `ShowGallery` segue for the given cell
///
private func showGallery(segue: UIStoryboardSegue, cell: UITableViewCell) {
// Make sure there's an indexPath for the given cell
guard let indexPath = tableView.indexPath(for: cell) else {
return
}
// Make sure we're segueing to a `GalleryViewController`
guard let galleryVC = segue.destination.contents as? GalleryViewController else {
return
}
// Setup/prepare the controller
galleryVC.gallery = gallery(at: indexPath)
}
}
//
// RENAME galleries
//
extension DocumentsTableViewController {
///
/// Handle the tapping of the accessory button. Allows user to rename the gallery.
///
override func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) {
renameGalleryPrompt(at: indexPath)
}
///
/// Prompt the user for the oportunity to rename the gallery at the given indexPath
///
private func renameGalleryPrompt(at indexPath: IndexPath) {
// A pop-up alert will ask the user for a new name
let alert = UIAlertController(title: "Rename Gallery", message: nil, preferredStyle: .alert)
// Option #1: After providing a new name, the user can submit/accept the rename action
let ok = UIAlertAction(title: "Rename", style: .default) { (action) in
// Alert must contain a textField where new name is provided
let inputTextField = alert.textFields![0]
// Use the newName provided by the user, or default to something else if none is set
let newName = inputTextField.text ?? "[Unnamed]"
// Rename the gallery
self.renameGallery(newName: newName, at: indexPath)
}
// Option #2: Cancel the renaming (does nothing = ignores renaming)
let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
// Add both actions to our alert
alert.addAction(ok)
alert.addAction(cancel)
// Add a textfield to allow the user for input
alert.addTextField { (textField) in
textField.placeholder = "New name..."
textField.autocapitalizationType = .words
}
// Present the alert
present(alert, animated: true)
}
///
/// Rename gallery at `indexPath` using the `newName`
///
private func renameGallery(newName: String, at indexPath: IndexPath) {
Database.rename(newName, section: indexPath.section, row: indexPath.row)
tableView.reloadRows(at: [indexPath], with: .automatic)
}
}
//
// Create new document
//
extension DocumentsTableViewController {
///
/// Prompt the user to create a new document (i.e. provide name)
///
private func newDocumentPrompt() {
let alert = UIAlertController(title: "New Gallery", message: nil, preferredStyle: .alert)
// Add input textfield to the alert
alert.addTextField { (textField) in
// Ask for gallery name
textField.placeholder = "Name..."
// Make textfield autocapitalize words
textField.autocapitalizationType = .words
}
// Option #1: Ok/accept
let okAction = UIAlertAction(title: "Create", style: .default) { (action) in
let inputTextField = alert.textFields![0]
let newName = inputTextField.text ?? "[Unnamed]"
self.insertNewDocument(name: newName)
}
// Option #2: Cancel
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel)
// Add actions and present the alert
alert.addAction(okAction)
alert.addAction(cancelAction)
present(alert, animated: true)
}
///
/// Insert a new document/gallery at the beginning of the "regularDocuments" section with the given `name`
///
private func insertNewDocument(name: String) {
// Create new gallery with the given name
let gallery = ImageGallery(name: name, items: [])
// Insert at the beginning of the "regularDocuments" section
let indexPathInsertion = IndexPath(row: 0, section: Section.regularDocuments.index)
// Update model
Database.insert(gallery, section: indexPathInsertion.section, row: indexPathInsertion.row)
// Update view
tableView.insertRows(at: [indexPathInsertion], with: .automatic)
}
}
| 31.515152 | 150 | 0.599808 |
092a0a59fa6332fde5fcaf34629eb9eacb74663e | 5,118 | //
// CGXFixedTopGeneralTitleView.swift
// LXFMenuPageControllerDemo
//
// Created by 曹贵鑫 on 2018/7/21.
// Copyright © 2018年 LXF. All rights reserved.
//
import UIKit
@objc protocol CGXFixedTopGeneralMainViewDelgate:NSObjectProtocol {
@objc optional func selectIndexCGXFixedTopGeneralMainView(baseView:UIView,index:NSInteger) -> Void
}
class CGXFixedTopGeneralMainView: UIView,UIScrollViewDelegate {
fileprivate var mainScrollView = UIScrollView()
fileprivate var vcArray: [UIViewController] = [UIViewController]()
fileprivate var currentSelected:NSInteger = 0
//标签给外部提供的方法
weak var delegate:CGXFixedTopGeneralMainViewDelgate?
override init(frame: CGRect) {
super.init(frame: frame)
self.vcArray = NSMutableArray.init() as! [UIViewController]
}
//加载数据
func loadMainVC(vcAry:[UIViewController],currentSelected:Int,isScroller:Bool) {
self.mainScrollView.isScrollEnabled = isScroller
configMenuMainView()
self.currentSelected = currentSelected;
vcArray = vcAry;
configSubview()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
}
// MARK:- 配置子标题
extension CGXFixedTopGeneralMainView {
fileprivate func configMenuMainView() {
mainScrollView = UIScrollView()
mainScrollView.frame = CGRect.init(x: 0, y: 0, width: self.bounds.size.width, height: self.bounds.size.height)
self.addSubview(mainScrollView)
mainScrollView.showsVerticalScrollIndicator = false
mainScrollView.showsHorizontalScrollIndicator = false
mainScrollView.bounces = false
mainScrollView.isPagingEnabled = true
//设置内容区域
mainScrollView.contentSize = CGSize.init(width: self.frame.size.width, height:self.frame.size.height)
//设置代理
mainScrollView.delegate = self
//滚动矩形区域到可见的区域,如果完全可见就不做任何操作
mainScrollView.scrollRectToVisible(CGRect.init(x: 0, y: 0, width: mainScrollView.frame.size.width, height: mainScrollView.frame.size.height), animated: true)
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
if scrollView == mainScrollView{
let inter = NSInteger(scrollView.contentOffset.x / self.bounds.width)
if self.currentSelected != inter{
self.currentSelected = inter
if self.delegate != nil && (self.delegate?.responds(to: #selector(CGXFixedTopGeneralMainViewDelgate.selectIndexCGXFixedTopGeneralMainView(baseView:index:))))!{
self.delegate?.selectIndexCGXFixedTopGeneralMainView!(baseView: self, index: inter)
}
}
}
}
func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
if scrollView == mainScrollView{
let inter = NSInteger(scrollView.contentOffset.x / self.bounds.width)
if self.currentSelected != inter{
self.currentSelected = inter
if self.delegate != nil && (self.delegate?.responds(to: #selector(CGXFixedTopGeneralMainViewDelgate.selectIndexCGXFixedTopGeneralMainView(baseView:index:))))!{
self.delegate?.selectIndexCGXFixedTopGeneralMainView!(baseView: self, index: inter)
}
}
}
}
}
// MARK:- 配置子标题
extension CGXFixedTopGeneralMainView {
fileprivate func configSubview() {
for index in 0..<vcArray.count {
var vc = UIViewController.init()
vc = vcArray[index]
vc.view.frame = CGRect.init(x: CGFloat(index) * self.bounds.width, y: 0, width: mainScrollView.frame.size.width, height: mainScrollView.frame.size.height)
self.viewController(self)?.addChild(vc)
mainScrollView.addSubview(vc.view)
}
//设置内容区域
mainScrollView.contentSize = CGSize.init(width: self.bounds.width*CGFloat(vcArray.count), height:mainScrollView.frame.size.height)
}
func viewController(_ view: UIView?) -> UIViewController? {
var next = view?.superview
while (next != nil) {
let nextResponder: UIResponder? = next?.next
if (nextResponder is UINavigationController) || (nextResponder is UIViewController) {
return nextResponder as? UIViewController
}
next = next?.superview
}
return nil
}
}
// MARK:- 配置子标题
extension CGXFixedTopGeneralMainView {
func selectIndexWithCGXFixedTopGeneralMainView(index:NSInteger) {
//就变到倒数第二张的位置上
mainScrollView.scrollRectToVisible(CGRect.init(x: self.bounds.width*CGFloat(index), y: 0, width: mainScrollView.frame.size.width, height: mainScrollView.frame.size.height), animated: false)
}
}
| 37.357664 | 197 | 0.668621 |
33c915a22530800e5fcb2d41a7711fcf152d1c48 | 1,230 | //
// GameViewController.swift
// WordsPermutated
//
// Created by user913992 on 1/5/19.
// Copyright © 2019 nlharri. All rights reserved.
//
import UIKit
import SpriteKit
import GameplayKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let view = self.view as! SKView? {
// Load the SKScene from 'GameScene.sks'
if let scene = SKScene(fileNamed: "GameScene") {
// Set the scale mode to scale to fit the window
scene.scaleMode = .aspectFill
// Present the scene
view.presentScene(scene)
}
view.ignoresSiblingOrder = true
view.showsFPS = true
view.showsNodeCount = true
}
}
override var shouldAutorotate: Bool {
return true
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
if UIDevice.current.userInterfaceIdiom == .phone {
return .allButUpsideDown
} else {
return .all
}
}
override var prefersStatusBarHidden: Bool {
return true
}
}
| 24.117647 | 77 | 0.570732 |
d58714bbe5542270442991fdf3e8dbc426e5e686 | 7,971 | // GymfileProtocol.swift
// Copyright (c) 2021 FastlaneTools
public protocol GymfileProtocol: class {
/// Path to the workspace file
var workspace: String? { get }
/// Path to the project file
var project: String? { get }
/// The project's scheme. Make sure it's marked as `Shared`
var scheme: String? { get }
/// Should the project be cleaned before building it?
var clean: Bool { get }
/// The directory in which the ipa file should be stored in
var outputDirectory: String { get }
/// The name of the resulting ipa file
var outputName: String? { get }
/// The configuration to use when building the app. Defaults to 'Release'
var configuration: String? { get }
/// Hide all information that's not necessary while building
var silent: Bool { get }
/// The name of the code signing identity to use. It has to match the name exactly. e.g. 'iPhone Distribution: SunApps GmbH'
var codesigningIdentity: String? { get }
/// Should we skip packaging the ipa?
var skipPackageIpa: Bool { get }
/// Should we skip packaging the pkg?
var skipPackagePkg: Bool { get }
/// Should the ipa file include symbols?
var includeSymbols: Bool? { get }
/// Should the ipa file include bitcode?
var includeBitcode: Bool? { get }
/// Method used to export the archive. Valid values are: app-store, validation, ad-hoc, package, enterprise, development, developer-id and mac-application
var exportMethod: String? { get }
/// Path to an export options plist or a hash with export options. Use 'xcodebuild -help' to print the full set of available options
var exportOptions: [String: Any]? { get }
/// Pass additional arguments to xcodebuild for the package phase. Be sure to quote the setting names and values e.g. OTHER_LDFLAGS="-ObjC -lstdc++"
var exportXcargs: String? { get }
/// Export ipa from previously built xcarchive. Uses archive_path as source
var skipBuildArchive: Bool? { get }
/// After building, don't archive, effectively not including -archivePath param
var skipArchive: Bool? { get }
/// Build without codesigning
var skipCodesigning: Bool? { get }
/// Platform to build when using a Catalyst enabled app. Valid values are: ios, macos
var catalystPlatform: String? { get }
/// Full name of 3rd Party Mac Developer Installer or Developer ID Installer certificate. Example: `3rd Party Mac Developer Installer: Your Company (ABC1234XWYZ)`
var installerCertName: String? { get }
/// The directory in which the archive should be stored in
var buildPath: String? { get }
/// The path to the created archive
var archivePath: String? { get }
/// The directory where built products and other derived data will go
var derivedDataPath: String? { get }
/// Should an Xcode result bundle be generated in the output directory
var resultBundle: Bool { get }
/// Path to the result bundle directory to create. Ignored if `result_bundle` if false
var resultBundlePath: String? { get }
/// The directory where to store the build log
var buildlogPath: String { get }
/// The SDK that should be used for building the application
var sdk: String? { get }
/// The toolchain that should be used for building the application (e.g. com.apple.dt.toolchain.Swift_2_3, org.swift.30p620160816a)
var toolchain: String? { get }
/// Use a custom destination for building the app
var destination: String? { get }
/// Optional: Sometimes you need to specify a team id when exporting the ipa file
var exportTeamId: String? { get }
/// Pass additional arguments to xcodebuild for the build phase. Be sure to quote the setting names and values e.g. OTHER_LDFLAGS="-ObjC -lstdc++"
var xcargs: String? { get }
/// Use an extra XCCONFIG file to build your app
var xcconfig: String? { get }
/// Suppress the output of xcodebuild to stdout. Output is still saved in buildlog_path
var suppressXcodeOutput: Bool? { get }
/// Disable xcpretty formatting of build output
var disableXcpretty: Bool? { get }
/// Use the test (RSpec style) format for build output
var xcprettyTestFormat: Bool? { get }
/// A custom xcpretty formatter to use
var xcprettyFormatter: String? { get }
/// Have xcpretty create a JUnit-style XML report at the provided path
var xcprettyReportJunit: String? { get }
/// Have xcpretty create a simple HTML report at the provided path
var xcprettyReportHtml: String? { get }
/// Have xcpretty create a JSON compilation database at the provided path
var xcprettyReportJson: String? { get }
/// Analyze the project build time and store the output in 'culprits.txt' file
var analyzeBuildTime: Bool? { get }
/// Have xcpretty use unicode encoding when reporting builds
var xcprettyUtf: Bool? { get }
/// Do not try to build a profile mapping from the xcodeproj. Match or a manually provided mapping should be used
var skipProfileDetection: Bool { get }
/// Sets a custom path for Swift Package Manager dependencies
var clonedSourcePackagesPath: String? { get }
/// Skips resolution of Swift Package Manager dependencies
var skipPackageDependenciesResolution: Bool { get }
/// Prevents packages from automatically being resolved to versions other than those recorded in the `Package.resolved` file
var disablePackageAutomaticUpdates: Bool { get }
/// Lets xcodebuild use system's scm configuration
var useSystemScm: Bool { get }
}
public extension GymfileProtocol {
var workspace: String? { return nil }
var project: String? { return nil }
var scheme: String? { return nil }
var clean: Bool { return false }
var outputDirectory: String { return "." }
var outputName: String? { return nil }
var configuration: String? { return nil }
var silent: Bool { return false }
var codesigningIdentity: String? { return nil }
var skipPackageIpa: Bool { return false }
var skipPackagePkg: Bool { return false }
var includeSymbols: Bool? { return nil }
var includeBitcode: Bool? { return nil }
var exportMethod: String? { return nil }
var exportOptions: [String: Any]? { return nil }
var exportXcargs: String? { return nil }
var skipBuildArchive: Bool? { return nil }
var skipArchive: Bool? { return nil }
var skipCodesigning: Bool? { return nil }
var catalystPlatform: String? { return nil }
var installerCertName: String? { return nil }
var buildPath: String? { return nil }
var archivePath: String? { return nil }
var derivedDataPath: String? { return nil }
var resultBundle: Bool { return false }
var resultBundlePath: String? { return nil }
var buildlogPath: String { return "~/Library/Logs/gym" }
var sdk: String? { return nil }
var toolchain: String? { return nil }
var destination: String? { return nil }
var exportTeamId: String? { return nil }
var xcargs: String? { return nil }
var xcconfig: String? { return nil }
var suppressXcodeOutput: Bool? { return nil }
var disableXcpretty: Bool? { return nil }
var xcprettyTestFormat: Bool? { return nil }
var xcprettyFormatter: String? { return nil }
var xcprettyReportJunit: String? { return nil }
var xcprettyReportHtml: String? { return nil }
var xcprettyReportJson: String? { return nil }
var analyzeBuildTime: Bool? { return nil }
var xcprettyUtf: Bool? { return nil }
var skipProfileDetection: Bool { return false }
var clonedSourcePackagesPath: String? { return nil }
var skipPackageDependenciesResolution: Bool { return false }
var disablePackageAutomaticUpdates: Bool { return false }
var useSystemScm: Bool { return false }
}
// Please don't remove the lines below
// They are used to detect outdated files
// FastlaneRunnerAPIVersion [0.9.76]
| 39.855 | 166 | 0.692761 |
2fe33e76706b5c4b3f83147d8eae66d84ea1b8fe | 886 | //
// Hard124.swift
// SwiftLeetcodeTests
//
// Created by roosky on 3/2/19.
// Copyright © 2019 K W. All rights reserved.
//
import UIKit
/**
124. Binary Tree Maximum Path Sum
https://leetcode.com/problems/binary-tree-maximum-path-sum/
time: O(n)
space: O(logn), height of the tree
**/
class Hard124: NSObject {
var maxSum = Int.min
func maxPathSum(_ root: TreeNode?) -> Int {
if root == nil {
return 0
}
_ = dfs(root);
return maxSum;
}
func dfs(_ root: TreeNode?)-> Int {
guard let r = root else {
return 0
}
let leftMaxSum = max(dfs(r.left), 0)
let rightMaxSum = max(dfs(r.right), 0)
let sumNode = r.val + leftMaxSum + rightMaxSum;
self.maxSum = max(sumNode, self.maxSum)
return max(leftMaxSum, rightMaxSum) + r.val
}
}
| 22.15 | 59 | 0.563205 |
76522d20ab29cd7d88a39852fa6b852e6eb8c546 | 3,249 | //
// MUEmptyStateControl.swift
//
// Created by Dmitry Smirnov on 01/02/2019.
// Copyright © 2019 MobileUp LLC. All rights reserved.
//
import UIKit
// MARK: - MUEmptyStateControl
open class MUEmptyStateControl: NSObject {
public enum Style {
case none
case table
case view
}
// MARK: - Public properties
open weak var emptyView: UIView?
open var style: Style = .table
open var isHidden: Bool = true { didSet { updateVisibility() } }
// MARK: - Private properties
private weak var contentView: UIView?
private weak var emptyTableView: UITableView?
private let refreshControl = MURefreshControl()
// MARK: - Public methods
open func setup(with controller: MUListController) {
style = controller.emptyStateStyle
contentView = controller.tableView ?? controller.collectionView
switch style {
case .none:
return
case .table:
configureEmptyState(with: controller.hasRefresh ? controller.refreshControl : nil)
case .view:
configureEmptyState()
}
updateVisibility()
}
open func stopAnimation() {
refreshControl.stopAnimation()
}
open func updateLayout() {
emptyTableView?.viewForFooter(with: emptyView)
}
// MARK: - Private methods
private func configureEmptyState(with refreshControl: MURefreshControl?) {
guard self.emptyTableView == nil, let contentView = contentView else { return }
let emptyTableView = UITableView(frame: contentView.frame)
emptyTableView.backgroundColor = .clear
emptyTableView.viewForFooter(with: emptyView)
contentView.superview?.insertSubview(emptyTableView, at: 0)
emptyTableView.appendConstraints(to: contentView)
self.emptyTableView = emptyTableView
guard let refreshControl = refreshControl else { return }
refreshControl.setup(
with : emptyTableView,
delegate : refreshControl.delegate,
tintColor : refreshControl.tintColor
)
}
private func configureEmptyState() {
guard let emptyView = emptyView else {
assertionFailure("Missing empty view for \(self)")
return
}
guard let conterParentView = contentView?.superview else {
assertionFailure("Missing parent view for content view in \(self)")
return
}
conterParentView.layoutSubview(emptyView, safe: true)
}
private func updateVisibility() {
contentView?.isHidden = isHidden == false
switch style {
case .none:
break
case .table:
updateTableVisibility()
case .view:
updateViewVisibility()
}
}
private func updateTableVisibility() {
emptyTableView?.isHidden = isHidden
emptyTableView?.setFooterVisibility(asHidden: isHidden)
}
private func updateViewVisibility() {
emptyView?.isHidden = isHidden
}
}
| 22.406897 | 94 | 0.601108 |
f9ab34fd0484299e3b4c77b8caeca48879afda08 | 1,318 | // ___FILEHEADER___
import UIKit
protocol AppStateProtocol {
static var shared: AppStateProtocol { get }
func reset()
var isAuthenticated: Bool { get set }
var onboardingWasShown: Bool { get set }
var username: String? { get set }
}
class AppState: AppStateProtocol {
private let defaults: UserDefaults!
static var shared: AppStateProtocol = AppState(defaults: UserDefaults.standard)
init(defaults: UserDefaults) {
self.defaults = defaults
}
// MARK: - Methods
public func reset() {
defaults.dictionaryRepresentation().keys.forEach(defaults.removeObject(forKey:))
}
// MARK: - State Variables
private enum Key {
static let isAuthenticated = "isAuthenticated"
static let onboardingWasShown = "onboardingWasShown"
static let username = "username"
}
var isAuthenticated: Bool {
get { return defaults.bool(forKey: Key.isAuthenticated) }
set { defaults.set(newValue, forKey: Key.isAuthenticated) }
}
var onboardingWasShown: Bool {
get { return defaults.bool(forKey: Key.onboardingWasShown) }
set { defaults.set(newValue, forKey: Key.onboardingWasShown) }
}
var username: String? {
get { return defaults.string(forKey: Key.username) ?? nil }
set { defaults.set(newValue, forKey: Key.username) }
}
}
| 24.407407 | 84 | 0.694992 |
5df726274af37ebe01f2d39a847b74fa01f16636 | 2,863 | //
// Copyright 2016 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.
//
public func EarlGrey() -> EarlGreyImpl {
return EarlGreyImpl.invokedFromFile(#file, lineNumber: #line)
}
public func GREYAssert(@autoclosure expression: () -> BooleanType, reason: String) {
GREYAssert(expression, reason, details: "Expected expression to be true")
}
public func GREYAssertTrue(@autoclosure expression: () -> BooleanType, reason: String) {
GREYAssert(expression().boolValue,
reason,
details: "Expected the boolean expression to be true")
}
public func GREYAssertFalse(@autoclosure expression: () -> BooleanType, reason: String) {
GREYAssert(!expression().boolValue,
reason,
details: "Expected the boolean expression to be true")
}
public func GREYAssertNotNil(@autoclosure expression: () -> Any?, reason: String) {
GREYAssert(expression() != nil, reason, details: "Expected expression to be not nil")
}
public func GREYAssertNil(@autoclosure expression: () -> Any?, reason: String) {
GREYAssert(expression() == nil, reason, details: "Expected expression to be nil")
}
public func GREYAssertEqual<T : Equatable>(@autoclosure left: () -> T?,
@autoclosure _ right: () -> T?, reason: String) {
GREYAssert(left() == right(), reason, details: "Expeted left term to be equal to right term")
}
public func GREYFail(reason: String) {
greyFailureHandler.handleException(GREYFrameworkException(name: kGREYAssertionFailedException,
reason: reason),
details: "")
}
public func GREYFail(reason: String, details: String) {
greyFailureHandler.handleException(GREYFrameworkException(name: kGREYAssertionFailedException,
reason: reason),
details: details)
}
private func GREYAssert(@autoclosure expression: () -> BooleanType,
_ reason: String, details: String) {
GREYSetCurrentAsFailable()
if !expression().boolValue {
greyFailureHandler.handleException(GREYFrameworkException(name: kGREYAssertionFailedException,
reason: reason),
details: details)
}
}
private func GREYSetCurrentAsFailable() {
let greyFailureHandlerSelector =
#selector(GREYFailureHandler.setInvocationFile(_:andInvocationLine:))
if greyFailureHandler.respondsToSelector(greyFailureHandlerSelector) {
greyFailureHandler.setInvocationFile!(#file, andInvocationLine: #line)
}
}
| 36.240506 | 98 | 0.736989 |
ebc90de5f311c7363e7d98ad9211db94ecf7546a | 2,237 | import Foundation
import UIKit
public protocol NavigablePresenting: Presenter {
/// The `navigationController` which can push `viewControllers`
var navigationController: UINavigationController? { get }
/// Pushes the `viewController` on the `navigationController`
/// - parameters:
/// - viewController: The `viewController` which should be pushed
/// - animated: A flag that defines if the push should be animated
func push(_ viewController: UIViewController, animated: Bool)
/// Pops the `viewController` from the `navigationController` but only if it is the topViewController of the
/// ViewController stack of the `navigationController`
/// - parameters:
/// - viewController: The `viewController` which should be popped
/// - animated: A flag that defines if the pop should be animated
func pop(_ viewController: UIViewController, animated: Bool)
}
// swiftLint:disable multiline_arguments_brackets
extension NavigablePresenting {
public func push(_ viewController: UIViewController, animated: Bool) {
guard let navigationController = navigationController else {
NSLog("⚠️ UINavigationController is nil in %@ - \(#function).", String(describing: self))
return
}
navigationController.pushViewController(viewController, animated: animated)
}
public func pop(_ viewController: UIViewController, animated: Bool) {
guard let navigationController = navigationController else {
NSLog(
"⚠️ UINavigationController is nil in %@ - \(#function), while trying to push UIViewController %@",
String(describing: self),
String(describing: viewController)
)
return
}
guard navigationController.topViewController === viewController else {
NSLog(
"⚠️ \(#function) Trying to pop UIViewController %@ which is not the TopViewController of UINavigationController in %@",
String(describing: viewController),
String(describing: self)
)
return
}
navigationController.popViewController(animated: animated)
}
}
| 39.245614 | 135 | 0.663388 |
f522705b6193e8a4f9bd203a155c1e1d699e63cc | 18,944 | // The MIT License (MIT)
//
// Copyright (c) 2015-2021 Alexander Grebenyuk (github.com/kean).
import Foundation
/// `ImagePipeline` is the primary way to load images directly (without a UI).
///
/// The pipeline is fully customizable. You can change its configuration using
/// `ImagePipeline.Configuration` type: set custom data loader and cache, configure
/// image encoders and decoders, etc. You can also set an `ImagePipelineDelegate`
/// to get even more granular control on a per-request basis.
///
/// See ["Image Pipeline"](https://kean.blog/nuke/guides/image-pipeline) to learn
/// more about how to use the pipeline. You can also learn about they way it
/// works internally in a [dedicated guide](https://kean.blog/nuke/guides/image-pipeline-guide).
///
/// `ImagePipeline` also suppors Combine. You can learn more in a dedicated
/// [guide](https://kean.blog/nuke/guides/combine) with some common use-cases.
///
/// `ImagePipeline` is fully thread-safe.
public final class ImagePipeline {
/// Shared image pipeline.
public static var shared = ImagePipeline(configuration: .withURLCache)
/// The pipeline configuration.
public let configuration: Configuration
/// Provides access to the underlying caching subsystems.
public var cache: ImagePipeline.Cache { ImagePipeline.Cache(pipeline: self) }
// Deprecated in 10.0.0
@available(*, deprecated, message: "Please use ImagePipelineDelegate")
public var observer: ImagePipelineObserving?
let delegate: ImagePipelineDelegate // swiftlint:disable:this all
private(set) var imageCache: ImageCache?
private var tasks = [ImageTask: TaskSubscription]()
private let tasksLoadData: TaskPool<ImageLoadKey, (Data, URLResponse?), Error>
private let tasksLoadImage: TaskPool<ImageLoadKey, ImageResponse, Error>
private let tasksFetchDecodedImage: TaskPool<DecodedImageLoadKey, ImageResponse, Error>
private let tasksFetchOriginalImageData: TaskPool<DataLoadKey, (Data, URLResponse?), Error>
private let tasksProcessImage: TaskPool<ImageProcessingKey, ImageResponse, Swift.Error>
// The queue on which the entire subsystem is synchronized.
let queue = DispatchQueue(label: "com.github.kean.Nuke.ImagePipeline", qos: .userInitiated)
private var isInvalidated = false
private var nextTaskId: Int64 { OSAtomicIncrement64(_nextTaskId) }
private let _nextTaskId: UnsafeMutablePointer<Int64>
let rateLimiter: RateLimiter?
let id = UUID()
deinit {
_nextTaskId.deallocate()
ResumableDataStorage.shared.unregister(self)
#if TRACK_ALLOCATIONS
Allocations.decrement("ImagePipeline")
#endif
}
/// Initializes `ImagePipeline` instance with the given configuration.
///
/// - parameter configuration: `Configuration()` by default.
/// - parameter delegate: `nil` by default.
public init(configuration: Configuration = Configuration(), delegate: ImagePipelineDelegate? = nil) {
self.configuration = configuration
self.rateLimiter = configuration.isRateLimiterEnabled ? RateLimiter(queue: queue) : nil
self.delegate = delegate ?? ImagePipelineDefaultDelegate()
let isCoalescingEnabled = configuration.isTaskCoalescingEnabled
self.tasksLoadData = TaskPool(isCoalescingEnabled)
self.tasksLoadImage = TaskPool(isCoalescingEnabled)
self.tasksFetchDecodedImage = TaskPool(isCoalescingEnabled)
self.tasksFetchOriginalImageData = TaskPool(isCoalescingEnabled)
self.tasksProcessImage = TaskPool(isCoalescingEnabled)
self._nextTaskId = UnsafeMutablePointer<Int64>.allocate(capacity: 1)
self._nextTaskId.initialize(to: 0)
if let imageCache = configuration.imageCache as? ImageCache {
self.imageCache = imageCache
}
ResumableDataStorage.shared.register(self)
#if TRACK_ALLOCATIONS
Allocations.increment("ImagePipeline")
#endif
}
public convenience init(delegate: ImagePipelineDelegate? = nil, _ configure: (inout ImagePipeline.Configuration) -> Void) {
var configuration = ImagePipeline.Configuration()
configure(&configuration)
self.init(configuration: configuration, delegate: delegate)
}
/// Invalidates the pipeline and cancels all outstanding tasks. No new
/// requests can be started.
public func invalidate() {
queue.async {
guard !self.isInvalidated else { return }
self.isInvalidated = true
self.tasks.keys.forEach(self.cancel)
}
}
// MARK: - Loading Images
/// Loads an image for the given request.
@discardableResult public func loadImage(
with request: ImageRequestConvertible,
completion: @escaping (_ result: Result<ImageResponse, Error>) -> Void
) -> ImageTask {
loadImage(with: request, queue: nil, progress: nil, completion: completion)
}
/// Loads an image for the given request.
///
/// See [Nuke Docs](https://kean.blog/nuke/guides/image-pipeline) to learn more.
///
/// - parameter request: An image request.
/// - parameter queue: A queue on which to execute `progress` and `completion`
/// callbacks. By default, the pipeline uses `.main` queue.
/// - parameter progress: A closure to be called periodically on the main thread
/// when the progress is updated. `nil` by default.
/// - parameter completion: A closure to be called on the main thread when the
/// request is finished. `nil` by default.
@discardableResult public func loadImage(
with request: ImageRequestConvertible,
queue: DispatchQueue? = nil,
progress: ((_ response: ImageResponse?, _ completed: Int64, _ total: Int64) -> Void)?,
completion: @escaping ((_ result: Result<ImageResponse, Error>) -> Void)
) -> ImageTask {
loadImage(with: request.asImageRequest(), isConfined: false, queue: queue, progress: progress, completion: completion)
}
#if swift(>=5.5.2)
/// Loads an image for the given request.
///
/// See [Nuke Docs](https://kean.blog/nuke/guides/image-pipeline) to learn more.
///
/// - parameter request: An image request.
@available(iOS 13.0, tvOS 13.0, macOS 10.15, watchOS 6.0, *)
public func loadImage(with request: ImageRequestConvertible) async throws -> ImageResponse {
final class TaskBox {
var task: ImageTask?
}
let box = TaskBox()
return try await withTaskCancellationHandler(handler: {
box.task?.cancel()
}, operation: {
try await withUnsafeThrowingContinuation { continuation in
// The pipeline guarantees that the callbacks (either onCancel or
// completion) are called exactly once. `onCancel` is a new addition
// just for Async/Await. Ideally, the completion should be called on
// cancellation instead, but that ship has sailed. Maybe in Nuke 11.
box.task = loadImage(with: request.asImageRequest(), isConfined: false, queue: nil, progress: nil, onCancel: {
continuation.resume(throwing: CancellationError())
}, completion: {
continuation.resume(with: $0)
})
}
})
}
#endif
func loadImage(
with request: ImageRequest,
isConfined: Bool,
queue: DispatchQueue?,
progress: ((_ response: ImageResponse?, _ completed: Int64, _ total: Int64) -> Void)?,
onCancel: (() -> Void)? = nil,
completion: ((_ result: Result<ImageResponse, Error>) -> Void)?
) -> ImageTask {
let request = configuration.inheritOptions(request)
let task = ImageTask(taskId: nextTaskId, request: request, isDataTask: false)
task.pipeline = self
if let onCancel = onCancel {
task.onCancel = { [weak self] in self?.dispatchCallback(to: queue, onCancel) }
}
if isConfined {
self.startImageTask(task, callbackQueue: queue, progress: progress, completion: completion)
} else {
self.queue.async {
self.startImageTask(task, callbackQueue: queue, progress: progress, completion: completion)
}
}
return task
}
private func startImageTask(
_ task: ImageTask,
callbackQueue: DispatchQueue?,
progress progressHandler: ((ImageResponse?, Int64, Int64) -> Void)?,
completion: ((_ result: Result<ImageResponse, Error>) -> Void)?
) {
guard !isInvalidated else { return }
self.send(.started, task)
tasks[task] = makeTaskLoadImage(for: task.request)
.subscribe(priority: task._priority.taskPriority, subscriber: task) { [weak self, weak task] event in
guard let self = self, let task = task else { return }
self.send(ImageTaskEvent(event), task)
if event.isCompleted {
self.tasks[task] = nil
}
self.dispatchCallback(to: callbackQueue) {
guard !task.isCancelled else { return }
switch event {
case let .value(response, isCompleted):
if isCompleted {
completion?(.success(response))
} else {
progressHandler?(response, task.completedUnitCount, task.totalUnitCount)
}
case let .progress(progress):
task.setProgress(progress)
progressHandler?(nil, progress.completed, progress.total)
case let .error(error):
completion?(.failure(error))
}
}
}
}
// MARK: - Loading Image Data
/// Loads the image data for the given request. The data doesn't get decoded
/// or processed in any other way.
@discardableResult public func loadData(
with request: ImageRequestConvertible,
completion: @escaping (Result<(data: Data, response: URLResponse?), Error>) -> Void
) -> ImageTask {
loadData(with: request, queue: nil, progress: nil, completion: completion)
}
/// Loads the image data for the given request. The data doesn't get decoded
/// or processed in any other way.
///
/// You can call `loadImage(:)` for the request at any point after calling
/// `loadData(:)`, the pipeline will use the same operation to load the data,
/// no duplicated work will be performed.
///
/// - parameter request: An image request.
/// - parameter queue: A queue on which to execute `progress` and `completion`
/// callbacks. By default, the pipeline uses `.main` queue.
/// - parameter progress: A closure to be called periodically on the main thread
/// when the progress is updated. `nil` by default.
/// - parameter completion: A closure to be called on the main thread when the
/// request is finished.
@discardableResult public func loadData(
with request: ImageRequestConvertible,
queue: DispatchQueue? = nil,
progress: ((_ completed: Int64, _ total: Int64) -> Void)?,
completion: @escaping (Result<(data: Data, response: URLResponse?), Error>) -> Void
) -> ImageTask {
loadData(with: request.asImageRequest(), isConfined: false, queue: queue, progress: progress, completion: completion)
}
func loadData(
with request: ImageRequest,
isConfined: Bool,
queue callbackQueue: DispatchQueue?,
progress: ((_ completed: Int64, _ total: Int64) -> Void)?,
completion: @escaping (Result<(data: Data, response: URLResponse?), Error>) -> Void
) -> ImageTask {
let task = ImageTask(taskId: nextTaskId, request: request, isDataTask: true)
task.pipeline = self
if isConfined {
self.startDataTask(task, callbackQueue: callbackQueue, progress: progress, completion: completion)
} else {
self.queue.async {
self.startDataTask(task, callbackQueue: callbackQueue, progress: progress, completion: completion)
}
}
return task
}
private func startDataTask(
_ task: ImageTask,
callbackQueue: DispatchQueue?,
progress progressHandler: ((_ completed: Int64, _ total: Int64) -> Void)?,
completion: @escaping (Result<(data: Data, response: URLResponse?), Error>) -> Void
) {
guard !isInvalidated else { return }
tasks[task] = makeTaskLoadData(for: task.request)
.subscribe(priority: task._priority.taskPriority, subscriber: task) { [weak self, weak task] event in
guard let self = self, let task = task else { return }
if event.isCompleted {
self.tasks[task] = nil
}
self.dispatchCallback(to: callbackQueue) {
guard !task.isCancelled else { return }
switch event {
case let .value(response, isCompleted):
if isCompleted {
completion(.success(response))
}
case let .progress(progress):
task.setProgress(progress)
progressHandler?(progress.completed, progress.total)
case let .error(error):
completion(.failure(error))
}
}
}
}
// MARK: - Errors
/// Represents all possible image pipeline errors.
public enum Error: Swift.Error, CustomStringConvertible {
/// Data loader failed to load image data with a wrapped error.
case dataLoadingFailed(Swift.Error)
/// Decoder failed to produce a final image.
case decodingFailed
/// Processor failed to produce a final image.
case processingFailed(ImageProcessing)
public var description: String {
switch self {
case let .dataLoadingFailed(error): return "Failed to load image data: \(error)"
case .decodingFailed: return "Failed to create an image from the image data"
case .processingFailed(let processor): return "Failed to process the image using processor \(processor)"
}
}
/// Returns underlying data loading error.
public var dataLoadingError: Swift.Error? {
switch self {
case .dataLoadingFailed(let error):
return error
default:
return nil
}
}
}
// MARK: - Image Task Events
func imageTaskCancelCalled(_ task: ImageTask) {
queue.async {
self.cancel(task)
}
}
private func cancel(_ task: ImageTask) {
guard let subscription = self.tasks.removeValue(forKey: task) else { return }
if !task.isDataTask {
self.send(.cancelled, task)
}
task.onCancel?()
subscription.unsubscribe()
}
func imageTaskUpdatePriorityCalled(_ task: ImageTask, priority: ImageRequest.Priority) {
queue.async {
task._priority = priority
guard let subscription = self.tasks[task] else { return }
if !task.isDataTask {
self.send(.priorityUpdated(priority: priority), task)
}
subscription.setPriority(priority.taskPriority)
}
}
private func dispatchCallback(to callbackQueue: DispatchQueue?, _ closure: @escaping () -> Void) {
if callbackQueue === self.queue {
closure()
} else {
(callbackQueue ?? self.configuration.callbackQueue).async(execute: closure)
}
}
// MARK: - Task Factory (Private)
// When you request an image or image data, the pipeline creates a graph of tasks
// (some tasks are added to the graph on demand).
//
// `loadImage()` call is represented by TaskLoadImage:
//
// TaskLoadImage -> TaskFetchDecodedImage -> TaskFetchOriginalImageData
// -> TaskProcessImage
//
// `loadData()` call is represented by TaskLoadData:
//
// TaskLoadData -> TaskFetchOriginalImageData
//
//
// Each task represents a resource or a piece of work required to produce the
// final result. The pipeline reduces the amount of duplicated work by coalescing
// the tasks that represent the same work. For example, if you all `loadImage()`
// and `loadData()` with the same request, only on `TaskFetchOriginalImageData`
// is created. The work is split between tasks to minimize any duplicated work.
func makeTaskLoadImage(for request: ImageRequest) -> AsyncTask<ImageResponse, Error>.Publisher {
tasksLoadImage.publisherForKey(request.makeImageLoadKey()) {
TaskLoadImage(self, request)
}
}
func makeTaskLoadData(for request: ImageRequest) -> AsyncTask<(Data, URLResponse?), Error>.Publisher {
tasksLoadData.publisherForKey(request.makeImageLoadKey()) {
TaskLoadData(self, request)
}
}
func makeTaskProcessImage(key: ImageProcessingKey, process: @escaping () -> ImageResponse?) -> AsyncTask<ImageResponse, Swift.Error>.Publisher {
tasksProcessImage.publisherForKey(key) {
OperationTask(self, configuration.imageProcessingQueue, process)
}
}
func makeTaskFetchDecodedImage(for request: ImageRequest) -> AsyncTask<ImageResponse, Error>.Publisher {
tasksFetchDecodedImage.publisherForKey(request.makeDecodedImageLoadKey()) {
TaskFetchDecodedImage(self, request)
}
}
func makeTaskFetchOriginalImageData(for request: ImageRequest) -> AsyncTask<(Data, URLResponse?), Error>.Publisher {
tasksFetchOriginalImageData.publisherForKey(request.makeDataLoadKey()) {
request.publisher == nil ?
TaskFetchOriginalImageData(self, request) :
TaskFetchWithPublisher(self, request)
}
}
}
// MARK: - Misc (Private)
extension ImagePipeline: SendEventProtocol {
func send(_ event: ImageTaskEvent, _ task: ImageTask) {
delegate.pipeline(self, imageTask: task, didReceiveEvent: event)
(self as SendEventProtocol)._send(event, task)
}
// Deprecated in 10.0.0
@available(*, deprecated, message: "Please use ImagePipelineDelegate")
func _send(_ event: ImageTaskEvent, _ task: ImageTask) {
observer?.pipeline(self, imageTask: task, didReceiveEvent: event)
}
}
// Just to workaround the deprecation warning.
private protocol SendEventProtocol {
func _send(_ event: ImageTaskEvent, _ task: ImageTask)
}
| 41.004329 | 148 | 0.635241 |
290d289f555fac2b5d9e1bb44296b6624c68dba9 | 3,265 | //
// SceneDelegate.swift
// Calculator
//
// Created by Ficow on 2021/12/11.
//
import UIKit
import SwiftUI
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// Get the managed object context from the shared persistent container.
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
// Create the SwiftUI view and set the context as the value for the managedObjectContext environment keyPath.
// Add `@Environment(\.managedObjectContext)` in the views that will need the context.
let contentView = ContentView()//.environment(\.managedObjectContext, context)
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
}
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
// Save changes in the application's managed object context when the application transitions to the background.
(UIApplication.shared.delegate as? AppDelegate)?.saveContext()
}
}
| 45.985915 | 147 | 0.713629 |
39d0b37ad71de1d744b0ad9466426129357ba17a | 1,163 | //
// tumblrUITests.swift
// tumblrUITests
//
// Created by Matthew Lambert on 9/11/19.
// Copyright © 2019 Matthew Lambert. All rights reserved.
//
import XCTest
class tumblrUITests: XCTestCase {
override func setUp() {
// 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
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// 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 tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 33.228571 | 182 | 0.690456 |
fc60c9f2b0b03f8449cef019d14277918c75d2c6 | 713 | //
// ResponseObject.swift
// Retrofire
//
// Created by Stant 02 on 03/05/18.
// Copyright © 2018 Stant. All rights reserved.
//
import Foundation
import SwiftyJSON
@testable import Retrofire
public struct ResponseObject: Retrofire.Mappable {
let userId: Int?
let id: Int?
let title: String?
let body: String?
public static func instanceBy<M>(json: JSON) -> M {
let userId = json.dictionary?["userId"]?.int
let id = json.dictionary?["id"]?.int
let title = json.dictionary?["title"]?.string
let body = json.dictionary?["body"]?.string
return ResponseObject.init(userId: userId, id: id, title: title, body: body) as! M
}
}
| 25.464286 | 90 | 0.629734 |
fc23e6860a52a71afc71d24632340463c9e2f6a8 | 931 | //
// ISO8601DateFormatter.swift
// XMLParsing
//
// Created by Shawn Moore on 11/21/17.
// Copyright © 2017 Shawn Moore. All rights reserved.
//
import Foundation
#if canImport(FoundationXML)
import FoundationXML
#endif
//===----------------------------------------------------------------------===//
// Shared ISO8601 Date Formatter
//===----------------------------------------------------------------------===//
// NOTE: This value is implicitly lazy and _must_ be lazy. We're compiled against the latest SDK (w/ ISO8601DateFormatter), but linked against whichever Foundation the user has. ISO8601DateFormatter might not exist, so we better not hit this code path on an older OS.
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
internal var _iso8601Formatter: ISO8601DateFormatter = {
let formatter = ISO8601DateFormatter()
formatter.formatOptions = .withInternetDateTime
return formatter
}()
| 34.481481 | 267 | 0.625134 |
ffdf717b5415075a6aed3312038913dae0276532 | 203 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let a{struct S<T where T=A{var b=a | 40.6 | 87 | 0.763547 |
03b8295c759fb6232f7c7c78f72186eaac4cfc1c | 4,568 | //
// StudentInformationMapViewControllerTest.swift
// OnTheMapMeyerTests
//
// Created by Meyer, Gustavo on 5/15/19.
// Copyright © 2019 Gustavo Meyer. All rights reserved.
//
import XCTest
import MapKit
@testable import OnTheMapMeyer
class StudentLocationMapViewControllerTest: XCTestCase {
func test_viewDidLoad_rendersStudentInformation() {
let informations1 = [StudentInformation.makeMock()]
let informations2 = [StudentInformation.makeMock(), StudentInformation.makeMock()]
XCTAssertEqual(makeSUT(locations: []).mapView.annotations.count, 0)
XCTAssertEqual(makeSUT(locations: informations1).mapView.annotations.count, 1)
XCTAssertEqual(makeSUT(locations: informations2).mapView.annotations.count, 2)
}
func test_viewDidLoad_withStudentInformation_configuresPin(){
let studentInformation = StudentInformation.make(firstName: "Jarrod",
lastName: "Parkes",
mediaURL: "https://www.linkedin.com/in/jarrodparkes",
latitude: 34.7303688,
longitude: -86.5861037)
let sut = makeSUT(locations: [studentInformation])
let marker = sut.mapView.delegate?.mapView?(sut.mapView,
viewFor: sut.mapView.annotations[0]) as? MKMarkerAnnotationView
let annotation = marker?.annotation
XCTAssertNotNil(marker)
XCTAssertNotNil(annotation)
XCTAssertEqual(annotation?.title, "Jarrod Parkes")
XCTAssertEqual(annotation?.subtitle, "https://www.linkedin.com/in/jarrodparkes")
XCTAssertEqual(annotation?.coordinate.latitude, 34.7303688)
XCTAssertEqual(annotation?.coordinate.longitude, -86.5861037)
}
func test_selectStudentInformation_notifiesDelegateSelectionAndDeselectMarkerAnnotationView(){
var countCallback = 0
let sut = makeSUT(locations: [StudentInformation.makeMock()], selection: {_ in countCallback += 1 })
let marker = MKMarkerAnnotationView(annotation: sut.mapView.annotations[0], reuseIdentifier: "marker")
sut.mapView.delegate?.mapView?(sut.mapView,
annotationView: marker,
calloutAccessoryControlTapped: UIControl())
XCTAssertEqual(countCallback, 1)
}
func test_updateWillBegin_activityIndicatorHidden_showsActivityIndicator() {
let sut = makeSUT(locations: [StudentInformation.makeMock()])
sut.updateWillBegin()
XCTAssertFalse(sut.activityIndicator.isHidden)
}
func test_update_withEmptyResult_doesNotRenderStudentInformation() {
let sut = makeSUT(locations: [StudentInformation.makeMock()])
StudentLocationManager.shared.locations = []
sut.update()
XCTAssertEqual(sut.mapView.annotations.count, 0)
XCTAssertTrue(sut.activityIndicator.isHidden)
}
func test_update_withTowResult_rendersTwoStudentInformation() {
let sut = makeSUT(locations: [StudentInformation.makeMock()])
StudentLocationManager.shared.locations = [StudentInformation.makeMock(), StudentInformation.makeMock()]
sut.update()
XCTAssertEqual(sut.mapView.annotations.count, 2)
XCTAssertTrue(sut.activityIndicator.isHidden)
}
func test_showAlert_withTitleAndMessage_notifiesDelegateAlertView() {
var countCallback = 0
let sut = makeSUT(locations: [StudentInformation.makeMock()], alertView: { _ , _, _ in countCallback += 1 })
sut.showAlert(title: "title", message: "message")
XCTAssertEqual(countCallback, 1)
XCTAssertTrue(sut.activityIndicator.isHidden)
}
override func tearDown() {
StudentLocationManager.shared.locations = []
}
// MARK: Helpers
func makeSUT(locations: [StudentInformation] = [],
selection: @escaping SelectionHandler = { _ in },
alertView: @escaping AlerViewHandler = { _ ,_ ,_ in }) -> StudentLocationMapViewController {
StudentLocationManager.shared.locations = locations
let sut = StudentLocationMapViewController(user: User(key: "0", firstName: "Bob", lastName: "O"),
selection: selection,
alertView: alertView)
_ = sut.view
return sut
}
}
| 39.721739 | 117 | 0.642951 |
9bc6feb81d5ad85601cc259214b653eb876c0af2 | 2,273 | //
// AppDelegate.swift
// WhereIsMaFood
//
// Created by Davide Callegari on 13/07/17.
// Copyright © 2017 Davide Callegari. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var app: App?
static func getIntroductionStoryboard() -> UIStoryboard {
return UIStoryboard(name: "Introduction", bundle: nil)
}
static func getMainStoryboard() -> UIStoryboard {
return UIStoryboard(name: "Main", bundle: nil)
}
static func getDebugStoryboard() -> UIStoryboard {
return UIStoryboard(name: "Debug", bundle: nil)
}
static func hasUserSeenIntroduction() -> Bool {
return UserDefaults.standard.object(forKey: "HasSeenIntroduction") as? Bool ?? false
}
static func setUserHasSeenIntroduction(){
UserDefaults.standard.set(true, forKey: "HasSeenIntroduction")
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
do {
try app = App.setup()
} catch {
fatalError("Unable to instantiate App")
}
setupCorrectStoryBoard(debug: false)
return true
}
func startDebugger(){
let _ = app!.onAny() { notification in
self.app!.logger.log(notification)
}
}
func setupCorrectStoryBoard(debug: Bool){
var storyBoardToUse: UIStoryboard
if debug {
storyBoardToUse = AppDelegate.getDebugStoryboard()
startDebugger()
} else if !AppDelegate.hasUserSeenIntroduction(){
storyBoardToUse = AppDelegate.getIntroductionStoryboard()
} else {
storyBoardToUse = AppDelegate.getMainStoryboard()
}
let rootController = storyBoardToUse.instantiateInitialViewController()
self.window?.rootViewController = rootController
self.window?.makeKeyAndVisible()
}
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.
App.main?.trigger(App.Message.appEnteredForeground)
}
}
| 29.907895 | 190 | 0.715354 |
e83dd9c0bb6fa1fa3242474179e4144896889129 | 609 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
import Foundation
// GetObjectsParametersProtocol is request parameters for the GetObjectsByObjectIds API.
public protocol GetObjectsParametersProtocol : Codable {
var additionalProperties: [String:[String: String?]]? { get set }
var objectIds: [String]? { get set }
var types: [String]? { get set }
var includeDirectoryObjectReferences: Bool { get set }
}
| 46.846154 | 96 | 0.73399 |
eb0c09fda3dbd597f706e1410563bb021812414a | 1,033 | //
// ActivityPlaylistCollectionHeaderView.swift
// MyMusic
//
// Created by kathy yin on 5/15/17.
// Copyright © 2017 Yerneni, Naresh. All rights reserved.
//
import UIKit
class ActivityPlaylistCollectionHeaderView: UIView {
@IBOutlet var contentView: UIView!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initSubView()
}
override init(frame: CGRect) {
super.init(frame: frame)
initSubView()
}
func initSubView() {
let xib = UINib(nibName: "ActivityPlaylistCollectionHeaderView", bundle: nil)
xib.instantiate(withOwner: self, options: nil)
contentView.frame = self.bounds
self.addSubview(contentView)
self.layer.cornerRadius = 15
self.clipsToBounds = true
}
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
}
| 25.825 | 85 | 0.649564 |
871ccf222e08aa44289fd054d283be90ca49ffcb | 779 | //
// SuggestinatorViewController.swift
// Suggestinator
//
// Created by Vincent Kelleher on 21/10/2015.
// Copyright © 2015 Vincent Kelleher. All rights reserved.
//
import UIKit
class SuggestionatorViewController: UITableViewController {
@IBOutlet weak var query: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "FindSuggestions" {
if let destination = segue.destinationViewController as? SuggestionsViewController {
destination.query = query.text!
}
}
}
} | 25.966667 | 96 | 0.662388 |
506b288b6a49110a4a11506c990fdd4c34370c02 | 820 | //
// ViewController.swift
// CustomTextField
//
// Created by Yogesh Bharate on 9/10/18.
// Copyright © 2018 Bharate, Yogesh. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var textField: CustomTextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
textField.placeholder = "Hello User"
// textField.isEnabled = false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func showErrorButtonPressed(_ sender: Any) {
textField.errorMessage = "Invalid Entry"
}
}
| 23.428571 | 76 | 0.710976 |
d768d6dd2d1e5bab1ba1280ab5f6292e51c74b68 | 3,082 | //
// SelectPhotoViewController.swift
// Instagram
//
// Created by Cesar Gutierrez on 10/9/18.
// Copyright © 2018 Cesar Gutierrez. All rights reserved.
//
import UIKit
import Photos
class SelectPhotoViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet weak var photoSelectedImageView: UIImageView!
@IBOutlet weak var captionTextField: UITextField!
// UI, UX Outlet Variables
// Backend Logic Variables
var photoSelected : Bool = false
override func viewDidLoad() {
super.viewDidLoad()
//UIImagePickerController.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// Event Handlers
@IBAction func loadCameraPhotoLibrary(_ sender: Any) {
self.selectPhoto()
}
@IBAction func endEditingCaption(_ sender: Any) {
view.endEditing(true)
}
@IBAction func postPhoto(_ sender: Any) {
let caption = captionTextField.text ?? ""
let image = photoSelectedImageView.image
if (!photoSelected) {
let alertController = UIAlertController(title: "Photo Not Chosen", message: "Please choose a photo to create a new post.", preferredStyle: .alert)
let dismissAction = UIAlertAction(title: "Dismiss", style: .default)
alertController.addAction(dismissAction)
present(alertController, animated: true) { }
return;
}
Post.postUserImage(image: image, withCaption: caption) { (success, error) in
if (error != nil) {
print(error.debugDescription)
}
}
self.performSegue(withIdentifier: "PostPhotoSegue", sender: nil)
}
@IBAction func cancelNewPost(_ sender: Any) {
self.performSegue(withIdentifier: "PostPhotoSegue", sender: nil)
}
@objc func selectPhoto() {
let vc = UIImagePickerController()
vc.delegate = self
vc.allowsEditing = true
if UIImagePickerController.isSourceTypeAvailable(.camera) {
//print("Camera is available 📸")
vc.sourceType = .camera
} else {
//print("Camera 🚫 available so we will use photo library instead")
vc.sourceType = .photoLibrary
}
self.present(vc, animated: true, completion: nil)
}
// Delegate Protocols
@objc func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
// Get the image captured by the UIImagePickerController
// let originalImage = info[UIImagePickerControllerOriginalImage] as! UIImage
let editedImage = info[.editedImage] as! UIImage
photoSelectedImageView.image = editedImage
photoSelected = true
// Dismiss UIImagePickerController to go back to your original view controller
dismiss(animated: true, completion: nil)
}
}
| 34.244444 | 158 | 0.645036 |
1d06ae4ad35a3ad450b65017969aca499c580423 | 2,298 | //
// SceneDelegate.swift
// Tip Calculator
//
// Created by Tufayel Ahmed on 12/19/20.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 43.358491 | 147 | 0.713229 |
08d870eca501527474a053977287a645775a7d9c | 5,847 | //
// FieldTests.swift
// Stardaze
//
// Created by William Wilson on 2/10/17.
// Copyright © 2017 LeTote. All rights reserved.
//
@testable import Stardaze
import XCTest
final class FieldTests: XCTestCase {
enum TestEnum: String {
case brown
}
let unencodedStringFormatter = OutputFormatter(outputOption: .prettyPrinted)
let testField = Field(name: "test_field")
func testUserRepresentation() {
XCTAssertEqual(testField.accept(visitor: unencodedStringFormatter), "test_field")
}
func testAlias() {
let field = Field(name: "test_field", alias: "testField")
XCTAssertEqual(field.accept(visitor: unencodedStringFormatter), "testField: test_field")
let withID = field.appended(subField: "id")
XCTAssertEqual(withID.accept(visitor: unencodedStringFormatter),
"testField: test_field {" +
"\n\tid" +
"\n}")
}
func testArguments() {
let copy = testField.appended(argument: Argument(key: "id", value: 5))
XCTAssertEqual(copy.accept(visitor: unencodedStringFormatter), "test_field(id: 5)")
let withColor = copy.appended(argument: Argument(key: "color", value: TestEnum.brown))
XCTAssertEqual(withColor.accept(visitor: unencodedStringFormatter), "test_field(id: 5, color: brown)")
let withID = withColor.appended(subField: "id")
XCTAssertEqual(withID.accept(visitor: unencodedStringFormatter),
"test_field(id: 5, color: brown) {" +
"\n\tid" +
"\n}")
}
func testAppendingMultipleArguments() {
let copy = testField.appended(arguments: [
Argument(key: "id", value: 5),
Argument(key: "color", value: TestEnum.brown)
])
XCTAssertEqual(copy.accept(visitor: unencodedStringFormatter), "test_field(id: 5, color: brown)")
}
func testDirectives() {
let copy = testField.appended(directive: .include(Variable("testVar")))
XCTAssertEqual(copy.accept(visitor: unencodedStringFormatter), "test_field @include(if: $testVar)")
let withDeprecation = copy.appended(directive: .deprecated(Variable("deprecationReason")))
XCTAssertEqual(withDeprecation.accept(visitor: unencodedStringFormatter),
"test_field @include(if: $testVar), @deprecated(reason: $deprecationReason)")
let withID = withDeprecation.appended(argument: Argument(key: "id", value: 5))
XCTAssertEqual(withID.accept(visitor: unencodedStringFormatter), "test_field(id: 5) @include(if: $testVar), " +
"@deprecated(reason: $deprecationReason)")
let withIDField = withID.appended(subField: "id")
XCTAssertEqual(withIDField.accept(visitor: unencodedStringFormatter),
"test_field(id: 5) @include(if: $testVar), @deprecated(reason: $deprecationReason) {" +
"\n\tid" +
"\n}")
}
func testAppendingMultipleDirectives() {
let copy = testField.appended(directives: [
.skip(Variable("testVar")),
.deprecated(Variable("deprecationReason"))
])
XCTAssertEqual(copy.accept(visitor: unencodedStringFormatter), "test_field @skip(if: $testVar), " +
"@deprecated(reason: $deprecationReason)")
}
func testFragments() {
let copy = testField.appended(fragment: Fragment(name: "testFragment",
type: "TestObject",
fields: ["id"]))
XCTAssertEqual(copy.accept(visitor: unencodedStringFormatter),
"test_field {" +
"\n\t...testFragment" +
"\n}")
let withTitleFragment = copy.appended(fragment: Fragment(name: "titleFragment",
type: "TestObject",
fields: [Field(name: "title")]))
XCTAssertEqual(withTitleFragment.accept(visitor: unencodedStringFormatter),
"test_field {" +
"\n\t...testFragment" +
"\n\t...titleFragment" +
"\n}")
let withPhotos = withTitleFragment.appended(subField: Field(name: "customer_photos", subFields: [
"medium_url"
]))
XCTAssertEqual(withPhotos.accept(visitor: unencodedStringFormatter),
"test_field {" +
"\n\tcustomer_photos {" +
"\n\t\tmedium_url" +
"\n\t}" +
"\n\t...testFragment" +
"\n\t...titleFragment" +
"\n}")
}
func testAppendingMultipleFragments() {
let copy = testField.appended(fragments: [
Fragment(name: "testFragment", type: "TestObject", fields: ["id"]),
Fragment(name: "titleFragment", type: "TestObject", fields: ["title"])
])
XCTAssertEqual(copy.accept(visitor: unencodedStringFormatter),
"test_field {" +
"\n\t...testFragment" +
"\n\t...titleFragment" +
"\n}")
}
func testAppendingMultipleFields() {
let copy = testField.appended(subFields: ["id", "title"])
XCTAssertEqual(copy.accept(visitor: unencodedStringFormatter),
"test_field {" +
"\n\tid" +
"\n\ttitle" +
"\n}")
}
}
| 38.215686 | 119 | 0.540619 |
5ddc3f065513e9fcb2d279a9de3dede49e716cd3 | 516 | //
// InertiaStampedMessage.swift
//
// Created by wesgoodhoofd on 2019-01-22.
//
import UIKit
import ObjectMapper
public class InertiaStampedMessage: RBSMessage {
public var header: HeaderMessage?
public var inertia: InertiaMessage?
public override init() {
super.init()
header = HeaderMessage()
inertia = InertiaMessage()
}
public required init?(map: Map) {
super.init(map: map)
}
public override func mapping(map: Map) {
header <- map["header"]
inertia <- map["inertia"]
}
}
| 18.428571 | 48 | 0.687984 |
8ad0065e32419eeead4524163282982ba37a5dfc | 14,146 | //
// ChatRoomDAO.swift
// SIMSmeCore
//
// Created by Robert Burchert on 05.08.19.
// Copyright © 2020 ginlo.net GmbH. All rights reserved.
//
import CoreData
import Foundation
struct ChatRoomDAOUpdateGroupResult {
let unknownGuids: [String]
let doNotify: Bool
}
protocol ChatRoomDAOProtocol {
func isEditingEnabled(groupGuid: String) -> Bool
func setGroupRemotelyDeleted(groupGuid: String)
func getJsonStringForAddMembers(_ memberGuids: Set<String>, groupGuid: String, groupName: String, groupAesKey: String, isNewGroup: Bool, groupType: String?) throws -> String
func createGroupStream(config: DPAGChatRoomCreationConfig, aesKey decAesKey: String, _ type: String)
func aesKey(forGroupGuid groupGuid: String) -> String?
func updateGroupAndReturnUnknownContactGuids(config: DPAGChatRoomUpdateConfig, responseDict dict: [String: Any]) -> [String]
func updateGroup(groupGuid: String, responseDict dict: [AnyHashable: Any]) -> ChatRoomDAOUpdateGroupResult
func removeRoom(roomGuid: String) throws
func updateGroup(groupGuid: String, ownGuid: String, apiGroup: API.Response.Group, unknownGuids: inout [String])
}
class ChatRoomDAO: ChatRoomDAOProtocol {
private let queueDBAccess: DispatchQueue = DispatchQueue(label: "de.dpag.simsme.ChatRoomDAO.queue", qos: .default, attributes: .concurrent, autoreleaseFrequency: .inherit, target: nil)
func isEditingEnabled(groupGuid: String) -> Bool {
var enabled = true
self.queueDBAccess.sync(flags: .barrier) {
DPAGApplicationFacade.persistance.loadWithBlock { localContext in
if let stream = SIMSMessageStream.findFirst(byGuid: groupGuid, in: localContext) as? SIMSGroupStream {
enabled = enabled && (stream.streamState == .write)
}
}
}
return enabled
}
func setGroupRemotelyDeleted(groupGuid: String) {
self.queueDBAccess.sync(flags: .barrier) {
DPAGApplicationFacade.persistance.saveWithBlock { localContext in
if let group = SIMSGroup.findFirst(byGuid: groupGuid, in: localContext) {
if group.wasDeleted == false {
group.wasDeleted = true
}
}
}
}
}
func getJsonStringForAddMembers(_ memberGuids: Set<String>, groupGuid: String, groupName: String, groupAesKey: String, isNewGroup: Bool, groupType: String? = "ChatRoom") throws -> String {
var addMembersJSON: String?
try self.queueDBAccess.sync(flags: .barrier) {
try DPAGApplicationFacade.persistance.loadWithError { localContext in
let recipients = memberGuids.compactMap { (memberGuid) -> SIMSContactIndexEntry? in
SIMSContactIndexEntry.findFirst(byGuid: memberGuid, in: localContext)
}
let invGroupType: String
if let groupType = groupType {
invGroupType = groupType
} else {
invGroupType = "ChatRoom"
}
if let messages = try DPAGApplicationFacade.messageFactory.invitationForGroup(groupGuid: groupGuid, groupName: groupName, groupAesKey: groupAesKey, forRecipients: recipients, isNewGroup: isNewGroup, groupType: invGroupType, in: localContext) {
addMembersJSON = messages.JSONString
}
}
}
return addMembersJSON ?? ""
}
func createGroupStream(config: DPAGChatRoomCreationConfig, aesKey decAesKey: String, _ type: String = "ChatRoom") {
self.queueDBAccess.sync(flags: .barrier) {
DPAGApplicationFacade.persistance.saveWithBlock { localContext in
guard let groupStream = self.createGroupStream(config.groupName, ownerGuid: config.ownerGuid, groupGuid: config.groupGuid, decAesKey: decAesKey, in: localContext), let group = groupStream.group, let ownGuid = DPAGApplicationFacade.cache.account?.guid else { return }
var newMemberGuids = config.memberGuids
newMemberGuids.insert(config.ownerGuid)
_ = group.updateMembers(memberGuids: Array(newMemberGuids), ownGuid: ownGuid, in: localContext)
var newAdminGuids = config.adminGuids
newAdminGuids.insert(config.ownerGuid)
group.typeName = type
group.updateAdmins(adminGuids: Array(newAdminGuids))
group.updateStatus(in: localContext)
// DPAGApplicationFacade.cache.updateDecryptedStreamWithGuid(groupGuid, stream: groupStream, in: localContext)
}
}
}
private func createGroupStream(_ groupName: String, ownerGuid: String, groupGuid: String, decAesKey: String, in localContext: NSManagedObjectContext) -> SIMSGroupStream? {
guard let stream = SIMSMessageStream.findFirst(byGuid: groupGuid, in: localContext) as? SIMSGroupStream ?? SIMSGroupStream.mr_createEntity(in: localContext) else { return nil }
stream.guid = groupGuid
stream.typeStream = .group
stream.optionsStream = DPAGApplicationFacade.preferences.streamVisibilityGroup ? [] : [.filtered]
guard let group = SIMSGroup.findFirst(byGuid: groupGuid, in: localContext) ?? SIMSGroup.mr_createEntity(in: localContext) else {
stream.mr_deleteEntity(in: localContext)
return nil
}
group.guid = groupGuid
stream.group = group
stream.group?.isConfirmed = true
group.aesKey = decAesKey
group.groupName = groupName
group.ownerGuid = ownerGuid
group.invitedAt = Date()
stream.lastMessageDate = group.invitedAt
let key = SIMSKey.mr_findFirst(in: localContext)
group.keyRelationship = key
group.members?.removeAll()
if let member = SIMSGroupMember.mr_findFirst(with: NSComparisonPredicate(leftExpression: NSExpression(forKeyPath: \SIMSGroupMember.accountGuid), rightExpression: NSExpression(forConstantValue: ownerGuid)), in: localContext) ?? SIMSGroupMember.mr_createEntity(in: localContext) {
member.accountGuid = ownerGuid
group.members?.insert(member)
}
return stream
}
func aesKey(forGroupGuid groupGuid: String) -> String? {
var aesKeyGroup: String?
self.queueDBAccess.sync(flags: .barrier) {
DPAGApplicationFacade.persistance.loadWithBlock { localContext in
if let group = SIMSGroup.findFirst(byGuid: groupGuid, in: localContext), let decAesKey = group.aesKey {
aesKeyGroup = decAesKey
}
}
}
return aesKeyGroup
}
func updateGroupAndReturnUnknownContactGuids(config: DPAGChatRoomUpdateConfig, responseDict dict: [String: Any]) -> [String] {
var unknownGuids: [String] = []
self.queueDBAccess.sync(flags: .barrier) {
DPAGApplicationFacade.persistance.saveWithBlock { localContext in
guard let group = SIMSGroup.findFirst(byGuid: config.groupGuid, in: localContext), let ownGuid = DPAGApplicationFacade.cache.account?.guid else { return }
group.groupName = config.groupName
if let data = dict[DPAGStrings.Server.Group.Response.DATA] as? String {
group.update(withData: data, keyIV: dict[DPAGStrings.Server.Group.Response.KEY_IV] as? String)
}
if let ownerGuid = dict[DPAGStrings.Server.Group.Response.OWNER] as? String {
group.ownerGuid = ownerGuid
}
if let currentMemberGuids = dict[DPAGStrings.Server.Group.Response.MEMBER] as? [String] {
unknownGuids += group.updateMembers(memberGuids: currentMemberGuids, ownGuid: ownGuid, in: localContext)
}
if let adminGuids = dict[DPAGStrings.Server.Group.Response.ADMINS] as? [String] {
group.updateAdmins(adminGuids: adminGuids)
}
if let writerGuids = dict[DPAGStrings.Server.Group.Response.WRITERS] as? [String] {
group.updateWriters(writerGuids: writerGuids)
}
group.updateStatus(in: localContext)
DPAGApplicationFacade.cache.updateDecryptedStream(streamGuid: config.groupGuid, stream: group.stream, in: localContext)
}
}
return unknownGuids
}
func updateGroup(groupGuid: String, responseDict dict: [AnyHashable: Any]) -> ChatRoomDAOUpdateGroupResult {
var unknownGuids: [String] = []
var doNotify = false
self.queueDBAccess.sync(flags: .barrier) {
DPAGApplicationFacade.persistance.saveWithBlock { localContext in
guard let group = SIMSGroup.findFirst(byGuid: groupGuid, in: localContext), let ownGuid = DPAGApplicationFacade.cache.account?.guid else { return }
if let data = dict[DPAGStrings.Server.Group.Response.DATA] as? String {
group.update(withData: data, keyIV: dict[DPAGStrings.Server.Group.Response.KEY_IV] as? String)
}
if let ownerGuid = dict[DPAGStrings.Server.Group.Response.OWNER] as? String {
group.ownerGuid = ownerGuid
}
if let memberGuids = dict[DPAGStrings.Server.Group.Response.MEMBER] as? [String] {
unknownGuids += group.updateMembers(memberGuids: memberGuids, ownGuid: ownGuid, in: localContext)
}
if let adminGuids = dict[DPAGStrings.Server.Group.Response.ADMINS] as? [String] {
group.updateAdmins(adminGuids: adminGuids)
}
if let writerGuids = dict[DPAGStrings.Server.Group.Response.WRITERS] as? [String] {
group.updateWriters(writerGuids: writerGuids)
}
let groupStreamOptionsValue = (group.stream?.optionsStream ?? [])
if let readOnly = dict[DPAGStrings.Server.Group.Response.READONLY] as? String {
if readOnly == "1" {
if groupStreamOptionsValue.contains(.isReadOnly) == false {
group.stream?.optionsStream = groupStreamOptionsValue.union(.isReadOnly)
doNotify = true
}
} else if groupStreamOptionsValue.contains(.isReadOnly) {
group.stream?.optionsStream = groupStreamOptionsValue.subtracting(.isReadOnly)
doNotify = true
}
} else if groupStreamOptionsValue.contains(.isReadOnly) {
group.stream?.optionsStream = groupStreamOptionsValue.subtracting(.isReadOnly)
doNotify = true
}
group.updateStatus(in: localContext)
DPAGApplicationFacade.cache.updateDecryptedStream(streamGuid: groupGuid, stream: group.stream, in: localContext)
}
}
return ChatRoomDAOUpdateGroupResult(unknownGuids: unknownGuids, doNotify: doNotify)
}
func removeRoom(roomGuid: String) throws {
try self.queueDBAccess.sync(flags: .barrier) {
try DPAGApplicationFacade.persistance.saveWithError { localContext in
if let group = SIMSGroup.findFirst(byGuid: roomGuid, in: localContext) {
group.removeMembers(in: localContext)
let groupStream = group.stream
if let messages = groupStream?.messages?.array {
messages.forEach { obj in
if let msg = obj as? SIMSMessage {
DPAGApplicationFacade.persistance.deleteMessage(msg, in: localContext)
}
}
}
group.mr_deleteEntity(in: localContext)
groupStream?.mr_deleteEntity(in: localContext)
}
let timedMessages = try SIMSMessageToSendGroup.findAll(in: localContext, with: NSComparisonPredicate(leftExpression: NSExpression(forKeyPath: \SIMSMessageToSend.streamGuid), rightExpression: NSExpression(forConstantValue: roomGuid)))
for timedMessage in timedMessages {
DPAGApplicationFacade.persistance.deleteMessage(timedMessage, in: localContext)
}
DPAGApplicationFacade.cache.removeStream(guid: roomGuid)
}
}
}
func updateGroup(groupGuid: String, ownGuid: String, apiGroup: API.Response.Group, unknownGuids: inout [String]) {
var unknownUserIds: [String] = []
self.queueDBAccess.sync(flags: .barrier) {
DPAGApplicationFacade.persistance.saveWithBlock { localContext in
guard let groupStream = SIMSMessageStream.findFirst(byGuid: groupGuid, in: localContext) as? SIMSGroupStream, let group = groupStream.group else { return }
if let data = apiGroup.data {
group.update(withData: data, keyIV: apiGroup.keyIv)
}
if let ownerGuid = apiGroup.ownerId {
group.ownerGuid = ownerGuid
}
if let memberGuids = apiGroup.memberIds {
unknownUserIds += group.updateMembers(memberGuids: memberGuids, ownGuid: ownGuid, in: localContext)
}
if let adminGuids = apiGroup.adminIds {
group.updateAdmins(adminGuids: adminGuids)
}
if let writerGuids = apiGroup.writerIds {
group.updateWriters(writerGuids: writerGuids)
}
group.updateStatus(in: localContext)
group.isConfirmed = true
group.wasDeleted = false
DPAGApplicationFacade.cache.updateDecryptedStream(streamGuid: groupGuid, stream: groupStream, in: localContext)
}
}
unknownGuids += unknownUserIds
}
}
| 54.617761 | 286 | 0.629931 |
4b8cfdab4911d6ddce303326381f6b46e5bb3bb1 | 2,390 | //
// PlaneDebugVisualization.swift
// Don't Flinch
//
// Created by Michael Thomas on 7/12/17.
// Copyright © 2017 Biscuit Labs, LLC. All rights reserved.
//
/*
See LICENSE folder for this sample’s licensing information.
Abstract:
SceneKit node wrapper shows debug info for AR detected planes.
*/
import Foundation
import ARKit
class PlaneDebugVisualization: SCNNode {
var planeAnchor: ARPlaneAnchor
var planeGeometry: SCNPlane
var planeNode: SCNNode
init(anchor: ARPlaneAnchor) {
self.planeAnchor = anchor
let grid = UIImage(named: "art.scnassets/plane_grid.png")
self.planeGeometry = createPlane(size: CGSize(width: CGFloat(anchor.extent.x), height: CGFloat(anchor.extent.z)),
contents: grid)
self.planeNode = SCNNode(geometry: planeGeometry)
self.planeNode.transform = SCNMatrix4MakeRotation(-Float.pi / 2.0, 1, 0, 0)
super.init()
let originVisualizationNode = createAxesNode(quiverLength: 0.1, quiverThickness: 1.0)
self.addChildNode(originVisualizationNode)
self.addChildNode(planeNode)
self.position = SCNVector3(anchor.center.x, -0.002, anchor.center.z) // 2 mm below the origin of plane.
adjustScale()
}
func update(_ anchor: ARPlaneAnchor) {
self.planeAnchor = anchor
self.planeGeometry.width = CGFloat(anchor.extent.x)
self.planeGeometry.height = CGFloat(anchor.extent.z)
self.position = SCNVector3Make(anchor.center.x, -0.002, anchor.center.z)
adjustScale()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func adjustScale() {
let scaledWidth: Float = Float(planeGeometry.width / 2.4)
let scaledHeight: Float = Float(planeGeometry.height / 2.4)
let offsetWidth: Float = -0.5 * (scaledWidth - 1)
let offsetHeight: Float = -0.5 * (scaledHeight - 1)
let material = self.planeGeometry.materials.first
var transform = SCNMatrix4MakeScale(scaledWidth, scaledHeight, 1)
transform = SCNMatrix4Translate(transform, offsetWidth, offsetHeight, 0)
material?.diffuse.contentsTransform = transform
}
}
| 31.447368 | 121 | 0.637657 |
6200f4c2e55fceded37fc929c8c4038c76c86739 | 15,025 | //
// ToDoViewController.swift
// toPether
//
// Created by 林宜萱 on 2021/10/30.
//
import UIKit
import Lottie
import Firebase
class ToDoViewController: UIViewController {
private var toDos = [ToDo]()
private var executorNameCache = [String: String]() {
didSet {
toDoTableView.reloadData()
}
}
private var petNameCache = [String: String]() {
didSet {
toDoTableView.reloadData()
}
}
private var listener: ListenerRegistration?
// MARK: - Life Cycles
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .mainBlue
configCardView()
configCalendar()
configToDoTableView()
// MARK: Data
addToDoListenerOnDate(date: Date())
addToDoListenerNotification()
}
override func viewWillAppear(_ animated: Bool) {
self.navigationItem.title = "Todos"
self.setNavigationBarColor(bgColor: .mainBlue, textColor: .white, tintColor: .white)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: Img.iconsAddWhite.obj, style: .plain, target: self, action: #selector(tapAdd))
self.tabBarController?.tabBar.isHidden = false
}
// MARK: - Data Functions
private func addToDoListenerOnDate(date: Date) {
guard let currentUser = MemberManager.shared.current else { return }
listener = ToDoManager.shared.addToDosListenerOnDate(petIds: currentUser.petIds, date: date) { [weak self] result in
guard let self = self else { return }
switch result {
case .success(let todos):
self.toDos = todos
let group: DispatchGroup = DispatchGroup()
let queue = DispatchQueue(label: "queue", attributes: .concurrent)
for todo in todos where self.executorNameCache[todo.executorId] == nil || self.petNameCache[todo.petId] == nil {
group.enter()
queue.async(group: group) {
MemberManager.shared.queryMember(id: todo.executorId) { member in
guard let member = member else {
self.executorNameCache[todo.executorId] = "anonymous"
group.leave()
return
}
self.executorNameCache[todo.executorId] = member.name
group.leave()
}
}
group.enter()
queue.async(group: group) {
PetManager.shared.queryPet(id: todo.petId) { result in
switch result {
case .success(let pet):
self.petNameCache[todo.petId] = pet.name
group.leave()
case .failure(let error):
self.presentErrorAlert(message: error.localizedDescription + " Please try again")
group.leave()
}
}
}
}
group.notify(queue: DispatchQueue.main) {
self.toDoTableView.reloadData()
}
case .failure(let error):
print("listen todo error", error)
self.presentErrorAlert(message: error.localizedDescription + " Please try again")
}
}
}
private func addToDoListenerNotification() {
ToDoManager.shared.todoListener { [weak self] result in
guard let self = self else { return }
switch result {
case .success(.added(data: let todos)):
var badgeStepper: Int = 0
for todo in todos {
if todo.dueTime.hasSame(.day, as: Date()) {
badgeStepper += 1
}
self.createNotification(todo: todo, badgeStepper: badgeStepper as NSNumber)
}
case .success(.modified(data: let todos)):
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: todos.compactMap{ $0.id })
var badgeStepper: Int = 0
for todo in todos {
if todo.dueTime.hasSame(.day, as: Date()) {
badgeStepper += 1
}
self.createNotification(todo: todo, badgeStepper: badgeStepper as NSNumber)
}
case .success(.removed(data: let todos)):
var badgeStepper: Int = 0
for todo in todos {
if todo.dueTime.hasSame(.day, as: Date()) {
badgeStepper += 1
}
}
case .failure(let error):
print("add todoListeners for notifications error", error)
self.presentErrorAlert(message: error.localizedDescription + " Please try again")
}
}
}
private func createNotification(todo: ToDo, badgeStepper: NSNumber?) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM d HH:mm"
dateFormatter.timeZone = TimeZone.current
let content = UNMutableNotificationContent()
content.title = "Todo list"
content.subtitle = dateFormatter.string(from: todo.dueTime)
content.body = todo.content
content.badge = badgeStepper
content.sound = .default
let calendar = Calendar.current
let year = calendar.component(.year, from: todo.dueTime)
let month = calendar.component(.month, from: todo.dueTime)
let day = calendar.component(.day, from: todo.dueTime)
var dateComponents = DateComponents()
dateComponents.timeZone = .current
dateComponents.year = year
dateComponents.month = month
dateComponents.day = day
dateComponents.hour = 7
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)
let request = UNNotificationRequest(identifier: todo.id, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { error in
if error != nil {
print("add notification failed")
self.presentErrorAlert(message: error?.localizedDescription ?? "" + " Please try again")
}
}
}
// MARK: - @objc Functions
@objc private func tapAdd(_ sender: UIBarButtonItem) {
let toDoRecordViewController = ToDoRecordViewController(todo: nil, petName: nil, executorName: nil)
navigationController?.pushViewController(toDoRecordViewController, animated: true)
}
@objc func tapDate(sender: UIDatePicker) {
let date = sender.date
listener?.remove()
addToDoListenerOnDate(date: date)
}
// MARK: - UI Properties
private var cardView: CardView!
private var calendar: UIDatePicker!
private var toDoTableView: UITableView!
private var animationView: AnimationView!
}
// MARK: - UITableViewDataSource
extension ToDoViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return toDos.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: ToDoTableViewCell.identifier, for: indexPath)
guard let toDoCell = cell as? ToDoTableViewCell else { return cell }
let todo = toDos[indexPath.row]
let executorName = executorNameCache[todo.executorId]
let petName = petNameCache[todo.petId]
toDoCell.reload(todo: todo, executorName: executorName, petName: petName)
toDoCell.delegate = self
return toDoCell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let todo = toDos[indexPath.row]
let petName = petNameCache[todo.petId]
let executorName = executorNameCache[todo.executorId]
if !todo.doneStatus {
let todoRecordViewController = ToDoRecordViewController(todo: todo, petName: petName, executorName: executorName)
navigationController?.pushViewController(todoRecordViewController, animated: true)
}
}
}
// MARK: - UITableViewDelegate
extension ToDoViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let deleteAction = UIContextualAction(style: .destructive, title: "delete") { [weak self] (_, _, completionHandler) in
guard let self = self else { return }
self.presentDeleteAlert(title: "Delete todo", message: "Do you want to delete this todo?") {
let deleteId = self.toDos[indexPath.row].id
let deleteContent = self.toDos[indexPath.row].content
ToDoManager.shared.deleteToDo(id: deleteId) { result in
switch result {
case .success(let string):
print(string + deleteContent)
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [deleteId])
case .failure(let error):
self.presentErrorAlert(message: error.localizedDescription + " Please try again")
}
}
}
completionHandler(true)
}
deleteAction.image = Img.iconsDelete.obj
deleteAction.backgroundColor = .white
let swipeAction = UISwipeActionsConfiguration(actions: [deleteAction])
swipeAction.performsFirstActionWithFullSwipe = false
return swipeAction
}
}
// MARK: - ToDoTableViewCellDelegate
extension ToDoViewController: ToDoTableViewCellDelegate {
func didChangeDoneStatusOnCell(_ cell: ToDoTableViewCell) {
guard let indexPath = toDoTableView.indexPath(for: cell) else { return }
toDos[indexPath.row].doneStatus.toggle()
ToDoManager.shared.updateToDo(todo: toDos[indexPath.row]) { [weak self] result in
guard let self = self else { return }
switch result {
case .success(let todo):
if todo.doneStatus {
self.configAnimation()
}
print("updated todo: \(todo.id)")
case .failure(let error):
self.presentErrorAlert(message: error.localizedDescription)
}
self.toDoTableView.reloadRows(at: [indexPath], with: .none)
}
}
}
// MARK: - UI Configure functions
extension ToDoViewController {
private func configCardView() {
cardView = CardView(color: .white, cornerRadius: 20)
view.addSubview(cardView)
NSLayoutConstraint.activate([
cardView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
cardView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
cardView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
cardView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
}
private func configCalendar() {
calendar = UIDatePicker()
calendar.datePickerMode = .date
calendar.preferredDatePickerStyle = .inline
calendar.tintColor = .mainYellow
calendar.backgroundColor = .white
calendar.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(calendar)
NSLayoutConstraint.activate([
calendar.topAnchor.constraint(equalTo: cardView.topAnchor, constant: 20),
calendar.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 32),
calendar.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -32),
calendar.heightAnchor.constraint(equalTo: calendar.widthAnchor)
])
calendar.addTarget(self, action: #selector(tapDate), for: .valueChanged)
}
private func configToDoTableView() {
toDoTableView = UITableView()
toDoTableView.register(ToDoTableViewCell.self, forCellReuseIdentifier: "ToDoTableViewCell")
toDoTableView.separatorColor = .clear
toDoTableView.backgroundColor = .white
toDoTableView.estimatedRowHeight = 150
toDoTableView.rowHeight = UITableView.automaticDimension
toDoTableView.allowsSelection = true
toDoTableView.delegate = self
toDoTableView.dataSource = self
toDoTableView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(toDoTableView)
NSLayoutConstraint.activate([
toDoTableView.topAnchor.constraint(equalTo: calendar.bottomAnchor, constant: 4),
toDoTableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
toDoTableView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
toDoTableView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor)
])
}
private func configAnimation() {
animationView = .init(name: "lottieCongratulation")
animationView.contentMode = .scaleAspectFit
animationView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(animationView)
NSLayoutConstraint.activate([
animationView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
animationView.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 60),
animationView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.9),
animationView.heightAnchor.constraint(equalTo: animationView.widthAnchor)
])
animationView.loopMode = .playOnce
animationView.play { [weak self] _ in
guard let self = self else { return }
self.animationView.isHidden = true
}
}
}
| 38.724227 | 150 | 0.581564 |
6918ba7b399417fac36d3b5ce51f7b58e9d2b9c6 | 10,155 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2020 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
@testable import PackageCollections
import TSCBasic
import TSCTestSupport
import XCTest
final class PackageCollectionProfileStorageTest: XCTestCase {
func testHappyCase() throws {
let mockFileSystem = InMemoryFileSystem()
let storage = FilePackageCollectionsProfileStorage(fileSystem: mockFileSystem)
try assertHappyCase(storage: storage)
let buffer = try mockFileSystem.readFileContents(storage.path)
XCTAssertNotEqual(buffer.count, 0, "expected file to be written")
print(buffer)
}
func testRealFile() throws {
try testWithTemporaryDirectory { tmpPath in
let fileSystem = localFileSystem
let path = tmpPath.appending(component: "test.json")
let storage = FilePackageCollectionsProfileStorage(fileSystem: fileSystem, path: path)
try assertHappyCase(storage: storage)
let buffer = try fileSystem.readFileContents(storage.path)
XCTAssertNotEqual(buffer.count, 0, "expected file to be written")
print(buffer)
}
}
func assertHappyCase(storage: PackageCollectionsProfileStorage) throws {
let sources = makeMockSources()
try sources.forEach { source in
_ = try tsc_await { callback in storage.add(source: source, order: nil, to: .default, callback: callback) }
}
let profiles = try tsc_await { callback in storage.listProfiles(callback: callback) }
XCTAssertEqual(profiles.count, 1, "profiles should match")
do {
let list = try tsc_await { callback in storage.listSources(in: .default, callback: callback) }
XCTAssertEqual(list.count, sources.count, "collections should match")
}
let remove = sources.enumerated().filter { index, _ in index % 2 == 0 }.map { $1 }
try remove.forEach { source in
_ = try tsc_await { callback in storage.remove(source: source, from: .default, callback: callback) }
}
do {
let list = try tsc_await { callback in storage.listSources(in: .default, callback: callback) }
XCTAssertEqual(list.count, sources.count - remove.count, "collections should match")
}
let remaining = sources.filter { !remove.contains($0) }
try sources.forEach { source in
XCTAssertEqual(try tsc_await { callback in storage.exists(source: source, in: .default, callback: callback) }, remaining.contains(source))
XCTAssertEqual(try tsc_await { callback in storage.exists(source: source, in: nil, callback: callback) }, remaining.contains(source))
}
do {
_ = try tsc_await { callback in storage.move(source: remaining.last!, to: 0, in: .default, callback: callback) }
let list = try tsc_await { callback in storage.listSources(in: .default, callback: callback) }
XCTAssertEqual(list.count, remaining.count, "collections should match")
XCTAssertEqual(list.first, remaining.last, "item should match")
}
do {
_ = try tsc_await { callback in storage.move(source: remaining.last!, to: remaining.count - 1, in: .default, callback: callback) }
let list = try tsc_await { callback in storage.listSources(in: .default, callback: callback) }
XCTAssertEqual(list.count, remaining.count, "collections should match")
XCTAssertEqual(list.last, remaining.last, "item should match")
}
}
func testFileDeleted() throws {
let mockFileSystem = InMemoryFileSystem()
let storage = FilePackageCollectionsProfileStorage(fileSystem: mockFileSystem)
let sources = makeMockSources()
try sources.forEach { source in
_ = try tsc_await { callback in storage.add(source: source, order: nil, to: .default, callback: callback) }
}
do {
let list = try tsc_await { callback in storage.listSources(in: .default, callback: callback) }
XCTAssertEqual(list.count, sources.count, "collections should match")
}
try mockFileSystem.removeFileTree(storage.path)
XCTAssertFalse(mockFileSystem.exists(storage.path), "expected file to be deleted")
do {
let list = try tsc_await { callback in storage.listSources(in: .default, callback: callback) }
XCTAssertEqual(list.count, 0, "collections should match")
}
}
func testFileEmpty() throws {
let mockFileSystem = InMemoryFileSystem()
let storage = FilePackageCollectionsProfileStorage(fileSystem: mockFileSystem)
let sources = makeMockSources()
try sources.forEach { source in
_ = try tsc_await { callback in storage.add(source: source, order: nil, to: .default, callback: callback) }
}
do {
let list = try tsc_await { callback in storage.listSources(in: .default, callback: callback) }
XCTAssertEqual(list.count, sources.count, "collections should match")
}
try mockFileSystem.writeFileContents(storage.path, bytes: ByteString("".utf8))
let buffer = try mockFileSystem.readFileContents(storage.path)
XCTAssertEqual(buffer.count, 0, "expected file to be empty")
do {
let list = try tsc_await { callback in storage.listSources(in: .default, callback: callback) }
XCTAssertEqual(list.count, 0, "collections should match")
}
}
func testFileCorrupt() throws {
let mockFileSystem = InMemoryFileSystem()
let storage = FilePackageCollectionsProfileStorage(fileSystem: mockFileSystem)
let sources = makeMockSources()
try sources.forEach { source in
_ = try tsc_await { callback in storage.add(source: source, order: nil, to: .default, callback: callback) }
}
let list = try tsc_await { callback in storage.listSources(in: .default, callback: callback) }
XCTAssertEqual(list.count, sources.count, "collections should match")
try mockFileSystem.writeFileContents(storage.path, bytes: ByteString("{".utf8))
let buffer = try mockFileSystem.readFileContents(storage.path)
XCTAssertNotEqual(buffer.count, 0, "expected file to be written")
print(buffer)
XCTAssertThrowsError(try tsc_await { callback in storage.listSources(in: .default, callback: callback) }, "expected an error", { error in
XCTAssert(error is DecodingError, "expected error to match")
})
}
func testCustomProfile() throws {
let mockFileSystem = InMemoryFileSystem()
let storage = FilePackageCollectionsProfileStorage(fileSystem: mockFileSystem)
let profile = PackageCollectionsModel.Profile(name: "profile-\(UUID().uuidString)")
let sources = makeMockSources()
try sources.forEach { source in
_ = try tsc_await { callback in storage.add(source: source, order: nil, to: profile, callback: callback) }
}
let profiles = try tsc_await { callback in storage.listProfiles(callback: callback) }
XCTAssertEqual(profiles.count, 1, "profiles should match")
do {
let list = try tsc_await { callback in storage.listSources(in: profile, callback: callback) }
XCTAssertEqual(list.count, sources.count, "sources should match")
}
let remove = sources.enumerated().filter { index, _ in index % 2 == 0 }.map { $1 }
try remove.forEach { source in
_ = try tsc_await { callback in storage.remove(source: source, from: profile, callback: callback) }
}
do {
let list = try tsc_await { callback in storage.listSources(in: profile, callback: callback) }
XCTAssertEqual(list.count, sources.count - remove.count, "sources should match")
}
try sources.forEach { source in
XCTAssertEqual(try tsc_await { callback in storage.exists(source: source, in: profile, callback: callback) }, !remove.contains(source))
XCTAssertEqual(try tsc_await { callback in storage.exists(source: source, in: nil, callback: callback) }, !remove.contains(source))
}
let buffer = try mockFileSystem.readFileContents(storage.path)
XCTAssertNotEqual(buffer.count, 0, "expected file to be written")
print(buffer)
}
func testMultipleProfiles() throws {
let mockFileSystem = InMemoryFileSystem()
let storage = FilePackageCollectionsProfileStorage(fileSystem: mockFileSystem)
let sources = makeMockSources()
var profiles = [PackageCollectionsModel.Profile(name: "profile-\(UUID().uuidString)"): [PackageCollectionsModel.CollectionSource](),
PackageCollectionsModel.Profile(name: "profile-\(UUID().uuidString)"): [PackageCollectionsModel.CollectionSource]()]
try sources.enumerated().forEach { index, source in
let profile = index % 2 == 0 ? Array(profiles.keys)[0] : Array(profiles.keys)[1]
_ = try tsc_await { callback in storage.add(source: source, order: nil, to: profile, callback: callback) }
profiles[profile]?.append(source)
}
let list = try tsc_await { callback in storage.listProfiles(callback: callback) }
XCTAssertEqual(list.count, profiles.count, "list count should match")
try profiles.forEach { profile, profileCollections in
let list = try tsc_await { callback in storage.listSources(in: profile, callback: callback) }
XCTAssertEqual(list.count, profileCollections.count, "list count should match")
}
let buffer = try mockFileSystem.readFileContents(storage.path)
XCTAssertNotEqual(buffer.count, 0, "expected file to be written")
print(buffer)
}
}
| 44.735683 | 150 | 0.664796 |
69ec745ed73f7198e61aa3f06fe68026398374c1 | 414 | //
// NearByCell.swift
// Adventurist
//
// Created by Touseef Sarwar on 09/09/2020.
// Copyright © 2020 Touseef Sarwar. All rights reserved.
//
import UIKit
class LocationCell: UICollectionViewCell {
static var identifier = "LocationCell"
@IBOutlet weak var locationLabel : UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
}
| 17.25 | 57 | 0.661836 |
76edbece08ef259ca2cd90013ef0bee59ce1f3f0 | 1,403 | //
// UIViewControllerExtensions.swift
// BoundlessKit
//
// Created by Akash Desai on 4/9/18.
//
import Foundation
internal extension UIViewController {
static func getViewControllers(ofType aClass: AnyClass) -> [UIViewController] {
return UIApplication.shared.windows.reversed().flatMap({$0.rootViewController?.getChildViewControllers(ofType: aClass)}).flatMap({$0})
}
func getChildViewControllers(ofType aClass: AnyClass) -> [UIViewController] {
var vcs = [UIViewController]()
if aClass == type(of: self) {
vcs.append(self)
}
if let tabController = self as? UITabBarController,
let tabVCs = tabController.viewControllers {
for vc in tabVCs.reversed() {
vcs += vc.getChildViewControllers(ofType: aClass)
}
} else if let navController = self as? UINavigationController {
for vc in navController.viewControllers.reversed() {
vcs += vc.getChildViewControllers(ofType: aClass)
}
} else {
if let vc = self.presentedViewController {
vcs += vc.getChildViewControllers(ofType: aClass)
}
for vc in childViewControllers.reversed() {
vcs += vc.getChildViewControllers(ofType: aClass)
}
}
return vcs
}
}
| 32.627907 | 142 | 0.59943 |
90303e5b15f6b3bd393793dd42be357873037e0d | 746 | import XCTest
import KosignLib
class Tests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure() {
// Put the code you want to measure the time of here.
}
}
}
| 25.724138 | 111 | 0.600536 |
293a6dc9e4ab85bcd01c04d1d9afa2046e374b5c | 1,395 | //
// tipUITests.swift
// tipUITests
//
// Created by Nayoung on 10/19/20.
//
import XCTest
class tipUITests: 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: [XCTApplicationLaunchMetric()]) {
XCUIApplication().launch()
}
}
}
}
| 32.44186 | 182 | 0.651613 |
e87ab14f16645701e7296e344d3250194f83d6c8 | 3,670 | //
// Fragment+CheckoutQuery.swift
// Storefront
//
// Created by Shopify.
// Copyright (c) 2017 Shopify Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Buy
extension Storefront.CheckoutQuery {
@discardableResult
func fragmentForCheckout() -> Storefront.CheckoutQuery { return self
.id()
.ready()
.requiresShipping()
.taxesIncluded()
.email()
.discountApplications(first: 250) { $0
.edges { $0
.node { $0
.fragmentForDiscountApplication()
}
}
}
.shippingDiscountAllocations { $0
.fragmentForDiscountAllocation()
}
.appliedGiftCards { $0
.id()
.balanceV2 { $0
.amount()
.currencyCode()
}
.amountUsedV2 { $0
.amount()
.currencyCode()
}
.lastCharacters()
}
.shippingAddress { $0
.firstName()
.lastName()
.phone()
.address1()
.address2()
.city()
.country()
.countryCodeV2()
.province()
.provinceCode()
.zip()
}
.shippingLine { $0
.handle()
.title()
.priceV2 { $0
.amount()
.currencyCode()
}
}
.note()
.lineItems(first: 250) { $0
.edges { $0
.cursor()
.node { $0
.variant { $0
.id()
.priceV2 { $0
.amount()
.currencyCode()
}
}
.title()
.quantity()
.discountAllocations { $0
.fragmentForDiscountAllocation()
}
}
}
}
.totalDuties { $0
.amount()
.currencyCode()
}
.webUrl()
.currencyCode()
.subtotalPriceV2 { $0
.amount()
.currencyCode()
}
.totalTaxV2 { $0
.amount()
.currencyCode()
}
.totalPriceV2 { $0
.amount()
.currencyCode()
}
.paymentDueV2 { $0
.amount()
.currencyCode()
}
}
}
| 28.015267 | 81 | 0.477929 |
625032166582f34eacf911502fea6a8cde255894 | 2,056 | //
// FoodManager.swift
// WeeklyFoodPlan
//
// Created by vulgur on 2017/3/15.
// Copyright © 2017年 MAD. All rights reserved.
//
import Foundation
import RealmSwift
class FoodManager {
static let shared = FoodManager()
let realm = try! Realm()
func randomFood(of when: Food.When) -> Food {
let whenObject = realm.objects(WhenObject.self).first { (w) -> Bool in
w.value == when.rawValue
}
let results = realm.objects(Food.self).filter("%@ IN whenObjects", whenObject!)
let randomIndex = Int(arc4random_uniform(UInt32(results.count)))
return results[randomIndex]
}
func randomMealFood(of when: Food.When) -> MealFood {
let food = randomFood(of: when)
let mealFood = MealFood(food: food)
return mealFood
}
func allFoods(of when: Food.When) -> [Food] {
let whenObject = realm.objects(WhenObject.self).first { (w) -> Bool in
w.value == when.rawValue
}
let results = realm.objects(Food.self).filter("%@ IN whenObjects", whenObject!)
return results.toArray()
}
func allFoods(of keyword: String) -> [Food] {
var result = Set<Food>()
// by name
let nameResults = realm.objects(Food.self).filter("name CONTAINS %@", keyword).toArray()
result = result.union(nameResults)
// by tag
if let tag = realm.objects(Tag.self).first(where: { (t) -> Bool in
t.name.contains(keyword)
}) {
let tagResults = realm.objects(Food.self).filter("%@ IN tags", tag).toArray()
result = result.union(tagResults)
}
// by ingredient
if let ingredient = realm.objects(Ingredient.self).first(where: { (i) -> Bool in
i.name.contains(keyword)
}) {
let ingredentResults = realm.objects(Food.self).filter("%@ IN ingredients", ingredient).toArray()
result = result.union(ingredentResults)
}
return Array(result)
}
}
| 32.125 | 109 | 0.588521 |
e0b416838137eccfa2696fdc00bb092df5d2c0ce | 1,926 | public enum ImageOrientation {
case portrait
case portraitUpsideDown
case landscapeLeft
case landscapeRight
func rotationNeeded(for targetOrientation: ImageOrientation) -> Rotation {
switch (self, targetOrientation) {
case (.portrait, .portrait), (.portraitUpsideDown, .portraitUpsideDown), (.landscapeLeft, .landscapeLeft), (.landscapeRight, .landscapeRight): return .noRotation
case (.portrait, .portraitUpsideDown): return .rotate180
case (.portraitUpsideDown, .portrait): return .rotate180
case (.portrait, .landscapeLeft): return .rotateCounterclockwise
case (.landscapeLeft, .portrait): return .rotateClockwise
case (.portrait, .landscapeRight): return .rotateClockwise
case (.landscapeRight, .portrait): return .rotateCounterclockwise
case (.landscapeLeft, .landscapeRight): return .rotate180
case (.landscapeRight, .landscapeLeft): return .rotate180
case (.portraitUpsideDown, .landscapeLeft): return .rotateClockwise
case (.landscapeLeft, .portraitUpsideDown): return .rotateCounterclockwise
case (.portraitUpsideDown, .landscapeRight): return .rotateCounterclockwise
case (.landscapeRight, .portraitUpsideDown): return .rotateClockwise
}
}
}
public enum Rotation {
case noRotation
case rotateCounterclockwise
case rotateClockwise
case rotate180
case flipHorizontally
case flipVertically
case rotateClockwiseAndFlipVertically
case rotateClockwiseAndFlipHorizontally
func flipsDimensions() -> Bool {
switch self {
case .noRotation, .rotate180, .flipHorizontally, .flipVertically: return false
case .rotateCounterclockwise, .rotateClockwise, .rotateClockwiseAndFlipVertically, .rotateClockwiseAndFlipHorizontally: return true
}
}
}
| 44.790698 | 173 | 0.699896 |
f8516423d53f640cc2633addf50a6c367f95816f | 856 | //
// AperiodicityEstimation.swift
// WorldInApple
//
// Created by fuziki on 2020/02/09.
// Copyright © 2020 factory.fuziki. All rights reserved.
//
import Foundation
import WorldLib
public class AperiodicityEstimator: WorldInAppleComponents {
private var parameters: WorldInAppleParameters
private var d4cOption = D4COption()
required public init(parameters: WorldInAppleParameters) {
self.parameters = parameters
InitializeD4COption(&d4cOption)
d4cOption.threshold = 0.85
}
public func estimatAperiodicity(x: UnsafeMutablePointer<Double>, x_length: Int32) {
D4C(x, x_length, Int32(parameters.fs), parameters.time_axis,
parameters.f0, Int32(parameters.f0_length), Int32(parameters.fft_size),
&d4cOption, parameters.aperiodicity)
// output: parameters
}
}
| 26.75 | 87 | 0.709112 |
e96cbd8f1babffdc2a3b23ee7717ee438b3593fb | 2,444 | //
// EditViewController.swift
// GenerateCode
//
// Created by zhengjiacheng on 2018/1/24.
// Copyright © 2018年 zhengjiacheng. All rights reserved.
//
import Cocoa
protocol EditViewControllerProtocol: NSObjectProtocol {
func modelUpdated(model: EditMode, isAdd: Bool)
}
class EditViewController: NSWindowController {
var model: EditMode!
weak var delegate: EditViewControllerProtocol?
var isAdd: Bool = false
@IBOutlet weak var keyText: NSTextField!
@IBOutlet weak var valueText: NSTextField!
override func windowDidLoad() {
super.windowDidLoad()
self.window!.delegate = self;
// Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
}
func updateViewWith(model: EditMode, isAdd: Bool){
self.isAdd = isAdd
self.model = model
self.keyText.stringValue = ""
if !model.key.isEmpty {
self.keyText.stringValue = model.key
}
self.valueText.stringValue = ""
if !model.value.isEmpty {
self.valueText.stringValue = model.value
}
self.keyText.delegate = self
self.valueText.delegate = self
self.valueText.becomeFirstResponder()
}
}
extension EditViewController: NSWindowDelegate{
func windowWillClose(_ notification: Notification) {
delegate?.modelUpdated(model: self.model, isAdd: self.isAdd)
}
}
extension EditViewController: NSTextFieldDelegate, NSControlTextEditingDelegate{
override func controlTextDidChange(_ obj: Notification){
guard let textField = obj.object as? NSTextField else{
return
}
if textField == self.keyText {
model.key = textField.stringValue
} else if textField == self.valueText {
model.value = textField.stringValue
}
}
func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
var result = false
if control == self.valueText {
if commandSelector == #selector(insertNewline(_:)) {
textView.insertNewlineIgnoringFieldEditor(self)
result = true
}else if commandSelector == #selector(insertTab(_:)){
textView.insertTabIgnoringFieldEditor(self)
}
}
return result
}
}
| 30.55 | 134 | 0.643617 |
ab44319e1f2a00037aca6d87a3c52cde73469615 | 435 | import UIKit
class GameLogHeaderCell: UITableViewCell {
@IBOutlet weak var monthLabel: UILabel!
@IBOutlet weak var timeLine: UIView!
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.75 | 65 | 0.668966 |
1428385d76200e1a024e89599c1f2b3a0474a6d5 | 1,065 | import Foundation
// https://www.objc.io/blog/2017/12/28/weak-arrays/
final class WeakBox<A: AnyObject> {
weak var unbox: A?
init(_ value: A) {
unbox = value
}
}
struct WeakArray<Element: AnyObject> {
private var items: [WeakBox<Element>] = []
init(_ elements: [Element]) {
items = elements.map { WeakBox($0) }
}
}
extension WeakArray: Collection {
var startIndex: Int { items.startIndex }
var endIndex: Int { items.endIndex }
subscript(_ index: Int) -> Element? {
items[index].unbox
}
func index(after idx: Int) -> Int {
items.index(after: idx)
}
mutating func append(_ element: Element) {
items.append(WeakBox(element))
}
mutating func prune() {
items = items.filter { $0.unbox != nil }
}
typealias EquatableElement = AnyObject & Equatable
mutating func remove<E: EquatableElement>(_ element: E) {
if let index = items.firstIndex(where: { element == $0.unbox as? E }) {
items.remove(at: index)
}
}
}
| 22.1875 | 79 | 0.596244 |
5022712269663120b166575deee2808e81e37c6c | 47,409 | /*
* Copyright 2018-2020 TON DEV SOLUTIONS LTD.
*
* Licensed under the SOFTWARE EVALUATION License (the "License"); you may not use
* this file except in compliance with the License.
*
* 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 TON DEV software governing permissions and
* limitations under the License.
*/
import PromiseKit
import Foundation
import CoreNFC
@available(iOS 13.0, *)
public class CardKeyChainNfcApi: TonNfcApi {
let HMAC_FIELD: String = "hmac"
let KEY_LENGTH_FIELD: String = "length"
let NUMBER_OF_KEYS_FIELD: String = "numberOfKeys"
let OCCUPIED_SIZE_FIELD: String = "occupiedSize"
let FREE_SIZE_FIELD: String = "freeSize"
var keyMacs: [Data] = []
public override init() {}
//Todo: response must look as for TonNfcClientAndroid
public func getKeyChainDataAboutAllKeys(resolve : @escaping NfcResolver, reject : @escaping NfcRejecter) {
print("Start card operation: getAllHmacsOfKeysFromCard")
var keyHmacsAndLens = [[String: String]]()
apduRunner.setCallback(resolve : resolve, reject : reject)
apduRunner.setCardOperation(cardOperation: { () in
self.reselectKeyForHmac()
.then{(response : Data) -> Promise<Data> in
self.getSaultPromise()
}
.then{(sault : Data) -> Promise<Data> in
self.apduRunner.sendApdu(apduCommand: try TonWalletAppletApduCommands.getNumberOfKeysApdu(sault.bytes))
}
.then{(numOfKeys : Data) -> Promise<Data> in
let numOfKeys = ByteArrayAndHexHelper.makeShort(src: numOfKeys.bytes, srcOff: 0)
var hmacPromise = Promise<Data> { promise in promise.fulfill(Data(_ : []))}
//
for ind in 0..<numOfKeys {
hmacPromise = hmacPromise.then{ (response : Data) -> Promise<Data> in
self.getHmac(keyIndex: UInt16(ind))
}
.then { (hmacAndLen : Data) -> Promise<Data> in
// self.keyMacs.append(Data(_ : hmacAndLen.bytes[range : 0..<TonWalletAppletConstants.HMAC_SHA_SIG_SIZE]))
let hmac = Data(_ : hmacAndLen.bytes[range : 0..<TonWalletAppletConstants.HMAC_SHA_SIG_SIZE]).hexEncodedString()
let len = String(ByteArrayAndHexHelper.makeShort(src: hmacAndLen.bytes, srcOff: TonWalletAppletConstants.HMAC_SHA_SIG_SIZE))
keyHmacsAndLens.append([self.HMAC_FIELD : hmac, self.KEY_LENGTH_FIELD : len
])
return Promise<Data> { promise in promise.fulfill(Data(_ : []))}
}
}
return hmacPromise
}
.then{(response : Data) -> Promise<String> in
Promise<String> { promise in
promise.fulfill(self.jsonHelper.makeJsonString(data: keyHmacsAndLens))
}
}
})
apduRunner.startScan()
}
public func getKeyChainInfo(resolve : @escaping NfcResolver, reject : @escaping NfcRejecter) {
print("Start card operation: getKeyChainInfo")
var keyChainInfo: [String : String] = [:]
keyChainInfo[JsonHelper.STATUS_FIELD] = ResponsesConstants.SUCCESS_STATUS
apduRunner.setCallback(resolve : resolve, reject : reject)
apduRunner.setCardOperation(cardOperation: { () in
self.reselectKeyForHmac()
.then{(response : Data) -> Promise<Data> in
self.getSaultPromise()
}
.then{(sault : Data) -> Promise<Data> in
self.apduRunner.sendApdu(apduCommand: try TonWalletAppletApduCommands.getNumberOfKeysApdu(sault.bytes))
}
.then{(numOfKeys : Data) -> Promise<Data> in
keyChainInfo[self.NUMBER_OF_KEYS_FIELD] = String(ByteArrayAndHexHelper.makeShort(src: numOfKeys.bytes, srcOff: 0))
return self.getSaultPromise()
}
.then{(sault : Data) -> Promise<Data> in
self.apduRunner.sendApdu(apduCommand: try TonWalletAppletApduCommands.getGetOccupiedSizeApdu(sault.bytes))
}
.then{(occupiedSize : Data) -> Promise<Data> in
keyChainInfo[self.OCCUPIED_SIZE_FIELD] = String(ByteArrayAndHexHelper.makeShort(src: occupiedSize.bytes, srcOff: 0))
return self.getSaultPromise()
}
.then{(sault : Data) -> Promise<Data> in
self.apduRunner.sendApdu(apduCommand: try TonWalletAppletApduCommands.getGetFreeSizeApdu(sault.bytes))
}
.then{(freeSize : Data) -> Promise<Data> in
keyChainInfo[self.FREE_SIZE_FIELD] = String(ByteArrayAndHexHelper.makeShort(src: freeSize.bytes, srcOff: 0))
return self.getSaultPromise()
}
.then{(response : Data) -> Promise<String> in
Promise<String> { promise in
promise.fulfill(self.jsonHelper.makeJsonString(keyChainInfo))
}
}
})
apduRunner.startScan()
}
public func addKeyIntoKeyChain(newKey: String, resolve : @escaping NfcResolver, reject : @escaping NfcRejecter){
print("Start card operation: addKeyIntoKeyChain" )
guard dataVerifier.checkKeySize(key: newKey, reject : reject) &&
dataVerifier.checkKeyFormat(key: newKey, reject : reject) else {
return
}
print("Got newKey to add:" + newKey)
//Todo: add verificaion that key was not added already
let newKeyBytes = ByteArrayAndHexHelper.hexStrToUInt8Array(hexStr: newKey)
let keySize = UInt16(newKeyBytes.count)
let keySizeBytes = withUnsafeBytes(of: keySize.bigEndian, Array.init)
print(keySizeBytes.count)
print(keySizeBytes[0])
print(keySizeBytes[1])
print("keySize = " + String(keySize))
var macOfKey = Data(_ : [])
var oldNumOfKeys: Int = 0
apduRunner.setCallback(resolve : resolve, reject : reject)
apduRunner.setCardOperation(cardOperation: { () in
self.selectTonAppletAndCheckPersonalizedState()
.then{(response : Data) -> Promise<Data> in
self.reselectKeyForHmac()
}
.then{(response : Data) -> Promise<Data> in
self.getSaultPromise()
}
.then{(sault : Data) -> Promise<Data> in
self.apduRunner.sendApdu(apduCommand: try TonWalletAppletApduCommands.getNumberOfKeysApdu(sault.bytes))
}
.then{(numOfKeys : Data) -> Promise<Data> in
oldNumOfKeys = ByteArrayAndHexHelper.makeShort(src: numOfKeys.bytes, srcOff: 0)
return self.getSaultPromise()
}
.then{(sault : Data) -> Promise<Data> in
self.apduRunner.sendAppletApduAndCheckAppletState(apduCommand: try TonWalletAppletApduCommands.getCheckAvailableVolForNewKeyApdu(keySize: keySizeBytes , sault: sault.bytes))
}
.then{(response : Data) -> Promise<Int> in
macOfKey.append(try self.hmacHelper.computeHmac(data: Data(_ : newKeyBytes)))
return self.addKey(keyBytes: newKeyBytes, macOfKey: macOfKey.bytes)
}
.then{(newNumberOfKeys : Int) -> Promise<String> in
if (newNumberOfKeys != (oldNumOfKeys + 1)) {
throw ResponsesConstants.ERROR_MSG_NUM_OF_KEYS_INCORRECT_AFTER_ADD
}
return self.makeFinalPromise(result : macOfKey.hexEncodedString())
}
})
apduRunner.startScan()
}
public func changeKeyInKeyChain(newKey : String, oldKeyHMac : String, resolve : @escaping NfcResolver, reject : @escaping NfcRejecter) {
print("Start card operation: changeKeyInKeyChain" )
guard dataVerifier.checkMacSize(mac: oldKeyHMac, reject : reject) &&
dataVerifier.checkMacFormat(mac: oldKeyHMac, reject : reject) &&
dataVerifier.checkKeySize(key: newKey, reject : reject) &&
dataVerifier.checkKeyFormat(key: newKey, reject : reject) else {
return
}
print("Got newKey: " + newKey)
print("Got oldKeyHMac: " + oldKeyHMac)
let newKeyBytes = ByteArrayAndHexHelper.hexStrToUInt8Array(hexStr: newKey)
var macOfNewKey = Data(_ : [])
print("newKeySize = " + String(newKeyBytes.count))
var keyIndexToChange: [UInt8] = []
var oldNumOfKeys: Int = 0
apduRunner.setCallback(resolve : resolve, reject : reject)
apduRunner.setCardOperation(cardOperation: { () in
self.selectTonAppletAndCheckPersonalizedState()
.then{(response : Data) -> Promise<Data> in
self.reselectKeyForHmac()
}
.then{(response : Data) -> Promise<Data> in
self.getSaultPromise()
}
.then{(sault : Data) -> Promise<Data> in
self.apduRunner.sendApdu(apduCommand: try TonWalletAppletApduCommands.getNumberOfKeysApdu(sault.bytes))
}
.then{(numOfKeys : Data) -> Promise<Data> in
oldNumOfKeys = ByteArrayAndHexHelper.makeShort(src: numOfKeys.bytes, srcOff: 0)
return self.getIndexAndLenOfKeyInKeyChainPromise(keyHmac: oldKeyHMac)
}
.then{(response : Data) -> Promise<Data> in
let keyIndex = ByteArrayAndHexHelper.makeShort(src : response.bytes, srcOff : 0)
let keyLen = ByteArrayAndHexHelper.makeShort(src : response.bytes, srcOff : 2)
print("keyIndex = " + String(keyIndex))
print("keyLen = " + String(keyLen))
guard keyLen == newKeyBytes.count else {
throw ResponsesConstants.ERROR_MSG_NEW_KEY_LEN_INCORRECT + String(keyLen) + "."
}
keyIndexToChange = response.bytes[range : 0...1]
return Promise<Data> {promise in promise.fulfill(Data(_ : []))}
}
.then{(response : Data) -> Promise<Data> in
self.checkStateAndGetSault()
}
.then{(sault : Data) -> Promise<Data> in
self.apduRunner.sendAppletApduAndCheckAppletState(apduCommand: try TonWalletAppletApduCommands.getInitiateChangeOfKeyApdu(index: keyIndexToChange, sault: sault.bytes))
}
.then{(response : Data) -> Promise<Int> in
macOfNewKey.append(try self.hmacHelper.computeHmac(data: Data(_ : newKeyBytes)))
return self.changeKey(keyBytes : newKeyBytes, macOfKey: macOfNewKey.bytes)
}
.then{(newNumberOfKeys : Int) -> Promise<String> in
if (newNumberOfKeys != oldNumOfKeys) {
throw ResponsesConstants.ERROR_MSG_NUM_OF_KEYS_INCORRECT_AFTER_CHANGE
}
return self.makeFinalPromise(result : macOfNewKey.hexEncodedString())
}
})
apduRunner.startScan()
}
private func changeKey(keyBytes : [UInt8], macOfKey: [UInt8]) -> Promise<Int> {
sendKey(keyBytes : keyBytes, macOfKey: macOfKey, ins : TonWalletAppletApduCommands.INS_CHANGE_KEY_CHUNK)
}
private func addKey(keyBytes : [UInt8], macOfKey: [UInt8]) -> Promise<Int> {
sendKey(keyBytes : keyBytes, macOfKey: macOfKey, ins : TonWalletAppletApduCommands.INS_ADD_KEY_CHUNK)
}
private func sendKey(keyBytes : [UInt8], macOfKey: [UInt8], ins : UInt8) -> Promise<Int> {
let numberOfFullPackets = keyBytes.count / TonWalletAppletConstants.DATA_PORTION_MAX_SIZE
print("numberOfFullPackets = " + String(numberOfFullPackets))
var sendKeyPromise = self.apduRunner.sendApdu(apduCommand:
TonWalletAppletApduCommands.SELECT_TON_WALLET_APPLET_APDU)
for index in 0..<numberOfFullPackets {
let newSendKeyPromise = sendKeyPromise.then{(response : Data) -> Promise<Data> in
self.checkStateAndGetSault()
}
.then{(sault : Data) -> Promise<Data> in
print("#packet " + String(index))
let keyChunk = keyBytes[range: index * TonWalletAppletConstants.DATA_PORTION_MAX_SIZE..<(index + 1) * TonWalletAppletConstants.DATA_PORTION_MAX_SIZE]
return self.apduRunner.sendAppletApduAndCheckAppletState(apduCommand: try TonWalletAppletApduCommands.getSendKeyChunkApdu(ins : ins, p1: index == 0 ? 0x00 : 0x01, keyChunkOrMacBytes: keyChunk, sault: sault.bytes))
}
sendKeyPromise = newSendKeyPromise
}
let tailLen = keyBytes.count % TonWalletAppletConstants.DATA_PORTION_MAX_SIZE
if tailLen > 0 {
sendKeyPromise = sendKeyPromise.then{(response : Data) -> Promise<Data> in
self.checkStateAndGetSault()
}
.then{(sault : Data) -> Promise<Data> in
let keyChunk = keyBytes[range: numberOfFullPackets * TonWalletAppletConstants.DATA_PORTION_MAX_SIZE..<numberOfFullPackets * TonWalletAppletConstants.DATA_PORTION_MAX_SIZE + tailLen]
return self.apduRunner.sendAppletApduAndCheckAppletState(apduCommand: try TonWalletAppletApduCommands.getSendKeyChunkApdu(ins : ins, p1: numberOfFullPackets == 0 ? 0x00 : 0x01, keyChunkOrMacBytes: keyChunk, sault: sault.bytes))
}
}
return sendKeyPromise.then{(response : Data) -> Promise<Data> in
self.checkStateAndGetSault()
}
.then{(sault : Data) -> Promise<Data> in
return self.apduRunner.sendAppletApduAndCheckAppletState(apduCommand: try TonWalletAppletApduCommands.getSendKeyChunkApdu(ins : ins, p1: 0x02, keyChunkOrMacBytes: macOfKey, sault: sault.bytes))
}
.then{(response : Data) -> Promise<Int> in
if (response.count != TonWalletAppletConstants.SEND_CHUNK_LE) {
throw ResponsesConstants.ERROR_MSG_SEND_CHUNK_RESPONSE_LEN_INCORRECT
}
let numOfKeys = ByteArrayAndHexHelper.makeShort(src : response.bytes, srcOff : 0)
if (numOfKeys <= 0 || numOfKeys > TonWalletAppletConstants.MAX_NUMBER_OF_KEYS_IN_KEYCHAIN) {
throw ResponsesConstants.ERROR_MSG_NUMBER_OF_KEYS_RESPONSE_INCORRECT
}
return Promise<Int>{promise in promise.fulfill(numOfKeys)}
}
}
public func getKeyFromKeyChain(keyMac: String, resolve : @escaping NfcResolver, reject : @escaping NfcRejecter) {
print("Start card operation: getKeyFromKeyChain" )
guard dataVerifier.checkMacSize(mac: keyMac, reject : reject) &&
dataVerifier.checkMacFormat(mac: keyMac, reject : reject) else {
return
}
print("Got mac: " + keyMac)
apduRunner.setCallback(resolve : resolve, reject : reject)
apduRunner.setCardOperation(cardOperation: { () in
self.getIndexAndLenOfKeyInKeyChainPromise(keyHmac: keyMac)
.then{(response : Data) -> Promise<String> in
let keyLen = ByteArrayAndHexHelper.makeShort(src : response.bytes, srcOff : 2)
print("keyIndex = " + String(ByteArrayAndHexHelper.makeShort(src : response.bytes, srcOff : 0)))
print("keyLen = " + String(keyLen))
return self.getKeyFromKeyChain(keyLen : keyLen, ind: response.bytes[range : 0...1])
}
})
apduRunner.startScan()
}
private func getKeyFromKeyChain(keyLen : Int, ind : [UInt8]) -> Promise<String> {
let numberOfFullPackets = keyLen / TonWalletAppletConstants.DATA_PORTION_MAX_SIZE
print("numberOfFullPackets = " + String(numberOfFullPackets))
var getKeyPromise = self.apduRunner.sendApdu(apduCommand:
TonWalletAppletApduCommands.SELECT_TON_WALLET_APPLET_APDU)
var startPos: UInt16 = 0
var key = Data(_ : [])
for index in 0..<numberOfFullPackets {
let newGetKeyPromise = getKeyPromise.then{(response : Data) -> Promise<Data> in
self.checkStateAndGetSault()
}
.then{(sault : Data) -> Promise<Data> in
print("packet# " + String(index))
return self.apduRunner.sendAppletApduAndCheckAppletState(apduCommand: try TonWalletAppletApduCommands.getGetKeyChunkApdu(index: ind, startPos: startPos, sault: sault.bytes, le: TonWalletAppletConstants.DATA_PORTION_MAX_SIZE))
}
.then{(keyChunk : Data) -> Promise<Data> in
guard keyChunk.count == TonWalletAppletConstants.DATA_PORTION_MAX_SIZE else {
throw ResponsesConstants.ERROR_KEY_DATA_PORTION_INCORRECT_LEN + String(TonWalletAppletConstants.DATA_PORTION_MAX_SIZE) + "."
}
startPos = startPos + UInt16(TonWalletAppletConstants.DATA_PORTION_MAX_SIZE)
key.append(keyChunk)
return Promise { promise in promise.fulfill(key)}
}
getKeyPromise = newGetKeyPromise
}
let tailLen = keyLen % TonWalletAppletConstants.DATA_PORTION_MAX_SIZE
if tailLen > 0 {
getKeyPromise = getKeyPromise.then{(response : Data) -> Promise<Data> in
self.checkStateAndGetSault()
}
.then{(sault : Data) -> Promise<Data> in
return self.apduRunner.sendAppletApduAndCheckAppletState(apduCommand: try TonWalletAppletApduCommands.getGetKeyChunkApdu(index: ind, startPos: startPos, sault: sault.bytes, le: tailLen))
}
.then{(keyChunk : Data) -> Promise<Data> in
guard keyChunk.count == tailLen else {
throw ResponsesConstants.ERROR_KEY_DATA_PORTION_INCORRECT_LEN + String(tailLen) + "."
}
key.append(keyChunk)
return Promise<Data> { promise in promise.fulfill(key)}
}
}
return getKeyPromise.then{(key : Data) -> Promise<String> in
print("KEY = " + key.hexEncodedString())
return self.makeFinalPromise(result : key.hexEncodedString())
}
}
public func deleteKeyFromKeyChain(keyMac: String, resolve : @escaping NfcResolver, reject : @escaping NfcRejecter) {
print("Start card operation: deleteKeyFromKeyChain" )
guard dataVerifier.checkMacSize(mac: keyMac, reject : reject) &&
dataVerifier.checkMacFormat(mac: keyMac, reject : reject) else {
return
}
print("Got mac: " + keyMac)
apduRunner.setCallback(resolve : resolve, reject : reject)
apduRunner.setCardOperation(cardOperation: { () in
self.selectTonAppletAndCheckDeleteState()
.then{(response : Data) -> Promise<Data> in
self.reselectKeyForHmac()
}
.then{(result : Data) -> Promise<Data> in
self.getIndexAndLenOfKeyInKeyChainPromise(keyHmac: keyMac)
}
.then{(response : Data) -> Promise<Data> in
let keyLen = ByteArrayAndHexHelper.makeShort(src : response.bytes, srcOff : 2)
print("keyIndex = " + String(ByteArrayAndHexHelper.makeShort(src : response.bytes, srcOff : 0)))
print("keyLen = " + String(keyLen))
return self.initiateDeleteOfKeyPromise(keyIndex: response.bytes[range : 0...1])
}
.then{(response : Data) -> Promise<Int> in
self.getDeleteKeyChunkNumOfPacketsPromise()
}
.then{(deleteKeyChunkNumOfPackets : Int) -> Promise<Data> in
print("deleteKeyChunkNumOfPackets = " + String(deleteKeyChunkNumOfPackets))
var deleteKeyChunkPromise = self.apduRunner.sendApdu(apduCommand:
TonWalletAppletApduCommands.SELECT_TON_WALLET_APPLET_APDU)
for index in 0...deleteKeyChunkNumOfPackets {
let newDeleteKeyChunkPromise = deleteKeyChunkPromise.then{(response : Data) -> Promise<Data> in
self.checkStateAndGetSault()
}
.then{(sault : Data) -> Promise<Data> in
print("#iteration " + String(index))
return self.deleteKeyChunkPromise(sault: sault)
}
deleteKeyChunkPromise = newDeleteKeyChunkPromise
}
return deleteKeyChunkPromise
}
.then{(response : Data) -> Promise<Int> in
self.getDeleteKeyRecordNumOfPacketsPromise()
}
.then{(deleteKeyRecordNumOfPackets : Int) -> Promise<Data> in
print("deleteKeyRecordNumOfPackets = " + String(deleteKeyRecordNumOfPackets))
var deleteKeyRecordPromise = self.apduRunner.sendApdu(apduCommand:
TonWalletAppletApduCommands.SELECT_TON_WALLET_APPLET_APDU)
for index in 0...deleteKeyRecordNumOfPackets {
let newDeleteKeyRecordPromise = deleteKeyRecordPromise.then{(response : Data) -> Promise<Data> in
self.checkStateAndGetSault()
}
.then{(sault : Data) -> Promise<Data> in
print("#iteration " + String(index))
return self.deleteKeyRecordPromise(sault: sault)
}
deleteKeyRecordPromise = newDeleteKeyRecordPromise
}
return deleteKeyRecordPromise
}
.then{(response : Data) -> Promise<Data> in
self.getSaultPromise()
}
.then{(sault : Data) -> Promise<Data> in
self.apduRunner.sendApdu(apduCommand: try TonWalletAppletApduCommands.getNumberOfKeysApdu(sault.bytes))
}
.then{(response : Data) -> Promise<String> in
return self.makeFinalPromise(result : String(ByteArrayAndHexHelper.makeShort(src: response.bytes, srcOff: 0)))
}
})
apduRunner.startScan()
}
public func finishDeleteKeyFromKeyChainAfterInterruption(keyMac: String, resolve : @escaping NfcResolver, reject : @escaping NfcRejecter) {
print("Start card operation: finishDeleteKeyFromKeyChainAfterInterruption" )
guard dataVerifier.checkMacSize(mac: keyMac, reject : reject) &&
dataVerifier.checkMacFormat(mac: keyMac, reject : reject) else {
return
}
print("Got mac: " + keyMac)
apduRunner.setCallback(resolve : resolve, reject : reject)
apduRunner.setCardOperation(cardOperation: { () in
self.selectTonAppletAndCheckDeleteState()
.then{(response : Data) -> Promise<Data> in
self.reselectKeyForHmac()
}
.then{(response : Data) -> Promise<Int> in
self.getDeleteKeyChunkNumOfPacketsPromise()
}
.then{(deleteKeyChunkNumOfPackets : Int) -> Promise<Data> in
print("deleteKeyChunkNumOfPackets = " + String(deleteKeyChunkNumOfPackets))
var deleteKeyChunkPromise = Promise<Data> {promise in promise.fulfill(Data(_ : []))}
var deleteKeyChunkIsDone = 0
for index in 0...deleteKeyChunkNumOfPackets {
let newDeleteKeyChunkPromise = deleteKeyChunkPromise.then{(response : Data) -> Promise<Data> in
if deleteKeyChunkIsDone == 1 {
return Promise<Data> { promise in promise.fulfill(Data(_:[1]))}
}
else {
return self.checkStateAndGetSault()
}
}
.then{(sault : Data) -> Promise<Data> in
print("#iteration " + String(index))
return self.deleteKeyChunkPromise(sault: sault)
}
.then{(response : Data) -> Promise<Data> in
deleteKeyChunkIsDone = Int(response.bytes[0])
print("deleteKeyChunkIsDone = " + String(deleteKeyChunkIsDone))
return Promise<Data> { promise in promise.fulfill(Data(_:[]))}
}
deleteKeyChunkPromise = newDeleteKeyChunkPromise
}
return deleteKeyChunkPromise
}
.then{(response : Data) -> Promise<Int> in
self.getDeleteKeyRecordNumOfPacketsPromise()
}
.then{(deleteKeyRecordNumOfPackets : Int) -> Promise<Data> in
print("deleteKeyRecordNumOfPackets = " + String(deleteKeyRecordNumOfPackets))
var deleteKeyRecordPromise = Promise<Data> {promise in promise.fulfill(Data(_ : []))}
var deleteKeyRecordIsDone = 0
for index in 0...deleteKeyRecordNumOfPackets {
let newDeleteKeyRecordPromise = deleteKeyRecordPromise.then{(response : Data) -> Promise<Data> in
if deleteKeyRecordIsDone == 1 {
return Promise<Data> { promise in promise.fulfill(Data(_:[1]))}
}
else {
return self.checkStateAndGetSault()
}
}
.then{(sault : Data) -> Promise<Data> in
print("#iteration " + String(index))
return self.deleteKeyRecordPromise(sault: sault)
}
.then{(response : Data) -> Promise<Data> in
deleteKeyRecordIsDone = Int(response.bytes[0])
print("deleteKeyRecordIsDone = " + String(deleteKeyRecordIsDone))
return Promise<Data> { promise in promise.fulfill(Data(_:[]))}
}
deleteKeyRecordPromise = newDeleteKeyRecordPromise
}
return deleteKeyRecordPromise
}
.then{(response : Data) -> Promise<Data> in
self.getSaultPromise()
}
.then{(sault : Data) -> Promise<Data> in
self.apduRunner.sendApdu(apduCommand: try TonWalletAppletApduCommands.getNumberOfKeysApdu(sault.bytes))
}
.then{(response : Data) -> Promise<String> in
return self.makeFinalPromise(result : String(ByteArrayAndHexHelper.makeShort(src: response.bytes, srcOff: 0)))
}
})
apduRunner.startScan()
}
private func initiateDeleteOfKeyPromise(keyIndex: [UInt8]) -> Promise<Data> {
return self.selectTonAppletAndCheckPersonalizedState()
.then{(response : Data) -> Promise<Data> in
self.getSaultPromise()
}
.then{(sault : Data) -> Promise<Data> in
self.apduRunner.sendApdu(apduCommand: try TonWalletAppletApduCommands.getInitiateDeleteOfKeyApdu(index:keyIndex, sault: sault.bytes))
}
.then{(response : Data) -> Promise<Data> in
if (response.count != TonWalletAppletConstants.INITIATE_DELETE_KEY_LE) {
throw ResponsesConstants.ERROR_MSG_INITIATE_DELETE_KEY_RESPONSE_LEN_INCORRECT
}
let len = ByteArrayAndHexHelper.makeShort(src : response.bytes, srcOff : 2)
if (len <= 0 || len > TonWalletAppletConstants.MAX_KEY_SIZE_IN_KEYCHAIN) {
throw ResponsesConstants.ERROR_MSG_KEY_LENGTH_INCORRECT
}
return Promise{promise in promise.fulfill(Data(_ : []))}
}
}
private func deleteKeyChunkPromise(sault : Data) -> Promise<Data>{
return Promise{promise in promise.fulfill(Data(_ : []))}
.then{_ in self.apduRunner.sendApdu(apduCommand: try TonWalletAppletApduCommands.getDeleteKeyChunkApdu(sault.bytes))
}
.then{(response : Data) -> Promise<Data> in
if (response.count != TonWalletAppletConstants.DELETE_KEY_CHUNK_LE) {
throw ResponsesConstants.ERROR_MSG_DELETE_KEY_CHUNK_RESPONSE_LEN_INCORRECT
}
let status = response.bytes[0]
if (status < 0 || status > 2) {
throw ResponsesConstants.ERROR_MSG_DELETE_KEY_CHUNK_RESPONSE_INCORRECT
}
return Promise { promise in promise.fulfill(response)}
}
}
private func deleteKeyRecordPromise(sault : Data) -> Promise<Data> {
return Promise{promise in promise.fulfill(Data(_ : []))}
.then{_ in self.apduRunner.sendApdu(apduCommand: try TonWalletAppletApduCommands.getDeleteKeyRecordApdu(sault.bytes))
}
.then{(response : Data) -> Promise<Data> in
if (response.count != TonWalletAppletConstants.DELETE_KEY_RECORD_LE) {
throw ResponsesConstants.ERROR_MSG_DELETE_KEY_RECORD_RESPONSE_LEN_INCORRECT
}
let status = response.bytes[0]
if (status < 0 || status > 2) {
throw ResponsesConstants.ERROR_MSG_DELETE_KEY_RECORD_RESPONSE_INCORRECT
}
return Promise { promise in promise.fulfill(response)}
}
}
public func getDeleteKeyRecordNumOfPackets(resolve : @escaping NfcResolver, reject : @escaping NfcRejecter) {
print("Start card operation: getDeleteKeyRecordNumOfPackets")
apduRunner.setCallback(resolve : resolve, reject : reject)
apduRunner.setCardOperation(cardOperation: { () in
return self.reselectKeyForHmac()
.then{(response : Data) -> Promise<Int> in
self.getDeleteKeyRecordNumOfPacketsPromise()
}
.then{(response : Int) -> Promise<String> in
return self.makeFinalPromise(result : String(response))
}
})
apduRunner.startScan()
}
private func getDeleteKeyRecordNumOfPacketsPromise() -> Promise<Int> {
self.selectTonAppletAndGetSault()
.then{(sault : Data) -> Promise<Data> in
self.apduRunner.sendApdu(apduCommand: try TonWalletAppletApduCommands.getDeleteKeyRecordNumOfPacketsApdu(sault.bytes))
}
.then{(response : Data) -> Promise<Int> in
if (response.count != TonWalletAppletConstants.GET_DELETE_KEY_RECORD_NUM_OF_PACKETS_LE) {
throw ResponsesConstants.ERROR_MSG_GET_DELETE_KEY_RECORD_NUM_OF_PACKETS_RESPONSE_LEN_INCORRECT
}
let num = ByteArrayAndHexHelper.makeShort(src : response.bytes, srcOff : 0)
if (num < 0) {
throw ResponsesConstants.ERROR_MSG_GET_DELETE_KEY_RECORD_NUM_OF_PACKETS_RESPONSE_INCORRECT
}
return Promise<Int>{promise in promise.fulfill(ByteArrayAndHexHelper.makeShort(src: response.bytes, srcOff: 0))}
}
}
public func getDeleteKeyChunkNumOfPackets(resolve : @escaping NfcResolver, reject : @escaping NfcRejecter) {
print("Start card operation: getDeleteKeyChunkNumOfPackets")
apduRunner.setCallback(resolve : resolve, reject : reject)
apduRunner.setCardOperation(cardOperation: { () in
return self.reselectKeyForHmac()
.then{(response : Data) -> Promise<Int> in
self.getDeleteKeyChunkNumOfPacketsPromise()
}
.then{(response : Int) -> Promise<String> in
return self.makeFinalPromise(result : String(response))
}
})
apduRunner.startScan()
}
private func getDeleteKeyChunkNumOfPacketsPromise() -> Promise<Int> {
self.selectTonAppletAndGetSault()
.then{(sault : Data) -> Promise<Data> in
self.apduRunner.sendApdu(apduCommand: try TonWalletAppletApduCommands.getDeleteKeyChunkNumOfPacketsApdu(sault.bytes))
}
.then{(response : Data) -> Promise<Int> in
if (response.count != TonWalletAppletConstants.GET_DELETE_KEY_CHUNK_NUM_OF_PACKETS_LE) {
throw ResponsesConstants.ERROR_MSG_GET_DELETE_KEY_CHUNK_NUM_OF_PACKETS_RESPONSE_LEN_INCORRECT
}
let num = ByteArrayAndHexHelper.makeShort(src : response.bytes, srcOff : 0)
if (num < 0) {
throw ResponsesConstants.ERROR_MSG_GET_DELETE_KEY_CHUNK_NUM_OF_PACKETS_RESPONSE_INCORRECT
}
return Promise<Int>{promise in promise.fulfill(ByteArrayAndHexHelper.makeShort(src: response.bytes, srcOff: 0))}
}
}
public func resetKeyChain(resolve : @escaping NfcResolver, reject : @escaping NfcRejecter) {
print("Start card operation resetKeyChain" )
apduRunner.setCallback(resolve : resolve, reject : reject)
apduRunner.setCardOperation(cardOperation: { () in
return self.reselectKeyForHmac()
.then{(response : Data) -> Promise<Data> in
self.getSaultPromise()
}
.then{(sault : Data) -> Promise<Data> in
self.apduRunner.sendApdu(apduCommand: try TonWalletAppletApduCommands.getResetKeyChainApdu(sault.bytes))
}
.then{(response : Data) -> Promise<String> in
self.keyMacs = []
return self.makeFinalPromise(result : ResponsesConstants.DONE_MSG)
}
})
apduRunner.startScan()
}
public func getNumberOfKeys(resolve : @escaping NfcResolver, reject : @escaping NfcRejecter) {
print("Start card operation: getNumberOfKeys" )
apduRunner.setCallback(resolve : resolve, reject : reject)
apduRunner.setCardOperation(cardOperation: { () in
return self.reselectKeyForHmac()
.then{(response : Data) -> Promise<Data> in
self.getSaultPromise()
}
.then{(sault : Data) -> Promise<Data> in
self.apduRunner.sendApdu(apduCommand: try TonWalletAppletApduCommands.getNumberOfKeysApdu(sault.bytes))
}
.then{(response : Data) -> Promise<String> in
if (response.count != TonWalletAppletConstants.GET_NUMBER_OF_KEYS_LE) {
throw ResponsesConstants.ERROR_MSG_GET_NUMBER_OF_KEYS_RESPONSE_LEN_INCORRECT
}
let numOfKeys = ByteArrayAndHexHelper.makeShort(src: response.bytes, srcOff: 0)
if (numOfKeys < 0 || numOfKeys > TonWalletAppletConstants.MAX_NUMBER_OF_KEYS_IN_KEYCHAIN) {
throw ResponsesConstants.ERROR_MSG_NUMBER_OF_KEYS_RESPONSE_INCORRECT
}
return self.makeFinalPromise(result : String(numOfKeys))
}
})
apduRunner.startScan()
}
public func getOccupiedStorageSize(resolve : @escaping NfcResolver, reject : @escaping NfcRejecter) {
print("Start card operation: getOccupiedSize")
apduRunner.setCallback(resolve : resolve, reject : reject)
apduRunner.setCardOperation(cardOperation: { () in
return self.reselectKeyForHmac()
.then{(response : Data) -> Promise<Data> in
self.getSaultPromise()
}
.then{(sault : Data) -> Promise<Data> in
self.apduRunner.sendApdu(apduCommand: try TonWalletAppletApduCommands.getGetOccupiedSizeApdu(sault.bytes))
}
.then{(response : Data) -> Promise<String> in
if (response.count != TonWalletAppletConstants.GET_OCCUPIED_SIZE_LE){
throw ResponsesConstants.ERROR_MSG_GET_OCCUPIED_SIZE_RESPONSE_LEN_INCORRECT
}
let size = ByteArrayAndHexHelper.makeShort(src: response.bytes, srcOff: 0)
if (size < 0) {
throw ResponsesConstants.ERROR_MSG_OCCUPIED_SIZE_RESPONSE_INCORRECT
}
return self.makeFinalPromise(result : String(size))
}
})
apduRunner.startScan()
}
public func getFreeStorageSize(resolve : @escaping NfcResolver, reject : @escaping NfcRejecter) {
print("Start card operation: getFreeSize")
apduRunner.setCallback(resolve : resolve, reject : reject)
apduRunner.setCardOperation(cardOperation: { () in
return self.reselectKeyForHmac()
.then{(response : Data) -> Promise<Data> in
self.getSaultPromise()
}
.then{(sault : Data) -> Promise<Data> in
self.apduRunner.sendApdu(apduCommand: try TonWalletAppletApduCommands.getGetFreeSizeApdu(sault.bytes))
}
.then{(response : Data) -> Promise<String> in
if (response.count != TonWalletAppletConstants.GET_FREE_SIZE_LE){
throw ResponsesConstants.ERROR_MSG_GET_FREE_SIZE_RESPONSE_LEN_INCORRECT
}
let size = ByteArrayAndHexHelper.makeShort(src: response.bytes, srcOff: 0)
if (size < 0) {
throw ResponsesConstants.ERROR_MSG_FREE_SIZE_RESPONSE_INCORRECT
}
return self.makeFinalPromise(result : String(size))
}
})
apduRunner.startScan()
}
public func checkKeyHmacConsistency(keyHmac: String, resolve : @escaping NfcResolver, reject : @escaping NfcRejecter){
print("Start card operation: checkKeyHmacConsistency" )
guard dataVerifier.checkMacSize(mac: keyHmac, reject : reject) &&
dataVerifier.checkMacFormat(mac: keyHmac, reject : reject) else {
return
}
print("Got keyHmac:" + keyHmac)
let keyHmacBytes = ByteArrayAndHexHelper.hexStrToUInt8Array(hexStr: keyHmac)
apduRunner.setCallback(resolve : resolve, reject : reject)
apduRunner.setCardOperation(cardOperation: { () in
return self.reselectKeyForHmac()
.then{(response : Data) -> Promise<Data> in
self.getSaultPromise()
}
.then{(sault : Data) -> Promise<Data> in
self.apduRunner.sendApdu(apduCommand: try TonWalletAppletApduCommands.getCheckKeyHmacConsistencyApdu(keyHmac: keyHmacBytes, sault: sault.bytes))
}
.then{(response : Data) -> Promise<String> in
return self.makeFinalPromise(result : ResponsesConstants.DONE_MSG)
}
})
apduRunner.startScan()
}
//Todo: response must look as for TonNfcClientAndroid
public func getIndexAndLenOfKeyInKeyChain(keyHmac: String, resolve : @escaping NfcResolver, reject : @escaping NfcRejecter){
print("Start card operation: getIndexAndLenOfKeyInKeyChain" )
guard dataVerifier.checkMacSize(mac: keyHmac, reject : reject) &&
dataVerifier.checkMacFormat(mac: keyHmac, reject : reject) else {
return
}
print("Got keyHmac:" + keyHmac)
apduRunner.setCallback(resolve : resolve, reject : reject)
apduRunner.setCardOperation(cardOperation: { () in
self.getIndexAndLenOfKeyInKeyChainPromise(keyHmac: keyHmac)
.then{(response : (Data)) -> Promise<String> in
let index = ByteArrayAndHexHelper.makeShort(src: response.bytes, srcOff: 0)
let len = ByteArrayAndHexHelper.makeShort(src: response.bytes, srcOff: 2)
return self.makeFinalPromise(result : self.jsonHelper.createJson(index : index, len : len))
}
})
apduRunner.startScan()
}
private func getIndexAndLenOfKeyInKeyChainPromise(keyHmac: String) -> Promise<Data>{
let keyHmacBytes = ByteArrayAndHexHelper.hexStrToUInt8Array(hexStr: keyHmac)
return self.reselectKeyForHmac()
.then{(response : Data) -> Promise<Data> in
self.getSaultPromise()
}
.then{(sault : Data) -> Promise<Data> in
self.apduRunner.sendApdu(apduCommand: try TonWalletAppletApduCommands.getGetIndexAndLenOfKeyInKeyChainApdu(keyHmac: keyHmacBytes, sault: sault.bytes))
}
.then{(response : Data) -> Promise<Data> in
if (response.count != TonWalletAppletConstants.GET_KEY_INDEX_IN_STORAGE_AND_LEN_LE) {
throw ResponsesConstants.ERROR_MSG_GET_KEY_INDEX_IN_STORAGE_AND_LEN_RESPONSE_LEN_INCORRECT
}
let index = ByteArrayAndHexHelper.makeShort(src: response.bytes, srcOff: 0)
if (index < 0 || index > TonWalletAppletConstants.MAX_NUMBER_OF_KEYS_IN_KEYCHAIN - 1) {
throw ResponsesConstants.ERROR_MSG_KEY_INDEX_INCORRECT
}
let len = ByteArrayAndHexHelper.makeShort(src: response.bytes, srcOff: 2)
if (len <= 0 || len > TonWalletAppletConstants.MAX_KEY_SIZE_IN_KEYCHAIN) {
throw ResponsesConstants.ERROR_MSG_KEY_LENGTH_INCORRECT
}
return Promise{promise in promise.fulfill(response)}
}
}
public func checkAvailableVolForNewKey(keySize: String, resolve : @escaping NfcResolver, reject : @escaping NfcRejecter){
print("Start card operation: checkAvailableVolForNewKey")
let keySizeVal = UInt16(keySize) ?? 0
guard dataVerifier.checkKeySizeVal(keySizeVal : keySizeVal, reject : reject) else {
return
}
print("Got keySize:" + keySize)
let keySize = UInt16(keySize)
apduRunner.setCallback(resolve : resolve, reject : reject)
apduRunner.setCardOperation(cardOperation: { () in
self.selectTonAppletAndCheckPersonalizedState()
.then{(response : Data) -> Promise<Data> in
self.getSaultPromise()
}
.then{(sault : Data) -> Promise<Data> in
self.apduRunner.sendApdu(apduCommand: try TonWalletAppletApduCommands.getCheckAvailableVolForNewKeyApdu(keySize: [UInt8(keySize! >> 8), UInt8(keySize!)], sault: sault.bytes))
}
.then{(response : Data) -> Promise<String> in
return self.makeFinalPromise(result : ResponsesConstants.DONE_MSG)
}
})
apduRunner.startScan()
}
private func getHmac(keyIndex: UInt16) -> Promise<Data> {
self.reselectKeyForHmac()
.then{(response : Data) -> Promise<Data> in
self.getSaultPromise()
}
.then{(sault : Data) -> Promise<Data> in
self.apduRunner.sendApdu(apduCommand: try TonWalletAppletApduCommands.getGetHmacApdu(index: [UInt8(keyIndex >> 8), UInt8(keyIndex)], sault: sault.bytes))
}
.then{(response : Data) -> Promise<Data> in
if (response.count != TonWalletAppletConstants.HMAC_SHA_SIG_SIZE + 2){
throw ResponsesConstants.ERROR_MSG_GET_HMAC_RESPONSE_LEN_INCORRECT
}
return Promise {promise in promise.fulfill(response)}
}
}
//Todo: response must look as for TonNfcClientAndroid
public func getHmac(index: String, resolve : @escaping NfcResolver, reject : @escaping NfcRejecter){
print("Start card operation: getHmac" )
guard dataVerifier.checkKeyIndexFormat(index : index, reject : reject) else {
return
}
let keyIndex = UInt16(index) ?? 0
guard dataVerifier.checkKeyIndexSize(index : keyIndex, reject : reject) else {
return
}
print("Got index of key:" + index)
apduRunner.setCallback(resolve : resolve, reject : reject)
apduRunner.setCardOperation(cardOperation: { () in
self.getHmac(keyIndex: keyIndex)
.then{(response : Data) -> Promise<String> in
return self.makeFinalPromise(result : response.hexEncodedString())
}
})
apduRunner.startScan()
}
private func selectTonAppletAndCheckPersonalizedState() -> Promise<Data> {
self.apduRunner.sendTonWalletAppletApdu(apduCommand: TonWalletAppletApduCommands.GET_APP_INFO_APDU)
.then{(response : Data) -> Promise<Data> in
if (response.count != TonWalletAppletConstants.GET_APP_INFO_LE) {
throw ResponsesConstants.ERROR_MSG_STATE_RESPONSE_LEN_INCORRECT
}
let appletState = response.bytes[0]
guard appletState == TonWalletAppletConstants.APP_PERSONALIZED else {
throw ResponsesConstants.ERROR_MSG_APPLET_IS_NOT_PERSONALIZED + TonWalletAppletConstants.APPLET_STATES[response.bytes[0]]!
}
return Promise { promise in promise.fulfill(Data())}
}
}
private func selectTonAppletAndCheckDeleteState() -> Promise<Data> {
self.apduRunner.sendTonWalletAppletApdu(apduCommand: TonWalletAppletApduCommands.GET_APP_INFO_APDU)
.then{(response : Data) -> Promise<Data> in
if (response.count != TonWalletAppletConstants.GET_APP_INFO_LE) {
throw ResponsesConstants.ERROR_MSG_STATE_RESPONSE_LEN_INCORRECT
}
let appletState = response.bytes[0]
guard appletState == TonWalletAppletConstants.APP_DELETE_KEY_FROM_KEYCHAIN_MODE else {
throw ResponsesConstants.ERROR_MSG_APPLET_DOES_NOT_WAIT_TO_DELETE_KEY + TonWalletAppletConstants.APPLET_STATES[response.bytes[0]]!
}
return Promise { promise in promise.fulfill(Data())}
}
}
}
| 53.690827 | 243 | 0.596068 |
fb220645b8c81b8aa90d06732565b6a25e537cbe | 1,368 | //
// GridMenuModel.swift
// LTXiOSUtils
// 格式菜单子项实体
// Created by CoderStar on 2020/1/11.
//
import Foundation
/// 格子菜单实体
public struct GridMenuItem {
/// 编码
public var code: String
/// 标题
public var title: String
/// 图片
public var image: UIImage?
/// 角标类型,默认为无
public var markType: CornerMarkType = .none
/// 构造函数
/// - Parameters:
/// - code: 编码
/// - title: 标题
public init(code: String, title: String) {
self.code = code
self.title = title
}
/// 构造函数
/// - Parameters:
/// - code: 编码
/// - title: 标题
/// - image: 图标
public init(code: String, title: String, image: UIImage?) {
self.code = code
self.title = title
self.image = image
}
/// 构造函数
/// - Parameters:
/// - code: 编码
/// - title: 标题
/// - image: 图标
public init(code: String, title: String, image: UIImage?, markType: CornerMarkType) {
self.code = code
self.title = title
self.image = image
self.markType = markType
}
/// /// 构造函数
/// - Parameters:
/// - code: 编码
/// - title: 标题
/// - markType: 角标类型
public init(code: String, title: String, markType: CornerMarkType) {
self.code = code
self.title = title
self.markType = markType
}
}
| 21.375 | 89 | 0.524123 |
c16726ed0f5804f5e524daf97b0f9a7b8c9ab75a | 1,100 | // swift-tools-version:5.3
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "DefaultDecodableWrapper",
products: [
// Products define the executables and libraries a package produces, and make them visible to other packages.
.library(
name: "DefaultDecodableWrapper",
targets: ["DefaultDecodableWrapper"]),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages this package depends on.
.target(
name: "DefaultDecodableWrapper",
dependencies: []),
.testTarget(
name: "DefaultDecodableWrapperTests",
dependencies: ["DefaultDecodableWrapper"]),
]
)
| 37.931034 | 117 | 0.648182 |
dbda3fdecd1f7adb718cf3460e919482402c018c | 1,616 | //
// SecondViewController.swift
// Rickenbacker_Example
//
// Created by Condy on 2021/10/3.
// Copyright © 2021 CocoaPods. All rights reserved.
//
import UIKit
import Rickenbacker
class SecondViewController: VMViewController<SecondViewModel> {
lazy var clickButton: UIButton = {
let button = UIButton.init(type: .custom)
button.frame = CGRect(x: 0, y: 0, width: 150, height: 88)
button.center = self.view.center
button.layer.cornerRadius = 10
button.backgroundColor = UIColor.green
button.setTitle("change title", for: .normal)
button.setTitleColor(UIColor.black, for: .normal)
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 18)
button.rx.tap.subscribe { [weak self] _ in
self?.viewModel.inputs.changeTitle(button.titleLabel?.text)
}.disposed(by: disposeBag)
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
self.setupUI()
self.setupBindings()
}
func setupUI() {
self.view.addSubview(self.clickButton)
self.hbd_tintColor = UIColor.purple
self.hbd_barTintColor = UIColor.green
}
func setupBindings() {
viewModel.outputs.setupTitle.asDriver().drive { [weak self] string in
self?.title = string
}.disposed(by: disposeBag)
viewModel.outputs.changeTitle.subscribe(onNext: { [weak self] string in
self?.title = string
}).disposed(by: disposeBag)
}
override func backAction() {
super.backAction()
}
}
| 29.381818 | 79 | 0.628094 |
90a733f94f66a989a6b4b254e2ed5507b174c651 | 211 | //
// Colors.swift
// RNFTDemo
//
// Created by Eric McGary on 3/16/22.
//
import SwiftUI
extension Color {
static var background = Color("Background")
static var foreground = Color("Foreground")
}
| 15.071429 | 47 | 0.663507 |
23abe3b93329f0e67ef76c53c095dd8870de9287 | 4,151 | //
// FincialCell.swift
// JXLiCai
//
// Created by dengtao on 2017/8/10.
// Copyright © 2017年 JingXian. All rights reserved.
//
import UIKit
class FincialCell: UITableViewCell {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var progressLabel: UILabel!
@IBOutlet weak var blueLabel: UILabel!//新手专享|加息券
@IBOutlet weak var redLabel: UILabel!//限购一次|现金红包
@IBOutlet weak var yearLabel: UILabel!//年化收益
@IBOutlet weak var timeLabel: UILabel!//投资期限
@IBOutlet weak var moneyLabel: UILabel!//起投金额
@IBOutlet weak var colorLabel: UILabel!
// Xib 初始化
override func awakeFromNib() {
super.awakeFromNib()
// self.backgroundColor = UIColor.redColor;
self.blueLabel.layer.cornerRadius = 4.0;
self.blueLabel.layer.masksToBounds = true;
self.redLabel.layer.cornerRadius = 4.0;
self.redLabel.layer.masksToBounds = true;
self.progressLabel.layer.cornerRadius = self.progressLabel.frame.size.width / 2;
self.progressLabel.layer.borderColor = UIColor.gray.cgColor;
self.progressLabel.layer.borderWidth = 3;
self.progressLabel.layer.masksToBounds = true;
self.colorLabel.layer.cornerRadius = self.progressLabel.frame.size.width / 2;
self.colorLabel.layer.borderColor = UIColor.orange.cgColor;
self.colorLabel.layer.borderWidth = 3;
self.colorLabel.layer.masksToBounds = true;
}
func configData(dic:NSDictionary) {
let progress = arc4random() % 100 + 1;
if progress >= 50 {
self.colorLabel.isHidden = true;
self.progressLabel.text = "售馨";
}else{
self.colorLabel.isHidden = false;
self.progressLabel.text = "75%";
}
}
// 弧线
override func draw(_ rect: CGRect) {
// let color = UIColor.orange
// color.set() // 设置线条颜色
// let aPath = UIBezierPath(arcCenter: self.colorLabel.center, radius: self.progressLabel.frame.size.width / 2,
// startAngle: 0, endAngle: (CGFloat)(90*3*M_PI/180), clockwise: true)
// aPath.lineWidth = 3.0 // 线条宽度
// aPath.stroke() // Draws line 根据坐标点连线,不填充
// // aPath.fill() // Draws line 根据坐标点连线,填充
}
// Class 初始化
override init(style: UITableViewCellStyle, reuseIdentifier: String?)
{
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.backgroundColor = UIColor.blue;
}
required init(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)!
}
override func setSelected(_ selected: Bool, animated: Bool) {
// 获取 contentView 所有子控件
// 创建颜色数组
let colors = NSMutableArray.init();
// 获取所有子控件颜色
for view in self.contentView.subviews {
if view.backgroundColor != nil {
colors .add(view.backgroundColor!);
}else{
colors .add(UIColor.clear);
}
}
// 调用super
super.setSelected(selected, animated: animated)
// 修改控件颜色
for i in 0..<self.contentView.subviews.count{
self.contentView.subviews[i].backgroundColor = colors[i] as? UIColor;
}
}
override func setHighlighted(_ highlighted: Bool, animated: Bool) {
// 获取 contentView 所有子控件
// 创建颜色数组
let colors = NSMutableArray.init();
// 获取所有子控件颜色
for view in self.contentView.subviews {
if view.backgroundColor != nil {
colors .add(view.backgroundColor!);
}else{
colors .add(UIColor.clear);
}
}
// 调用super
super.setHighlighted(highlighted, animated: animated);
// 修改控件颜色
for i in 0..<self.contentView.subviews.count{
self.contentView.subviews[i].backgroundColor = colors[i] as? UIColor;
}
}
}
| 30.522059 | 118 | 0.570706 |
9bbcd1c37fe073f1be00d8c3f3e3a6b85f442d24 | 4,731 | // CoachMarkBodyDefaultViewHelper.swift
//
// Copyright (c) 2015 - 2017 Frédéric Maquin <[email protected]>
// Esteban Soto <[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.
import UIKit
// MARK: - Main Class
/// A concrete implementation of the coach mark body view and the
/// default one provided by the library.
open class CoachMarkBodyDefaultViewHelper {
func makeHorizontalConstraints(for views: CoachMarkBodyDefaultSubViews)
-> [NSLayoutConstraint] {
return NSLayoutConstraint.constraints(
withVisualFormat: "H:|-(10)-[hintLabel]-(10)-[separator(==1)][nextLabel(==55)]|",
options: NSLayoutFormatOptions(rawValue: 0), metrics: nil,
views: ["hintLabel": views.hintLabel, "separator": views.separator,
"nextLabel": views.nextLabel]
)
}
func makeVerticalConstraints(for hint: UITextView) -> [NSLayoutConstraint] {
guard let superview = hint.superview else { return [] }
return [
hint.topAnchor.constraint(equalTo: superview.topAnchor, constant: 5),
superview.bottomAnchor.constraint(equalTo: hint.bottomAnchor, constant: 5)
]
}
func configureBackground(_ background: UIView, addTo parent: UIView) {
background.translatesAutoresizingMaskIntoConstraints = false
background.isUserInteractionEnabled = false
parent.addSubview(background)
background.fillSuperview()
}
func configureHint(_ hint: UITextView, addTo parent: UIView) {
hint.translatesAutoresizingMaskIntoConstraints = false
hint.isUserInteractionEnabled = false
hint.backgroundColor = UIColor.clear
hint.isScrollEnabled = false
configureTextPropertiesOfHint(hint)
parent.addSubview(hint)
parent.addConstraints(makeVerticalConstraints(for: hint))
}
func configureSimpleHint(_ hint: UITextView, addTo parent: UIView) {
configureHint(hint, addTo: parent)
hint.leadingAnchor.constraint(equalTo: parent.leadingAnchor, constant: 10).isActive = true
parent.trailingAnchor.constraint(equalTo: hint.trailingAnchor, constant: 10).isActive = true
}
func configureNext(_ next: UILabel, addTo parent: UIView) {
next.translatesAutoresizingMaskIntoConstraints = false
next.isUserInteractionEnabled = false
configureTextPropertiesOfNext(next)
parent.addSubview(next)
next.fillSuperviewVertically()
}
func configureSeparator(_ separator: UIView, addTo parent: UIView) {
separator.backgroundColor = UIColor.gray
separator.translatesAutoresizingMaskIntoConstraints = false
separator.isUserInteractionEnabled = false
parent.addSubview(separator)
separator.topAnchor.constraint(equalTo: parent.topAnchor,
constant: 15).isActive = true
parent.bottomAnchor.constraint(equalTo: separator.bottomAnchor,
constant: 15).isActive = true
}
private func configureTextPropertiesOfHint(_ hint: UITextView) {
hint.textColor = UIColor.darkGray
hint.font = UIFont.systemFont(ofSize: 15.0)
hint.textAlignment = .justified
hint.layoutManager.hyphenationFactor = 1.0
hint.isEditable = false
}
private func configureTextPropertiesOfNext(_ next: UILabel) {
next.textColor = UIColor.darkGray
next.font = UIFont.systemFont(ofSize: 17.0)
next.textAlignment = .center
}
}
typealias CoachMarkBodyDefaultSubViews =
(hintLabel: UITextView, nextLabel: UILabel, separator: UIView)
| 41.13913 | 100 | 0.700698 |
1800861704cf4b4fa20f2cb0248e85ec246e1a72 | 744 | //
// MovieTableViewCell.swift
// MovieBrowser
//
// Created by Mark Struzinski on 1/15/18.
// Copyright © 2018 BobStruz Software. All rights reserved.
//
import UIKit
class MovieTableViewCell: UITableViewCell {
@IBOutlet weak var posterImageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var releaseDateLabel: UILabel!
@IBOutlet weak var averageRatingLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
func configure(with movie: Movie) {
titleLabel.text = movie.title
releaseDateLabel.text = movie.releaseDate
averageRatingLabel.text = "Rating: \(String(format: "%.1F", movie.voteAverage))"
descriptionLabel.text = movie.overview
}
}
| 29.76 | 88 | 0.708333 |
9ced88cebfd08cde0dd4648da10aca4de361aef7 | 1,845 | /// Copyright (c) 2018 Razeware LLC
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
/// distribute, sublicense, create a derivative work, and/or sell copies of the
/// Software in any work that is designed, intended, or marketed for pedagogical or
/// instructional purposes related to programming, coding, application development,
/// or information technology. Permission for such use, copying, modification,
/// merger, publication, distribution, sublicensing, creation of derivative works,
/// or sale is expressly withheld.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
import Foundation
import CoreData
import UIKit
class Attachment: NSManagedObject {
@NSManaged var dateCreated: Date
@NSManaged var image: UIImage?
@NSManaged var note: Note?
}
| 48.552632 | 83 | 0.759892 |
9cf8ec1e4333337c81446ce3f93f2944af9d5f23 | 817 | //
// LoginRouter.swift
// SampleChatApp
//
// Created by Anton Poluianov on 20/06/2020.
// Copyright © 2020 anton.poluianov. All rights reserved.
//
import UIKit
protocol LoginRouting {
func routeToProfileInitSetup()
}
final class LoginRouter {
var rootViewController: UIViewController?
private weak var assembly: LoginAssembly?
init(assembly: LoginAssembly) {
self.assembly = assembly
}
}
extension LoginRouter: LoginRouting {
func routeToProfileInitSetup() {
guard let rootViewController = rootViewController else {
assertionFailure("rootViewController must be set")
return
}
rootViewController.modalPresentationStyle = .overFullScreen
if let viewController = assembly?.makeProfileInitSetupViewController() {
rootViewController.present(viewController, animated: true)
}
}
}
| 21.5 | 74 | 0.76377 |
eb9a0d1274e1d39fd69884b5ccafd667c43c629d | 1,617 | //
// ConfirmPasscodeState.swift
// PasscodeLock
//
// Created by Yanko Dimitrov on 8/28/15.
// Copyright © 2015 Yanko Dimitrov. All rights reserved.
//
import Foundation
struct ConfirmPasscodeState: PasscodeLockStateType {
let title: String
let description: String
let isCancellableAction: Bool
var isBiometricAuthAllowed: Bool = false
fileprivate var passcodeToConfirm: [String]
init(passcode: [String], allowCancellation: Bool = true) {
isCancellableAction = allowCancellation
passcodeToConfirm = passcode
title = localizedStringFor("PasscodeLockConfirmTitle", comment: "Confirm passcode title")
description = localizedStringFor("PasscodeLockConfirmDescription", comment: "Confirm passcode description")
}
func acceptPasscode(_ passcode: [String], fromLock lock: PasscodeLockType) {
if passcode == passcodeToConfirm {
lock.repository.savePasscode(passcode)
lock.delegate?.passcodeLockDidSucceed(lock)
} else {
let mismatchTitle = localizedStringFor("PasscodeLockMismatchTitle", comment: "Passcode mismatch title")
let mismatchDescription = localizedStringFor("PasscodeLockMismatchDescription", comment: "Passcode mismatch description")
let nextState = SetPasscodeState(title: mismatchTitle, description: mismatchDescription, allowCancellation: isCancellableAction)
lock.changeStateTo(nextState)
lock.delegate?.passcodeLockDidFail(lock)
}
}
}
| 34.404255 | 140 | 0.681509 |
e29bdc69553bc3d49c16863d47abe8468a683ac4 | 2,402 | /*
* --------------------------------------------------------------------------------------------------------------------
* <copyright company="Aspose">
* Copyright (c) 2020 Aspose.Slides for Cloud
* </copyright>
* <summary>
* 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.
* </summary>
* --------------------------------------------------------------------------------------------------------------------
*/
import Foundation
/** Slide list. */
public class Slides: ResourceBase {
/** List of slide links. */
public var slideList: [ResourceUri]?
private enum CodingKeys: String, CodingKey {
case slideList
}
public init(selfUri: ResourceUri? = nil, alternateLinks: [ResourceUri]? = nil, slideList: [ResourceUri]? = nil) {
super.init(selfUri: selfUri, alternateLinks: alternateLinks)
self.slideList = slideList
}
required init(from decoder: Decoder) throws {
try super.init(from: decoder)
let values = try decoder.container(keyedBy: CodingKeys.self)
slideList = try values.decode([ResourceUri]?.self, forKey: .slideList)
}
public override func encode(to encoder: Encoder) throws {
try super.encode(to: encoder)
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(slideList, forKey: .slideList)
}
}
| 38.741935 | 119 | 0.636969 |
16b8c4ac297b6fc9b673c3e309593326bddfcab5 | 2,355 | //
// Copyright (c) 2017. Uber Technologies
//
// 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 RIBs
protocol RootInteractable: Interactable, LoggedOutListener, LoggedInListener {
var router: RootRouting? { get set }
var listener: RootListener? { get set }
}
protocol RootViewControllable: ViewControllable {
func present(viewController: ViewControllable)
func dismiss(viewController: ViewControllable)
}
final class RootRouter: LaunchRouter<RootInteractable, RootViewControllable>, RootRouting {
init(interactor: RootInteractable,
viewController: RootViewControllable,
loggedOutBuilder: LoggedOutBuildable,
loggedInBuilder: LoggedInBuildable) {
self.loggedOutBuilder = loggedOutBuilder
self.loggedInBuilder = loggedInBuilder
super.init(interactor: interactor, viewController: viewController)
interactor.router = self
}
override func didLoad() {
super.didLoad()
routeToLoggedOut()
}
func routeToLoggedIn(withPlayer1Name player1Name: String, player2Name: String) {
if let loggedOut = self.loggedOut {
detachChild(loggedOut)
viewController.dismiss(viewController: loggedOut.viewControllable)
self.loggedOut = nil
}
let loggedIn = loggedInBuilder.build(withListener: interactor)
attachChild(loggedIn)
}
// MARK: - Private
private let loggedOutBuilder: LoggedOutBuildable
private let loggedInBuilder: LoggedInBuildable
private var loggedOut: ViewableRouting?
private func routeToLoggedOut() {
let loggedOut = loggedOutBuilder.build(withListener: interactor)
self.loggedOut = loggedOut
attachChild(loggedOut)
viewController.present(viewController: loggedOut.viewControllable)
}
}
| 33.169014 | 91 | 0.716348 |
1c03007490ef91fc4c46615e38c7ae885b1a9f71 | 629 | //
// testDemoPrintView.swift
// testDemoFrameworkPrintName
//
// Created by 5Exceptions6 on 08/05/18.
// Copyright © 2018 5Exceptions. All rights reserved.
//
import Foundation
public class SomeClass : NSObject
{
public class func PrintNameDemo()
{
print("test demo project print custom framework : class function")
// type method implementation goes here
}
public static let shared = SomeClass()
public func Printname() {
print("test demo project print custom framework public function ")
//Do any stuff for production mode
}
}
| 20.966667 | 74 | 0.643879 |
fb4d4c341863b48de0b928c95300b53658f8c385 | 1,337 | //
// AppDelegate.swift
// FiPay App iOS
//
// Created by user209843 on 1/31/22.
//
import UIKit
import Firebase
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 34.282051 | 179 | 0.739716 |
f866c32517fbb42f59cda030a7e4cb8fe6473b4f | 11,643 | //
// MemeViewController.swift
// MemeMe
//
// Created by Arno Seidel on 03.11.20.
//
import UIKit
// MARK: Static elements
let defaultTextTop: String = "Enter top text here"
let defaultTextBottom: String = "Enter bottom text here"
// MARK: Class MemeEditorViewController
class MemeEditorViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate {
// MARK: Outlets
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var cameraButton: UIBarButtonItem!
@IBOutlet weak var shareButton: UIBarButtonItem!
@IBOutlet weak var navigationBar: UINavigationBar!
@IBOutlet weak var toolBar: UIToolbar!
@IBOutlet weak var topTextField: UITextField!
@IBOutlet weak var bottomTextField: UITextField!
// MARK: Properties
let memeTextAttributes: [NSAttributedString.Key: Any] = [
NSAttributedString.Key.strokeColor: UIColor.black,
NSAttributedString.Key.foregroundColor: UIColor.white,
NSAttributedString.Key.font: UIFont(name: "HelveticaNeue-CondensedBlack", size: 40)!,
NSAttributedString.Key.strokeWidth: -6.0
]
// Flag and buffered values for editing memes
var isEdit: Bool = false
var oldMeme: Meme!
var tempMeme: UIImage!
// Function object set by calling view controller, run before dismissig meme editor
var completionHandle: (_ isMemeUpdated: Bool) -> Void = {(_) in }
// MARK: Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
self.setTextFieldProperties(topTextField, defaultText: defaultTextTop)
self.setTextFieldProperties(bottomTextField, defaultText: defaultTextBottom)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Update layout of subviews, esp. imageView frame
self.view.layoutSubviews()
self.cameraButton.isEnabled = UIImagePickerController.isSourceTypeAvailable(.camera)
// Flag for shareButton now set in the respective storyboard item
//self.shareButton.isEnabled = false
// Editing an existing meme
if self.isEdit == true {
self.isEdit = false
// Load in old meme properties
self.imageView.image = self.oldMeme.original
self.topTextField.text = self.oldMeme.topText
self.bottomTextField.text = self.oldMeme.bottomText
// Enable Share button (in case image is not changed)
self.shareButton.isEnabled = true
// Align text fields again
self.alignTextFielsdInImage(self.oldMeme.original)
}
self.subscribeToKeyboardNotifications()
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
// Adapt the text fields in case the device is rotated
coordinator.animate(alongsideTransition: nil) { _ in
if let image = self.imageView.image {
self.alignTextFielsdInImage(image)
}
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.unsubscribeFromKeyboardNotifications()
}
// MARK: Actions
@IBAction func pickanImageFromAlbum(_ sender: Any) {
self.pickAnImage(sourceType: .photoLibrary)
}
@IBAction func pickAnImageByCamera(_ sender: Any) {
self.pickAnImage(sourceType: .camera)
}
@IBAction func shareMeme(_ sender: Any) {
self.tempMeme = self.generateMemedImage()
// Create activity controller for sharing the meme present in the editor
let activityController = UIActivityViewController(activityItems: [self.tempMeme!], applicationActivities: nil)
activityController.completionWithItemsHandler = { (activityType, completed, returnedItems, error) in
if !completed {
self.completionHandle(false)
return
}
self.save()
self.completionHandle(true)
}
self.present(activityController, animated: true, completion: nil)
}
@IBAction func cancelEditor(_ sender: Any) {
self.completionHandle(false)
self.dismiss(animated: true, completion: nil)
}
// MARK: UIImagePickerControllerDelegate methods
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
self.imageView.image = image
self.alignTextFielsdInImage(image)
// Enable Share button
self.shareButton.isEnabled = true
} else {
print("image not existent")
}
picker.dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
// MARK: UITextFieldDelegate methods
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
textField.text = ""
return true
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
// MARK: Helper methods
func pickAnImage(sourceType: UIImagePickerController.SourceType) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = sourceType
self.present(imagePicker, animated: true, completion: nil)
}
func setTextFieldProperties(_ textfield: UITextField, defaultText: String = "") {
textfield.text = defaultText
textfield.defaultTextAttributes = memeTextAttributes
textfield.textAlignment = .center
textfield.delegate = self
}
func alignTextFielsdInImage(_ myImage: UIImage) {
let imageSize = self.imageView.image?.size
let imageAspectRatio: CGFloat = imageSize!.height / imageSize!.width
let frameSize = self.imageView.frame.size
let frameAspectRatio: CGFloat = frameSize.height / frameSize.width
var verticalConstant: CGFloat = 5.0
var horizontalConstant: CGFloat = 8.0
/* Compute the size of the image as seen on display (not in image pixels!) and
update the constraint constants for the textfields */
if imageAspectRatio > frameAspectRatio {
let scaledImageWidth = 1.0 / imageAspectRatio * frameSize.height
horizontalConstant += 0.5 * (frameSize.width - scaledImageWidth)
} else {
let scaledImageHeight = imageAspectRatio * frameSize.width
verticalConstant += 0.5 * (frameSize.height - scaledImageHeight)
}
// Adapt top and bottom textfield for the size of the chosen image
for constraint in self.view.constraints {
if constraint.identifier == "horizontalTextFieldConstraint" {
constraint.constant = horizontalConstant
} else if constraint.identifier == "verticalTextFieldConstraint" {
constraint.constant = verticalConstant
}
}
self.view.setNeedsUpdateConstraints()
}
func generateMemedImage() -> UIImage {
// Hide toolbar and navigationbar in meme
self.hideToolbarAndNavBar(true)
// Render view to an image
UIGraphicsBeginImageContext(self.view.frame.size)
self.view.drawHierarchy(in: self.view.frame, afterScreenUpdates: true)
let memedImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
// Crop meme to the original image size
let frameSize = self.imageView.frame.size
let frameAspectRatio: CGFloat = frameSize.height / frameSize.width
let imageSize = self.imageView.image?.size
let imageAspectRatio: CGFloat = imageSize!.height / imageSize!.width
var cropRectangular: CGRect = self.imageView.frame
do { // Compute CGRect for cropping
if imageAspectRatio > frameAspectRatio {
cropRectangular.size.height = frameSize.height
cropRectangular.size.width = 1.0 / imageAspectRatio * cropRectangular.size.height
cropRectangular.origin.x = (frameSize.width - cropRectangular.size.width) / 2
cropRectangular.origin.y = 0
} else {
cropRectangular.size.width = frameSize.width
cropRectangular.size.height = imageAspectRatio * cropRectangular.size.width
cropRectangular.origin.x = 0
cropRectangular.origin.y = (frameSize.height - cropRectangular.size.height) / 2
}
}
let imageRef = memedImage.cgImage!.cropping(to: cropRectangular)!
// Present toolbar and navigationbar again
self.hideToolbarAndNavBar(false)
return UIImage(cgImage: imageRef, scale: memedImage.scale, orientation: memedImage.imageOrientation)
}
// Create a meme object and save it to the memes array in the app delegate
func save() {
// Update the meme
let newMeme = Meme(topText: topTextField.text!, bottomText: bottomTextField.text!, originalImage: self.imageView.image!, memedImage: self.tempMeme!)
// Add it to the memes array in app delegate
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.memes.append(newMeme)
}
func hideToolbarAndNavBar(_ hidden: Bool) {
self.navigationBar.isHidden = hidden
self.toolBar.isHidden = hidden
}
// MARK: Keyboard Notification methods
func subscribeToKeyboardNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
func unsubscribeFromKeyboardNotifications() {
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
}
@objc func keyboardWillShow(_ notification: Notification) {
// Change view only for the bottom text field
if self.bottomTextField.isEditing {
self.view.frame.origin.y = -getKeyboardHeight(notification)
}
}
@objc func keyboardWillHide(_ notification: Notification) {
// Set frame back in case of keyboard is hiding
self.view.frame.origin.y = 0
}
func getKeyboardHeight(_ notification: Notification) -> CGFloat {
let userInfo = notification.userInfo
let keyboardSize = userInfo![UIResponder.keyboardFrameEndUserInfoKey] as! NSValue
return keyboardSize.cgRectValue.height
}
}
| 36.04644 | 156 | 0.650691 |
6956ca5bc15b3b8b37d85d9ca32b59da91b63e9b | 2,175 | //
// GameStateInfo.swift
// AahToZzz
//
// Created by David Fierstein on 2/13/18.
// Copyright © 2018 David Fierstein. All rights reserved.
// Works with GameState. Each
// Game has its GameState saved in the GameData managed object.
// Not yet in use, but
// could be used for info such as which game or view controller was last open when the game was last opened
// or any other game state info
struct GameStateInfo {
var state: GameState?
var viewController: String?
var screenshotPath: String?
var firstTimePlaying: Bool = true
// for reference
// @objc enum GameState: Int {
// case firstTime = 0
// case playingThreeLetter = 1
// case home = 2
// case tutorial = 3
// case statsGraph = 4
// case firstTimePlaying = 5
// }
init() {
}
init(gameState: GameState) {
self.state = gameState
guard let stateCase = self.state?.rawValue else {
return
}
// Dummy info for now
switch stateCase {
case 0 :
firstTimePlaying = true
viewController = "playing2"
screenshotPath = "somePath"
case 1 :
firstTimePlaying = false
viewController = "playing2"
screenshotPath = "somePath"
case 2:
firstTimePlaying = false
viewController = "playing2"
screenshotPath = "somePath"
case 3:
firstTimePlaying = false
viewController = "playing2"
screenshotPath = "somePath"
case 4:
firstTimePlaying = false
viewController = "playing2"
screenshotPath = "somePath"
case 5:
firstTimePlaying = false
viewController = "playing2"
screenshotPath = "somePath"
default :
firstTimePlaying = false
viewController = "playing2"
screenshotPath = "somePath"
}
}
}
| 25 | 107 | 0.523218 |
8f85dfb028e58918416feb76472c093733f8815e | 1,817 | //
// MIT License
//
// Copyright (c) 2018 Jesper Flodin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
public struct ActionData {
public fileprivate(set) var title: String?
public fileprivate(set) var subtitle: String?
public fileprivate(set) var image: UIImage?
public init(title: String) {
self.title = title
}
public init(title: String, subtitle: String) {
self.init(title: title)
self.subtitle = subtitle
}
public init(title: String, subtitle: String, image: UIImage) {
self.init(title: title, subtitle: subtitle)
self.image = image
}
public init(title: String, image: UIImage) {
self.init(title: title)
self.image = image
}
}
| 35.627451 | 82 | 0.698404 |
2085e86b0f54b9a9c7b49cdf1239b6cce5a83a15 | 1,353 | //
// AppDelegate.swift
// moovyApp
//
// Created by José Andrés Puglia on 7/26/21.
//
import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 36.567568 | 179 | 0.74575 |
7a15033fb71c121615465b598f4e195eec8bb618 | 1,474 | //
// Transaction+UI.swift
// AppKit
//
// Created by Nicholas Bosak on 10/11/16.
//
import Foundation
import ModelKit
extension Transaction {
var showsReceipt: Bool {
guard let status = self.status else { return false }
switch status {
case .approved, .requested:
return true
case .blocked, .declined, .reversed:
return false
}
}
var showsExpenseType: Bool {
guard let status = self.status else { return false }
switch status {
case .approved, .requested:
return true
case .blocked, .declined, .reversed:
return false
}
}
}
extension TransactionStatus {
var displayColor: UIColor {
switch self {
case .blocked, .declined:
return .red
case .requested, .approved:
return .gray
case .reversed:
return .green
}
}
var displayIcon: UIImage? {
switch self {
case .approved:
return UIImage(named: "check")?.withRenderingMode(.alwaysTemplate)
case .blocked, .declined:
return UIImage(named: "strike")?.withRenderingMode(.alwaysTemplate)
case .requested:
return UIImage(named: "hist_requested")?.withRenderingMode(.alwaysTemplate)
case .reversed:
return UIImage(named: "hist_reversal")?.withRenderingMode(.alwaysTemplate)
}
}
}
| 20.191781 | 87 | 0.574627 |
237eba98159826807449bc519dde321676b20d1f | 235 | //
// Identifier.swift
// JerryBit
//
// Created by HanSJin on 2020/12/07.
//
import Foundation
// MARK: - Identifier
protocol Identifier {
}
extension Identifier {
static var identifier: String {
"\(self)"
}
}
| 11.190476 | 37 | 0.617021 |
111e7606dc948fdddeb1172af0ed0ae6c0b79caa | 2,988 | //
// NSObject+Extension.swift
// Copyright (c) 2015-2016 Red Rain (http://mochxiao.com).
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
// MARK: - Associate Object
public extension NSObject {
/// Sets an associated value for a given object using a weak reference to the associated object.
/// **Note**: the `key` underlying type must be String.
public func associate(assignObject object: Any?, forKey key: UnsafeRawPointer) {
let strKey: String = convertUnsafePointerToSwiftType(key)
willChangeValue(forKey: strKey)
objc_setAssociatedObject(self, key, object, .OBJC_ASSOCIATION_ASSIGN)
didChangeValue(forKey: strKey)
}
/// Sets an associated value for a given object using a strong reference to the associated object.
/// **Note**: the `key` underlying type must be String.
public func associate(retainObject object: Any?, forKey key: UnsafeRawPointer) {
let strKey: String = convertUnsafePointerToSwiftType(key)
willChangeValue(forKey: strKey)
objc_setAssociatedObject(self, key, object, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
didChangeValue(forKey: strKey)
}
/// Sets an associated value for a given object using a copied reference to the associated object.
/// **Note**: the `key` underlying type must be String.
public func associate(copyObject object: Any?, forKey key: UnsafeRawPointer) {
let strKey: String = convertUnsafePointerToSwiftType(key)
willChangeValue(forKey: strKey)
objc_setAssociatedObject(self, key, object, .OBJC_ASSOCIATION_COPY_NONATOMIC)
didChangeValue(forKey: strKey)
}
/// Returns the value associated with a given object for a given key.
/// **Note**: the `key` underlying type must be String.
public func associatedObject(forKey key: UnsafeRawPointer) -> Any? {
return objc_getAssociatedObject(self, key)
}
}
| 48.193548 | 102 | 0.723896 |
504ced0bdd93f1a425bf5e453487dec9d67be92e | 236 | import Foundation
import Cocoa
import Combine
extension NSWindow {
var screenDidChange: AnyPublisher<NSScreen?, Never> {
publisher(for: \.screen)
.prepend(screen)
.eraseToAnyPublisher()
}
}
| 18.153846 | 57 | 0.635593 |
48cee59948e78d6b9fd35ff875379fe433faca56 | 2,625 | //
// AppDelegate.swift
// Tic Tac Toe
//
// Created by MR.Robot 💀 on 06/11/2018.
// Copyright © 2018 Joselson Dias. All rights reserved.
//
import UIKit
import RealmSwift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// MARK: Realm Data Address
print(Realm.Configuration.defaultConfiguration.fileURL!)
// MARK: Initializing Realm database
do{
let realm = try Realm()
} catch {
print("Error initialising new realm, \(error)")
}
// MARK: Printing path for userDefaults data
print(NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as String)
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:.
}
}
| 42.33871 | 285 | 0.718476 |
715ed31af2ddd73f174d396add5b7e5a34cbf498 | 573 | //
// BRPageControlTests.swift
// BRPageControl
//
// Created by anho on 01/05/2018.
// Copyright © 2018 BRPageControl. All rights reserved.
//
import Foundation
import XCTest
import BRPageControl
class BRPageControlTests: XCTestCase {
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
//// XCTAssertEqual(BRPageControl().text, "Hello, World!")
}
static var allTests = [
("testExample", testExample),
]
}
| 23.875 | 96 | 0.671902 |
20600f3cd5a86f26006b2955e1a5c00292cd4eaf | 9,321 | import KsApi
import Library
import Prelude
import UIKit
private enum Layout {
enum CTAContainerView {
static let minHeight: CGFloat = 130
}
}
public protocol ProjectPamphletViewControllerDelegate: AnyObject {
func projectPamphlet(
_ controller: ProjectPamphletViewController,
panGestureRecognizerDidChange recognizer: UIPanGestureRecognizer
)
}
public final class ProjectPamphletViewController: UIViewController, MessageBannerViewControllerPresenting {
internal weak var delegate: ProjectPamphletViewControllerDelegate?
fileprivate let viewModel: ProjectPamphletViewModelType = ProjectPamphletViewModel()
internal var messageBannerViewController: MessageBannerViewController?
fileprivate var navBarController: ProjectNavBarViewController!
fileprivate var contentController: ProjectPamphletContentViewController!
@IBOutlet private var navBarTopConstraint: NSLayoutConstraint!
private let pledgeCTAContainerView: PledgeCTAContainerView = {
PledgeCTAContainerView(frame: .zero) |> \.translatesAutoresizingMaskIntoConstraints .~ false
}()
public static func configuredWith(
projectOrParam: Either<Project, Param>,
refTag: RefTag?
) -> ProjectPamphletViewController {
let vc = Storyboard.ProjectPamphlet.instantiate(ProjectPamphletViewController.self)
vc.viewModel.inputs.configureWith(projectOrParam: projectOrParam, refTag: refTag)
return vc
}
public override func viewDidLoad() {
super.viewDidLoad()
self.configurePledgeCTAContainerView()
self.navBarController = self.children
.compactMap { $0 as? ProjectNavBarViewController }.first
self.navBarController.delegate = self
self.contentController = self.children
.compactMap { $0 as? ProjectPamphletContentViewController }.first
self.contentController.delegate = self
self.pledgeCTAContainerView.delegate = self
self.viewModel.inputs.initial(topConstraint: self.initialTopConstraint)
self.messageBannerViewController = self.configureMessageBannerViewController(on: self)
NotificationCenter.default
.addObserver(
self,
selector: #selector(ProjectPamphletViewController.didBackProject),
name: NSNotification.Name.ksr_projectBacked,
object: nil
)
self.viewModel.inputs.viewDidLoad()
}
public override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.viewModel.inputs.viewWillAppear(animated: animated)
}
public override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.setInitial(
constraints: [self.navBarTopConstraint],
constant: self.initialTopConstraint
)
self.updateContentInsets()
}
public override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.viewModel.inputs.viewDidAppear(animated: animated)
}
private var initialTopConstraint: CGFloat {
return self.parent?.view.safeAreaInsets.top ?? 0.0
}
private func configurePledgeCTAContainerView() {
// Configure subviews
_ = (self.pledgeCTAContainerView, self.view)
|> ksr_addSubviewToParent()
self.pledgeCTAContainerView.retryButton.addTarget(
self, action: #selector(ProjectPamphletViewController.pledgeRetryButtonTapped), for: .touchUpInside
)
// Configure constraints
let pledgeCTAContainerViewConstraints = [
self.pledgeCTAContainerView.leftAnchor.constraint(equalTo: self.view.leftAnchor),
self.pledgeCTAContainerView.rightAnchor.constraint(equalTo: self.view.rightAnchor),
self.pledgeCTAContainerView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor)
]
NSLayoutConstraint.activate(pledgeCTAContainerViewConstraints)
}
public override func bindViewModel() {
super.bindViewModel()
self.viewModel.outputs.goToRewards
.observeForControllerAction()
.observeValues { [weak self] params in
let (project, refTag) = params
self?.goToRewards(project: project, refTag: refTag)
}
self.viewModel.outputs.goToManagePledge
.observeForControllerAction()
.observeValues { [weak self] params in
self?.goToManagePledge(params: params)
}
self.viewModel.outputs.configureChildViewControllersWithProject
.observeForUI()
.observeValues { [weak self] project, refTag in
self?.contentController.configureWith(value: (project, refTag))
self?.navBarController.configureWith(project: project, refTag: refTag)
}
self.viewModel.outputs.setNavigationBarHiddenAnimated
.observeForUI()
.observeValues { [weak self] in self?.navigationController?.setNavigationBarHidden($0, animated: $1) }
self.viewModel.outputs.setNeedsStatusBarAppearanceUpdate
.observeForUI()
.observeValues { [weak self] in
UIView.animate(withDuration: 0.3) { self?.setNeedsStatusBarAppearanceUpdate() }
}
self.viewModel.outputs.topLayoutConstraintConstant
.observeForUI()
.observeValues { [weak self] value in
self?.navBarTopConstraint.constant = value
}
self.viewModel.outputs.configurePledgeCTAView
.observeForUI()
.observeValues { [weak self] value in
self?.pledgeCTAContainerView.configureWith(value: value)
}
self.viewModel.outputs.dismissManagePledgeAndShowMessageBannerWithMessage
.observeForControllerAction()
.observeValues { [weak self] message in
self?.dismiss(animated: true, completion: {
self?.messageBannerViewController?.showBanner(with: .success, message: message)
})
}
self.viewModel.outputs.popToRootViewController
.observeForControllerAction()
.observeValues { [weak self] in
self?.navigationController?.popToRootViewController(animated: false)
}
}
public override func willTransition(
to newCollection: UITraitCollection,
with _: UIViewControllerTransitionCoordinator
) {
self.viewModel.inputs.willTransition(toNewCollection: newCollection)
}
// MARK: - Private Helpers
@objc private func didBackProject() {
self.viewModel.inputs.didBackProject()
}
private func setInitial(constraints: [NSLayoutConstraint?], constant: CGFloat) {
constraints.forEach {
$0?.constant = constant
}
}
private func goToRewards(project: Project, refTag: RefTag?) {
let vc = RewardsCollectionViewController.controller(with: project, refTag: refTag)
self.present(vc, animated: true)
}
private func goToManagePledge(params: ManagePledgeViewParamConfigData) {
let vc = ManagePledgeViewController.instantiate()
|> \.delegate .~ self
vc.configureWith(params: params)
let nc = RewardPledgeNavigationController(rootViewController: vc)
if AppEnvironment.current.device.userInterfaceIdiom == .pad {
_ = nc
|> \.modalPresentationStyle .~ .pageSheet
}
self.present(nc, animated: true)
}
private func updateContentInsets() {
let ctaViewSize = self.pledgeCTAContainerView.systemLayoutSizeFitting(
UIView.layoutFittingCompressedSize
)
self.contentController.additionalSafeAreaInsets = UIEdgeInsets(bottom: ctaViewSize.height)
}
// MARK: - Selectors
@objc func pledgeRetryButtonTapped() {
self.viewModel.inputs.pledgeRetryButtonTapped()
}
}
// MARK: - PledgeCTAContainerViewDelegate
extension ProjectPamphletViewController: PledgeCTAContainerViewDelegate {
func pledgeCTAButtonTapped(with state: PledgeStateCTAType) {
self.viewModel.inputs.pledgeCTAButtonTapped(with: state)
}
}
// MARK: - ProjectPamphletContentViewControllerDelegate
extension ProjectPamphletViewController: ProjectPamphletContentViewControllerDelegate {
public func projectPamphletContent(
_: ProjectPamphletContentViewController,
didScrollToTop: Bool
) {
self.navBarController.setDidScrollToTop(didScrollToTop)
}
public func projectPamphletContent(
_: ProjectPamphletContentViewController,
imageIsVisible: Bool
) {
self.navBarController.setProjectImageIsVisible(imageIsVisible)
}
public func projectPamphletContent(
_: ProjectPamphletContentViewController,
scrollViewPanGestureRecognizerDidChange recognizer: UIPanGestureRecognizer
) {
self.delegate?.projectPamphlet(self, panGestureRecognizerDidChange: recognizer)
}
}
// MARK: - VideoViewControllerDelegate
extension ProjectPamphletViewController: VideoViewControllerDelegate {
public func videoViewControllerDidFinish(_: VideoViewController) {
self.navBarController.projectVideoDidFinish()
}
public func videoViewControllerDidStart(_: VideoViewController) {
self.navBarController.projectVideoDidStart()
}
}
// MARK: - ManagePledgeViewControllerDelegate
extension ProjectPamphletViewController: ManagePledgeViewControllerDelegate {
func managePledgeViewController(
_: ManagePledgeViewController,
managePledgeViewControllerFinishedWithMessage message: String?
) {
self.viewModel.inputs.managePledgeViewControllerFinished(with: message)
}
}
// MARK: - ProjectNavBarViewControllerDelegate
extension ProjectPamphletViewController: ProjectNavBarViewControllerDelegate {
public func projectNavBarControllerDidTapTitle(_: ProjectNavBarViewController) {
self.contentController.tableView.scrollToTop()
}
}
| 31.812287 | 108 | 0.758824 |
28901e1f45662fed1732b3918d6bef03fdd16219 | 4,308 | // Copyright 2017 Esri.
//
// 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 ArcGIS
fileprivate let rotationKeyPath = #keyPath(AGSMapView.rotation)
public class NorthArrowView: RoundedImageView {
@IBOutlet weak var mapView: AGSMapView? {
willSet {
mapView?.removeObserver(self, forKeyPath: rotationKeyPath)
}
didSet {
// Add NorthArrowController as an observer of the mapView's rotation.
mapView?.addObserver(self, forKeyPath: rotationKeyPath, options: [.new], context: &kvoContext)
setVisibilityFromMapView()
}
}
@IBInspectable var autoHide:Bool = true
@IBInspectable var tapForNorth:Bool = true {
didSet {
self.isUserInteractionEnabled = tapForNorth
if self.isUserInteractionEnabled {
self.addGestureRecognizer(tapGesture)
} else {
self.removeGestureRecognizer(tapGesture)
}
}
}
lazy var tapGesture:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(resetNorth))
private var kvoContext = 0
// Track any alpha override that may have been set in the Storyboard.
private var initialAlpha:CGFloat?
@objc func resetNorth() {
self.mapView?.setViewpointRotation(0, completion: nil)
}
func setVisibilityFromMapView(animate:Bool = false) {
DispatchQueue.main.async { [weak self] in
self?.doSetVisibilityFromMapiew(animate: animate)
}
}
private func doSetVisibilityFromMapiew(animate:Bool = false) {
guard autoHide else {
isHidden = false
return
}
if !isHidden && initialAlpha == nil {
// Remember this for when we re-show. Could be non-zero from the Storyboard.
initialAlpha = alpha
}
guard let maxAlpha = initialAlpha, maxAlpha > 0 else {
// No point animating if maxAlpha is fully transparent
return
}
let duration = animate ? 0.25 : 0
if mapView?.rotation != 0 {
guard isHidden else {
// Already visible. No need to animate
return
}
// Show if there's a MapView and rotation <> 0
isHidden = false
UIView.animate(withDuration: duration, animations: {
self.alpha = maxAlpha
})
} else {
guard alpha > 0 else {
// Already hidden. No need to animate
return
}
UIView.animate(withDuration: duration, animations: { [weak self] in
self?.alpha = 0
}, completion: { [weak self] _ in
self?.isHidden = true
})
}
}
override public func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == rotationKeyPath, context == &kvoContext {
// Rotate north arrow to match the map view rotation.
let mapRotation = self.degreesToRadians(degrees: (360 - (self.mapView?.rotation ?? 0)))
let transform = CGAffineTransform(rotationAngle: mapRotation)
DispatchQueue.main.async { [weak self] in
self?.transform = transform
}
setVisibilityFromMapView(animate: true)
}
else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
}
}
func degreesToRadians(degrees : Double) -> CGFloat {
return CGFloat(degrees * Double.pi / 180)
}
}
| 33.92126 | 158 | 0.596332 |
ac48c5ec738d543d278bee56594bad522e1e4159 | 2,497 | //
// DataCell.swift
// SwiftDataTables
//
// Created by Pavan Kataria on 22/02/2017.
// Copyright © 2017 Pavan Kataria. All rights reserved.
//
import UIKit
class DataCell: UICollectionViewCell {
//MARK: - Properties
private enum Properties {
static let verticalMargin: CGFloat = 0
static let horizontalMargin: CGFloat = 15
static let widthConstant: CGFloat = 20
}
let dataLabel = UILabel()
let separator = UIView()
//MARK: - Lifecycle
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setup() {
dataLabel.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(dataLabel)
NSLayoutConstraint.activate([
dataLabel.widthAnchor.constraint(greaterThanOrEqualToConstant: Properties.widthConstant),
dataLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: Properties.verticalMargin),
dataLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -Properties.verticalMargin),
dataLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: Properties.horizontalMargin),
dataLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: Properties.horizontalMargin),
])
separator.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(separator)
NSLayoutConstraint.activate([
separator.widthAnchor.constraint(equalTo: contentView.widthAnchor, multiplier: 1.0),
separator.heightAnchor.constraint(equalToConstant: 1),
separator.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: 0),
separator.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 0),
separator.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: 0),
])
}
func configure(_ viewModel: DataCellViewModel){
self.dataLabel.text = viewModel.data.stringRepresentation
// self.contentView.backgroundColor = .white
}
func updateUI(textColor: UIColor, font: UIFont, separatorColor: UIColor) {
dataLabel.textColor = textColor
dataLabel.font = font
separator.backgroundColor = separatorColor
}
}
| 37.833333 | 124 | 0.693632 |
d98e84903fa7d3ef079b03875bd15b92efa9ae9e | 4,315 | //
// RecentOrdersTableVC.swift
// DiberCourier
//
// Created by Alexander Tereshkov on 2/4/18.
// Copyright © 2018 Diber. All rights reserved.
//
import UIKit
protocol RecentOrdersTableDelegate: class {
func didReachLastCell(page: Int)
func didSelectOrder(order: OrderView)
func didPullRefresh(totalLoadedOrders: Int)
}
class RecentOrdersTableVC: UITableViewController {
fileprivate var orders = [OrderView]()
fileprivate var debounceTimer: WeakTimer?
weak var delegate: OrdersTableDelegate?
fileprivate var currentPage = 0
var totalItems = 0
fileprivate var dataLoading = false
var lastContentOffset: CGFloat = 0
private let refreshControlView = UIRefreshControl()
override func viewDidLoad() {
super.viewDidLoad()
setupRefreshControl()
}
deinit {
debounceTimer?.invalidate()
LogManager.log.info("Deinitialization")
}
// MARK: Public
func addOrders(_ orders: [OrderView]) {
self.orders.append(contentsOf: orders)
reloadOrdersDebounced()
}
func removeAll() {
self.currentPage = 0
self.orders.removeAll()
}
// MARK: Private
private func setupRefreshControl() {
refreshControlView.addTarget(self, action: #selector(handlePullRefresh(_:)), for: .valueChanged)
refreshControlView.tintColor = UIColor.gray
tableView.addSubview(refreshControlView)
}
@objc private func handlePullRefresh(_ refreshControl: UIRefreshControl) {
delegate?.didPullRefresh(totalLoadedOrders: orders.count)
refreshControl.endRefreshing()
}
fileprivate func reloadOrdersDebounced() {
debounceTimer?.invalidate()
debounceTimer = WeakTimer(timeInterval: 0.05, target: self, selector: #selector(reloadOrders), repeats: false)
}
@objc fileprivate func reloadOrders() {
self.tableView.reloadData()
}
private func fetchNextPage() {
self.currentPage += 1
self.delegate?.didReachLastCell(page: currentPage)
}
// MARK: TableView
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: Cells.recentOrder.rawValue, for: indexPath) as? RecentOrderCell else {
fatalError("The dequeued cell is not an instance of RecentOrderCell")
}
guard indexPath.row >= 0 && indexPath.row < orders.count else { return cell }
let order = orders[indexPath.row]
cell.bind(with: order)
return cell
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return orders.count
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard indexPath.row >= 0 && indexPath.row < orders.count else { return }
let order = orders[indexPath.row]
delegate?.didSelectOrder(order: order)
}
// MARK: TableView Scroll
override func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
self.dataLoading = false
self.lastContentOffset = scrollView.contentOffset.y
}
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
// Uncomment if you wanna have to hide Top View when scrolling
if (self.lastContentOffset < scrollView.contentOffset.y) {
//delegate?.hideTopView(hide: true)
} else if (self.lastContentOffset > scrollView.contentOffset.y) {
//delegate?.hideTopView(hide: false)
}
}
// Pagination handling
override func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
let contentOffset = tableView.contentOffset.y + tableView.frame.size.height
if (contentOffset + CGFloat(Pagination.cellOffset) >= tableView.contentSize.height) {
if !dataLoading && self.totalItems > orders.count {
self.dataLoading = true
fetchNextPage()
}
}
}
}
| 31.49635 | 141 | 0.656547 |
87549ae8aa6dc427eddafc373fbd3a508b14a101 | 9,614 | //
// SteppedProgressBar.swift
// JKSteppedProgressBar
//
// Created by Johnykutty Mathew on 12/09/16.
// Copyright © 2016 Johnykutty Mathew. All rights reserved.
//
import UIKit
public let SteppedProgressBarAutomaticDimension: CGFloat = -1
public enum StepDrawingMode: Int {
case fill
case drawIndex
case image
}
@IBDesignable
open class SteppedProgressBar: UIView {
// MARK: PROPERTIES
let paragraphStyle = NSMutableParagraphStyle()
// MARK: IBInspectable Properties
@IBInspectable open var activeColor: UIColor = UIColor.green {
didSet {
self.setNeedsDisplay()
}
}
@IBInspectable open var inactiveColor: UIColor = UIColor.gray {
didSet {
self.setNeedsDisplay()
}
}
@IBInspectable open var inactiveTextColor: UIColor = UIColor.gray {
didSet {
self.setNeedsDisplay()
}
}
@IBInspectable open var circleRadius: CGFloat = 20 {
didSet {
self.setNeedsDisplay()
}
}
// Addressing issue #3
// https://github.com/jkmathew/JKSteppedProgressBar/issues/3
@IBInspectable open var titleOffset: CGFloat = 0 {
didSet {
self.setNeedsDisplay()
}
}
@IBInspectable open var circleSpacing: CGFloat = SteppedProgressBarAutomaticDimension {
didSet {
self.setNeedsDisplay()
}
}
@IBInspectable open var lineWidth: CGFloat = 2 {
didSet {
self.setNeedsDisplay()
}
}
@IBInspectable open var currentTab: Int = 0 {
didSet {
self.setNeedsDisplay()
}
}
// Changes the tint color of theactiveImages image to the activeColor
@IBInspectable open var tintActiveImage = false
@IBInspectable open var justCheckCompleted = true
open var stepDrawingMode: StepDrawingMode = .drawIndex {
didSet {
self.setNeedsDisplay()
}
}
open var stepFont: UIFont = UIFont.systemFont(ofSize: 14.0) {
didSet {
self.setNeedsDisplay()
}
}
open var titleFont: UIFont = UIFont.systemFont(ofSize: 12.0) {
didSet {
self.setNeedsDisplay()
}
}
open var insets: UIEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) {
didSet {
self.setNeedsDisplay()
}
}
open var titles = ["One", "Two","Three", "Four","Five", "Six"] {
didSet {
self.setNeedsDisplay()
}
}
var availableFrame: CGRect {
var correctedFrame = bounds
correctedFrame.origin.x = insets.left
correctedFrame.origin.y = insets.top
correctedFrame.size.width -= insets.left + insets.right
correctedFrame.size.height -= insets.top + insets.bottom
return correctedFrame
}
/*
This will redraw and change color for the steps which are done. For example, if we set this as Red, Orange,
Yellow, Green, then when you are at step one, it(circle and lines to circle) be Red, and when you are in second
step, line and circles till that step(circle 1, line 1, circle 2) will be Orange, and so on.., then, when you are
in fourth step it wil be Green from start circle to end circle. There by you can show the user a level of
completion if wanted through colors.
*/
open var activeStepColors: [UIColor]? {
didSet {
self.setNeedsDisplay()
}
}
// MARK: Image Helper properties
/*
* setting images will only show the images instead of any text mentioned
*/
open var images: [UIImage]? {
didSet {
stepDrawingMode = .image
self.setNeedsDisplay()
}
}
open var activeImages: [UIImage]? {
didSet {
self.setNeedsDisplay()
}
}
// MARK: Private Properties
private var actualSpacing: CGFloat {
return (circleSpacing == SteppedProgressBarAutomaticDimension)
? (availableFrame.width - 6.0 - (CGFloat(numberOfItems) * circleRadius)) / CGFloat(numberOfItems - 1)
: circleSpacing
}
private var languageFactor: CGFloat {
return (UIApplication.shared.userInterfaceLayoutDirection == .rightToLeft) ? -1 : 1
}
private var numberOfItems: Int {
return stepDrawingMode == .image ? (images ?? []).count : titles.count
}
// MARK: METHODS
// MARK: View Lifecycle Methods
override open func awakeFromNib() {
super.awakeFromNib()
paragraphStyle.alignment = .center
}
override open func draw(_ rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
if currentTab == 0 {
drawTabs(from: 0, to: numberOfItems, color: inactiveColor, textColor: inactiveTextColor)
} else if currentTab == numberOfItems {
drawTabs(from: 0, to: numberOfItems, color: activeStepColor(currentTab), textColor: activeStepColor(currentTab))
}
else {
// Addressing issue #3
// https://github.com/jkmathew/JKSteppedProgressBar/issues/3
// Drawing in the order 1.inactive, 2.Line between active and inactive, 3.Active to avoid overlaping issue
let end = drawTabs(from: currentTab, to: numberOfItems, color: inactiveColor, textColor: inactiveTextColor).start
let path = UIBezierPath()
path.lineWidth = lineWidth
var start = end
start.x -= languageFactor * actualSpacing
path.move(to: start)
path.addLine(to: end)
context?.setStrokeColor(inactiveColor.cgColor)
path.stroke()
drawTabs(from: 0, to: currentTab , color: activeStepColor(currentTab), textColor: activeStepColor(currentTab))
}
}
override open func layoutSubviews() {
super.layoutSubviews()
self.setNeedsDisplay()
}
// MARK: Draw Helper Methods
@discardableResult
func drawTabs(from begin: Int, to end: Int, color: UIColor, textColor: UIColor) -> (start: CGPoint, end: CGPoint) {
let halfX = (CGFloat(numberOfItems - 1) * (actualSpacing + circleRadius) / 2.0)
let startX = availableFrame.midX - languageFactor * halfX
let x = startX + languageFactor * (actualSpacing + circleRadius) * CGFloat(begin)
var point = CGPoint(x: x, y: availableFrame.midY)
var start = point
start.x -= languageFactor * circleRadius / 2.0
let path = UIBezierPath()
path.lineWidth = lineWidth
for i in begin..<end {
draw(step: i, path: path, start : &point, textColor: textColor)
if i != (end - 1) {
//draw trailinng line
point.x += languageFactor * actualSpacing
path.addLine(to: point)
point.x += languageFactor * circleRadius / 2.0
}
}
let context = UIGraphicsGetCurrentContext()
context?.setStrokeColor(color.cgColor)
context?.setFillColor(color.cgColor)
path.stroke()
if stepDrawingMode == .fill {
path.fill()
}
return (start: start, end: point)
}
/*
* Draws the images with a predefined inset
*/
func drawImage(step i: Int, at rect: CGRect) {
guard ( images ?? [] ).count > i else {
return
}
( images ?? [] )[i].draw(inside: rect)
}
/*
* Draws the successImage. If tintActiveImage change the tint of the UIImage
*/
func drawSuccessImage(step i: Int, at rect: CGRect) {
guard ( activeImages ?? [] ).count > i else {
drawImage(step: i, at: rect)
return
}
(tintActiveImage
? ( activeImages ?? [] )[i].imageWithColor(activeColor)
: ( activeImages ?? [] )[i])
.draw(inside: rect)
}
func draw(step i: Int, path: UIBezierPath, start point: inout CGPoint, textColor: UIColor) {
let buttonRect = CGRect.make(center: point, diameter: circleRadius)
// Check if images are set and decide what image to draw
if ( images ?? [] ).count > i || ( activeImages ?? [] ).count > i {
if (i < currentTab - (justCheckCompleted ? 1 : 0)) {
drawSuccessImage(step: i, at: buttonRect)
} else {
drawImage(step: i, at: buttonRect)
}
}
//draw circle
path.move(to: point)
let circlePath = UIBezierPath(ovalIn: buttonRect)
#if swift(>=4.0)
var attributes = [NSAttributedString.Key.foregroundColor : textColor, NSAttributedString.Key.paragraphStyle: paragraphStyle]
#else
var attributes = [NSForegroundColorAttributeName : textColor, NSParagraphStyleAttributeName: paragraphStyle]
#endif
let index = i
// If a successImage was drawn dont draw text under it
if index >= currentTab - (justCheckCompleted ? 1 : 0) || ( activeImages ?? [] ).count <= index {
//draw index
if stepDrawingMode == .drawIndex {
let buttonTitle = "\(index + 1)"
#if swift(>=4.0)
attributes[NSAttributedString.Key.font] = self.stepFont
#else
attributes[NSFontAttributeName] = self.stepFont
#endif
let attributedString = NSAttributedString(string: buttonTitle, attributes: attributes)
attributedString.draw(center: point)
}
}
path.append(circlePath)
var titleCenter = point
titleCenter.y += circleRadius * 0.75 + titleOffset
let title = titles[index]
#if swift(>=4.0)
attributes[NSAttributedString.Key.font] = self.titleFont
#else
attributes[NSFontAttributeName] = self.titleFont
#endif
let attributedString = NSAttributedString(string: title, attributes: attributes)
attributedString.draw(center: titleCenter)
point.x += languageFactor * circleRadius / 2.0
path.move(to: point)
}
}
private extension SteppedProgressBar {
/* Returns the active step color to the caller, if its mentioned in activeStepColors array. If not return the
activeColor */
func activeStepColor(_ tabIndex: Int) -> UIColor {
var activeStepColor = activeColor
if let activeStepColors = activeStepColors, tabIndex - 1 < activeStepColors.count {
activeStepColor = activeStepColors[tabIndex - 1]
}
return activeStepColor
}
}
| 28.111111 | 128 | 0.665176 |
3959ad045d57846ecd890124991354f423f46efb | 1,450 | @testable import App
import XCTest
class SwiftVersionTests: XCTestCase {
func test_swiftVerRegex() throws {
XCTAssert(swiftVerRegex.matches("1"))
XCTAssert(swiftVerRegex.matches("1.2"))
XCTAssert(swiftVerRegex.matches("1.2.3"))
XCTAssert(swiftVerRegex.matches("v1"))
XCTAssertFalse(swiftVerRegex.matches("1."))
XCTAssertFalse(swiftVerRegex.matches("1.2."))
XCTAssertFalse(swiftVerRegex.matches("1.2.3-pre"))
}
func test_init() throws {
XCTAssertEqual(SwiftVersion("5"), SwiftVersion(5, 0, 0))
XCTAssertEqual(SwiftVersion("5.2"), SwiftVersion(5, 2, 0))
XCTAssertEqual(SwiftVersion("5.2.1"), SwiftVersion(5, 2, 1))
XCTAssertEqual(SwiftVersion("v5"), SwiftVersion(5, 0, 0))
}
func test_Comparable() throws {
XCTAssertTrue(SwiftVersion("5")! < SwiftVersion("5.1")!)
XCTAssertFalse(SwiftVersion("5")! < SwiftVersion("5.0")!)
XCTAssertFalse(SwiftVersion("5")! > SwiftVersion("5.0")!)
XCTAssertTrue(SwiftVersion("4.2")! < SwiftVersion("5")!)
}
func test_isCompatible() throws {
let v4_2 = SwiftVersion(4, 2, 0)
XCTAssertTrue(v4_2.isCompatible(with: .init(4, 2, 0)))
XCTAssertTrue(v4_2.isCompatible(with: .init(4, 2, 4)))
XCTAssertFalse(v4_2.isCompatible(with: .init(4, 0, 0)))
XCTAssertFalse(v4_2.isCompatible(with: .init(5, 0, 0)))
}
}
| 35.365854 | 68 | 0.629655 |
e6c142d0670b3c6435e1ef4a93e40cd4e08cb687 | 70 | //
// File.swift
// ApiStatusBarHeightExample
//
import Foundation
| 10 | 29 | 0.714286 |
1e5725a5f5183fa5bc7eb985999098a1df60b451 | 1,707 | // Generated by msgbuilder 2020-05-15 06:20:49 +0000
import StdMsgs
extension trajectory_msgs {
/// The header is used to specify the coordinate frame and the reference time for the trajectory durations
/// A representation of a multi-dof joint trajectory (each point is a transformation)
/// Each point along the trajectory will include an array of positions/velocities/accelerations
/// that has the same length as the array of joint names, and has the same order of joints as
/// the joint names array.
public struct MultiDOFJointTrajectory: MessageWithHeader {
public static let md5sum: String = "ef145a45a5f47b77b7f5cdde4b16c942"
public static let datatype = "trajectory_msgs/MultiDOFJointTrajectory"
public static let definition = """
# The header is used to specify the coordinate frame and the reference time for the trajectory durations
Header header
# A representation of a multi-dof joint trajectory (each point is a transformation)
# Each point along the trajectory will include an array of positions/velocities/accelerations
# that has the same length as the array of joint names, and has the same order of joints as
# the joint names array.
string[] joint_names
MultiDOFJointTrajectoryPoint[] points
"""
public var header: std_msgs.Header
public var joint_names: [String]
public var points: [MultiDOFJointTrajectoryPoint]
public init(header: std_msgs.Header, joint_names: [String], points: [MultiDOFJointTrajectoryPoint]) {
self.header = header
self.joint_names = joint_names
self.points = points
}
public init() {
header = std_msgs.Header()
joint_names = [String]()
points = [MultiDOFJointTrajectoryPoint]()
}
}
} | 41.634146 | 107 | 0.758055 |
d6375ac9b79310cacb07e6c90580576df15661e3 | 13,558 | //
// Repeat
// A modern alternative to NSTimer made in GCD with debouncer and throttle
// -----------------------------------------------------------------------
// Created by: Daniele Margutti
// [email protected]
// http://www.danielemargutti.com
//
// Twitter: @danielemargutti
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
open class Repeater: Equatable {
/// State of the timer
///
/// - paused: idle (never started yet or paused)
/// - running: timer is running
/// - executing: the observers are being executed
/// - finished: timer lifetime is finished
public enum State: Equatable, CustomStringConvertible {
case paused
case running
case executing
case finished
public static func == (lhs: State, rhs: State) -> Bool {
switch (lhs, rhs) {
case (.paused, .paused),
(.running, .running),
(.executing, .executing),
(.finished, .finished):
return true
default:
return false
}
}
/// Return `true` if timer is currently running, including when the observers are being executed.
public var isRunning: Bool {
guard self == .running || self == .executing else { return false }
return true
}
/// Return `true` if the observers are being executed.
public var isExecuting: Bool {
guard case .executing = self else { return false }
return true
}
/// Is timer finished its lifetime?
/// It return always `false` for infinite timers.
/// It return `true` for `.once` mode timer after the first fire,
/// and when `.remainingIterations` is zero for `.finite` mode timers
public var isFinished: Bool {
guard case .finished = self else { return false }
return true
}
/// State description
public var description: String {
switch self {
case .paused: return "idle/paused"
case .finished: return "finished"
case .running: return "running"
case .executing: return "executing"
}
}
}
/// Repeat interval
public enum Interval {
case nanoseconds(_: Int)
case microseconds(_: Int)
case milliseconds(_: Int)
case minutes(_: Int)
case seconds(_: Double)
case hours(_: Int)
case days(_: Int)
internal var value: DispatchTimeInterval {
switch self {
case .nanoseconds(let value): return .nanoseconds(value)
case .microseconds(let value): return .microseconds(value)
case .milliseconds(let value): return .milliseconds(value)
case .seconds(let value): return .milliseconds(Int( Double(value) * Double(1000)))
case .minutes(let value): return .seconds(value * 60)
case .hours(let value): return .seconds(value * 3600)
case .days(let value): return .seconds(value * 86400)
}
}
}
/// Mode of the timer.
///
/// - infinite: infinite number of repeats.
/// - finite: finite number of repeats.
/// - once: single repeat.
public enum Mode {
case infinite
case finite(_: Int)
case once
/// Is timer a repeating timer?
internal var isRepeating: Bool {
switch self {
case .once: return false
default: return true
}
}
/// Number of repeats, if applicable. Otherwise `nil`
public var countIterations: Int? {
switch self {
case .finite(let counts): return counts
default: return nil
}
}
/// Is infinite timer
public var isInfinite: Bool {
guard case .infinite = self else {
return false
}
return true
}
}
/// Handler typealias
public typealias Observer = ((Repeater) -> Void)
/// Token assigned to the observer
public typealias ObserverToken = UInt64
/// Current state of the timer
public private(set) var state: State = .paused {
didSet {
self.onStateChanged?(self, state)
}
}
/// Callback called to intercept state's change of the timer
public var onStateChanged: ((_ timer: Repeater, _ state: State) -> Void)?
/// List of the observer of the timer
private var observers = [ObserverToken: Observer]()
/// Next token of the timer
private var nextObserverID: UInt64 = 0
/// Internal GCD Timer
private var timer: DispatchSourceTimer?
/// Is timer a repeat timer
public private(set) var mode: Mode
/// Number of remaining repeats count
public private(set) var remainingIterations: Int?
/// Interval of the timer
private var interval: Interval
/// Accuracy of the timer
private var tolerance: DispatchTimeInterval
/// Dispatch queue parent of the timer
private var queue: DispatchQueue?
/// Initialize a new timer.
///
/// - Parameters:
/// - interval: interval of the timer
/// - mode: mode of the timer
/// - tolerance: tolerance of the timer, 0 is default.
/// - queue: queue in which the timer should be executed; if `nil` a new queue is created automatically.
/// - observer: observer
public init(interval: Interval, mode: Mode = .infinite, tolerance: DispatchTimeInterval = .nanoseconds(0), queue: DispatchQueue? = nil, observer: @escaping Observer) {
self.mode = mode
self.interval = interval
self.tolerance = tolerance
self.remainingIterations = mode.countIterations
self.queue = (queue ?? DispatchQueue(label: "com.repeat.queue"))
self.timer = configureTimer()
self.observe(observer)
}
/// Add new a listener to the timer.
///
/// - Parameter callback: callback to call for fire events.
/// - Returns: token used to remove the handler
@discardableResult
public func observe(_ observer: @escaping Observer) -> ObserverToken {
var (new, overflow) = self.nextObserverID.addingReportingOverflow(1)
if overflow { // you need to add an incredible number of offset...sure you can't
self.nextObserverID = 0
new = 0
}
self.nextObserverID = new
self.observers[new] = observer
return new
}
/// Remove an observer of the timer.
///
/// - Parameter id: id of the observer to remove
public func remove(observer identifier: ObserverToken) {
self.observers.removeValue(forKey: identifier)
}
/// Remove all observers of the timer.
///
/// - Parameter stopTimer: `true` to also stop timer by calling `pause()` function.
public func removeAllObservers(thenStop stopTimer: Bool = false) {
self.observers.removeAll()
if stopTimer {
self.pause()
}
}
/// Configure a new timer session.
///
/// - Returns: dispatch timer
private func configureTimer() -> DispatchSourceTimer {
let associatedQueue = (queue ?? DispatchQueue(label: "com.repeat.\(NSUUID().uuidString)"))
let timer = DispatchSource.makeTimerSource(queue: associatedQueue)
let repeatInterval = interval.value
let deadline: DispatchTime = (DispatchTime.now() + repeatInterval)
if self.mode.isRepeating {
timer.schedule(deadline: deadline, repeating: repeatInterval, leeway: tolerance)
} else {
timer.schedule(deadline: deadline, leeway: tolerance)
}
timer.setEventHandler { [weak self] in
if let unwrapped = self {
unwrapped.timeFired()
}
}
return timer
}
/// Destroy current timer
private func destroyTimer() {
self.timer?.cancel()
resume()
self.timer?.setEventHandler(handler: nil)
/*
If the timer is suspended, calling cancel without resuming
triggers a crash. This is documented here https://forums.developer.apple.com/thread/15902
*/
self.timer = nil
}
/// Create and schedule a timer that will call `handler` once after the specified time.
///
/// - Parameters:
/// - interval: interval delay for single fire
/// - queue: destination queue, if `nil` a new `DispatchQueue` is created automatically.
/// - observer: handler to call when timer fires.
/// - Returns: timer instance
@discardableResult
public class func once(after interval: Interval, tolerance: DispatchTimeInterval = .nanoseconds(0), queue: DispatchQueue? = nil, _ observer: @escaping Observer) -> Repeater {
let timer = Repeater(interval: interval, mode: .once, tolerance: tolerance, queue: queue, observer: observer)
timer.start()
return timer
}
/// Create and schedule a timer that will fire every interval optionally by limiting the number of fires.
///
/// - Parameters:
/// - interval: interval of fire
/// - count: a non `nil` and > 0 value to limit the number of fire, `nil` to set it as infinite.
/// - queue: destination queue, if `nil` a new `DispatchQueue` is created automatically.
/// - handler: handler to call on fire
/// - Returns: timer
@discardableResult
public class func every(_ interval: Interval, count: Int? = nil, tolerance: DispatchTimeInterval = .nanoseconds(0), queue: DispatchQueue? = nil, _ handler: @escaping Observer) -> Repeater {
let mode: Mode = (count != nil ? .finite(count!) : .infinite)
let timer = Repeater(interval: interval, mode: mode, tolerance: tolerance, queue: queue, observer: handler)
timer.start()
return timer
}
/// Force fire.
///
/// - Parameter pause: `true` to pause after fire, `false` to continue the regular firing schedule.
public func fire(andPause pause: Bool = false) {
self.timeFired()
if pause == true {
self.pause()
}
}
/// Reset the state of the timer, optionally changing the fire interval.
///
/// - Parameters:
/// - interval: new fire interval; pass `nil` to keep the latest interval set.
/// - restart: `true` to automatically restart the timer, `false` to keep it stopped after configuration.
public func reset(_ interval: Interval?, restart: Bool = true) {
if self.state.isRunning {
self.setPause(from: self.state)
}
// For finite counter we want to also reset the repeat count
if case .finite(let count) = self.mode {
self.remainingIterations = count
}
// Create a new instance of timer configured
if let newInterval = interval {
self.interval = newInterval
} // update interval
self.destroyTimer()
self.timer = configureTimer()
self.state = .paused
if restart {
resume()
}
}
/// Start timer. If timer is already running it does nothing.
@discardableResult
public func start() -> Bool {
guard self.state.isRunning == false else {
return false
}
// If timer has not finished its lifetime we want simply
// restart it from the current state.
guard self.state.isFinished == true else {
resume()
return true
}
// Otherwise we need to reset the state based upon the mode
// and start it again.
self.reset(nil, restart: true)
return true
}
/// Pause a running timer. If timer is paused it does nothing.
@discardableResult
public func pause() -> Bool {
guard state != .paused && state != .finished else {
return false
}
return self.setPause(from: self.state)
}
/// Resume a running timer. If timer is already resumed (running) it does nothing
private func resume() {
if state == .running {
return
}
state = .running
}
/// Suspend a timer. If timer is already suspended (paused or finished) it does nothing
private func suspend() {
if state == .paused || state == .finished {
return
}
state = .paused
timer?.suspend()
}
/// Pause a running timer optionally changing the state with regard to the current state.
///
/// - Parameters:
/// - from: the state which the timer should only be paused if it is the current state
/// - to: the new state to change to if the timer is paused
/// - Returns: `true` if timer is paused
@discardableResult
private func setPause(from currentState: State, to newState: State = .paused) -> Bool {
guard self.state == currentState else {
return false
}
suspend()
self.state = newState
return true
}
/// Called when timer is fired
private func timeFired() {
self.state = .executing
if case .finite = self.mode {
self.remainingIterations! -= 1
}
// dispatch to observers
self.observers.values.forEach { $0(self) }
// manage lifetime
switch self.mode {
case .once:
// once timer's lifetime is finished after the first fire
// you can reset it by calling `reset()` function.
self.setPause(from: .executing, to: .finished)
case .finite:
// for finite intervals we decrement the left iterations count...
if self.remainingIterations! == 0 {
// ...if left count is zero we just pause the timer and stop
self.setPause(from: .executing, to: .finished)
}
case .infinite:
// infinite timer does nothing special on the state machine
break
}
}
deinit {
self.observers.removeAll()
self.destroyTimer()
}
public static func == (lhs: Repeater, rhs: Repeater) -> Bool {
return lhs === rhs
}
}
| 30.062084 | 190 | 0.67982 |
2825220957290e6de99d601f1ae001cc292fdca5 | 1,034 | //
// HeaderFilterCollectionReusableView.swift
// LingoCoach
//
// Created by Lucas Fernandes on 26/11/20.
//
import UIKit
class HeaderFilterCollectionReusableView: UICollectionReusableView {
let titleLabel: UILabel = {
let label = UILabel()
label.textColor = .textBlack
label.font = UIFont.systemFont(ofSize: 22, weight: .semibold)
label.text = "Preço"
return label
}()
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .clear
setupTitleLabel()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupTitleLabel() {
addSubview(titleLabel)
titleLabel.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
titleLabel.topAnchor.constraint(equalTo: topAnchor, constant: 16),
titleLabel.leftAnchor.constraint(equalTo: leftAnchor, constant: 16)
])
}
}
| 25.85 | 79 | 0.636364 |
decf93db7008d662934de26c7ba1990fe5e73d00 | 3,789 | @_implementationOnly import EnvoyEngine
import Foundation
/// Mock implementation of `EnvoyEngine`. Used internally for testing the bridging layer & mocking.
final class MockEnvoyEngine: NSObject {
init(runningCallback onEngineRunning: (() -> Void)? = nil, logger: ((String) -> Void)? = nil,
eventTracker: (([String: String]) -> Void)? = nil) {}
/// Closure called when `run(withConfig:)` is called.
static var onRunWithConfig: ((_ config: EnvoyConfiguration, _ logLevel: String?) -> Void)?
/// Closure called when `run(withConfigYAML:)` is called.
static var onRunWithTemplate: ((
_ template: String,
_ config: EnvoyConfiguration,
_ logLevel: String?
) -> Void)?
/// Closure called when `recordCounterInc(_:tags:count:)` is called.
static var onRecordCounter: (
(_ elements: String, _ tags: [String: String], _ count: UInt) -> Void)?
/// Closure called when `recordGaugeSet(_:value:)` is called.
static var onRecordGaugeSet: (
(_ elements: String, _ tags: [String: String], _ value: UInt) -> Void)?
/// Closure called when `recordGaugeAdd(_:amount:)` is called.
static var onRecordGaugeAdd: (
(_ elements: String, _ tags: [String: String], _ amount: UInt) -> Void)?
/// Closure called when `recordGaugeSub(_:amount:)` is called.
static var onRecordGaugeSub: (
(_ elements: String, _ tags: [String: String], _ amount: UInt) -> Void)?
/// Closure called when `recordHistogramDuration(_:durationMs)` is called.
static var onRecordHistogramDuration: (
(_ elements: String, _ tags: [String: String], _ durationMs: UInt) -> Void)?
/// Closure called when `recordHistogramValue(_:value)` is called.
static var onRecordHistogramValue: (
(_ elements: String, _ tags: [String: String], _ value: UInt) -> Void)?
static var onFlushStats: (() -> Void)?
}
extension MockEnvoyEngine: EnvoyEngine {
func run(withConfig config: EnvoyConfiguration, logLevel: String) -> Int32 {
MockEnvoyEngine.onRunWithConfig?(config, logLevel)
return kEnvoySuccess
}
func run(withTemplate template: String, config: EnvoyConfiguration, logLevel: String) -> Int32 {
MockEnvoyEngine.onRunWithTemplate?(template, config, logLevel)
return kEnvoySuccess
}
func startStream(
with callbacks: EnvoyHTTPCallbacks,
explicitFlowControl: Bool
) -> EnvoyHTTPStream {
return MockEnvoyHTTPStream(handle: 0, callbacks: callbacks,
explicitFlowControl: explicitFlowControl)
}
func recordCounterInc(_ elements: String, tags: [String: String], count: UInt) -> Int32 {
MockEnvoyEngine.onRecordCounter?(elements, tags, count)
return kEnvoySuccess
}
func recordGaugeSet(_ elements: String, tags: [String: String], value: UInt) -> Int32 {
MockEnvoyEngine.onRecordGaugeSet?(elements, tags, value)
return kEnvoySuccess
}
func recordGaugeAdd(_ elements: String, tags: [String: String], amount: UInt) -> Int32 {
MockEnvoyEngine.onRecordGaugeAdd?(elements, tags, amount)
return kEnvoySuccess
}
func recordGaugeSub(_ elements: String, tags: [String: String], amount: UInt) -> Int32 {
MockEnvoyEngine.onRecordGaugeSub?(elements, tags, amount)
return kEnvoySuccess
}
func recordHistogramDuration(
_ elements: String, tags: [String: String], durationMs: UInt) -> Int32 {
MockEnvoyEngine.onRecordHistogramDuration?(elements, tags, durationMs)
return kEnvoySuccess
}
func recordHistogramValue(_ elements: String, tags: [String: String], value: UInt) -> Int32 {
MockEnvoyEngine.onRecordHistogramValue?(elements, tags, value)
return kEnvoySuccess
}
func flushStats() {
MockEnvoyEngine.onFlushStats?()
}
func dumpStats() -> String {
return ""
}
func terminate() {}
func drainConnections() {}
}
| 37.514851 | 99 | 0.702032 |
f41bc607c70e0a56cf206b7322d6db0649fa6e87 | 8,832 | //
// ImageCollectionViewController.swift
// MMImageLoader
//
// Created by Mohamed Maail on 5/26/16.
// Copyright © 2016 Mohamed Maail. All rights reserved.
//
import UIKit
private let reuseIdentifier = "ImageCell"
class ImageCollectionViewController: UICollectionViewController, UIViewControllerPreviewingDelegate {
var imageLoader = MMImageLoader()
var networking = MMNetworking.sharedManager
var imagedDownloaded:[Int] = []
var imageArray: [UnsplashModel] = []
var refreshControl = UIRefreshControl()
var activityIndicator = UIActivityIndicatorView()
override func viewDidLoad() {
super.viewDidLoad()
self.setDefault()
self.setStyle()
self.loadData()
}
func setDefault(){
//check for 3D Touch Availability
if #available(iOS 9.0, *) {
if( traitCollection.forceTouchCapability == .available){
registerForPreviewing(with: self, sourceView: view)
}
}
//register custom UICollectionViewCell
let xib : UINib = UINib (nibName: "ImageCollectionViewCell", bundle: nil)
self.collectionView!.register(xib, forCellWithReuseIdentifier: reuseIdentifier)
//pull to refresh setup
self.collectionView?.alwaysBounceVertical = true
self.refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
self.refreshControl.tintColor = UIColor.gray
self.refreshControl.addTarget(self, action: #selector(ImageCollectionViewController.refresh), for: UIControlEvents.valueChanged)
collectionView!.addSubview(refreshControl)
//add activity indicator on load
activityIndicator.frame = CGRect(x: 0, y: 0, width: 50, height: 50);
activityIndicator.center = self.view.center
activityIndicator.hidesWhenStopped = true
activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.whiteLarge
self.view.addSubview(activityIndicator)
}
func setStyle(){
self.collectionView?.backgroundColor = UIColor(red: 0.797, green: 0.797, blue: 0.797, alpha: 1)
}
func refresh(_ sender:AnyObject?){
self.loadData("Pull")
}
func loadData(_ Type:String = ""){
//Load Images from Unsplash.It and put in in an Array
showStatusBarActivity()
if Type != "Pull"{
self.activityIndicator.startAnimating()
}
self.imageArray.removeAll()
let apiURL = API.Client.rawValue + API.List.rawValue
networking.makeRequest(apiURL) { (Status, Data) in
self.activityIndicator.stopAnimating()
self.refreshControl.endRefreshing()
hideStatusBarActivity()
if Status{
do{
if let json = try JSONSerialization.jsonObject(with: Data, options: .allowFragments) as? [[String: AnyObject]]{
for list in json{
let Format = unwrapJSONString(list, "format")
let Width = unwrapJSONInt(list, "width")
let Height = unwrapJSONInt(list, "height")
let FileName = unwrapJSONString(list, "filename")
let ID = unwrapJSONInt(list, "id")
let Author = unwrapJSONString(list, "author")
let AuthorURL = unwrapJSONString(list, "author_url")
let PostURL = unwrapJSONString(list, "post_url")
self.imageArray.append(UnsplashModel(Format: Format, Width: Width, Height: Height, FileName: FileName, ID: ID, Author: Author, AuthorURL: AuthorURL, PostURL: PostURL))
}
self.collectionView?.reloadData()
}
}catch{
print("JSON Serializing Error: \(error)")
}
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: UICollectionViewDataSource
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.imageArray.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
var cell:ImageCollectionViewCell? = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as? ImageCollectionViewCell
if (cell == nil)
{
let nib:Array = Bundle.main.loadNibNamed("ImageCollectionViewCell", owner: self, options: nil)!
cell = nib[0] as? ImageCollectionViewCell
}
let source = self.imageArray[indexPath.row]
cell?.imageView.image = UIImage(named: "PlaceHolder")
if cell!.contentView.viewWithTag(source.ID + 1) == nil{
cell?.imageView.image = UIImage(named: "PlaceHolder")
cell!.imageView.tag = source.ID + 1
let resizeImageURL = API.Resize(Width: 200, Height: 0, ImageID: source.ID)
showStatusBarActivity()
imageLoader.requestImage(resizeImageURL) { (Status, Image) in
hideStatusBarActivity()
if Status{
cell?.imageView.image = Image
self.imagedDownloaded.append(source.ID)
}
}
}
return cell!
}
func collectionView(_ collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize{
if DeviceType.IS_IPAD{
return CGSize(width: self.view.frame.width/3.3, height: self.view.frame.width/3.3)
}else if DeviceType.IS_IPHONE_5{
return CGSize(width: self.view.frame.width/3.6, height: self.view.frame.width/3.6)
}else if DeviceType.IS_IPHONE_6P{
return CGSize(width: self.view.frame.width/3.5, height: self.view.frame.width/3.5)
}else{
return CGSize(width: self.view.frame.width/3.5, height: self.view.frame.width/3.5)
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
return 15.0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
return 15.0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
return UIEdgeInsetsMake(15, 10, 15, 10)
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
self.performSegue(withIdentifier: "ImageSegueDetails", sender: indexPath)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ImageSegueDetails"{
let vc = segue.destination as! ImageDetailsViewController
let indexPath = sender as! IndexPath
vc.imageDetails = self.imageArray[indexPath.row]
}
}
// MARK: UIViewControllerPreviewingDelegate
func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
let point : CGPoint = self.collectionView!.convert(location, from: collectionView!.superview)
let indexPath = self.collectionView!.indexPathForItem(at: point)
let storyboard:UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "ImageDetailsViewController") as! ImageDetailsViewController
vc.imageDetails = self.imageArray[indexPath!.row]
vc.preferredContentSize = CGSize(width: 0.0, height: 450)
return vc
}
func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
show(viewControllerToCommit, sender: self)
}
}
| 43.294118 | 195 | 0.620471 |
b9be70b02e82ec1e6ad05f7139342bb006011688 | 1,754 | //
// ViewCustomizableTests.swift
// Tests
//
// Created by Justin Jia on 9/1/16.
// Copyright © 2016 TintPoint. MIT license.
//
@testable import Overlay
import XCTest
class RefreshingView: UIView, DesignCustomizable {
func customizeDesign(using design: (Any) -> Void) {
design(self)
}
}
class TestRefreshingView: RefreshingView, CustomDesign {
var isRefreshed = false
let design: (Any) -> Void = {
let view = $0 as! TestRefreshingView
view.isRefreshed = true
}
}
class ViewCustomizableTests: XCTestCase {
func testRefresh() {
let view = TestRefreshingView()
let subview = TestRefreshingView()
view.addSubview(subview)
view.refresh(includingSubviews: false)
XCTAssert(view.isRefreshed)
XCTAssertFalse(subview.isRefreshed)
}
func testRefreshIncludingSubviews() {
let view = TestRefreshingView()
let first = TestRefreshingView()
let second = TestRefreshingView()
let third = TestRefreshingView()
view.addSubview(first)
view.addSubview(second)
view.addSubview(third)
view.refresh(includingSubviews: true)
XCTAssert(view.isRefreshed)
XCTAssert(first.isRefreshed)
XCTAssert(second.isRefreshed)
XCTAssert(third.isRefreshed)
}
func testRecursiveRefreshIncludingSubviews() {
let highest = TestRefreshingView()
let middle = TestRefreshingView()
let lowest = TestRefreshingView()
middle.addSubview(lowest)
highest.addSubview(middle)
highest.refresh(includingSubviews: true)
XCTAssert(highest.isRefreshed)
XCTAssert(middle.isRefreshed)
XCTAssert(lowest.isRefreshed)
}
}
| 27.40625 | 56 | 0.663056 |
62ef12d19f92c245203ee5c06606725a6bbb97ed | 2,481 | //
// Credentials.swift
// based on: https://gist.github.com/jeffrafter/6dc43c3341e12cf4e359092dc8c56f33
// jamf-migrator
//
// Created by Leslie Helou on 2/7/18.
// Copyright © 2018 jamf. All rights reserved.
//
import Security
import Foundation
class Credentials {
func save(_ service: String, account: String, data: String) {
var item: SecKeychainItem? = nil
// see if account exists
var status = SecKeychainFindGenericPassword(
nil,
UInt32(service.utf8.count),
service,
UInt32(account.utf8.count),
nil,
nil,
nil,
&item)
if status != noErr && status != errSecItemNotFound {
print("Error finding keychain item to modify: \(status), \(String(describing: SecCopyErrorMessageString(status, nil)))")
return
}
// if account exists, delete it then create with current password
if item != nil {
status = SecKeychainItemDelete(item!)
if status != noErr {
print("Error deleting existing keychain item: \(String(describing: SecCopyErrorMessageString(status, nil)))")
}
}
status = SecKeychainAddGenericPassword(
nil,
UInt32(service.utf8.count),
service,
UInt32(account.utf8.count),
account,
UInt32(data.utf8.count),
data,
nil)
if status != noErr {
print("Error setting keychain item: \(String(describing: SecCopyErrorMessageString(status, nil)))")
}
}
func retrieve(_ service: String, account: String) -> String? {
var passwordLength: UInt32 = 0
var password: UnsafeMutableRawPointer? = nil
let status = SecKeychainFindGenericPassword(
nil,
UInt32(service.utf8.count),
service,
UInt32(account.utf8.count),
account,
&passwordLength,
&password,
nil)
if status == errSecSuccess {
guard password != nil else { return nil }
let result = NSString(bytes: password!, length: Int(passwordLength), encoding: String.Encoding.utf8.rawValue) as String?
SecKeychainItemFreeContent(nil, password)
return result
}
return nil
}
}
| 30.62963 | 132 | 0.553003 |
bbfa37affb232528fd89e652ff8653279b9aa5e1 | 1,359 | //
// SKAction+SoundEffects.swift
// FityIt
//
// Created by Txai Wieser on 13/03/18.
// Copyright © 2018 Txai Wieser. All rights reserved.
//
import SpriteKit
import TWSpriteKitUtils
var userWantEffects: Bool? = nil
extension SKAction {
class var soundEffectsString: String { return "USER_SETTINGS_FX_DISABLE" }
class func playSoundFileIfEnabled(_ soundFile: String, waitForCompletion wait: Bool) -> SKAction? {
if shouldPlaySound() {
return self.playSoundFileNamed(soundFile, waitForCompletion: wait)
} else {
return nil
}
}
class func shouldPlaySound() -> Bool {
return userWantEffects ?? reloadSoundEffectsSettings()
}
class func reloadSoundEffectsSettings(_ newValue: Bool? = nil) -> Bool {
let newBool = newValue ?? !(UserDefaults.standard.bool(forKey: soundEffectsString))
userWantEffects = newBool
TWButton.defaultSoundEffectsEnabled = newBool
TWSwitch.defaultSoundEffectsEnabled = newBool
AppCache.instance.resetSounds(initializeAfter: newBool)
return newBool
}
class func saveNewSoundEffectsSettings(_ newBool:Bool) {
UserDefaults.standard.set(!newBool, forKey: soundEffectsString)
UserDefaults.standard.synchronize()
_ = reloadSoundEffectsSettings(newBool)
}
}
| 30.886364 | 103 | 0.688742 |
3ad57fe635fc713c5c5a8b0bc038c7653d55189c | 714 | //
// BayeuxClientContract.swift
//
//
// Created by Anthony Guiguen on 26/05/2020.
//
import Foundation
protocol BayeuxClientContract: class {
var transport: Transport? { get set }
var clientId: String? { get set }
var isConnected: Bool { get set }
var connectionInitiated: Bool { get set }
func handshake()
func sendPing(_ data: Data, completion: (() -> Void)?)
func openConnection(with fields: [String: Any])
func connect()
func closeConnection()
func disconnect()
func subscribe(_ models: [CometdSubscriptionModel]) throws
func subscribe(_ model: CometdSubscriptionModel) throws
func unsubscribe(_ channel: String)
func publish(_ data: [String: Any], channel: String)
}
| 25.5 | 60 | 0.708683 |
72c381205903ed3e920529f8cbe22cde1e032263 | 1,075 | //
// SelectBlur.swift
// free-blur
//
// Created by Justin Kambic on 6/3/17.
//
import UIKit
import CoreImage
class BlurSelectionView : UIView
{
var shouldBlurFace = false
var ciFaceCoords : CGRect
init(frame: CGRect, ciFaceCoords: CGRect) {
self.ciFaceCoords = ciFaceCoords
super.init(frame: frame)
self.isUserInteractionEnabled = true
self.layer.borderWidth = 1
self.layer.borderColor = UIColor.yellow.cgColor
self.clipsToBounds = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
if self.shouldBlurFace {
self.shouldBlurFace = false
self.backgroundColor = UIColor.clear
}
else {
self.shouldBlurFace = true
self.backgroundColor = UIColor(red: 0.239, green: 0.863, blue: 0.265, alpha: 0.685)
}
}
}
| 25.595238 | 95 | 0.616744 |
e0846093e5f833c11a2dacc35774b355d470ef1e | 2,052 | // RUN: %target-run-stdlib-swift
// REQUIRES: executable_test
import Swift
import SwiftPrivate
import StdlibUnittest
var HashingTestSuite = TestSuite("Hashing")
func checkHash(
for value: UInt64,
withSeed seed: (UInt64, UInt64),
expected: UInt64,
file: String = #file, line: UInt = #line
) {
var hasher = _Hasher(seed: seed)
hasher.append(bits: value)
let hash = hasher.finalize()
expectEqual(
hash, Int(truncatingIfNeeded: expected),
file: file, line: line)
}
HashingTestSuite.test("_Hasher/CustomKeys") {
// This assumes _Hasher implements SipHash-1-3.
checkHash(for: 0, withSeed: (0, 0), expected: 0xbd60acb658c79e45)
checkHash(for: 0, withSeed: (0, 1), expected: 0x1ce32b0b44e61175)
checkHash(for: 0, withSeed: (1, 0), expected: 0x9c44b7c8df2ca74b)
checkHash(for: 0, withSeed: (1, 1), expected: 0x9653ca0a3b455506)
checkHash(for: 0, withSeed: (.max, .max), expected: 0x3ab336a4895e4d36)
checkHash(for: 1, withSeed: (0, 0), expected: 0x1e9f734161d62dd9)
checkHash(for: 1, withSeed: (0, 1), expected: 0xb6fcf32d09f76cba)
checkHash(for: 1, withSeed: (1, 0), expected: 0xacb556b13007504a)
checkHash(for: 1, withSeed: (1, 1), expected: 0x7defec680db51d24)
checkHash(for: 1, withSeed: (.max, .max), expected: 0x212798441870ef6b)
checkHash(for: .max, withSeed: (0, 0), expected: 0x2f205be2fec8e38d)
checkHash(for: .max, withSeed: (0, 1), expected: 0x3ff7fa33381ecf7b)
checkHash(for: .max, withSeed: (1, 0), expected: 0x404afd8eb2c4b22a)
checkHash(for: .max, withSeed: (1, 1), expected: 0x855642d657c1bd46)
checkHash(for: .max, withSeed: (.max, .max), expected: 0x5b16b7a8181980c2)
}
HashingTestSuite.test("_Hasher/DefaultKey") {
let value: UInt64 = 0x0102030405060708
let defaultHash = _hashValue(for: value)
var defaultHasher = _Hasher()
defaultHasher.append(bits: value)
expectEqual(defaultHasher.finalize(), defaultHash)
var customHasher = _Hasher(seed: _Hasher._seed)
customHasher.append(bits: value)
expectEqual(customHasher.finalize(), defaultHash)
}
runAllTests()
| 33.639344 | 76 | 0.726608 |
09844de9f38f88ffd5763b458ae3c9df8377ffae | 5,644 | //
// SnippetExecuteView.swift
// mRayon
//
// Created by Lakr Aream on 2022/3/4.
//
import NSRemoteShell
import RayonModule
import SwiftUI
import XTerminalUI
struct SnippetExecuteView: View {
@StateObject var context: SnippetExecuteContext
@Environment(\.presentationMode) var presentationMode
@State var widthInstructor: CGSize = .init()
var terminalWidth: CGFloat {
if widthInstructor.width < 300 {
return 250
}
if widthInstructor.width > 500 {
return 500
}
return CGFloat(widthInstructor.width)
}
var body: some View {
Group {
if context.interfaceAllocated {
contentView
} else {
ProgressView().expended()
}
}
.padding(.horizontal)
.padding(.bottom)
.onAppear {
guard !context.interfaceAllocated else {
return
}
context.beginBootstrap()
}
.navigationTitle("Snippet - " + context.snippet.name)
.navigationBarTitleDisplayMode(.inline)
.toolbar {
Button {
if context.running.isEmpty {
presentationMode.wrappedValue.dismiss()
return
} else {
UIBridge.requiresConfirmation(
message: "Process in progress, terminate them all?"
) { yes in
if yes {
for machine in context.machineGroup {
context.close(for: machine.id)
}
presentationMode.wrappedValue.dismiss()
}
}
}
} label: {
Label("Terminate", systemImage: "xmark")
}
}
}
var contentView: some View {
VStack(alignment: .leading, spacing: 10) {
header
GeometryReader { r in
ScrollView(.horizontal) {
HStack(spacing: 10) {
ForEach(0 ..< context.machineGroup.count, id: \.self) { idx in
makeView(for: idx)
}
Divider().hidden()
}
}
.onChange(of: r.size) { newValue in
widthInstructor = newValue
}
}
.expended()
}
}
var header: some View {
Group {
VStack(alignment: .leading, spacing: 5) {
if context.running.isEmpty {
Image(
systemName: context.hasError
? "checkmark.circle.trianglebadge.exclamationmark" : "checkmark.circle.fill"
)
.foregroundColor(
context.hasError
? .orange : .green
)
.font(.system(.headline, design: .rounded))
.frame(maxWidth: .infinity)
} else {
runningItems
}
ProgressView(
context.running.isEmpty ? "Execution Complete" : "Execution In Progress",
value: context.completedProgress,
total: context.totalProgress
)
.animation(.interactiveSpring(), value: context.completedProgress)
.font(.system(.headline, design: .rounded))
.frame(maxWidth: .infinity)
}
}
.animation(.interactiveSpring(), value: context.running)
.padding()
.background(
Color(UIColor.systemGray6)
.cornerRadius(8)
)
}
var runningItems: some View {
HStack(spacing: 2) {
Image(systemName: "play.fill")
Spacer()
.frame(width: 2, height: 0)
ScrollView(.horizontal) {
HStack(spacing: 2) {
ForEach(context.running) { machine in
Text(machine.name)
.padding(4)
.background(
Color.accentColor
.opacity(0.1)
.cornerRadius(4)
)
.padding(4)
}
}
}
Text("\(context.running.count)")
}
.animation(.interactiveSpring(), value: context.running)
.font(.system(.subheadline, design: .rounded))
}
func makeView(for idx: Int) -> some View {
VStack(alignment: .center, spacing: 8) {
HStack {
Label(context.machineGroup[idx].name, systemImage: "arrow.right")
.font(.system(.headline, design: .rounded))
Spacer()
Button {
context.close(for: context.machineGroup[idx].id)
} label: {
Image(systemName: "xmark")
.foregroundColor(.red)
}
.disabled(context.completed.contains(context.machineGroup[idx]))
}
Divider()
context.terminalGroup[idx]
}
.expended()
.padding(12)
.background(
Color(UIColor.systemGray6)
.cornerRadius(8)
)
.frame(width: terminalWidth)
}
}
| 32.068182 | 104 | 0.445606 |
0e20f2093f8b4594fe8599e72790bfab297f52ea | 280 | //
// C2CDonorSizeSelectionViewController.swift
// CradlesToCrayons
//
// Created by Arun on 3/25/21.
//
import UIKit
class C2CDonorSizeSelectionViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
title = "Size"
}
}
| 15.555556 | 61 | 0.682143 |
8a4a5aec94cbb368cf477878deb4a7d9f2e07a50 | 9,008 | //
// LineNumberGutter.swift
//
//
// Created by Matthew Davidson on 13/12/19.
//
import Foundation
#if os(iOS)
import UIKit
#elseif os(macOS)
import Cocoa
/// A line number ruler view.
///
/// Adapted from: https://github.com/raphaelhanneken/line-number-text-view
public class LineNumberGutter: NSRulerView {
public var font: NSFont = NSFont.monospacedDigitSystemFont(ofSize: 12, weight: .light)
/// Holds the background color.
internal var backgroundColor: NSColor {
didSet {
self.needsDisplay = true
}
}
/// Holds the text color.
internal var foregroundColor: NSColor {
didSet {
self.needsDisplay = true
}
}
internal var currentLineForegroundColor: NSColor {
didSet {
self.needsDisplay = true
}
}
/// Initializes a LineNumberGutter with the given attributes.
///
/// - parameter textView: NSTextView to attach the LineNumberGutter to.
/// - parameter foregroundColor: Defines the foreground color.
/// - parameter backgroundColor: Defines the background color.
///
/// - returns: An initialized LineNumberGutter object.
public init(
withTextView textView: NSTextView,
foregroundColor: NSColor = .secondaryLabelColor,
backgroundColor: NSColor = .textBackgroundColor,
currentLineForegroundColor: NSColor = .selectedTextColor,
ruleThickness: CGFloat = 40
) {
// Set the color preferences.
self.backgroundColor = backgroundColor
self.foregroundColor = foregroundColor
self.currentLineForegroundColor = currentLineForegroundColor
// Make sure everything's set up properly before initializing properties.
super.init(scrollView: textView.enclosingScrollView, orientation: .verticalRuler)
// Set the rulers clientView to the supplied textview.
self.clientView = textView
// Define the ruler's width.
self.ruleThickness = ruleThickness
}
required init(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// Draws the line numbers.
///
/// - parameter rect: NSRect to draw the gutter view in.
override public func drawHashMarksAndLabels(in rect: NSRect) {
// Set the current background color...
self.backgroundColor.set()
// ...and fill the given rect.
rect.fill()
// Unwrap the clientView, the layoutManager and the textContainer, since we'll
// them sooner or later.
guard let textView = self.clientView as? NSTextView,
let layoutManager = textView.layoutManager,
let textContainer = textView.textContainer else {
return
}
let content = textView.string
// Get the range of the currently visible glyphs.
let visibleGlyphsRange = layoutManager.glyphRange(forBoundingRect: textView.visibleRect, in: textContainer)
// Check how many lines are out of the current bounding rect.
var lineNumber: Int = 1
do {
// Define a regular expression to find line breaks.
let newlineRegex = try NSRegularExpression(pattern: "\n", options: [])
// Check how many lines are out of view; From the glyph at index 0
// to the first glyph in the visible rect.
lineNumber += newlineRegex.numberOfMatches(in: content, options: [], range: NSMakeRange(0, visibleGlyphsRange.location))
} catch {
return
}
// Get the lines currently selected.
let currentLines = getVisibileSelectedLines(content: content, selectedRanges: textView.selectedRanges.map{$0.rangeValue}, visibleRange: visibleGlyphsRange, firstLineNumber: lineNumber)
// Get the index of the first glyph in the visible rect, as starting point...
var firstGlyphOfLineIndex = visibleGlyphsRange.location
// ...then loop through all visible glyphs, line by line.
while firstGlyphOfLineIndex < NSMaxRange(visibleGlyphsRange) {
// Get the character range of the line we're currently in.
let charRangeOfLine = (content as NSString).lineRange(for: NSRange(location: layoutManager.characterIndexForGlyph(at: firstGlyphOfLineIndex), length: 0))
// Get the glyph range of the line we're currently in.
let glyphRangeOfLine = layoutManager.glyphRange(forCharacterRange: charRangeOfLine, actualCharacterRange: nil)
var firstGlyphOfRowIndex = firstGlyphOfLineIndex
var lineWrapCount = 0
// Loop through all rows (soft wraps) of the current line.
while firstGlyphOfRowIndex < NSMaxRange(glyphRangeOfLine) {
// The effective range of glyphs within the current line.
var effectiveRange = NSRange(location: 0, length: 0)
// Get the rect for the current line fragment.
let lineRect = layoutManager.lineFragmentRect(forGlyphAt: firstGlyphOfRowIndex, effectiveRange: &effectiveRange, withoutAdditionalLayout: true)
// Draw the current line number;
// When lineWrapCount > 0 the current line spans multiple rows.
if lineWrapCount == 0 {
self.drawLineNumber(
num: lineNumber,
atY: lineRect.minY + textView.textContainerInset.height,
maxHeight: lineRect.height,
isCurrentLine: currentLines.contains(lineNumber)
)
}
else {
break
}
// Move to the next row.
firstGlyphOfRowIndex = NSMaxRange(effectiveRange)
lineWrapCount += 1
}
// Move to the next line.
firstGlyphOfLineIndex = NSMaxRange(glyphRangeOfLine)
lineNumber += 1
}
// Draw another line number for the extra line fragment.
if let _ = layoutManager.extraLineFragmentTextContainer {
self.drawLineNumber(
num: lineNumber,
atY: layoutManager.extraLineFragmentRect.minY + textView.textContainerInset.height,
maxHeight: layoutManager.extraLineFragmentRect.height,
isCurrentLine: visibleGlyphsRange.upperBound == textView.selectedRanges.last?.rangeValue.upperBound
)
}
}
/// Gets the lines currently selected out of the visible range.
func getVisibileSelectedLines(content: String, selectedRanges: [NSRange], visibleRange: NSRange, firstLineNumber: Int) -> [Int] {
// Get a list of the visible lines. Including newlines!
let startI = content.utf16.index(content.utf16.startIndex, offsetBy: visibleRange.location)
let endI = content.utf16.index(content.utf16.startIndex, offsetBy: visibleRange.upperBound)
let visLines = content[startI..<endI].split(separator: "\n", omittingEmptySubsequences: false).map{$0 + "\n"}
// Loop through each visible line.
var loc = visibleRange.location
var currentLines = [Int]()
for (i, line) in visLines.enumerated() {
// See if the any of the selected ranges has an intersection with the line, if so then this line is part of the selection.
let lineRange = NSRange(location: loc, length: line.utf16.count)
if selectedRanges.filter({
$0.intersection(lineRange) != nil
}).count > 0 {
currentLines.append(i + firstLineNumber)
}
loc += line.utf16.count
}
return currentLines
}
func drawLineNumber(num: Int, atY yPos: CGFloat, maxHeight: CGFloat, isCurrentLine: Bool = false) {
// Unwrap the text view.
guard let textView = self.clientView as? NSTextView else {
return
}
// Define attributes for the attributed string.
let attrs = [NSAttributedString.Key.font: font, NSAttributedString.Key.foregroundColor: isCurrentLine ? self.currentLineForegroundColor : self.foregroundColor]
// Define the attributed string.
let attributedString = NSAttributedString(string: "\(num)", attributes: attrs)
// Get the NSZeroPoint from the text view.
let relativePoint = self.convert(NSZeroPoint, from: textView)
// Calculate the x position, within the gutter.
let xPosition = ruleThickness - (attributedString.size().width + 5)
// Center it vertically
let yPosition = relativePoint.y + yPos + (maxHeight - attributedString.size().height) / 2
// Draw the attributed string to the calculated point.
attributedString.draw(at: NSPoint(x: xPosition, y: yPosition))
}
}
#endif
| 40.760181 | 192 | 0.629885 |
1c897c69b2e193ca5d24eab17097d80a7da2daa3 | 3,179 | //
// SequenceExtensionsTests.swift
// SwifterSwift
//
// Created by Anton Novoselov on 04/04/2018.
// Copyright © 2018 SwifterSwift
//
import XCTest
@testable import SwifterSwift
private enum SequenceTestError: Error {
case closureThrows
}
final class SequenceExtensionsTests: XCTestCase {
func testAllMatch() {
let collection = [2, 4, 6, 8, 10, 12]
XCTAssert(collection.all { $0 % 2 == 0 })
}
func testAnyMatch() {
let collection = [3, 5, 8, 9, 11, 13]
XCTAssert(collection.any { $0 % 2 == 0 })
}
func testNoneMatch() {
let collection = [3, 5, 7, 9, 11, 13]
XCTAssert(collection.none { $0 % 2 == 0 })
}
func testLastWhere() {
let array = [1, 1, 2, 1, 1, 1, 2, 1, 4, 1]
let element = array.last { $0 % 2 == 0 }
XCTAssertEqual(element, 4)
XCTAssertNil([Int]().last { $0 % 2 == 0 })
}
func testRejectWhere() {
let input = [1, 2, 3, 4, 5]
let output = input.reject { $0 % 2 == 0 }
XCTAssertEqual(output, [1, 3, 5])
}
func testCountWhere() {
let array = [1, 1, 1, 1, 4, 4, 1, 1, 1]
let count = array.count { $0 % 2 == 0 }
XCTAssertEqual(count, 2)
}
func testForEachReversed() {
let input = [1, 2, 3, 4, 5]
var output: [Int] = []
input.forEachReversed { output.append($0) }
XCTAssertEqual(output.first, 5)
}
func testForEachWhere() {
let input = [1, 2, 2, 2, 1, 4, 1]
var output: [Int] = []
input.forEach(where: {$0 % 2 == 0}, body: { output.append($0 * 2) })
XCTAssertEqual(output, [4, 4, 4, 8])
}
func testAccumulate() {
let input = [1, 2, 3]
let result = input.accumulate(initial: 0, next: +)
XCTAssertEqual([1, 3, 6], result)
}
func testFilteredMap() {
let input = [1, 2, 3, 4, 5]
let result = input.filtered({ $0 % 2 == 0 }, map: { $0.string })
XCTAssertEqual(result.count, 2)
XCTAssertEqual(["2", "4"], result)
}
func testSingle() {
XCTAssertNil([].single(where: { _ in true }))
XCTAssertEqual([4].single(where: { _ in true }), 4)
XCTAssertNil([2, 4].single(where: { _ in true }))
XCTAssertEqual([1, 4, 7].single(where: { $0 % 2 == 0 }), 4)
XCTAssertNil([2, 2, 4, 7].single(where: { $0 % 2 == 0 }))
XCTAssertThrowsError(try [2].single(where: { _ in throw SequenceTestError.closureThrows }))
}
func testContains() {
XCTAssert([Int]().contains([]))
XCTAssertFalse([Int]().contains([1, 2]))
XCTAssert([1, 2, 3].contains([1, 2]))
XCTAssert([1, 2, 3].contains([2, 3]))
XCTAssert([1, 2, 3].contains([1, 3]))
XCTAssertFalse([1, 2, 3].contains([4, 5]))
}
func testContainsDuplicates() {
XCTAssertFalse([String]().containsDuplicates())
XCTAssert(["a", "b", "b", "c"].containsDuplicates())
XCTAssertFalse(["a", "b", "c", "d"].containsDuplicates())
}
func testSum() {
XCTAssertEqual([1, 2, 3, 4, 5].sum(), 15)
XCTAssertEqual([1.2, 2.3, 3.4, 4.5, 5.6].sum(), 17)
}
}
| 29.165138 | 99 | 0.53067 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.