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
|
---|---|---|---|---|---|
e029f2210609366adbbdd72edb19269a7c39caa9 | 253 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct b {
let c : a
j {
}
protocol b {
typealias f: a
func a
}
let a = B
class B<T
| 16.866667 | 87 | 0.715415 |
6a90b130c74dee6dfde743da03cd5643bfd92c9b | 1,844 | //
// UILabel+Ext.swift
// Exemple
//
// Created by Bart on 26.10.2019
// Copyright © 2019 iDevs.io. All rights reserved.
//
import UIKit
@IBDesignable extension UILabel {
func setCharacterSpacing(_ characterSpacing: CGFloat = 0.0) {
guard let labelText = text else { return }
let attributedString: NSMutableAttributedString
if let labelAttributedText = attributedText {
attributedString = NSMutableAttributedString(attributedString: labelAttributedText)
} else {
attributedString = NSMutableAttributedString(string: labelText)
}
// Character spacing attribute
attributedString.addAttribute(NSAttributedString.Key.kern, value: characterSpacing, range: NSMakeRange(0, attributedString.length))
attributedText = attributedString
}
func setLineSpacing(_ lineSpacing: CGFloat = 0.0) {
guard let labelText = text else { return }
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = lineSpacing
let attributedString: NSMutableAttributedString
if let labelAttributedText = attributedText {
attributedString = NSMutableAttributedString(attributedString: labelAttributedText)
} else {
attributedString = NSMutableAttributedString(string: labelText)
}
// Character spacing attribute
attributedString.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range: NSMakeRange(0, attributedString.length))
attributedText = attributedString
}
@IBInspectable public var kern_: CGFloat {
set {
self.setCharacterSpacing(newValue)
}
get {
return 0
}
}
}
| 31.793103 | 147 | 0.653471 |
6777e20287ffa538aa8635c6d5dfa7e63ec4cb2b | 1,851 | //
// CheckOutView.swift
// terpscan
//
// Created by Justin Le on 5/8/20.
// Copyright © 2020 Justin Le. All rights reserved.
//
import SwiftUI
struct CheckOutView: View {
@Binding var isPresented: Bool
@Binding var packages: Set<Package>
var body: some View {
NavigationView {
List {
ForEach(Array(packages), id: \.self) { package in
NavigationLink(
destination: PackageDetailView(package: package)
) {
PackageCellView(package: package)
}
}
}
.padding(.all)
.navigationBarTitle("Check Out \(packages.count) Package(s)", displayMode: .inline)
.navigationBarItems(
leading: Button(
action: {
self.isPresented = false
}) {
Text("Cancel")
},
trailing:
NavigationLink(
destination: SignView(isPresented: $isPresented, packages: $packages)
) {
Text("Sign")
}
)
}.navigationViewStyle(StackNavigationViewStyle())
}
}
struct CheckOutView_Previews: PreviewProvider {
static var previews: some View {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let mailbox = initMailbox(in: context)
var packages = Set<Package>()
for _ in 1...3 {
let package = initPackage(in: context, for: mailbox)
packages.insert(package)
}
return CheckOutView(isPresented: .constant(true), packages: .constant(packages)).environment(\.managedObjectContext, context)
}
}
| 31.372881 | 133 | 0.522961 |
8f05445a404229c6bdf42558aa8c77fb42f27b97 | 13,819 | //
// APIManager.swift
// twitter_alamofire_demo
//
// Created by Charles Hieger on 4/4/17.
// Copyright © 2017 Charles Hieger. All rights reserved.
//
import Foundation
import Alamofire
import OAuthSwift
import OAuthSwiftAlamofire
import KeychainAccess
class APIManager: SessionManager {
// MARK: TODO: Add App Keys
static let consumerKey = "uFTmFW66AAMEUwx3rZlZDMSCf"
static let consumerSecret = "LtlxIoQpBvHcqjpSMIA9Gs2E9wCJbr7xkx9EpSdBYoNedaZUgh"
static let requestTokenURL = "https://api.twitter.com/oauth/request_token"
static let authorizeURL = "https://api.twitter.com/oauth/authorize"
static let accessTokenURL = "https://api.twitter.com/oauth/access_token"
static let callbackURLString = "alamoTwitter://"
static func logout() {
// 1. Clear current user
User.current = nil
// TODO: 2. Deauthorize OAuth tokens
// 3. Post logout notification
NotificationCenter.default.post(name: NSNotification.Name("didLogout"), object: nil)
}
// MARK: Twitter API methods
func login(success: @escaping () -> (), failure: @escaping (Error?) -> ()) {
// Add callback url to open app when returning from Twitter login on web
let callbackURL = URL(string: APIManager.callbackURLString)!
oauthManager.authorize(withCallbackURL: callbackURL, success: { (credential, _response, parameters) in
// Save Oauth tokens
self.save(credential: credential)
self.getCurrentAccount(completion: { (user, error) in
if let error = error {
failure(error)
} else if let user = user {
print("Welcome \(user.name)")
// MARK: TODO: set User.current, so that it's persisted
User.current = user
success()
}
})
}) { (error) in
failure(error)
}
}
func getCurrentAccount(completion: @escaping (User?, Error?) -> ()) {
request(URL(string: "https://api.twitter.com/1.1/account/verify_credentials.json")!)
.validate()
.responseJSON { response in
switch response.result {
case .failure(let error):
completion(nil, error)
break;
case .success:
guard let userDictionary = response.result.value as? [String: Any] else {
completion(nil, JSONError.parsing("Unable to create user dictionary"))
return
}
completion(User(dictionary: userDictionary), nil)
}
}
}
func updateUser() {
self.getCurrentAccount { (user: User?, error: Error?) in
User.current = user
}
}
func getHomeTimeLine(completion: @escaping ([Tweet]?, Error?) -> ()) {
// This uses tweets from disk to avoid hitting rate limit. Comment out if you want fresh
// tweets,
// if let data = UserDefaults.standard.object(forKey: "hometimeline_tweets") as? Data {
// let tweetDictionaries = NSKeyedUnarchiver.unarchiveObject(with: data) as! [[String: Any]]
// let tweets = tweetDictionaries.flatMap({ (dictionary) -> Tweet in
// Tweet(dictionary: dictionary)
// })
// completion(tweets, nil)
// return
// }
request(URL(string: "https://api.twitter.com/1.1/statuses/home_timeline.json")!, method: .get)
.validate()
.responseJSON { (response) in
switch response.result {
case .failure(let error):
completion(nil, error)
return
case .success:
guard let tweetDictionaries = response.result.value as? [[String: Any]] else {
print("Failed to parse tweets")
let error = NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey : "Failed to parse tweets"])
completion(nil, error)
return
}
let data = NSKeyedArchiver.archivedData(withRootObject: tweetDictionaries)
UserDefaults.standard.set(data, forKey: "hometimeline_tweets")
UserDefaults.standard.synchronize()
let tweets = Tweet.tweets(with: tweetDictionaries)
completion(tweets, nil)
}
}
}
// MARK: TODO: Favorite a Tweet
func favorite(_ tweet: Tweet, completion: @escaping (Tweet?, Error?) -> ()) {
let urlString = "https://api.twitter.com/1.1/favorites/create.json"
let parameters = ["id": tweet.id]
request(urlString, method: .post, parameters: parameters, encoding: URLEncoding.queryString).validate().responseJSON { (response) in
if response.result.isSuccess,
let tweetDictionary = response.result.value as? [String: Any] {
let tweet = Tweet(dictionary: tweetDictionary)
completion(tweet, nil)
} else {
completion(nil, response.result.error)
}
}
}
// MARK: TODO: Un-Favorite a Tweet
func unfavorite(_ tweet: Tweet, completion: @escaping (Tweet?, Error?) -> ()) {
let urlString = "https://api.twitter.com/1.1/favorites/destroy.json"
let parameters = ["id": tweet.id]
request(urlString, method: .post, parameters: parameters, encoding: URLEncoding.queryString).validate().responseJSON { (response) in
if response.result.isSuccess,
let tweetDictionary = response.result.value as? [String: Any] {
let tweet = Tweet(dictionary: tweetDictionary)
completion(tweet, nil)
} else {
completion(nil, response.result.error)
}
}
}
// MARK: TODO: Retweet
func retweet(_ tweet: Tweet, completion: @escaping (Tweet?, Error?) -> ()) {
let urlString = "https://api.twitter.com/1.1/statuses/retweet/" + String(tweet.id!) + ".json"
let parameters = ["id": tweet.id]
request(urlString, method: .post, parameters: parameters, encoding: URLEncoding.queryString).validate().responseJSON { (response) in
if response.result.isSuccess,
let tweetDictionary = response.result.value as? [String: Any] {
let tweet = Tweet(dictionary: tweetDictionary)
completion(tweet, nil)
} else {
completion(nil, response.result.error)
}
}
}
// MARK: TODO: Un-Retweet
func unretweet(_ tweet: Tweet, completion: @escaping (Tweet?, Error?) -> ()) {
let urlString = "https://api.twitter.com/1.1/statuses/unretweet/" + String(tweet.id!) + ".json"
let parameters = ["id": tweet.id]
request(urlString, method: .post, parameters: parameters, encoding: URLEncoding.queryString).validate().responseJSON { (response) in
if response.result.isSuccess,
let tweetDictionary = response.result.value as? [String: Any] {
let tweet = Tweet(dictionary: tweetDictionary)
completion(tweet, nil)
} else {
completion(nil, response.result.error)
}
}
}
// MARK: TODO: Compose Tweet
func composeTweet(status: String, replyTo: String? = nil, completion: @escaping (Error?) -> ()) {
let urlString = "https://api.twitter.com/1.1/statuses/update.json";
var parameters = ["status": status]
if (replyTo != nil) {
parameters = ["status": status, "in_reply_to_status_id": replyTo!]
}
request(urlString, method: .post, parameters: parameters, encoding: URLEncoding.queryString).validate().responseJSON { (response) in
if response.result.isSuccess {
print("successfully tweeted")
completion(nil)
} else {
completion(response.result.error)
}
}
}
// MARK: TODO: Get User Timeline
func getUserTimeLine(completion: @escaping ([Tweet]?, Error?) -> ()) {
request(URL(string: "https://api.twitter.com/1.1/statuses/user_timeline.json")!, method: .get)
.validate()
.responseJSON { (response) in
switch response.result {
case .failure(let error):
completion(nil, error)
return
case .success:
guard let tweetDictionaries = response.result.value as? [[String: Any]] else {
print("Failed to parse tweets")
let error = NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey : "Failed to parse tweets"])
completion(nil, error)
return
}
let tweets = Tweet.tweets(with: tweetDictionaries)
completion(tweets, nil)
}
}
}
func getBannerURLs(completion: @escaping ([String: Any]?, Error?) -> ()) {
request(URL(string: "https://api.twitter.com/1.1/users/profile_banner.json?screen_name=" + User.current!.screenName!)!, method: .get)
.validate()
.responseJSON { (response) in
switch response.result {
case .failure(let error):
print(error.localizedDescription)
return
case .success:
guard let bannerDictionary = response.result.value as? [String: Any] else {
print("Failed to parse tweets")
let error = NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey : "Failed to parse tweets"])
print(error.localizedDescription)
return
}
let bannerImgURLs = bannerDictionary["sizes"] as? [String: Any]
completion(bannerImgURLs, nil)
}
}
}
//--------------------------------------------------------------------------------//
func getTweetCell(cell: tweetCell, tweet: Tweet) -> tweetCell {
var profileImgURL = tweet.user?.profileImageURL! ?? "";
profileImgURL = profileImgURL.replacingOccurrences(of: "_normal", with: "")
cell.tweet = tweet
cell.selectionStyle = .none
cell.usernameLabel.text = tweet.user?.name
cell.tweetLabel.text = tweet.text
cell.handleLabel.text = "@" + String(tweet.user?.screenName ?? "")
cell.profileImageView.af_setImage(withURL: URL(string: profileImgURL)!)
cell.dateLabel.text = tweet.timeAgo
if (tweet.retweeted!) {
cell.retweetImageView.image = UIImage(named: "retweet-icon-green")
} else {
cell.retweetImageView.image = UIImage(named: "retweet-icon")
}
if (tweet.favorited!) {
cell.favoriteImageView.image = UIImage(named: "favor-icon-red")
} else {
cell.favoriteImageView.image = UIImage(named: "favor-icon")
}
return cell
}
//MARK: OAuth
static var shared: APIManager = APIManager()
var oauthManager: OAuth1Swift!
// Private init for singleton only
private init() {
super.init()
// Create an instance of OAuth1Swift with credentials and oauth endpoints
oauthManager = OAuth1Swift(
consumerKey: APIManager.consumerKey,
consumerSecret: APIManager.consumerSecret,
requestTokenUrl: APIManager.requestTokenURL,
authorizeUrl: APIManager.authorizeURL,
accessTokenUrl: APIManager.accessTokenURL
)
// Retrieve access token from keychain if it exists
if let credential = retrieveCredentials() {
oauthManager.client.credential.oauthToken = credential.oauthToken
oauthManager.client.credential.oauthTokenSecret = credential.oauthTokenSecret
}
// Assign oauth request adapter to Alamofire SessionManager adapter to sign requests
adapter = oauthManager.requestAdapter
}
// MARK: Handle url
// OAuth Step 3
// Finish oauth process by fetching access token
func handle(url: URL) {
OAuth1Swift.handle(url: url)
}
// MARK: Save Tokens in Keychain
private func save(credential: OAuthSwiftCredential) {
// Store access token in keychain
let keychain = Keychain()
let data = NSKeyedArchiver.archivedData(withRootObject: credential)
keychain[data: "twitter_credentials"] = data
}
// MARK: Retrieve Credentials
private func retrieveCredentials() -> OAuthSwiftCredential? {
let keychain = Keychain()
if let data = keychain[data: "twitter_credentials"] {
let credential = NSKeyedUnarchiver.unarchiveObject(with: data) as! OAuthSwiftCredential
return credential
} else {
return nil
}
}
// MARK: Clear tokens in Keychain
private func clearCredentials() {
// Store access token in keychain
let keychain = Keychain()
do {
try keychain.remove("twitter_credentials")
} catch let error {
print("error: \(error)")
}
}
}
enum JSONError: Error {
case parsing(String)
}
| 40.171512 | 141 | 0.564006 |
dd79512473650f312af10b41eadf40751c424cf0 | 1,664 | //
// ClosuresViewController.swift
// MemoryLeak
//
// Created by Victor Pereira on 13/06/20.
// Copyright © 2020 Victor Pereira. All rights reserved.
//
import UIKit
protocol NotificationCenterClosuresPresenterProtocol: PresenterProtocol {
}
final class NotificationCenterClosuresViewController: ViewController {
var presenter: NotificationCenterClosuresPresenterProtocol? {
basePresenter as? NotificationCenterClosuresPresenterProtocol
}
private lazy var warningLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.textColor = .yellow
label.textAlignment = .center
label.numberOfLines = 0
label.font = UIFont.systemFont(ofSize: 20, weight: .medium)
label.text = "Parece que precisamos de [weak self] nas closures do NotificationCenter.default.addObserver"
return label
}()
override func viewDidLoad() {
super.viewDidLoad()
setupView()
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "DoSomething"), object: nil, queue: .main) { _ in
self.view.backgroundColor = .green
}
}
private func setupView() {
view.backgroundColor = .red
view.addSubview(warningLabel)
NSLayoutConstraint.activate([
warningLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor),
warningLabel.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 16),
warningLabel.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -16)
])
}
}
| 32 | 135 | 0.678486 |
4bd78ddcba796412e4200975ada21d3d55211b1d | 503 | //
// MockCollectionViewLayout.swift
// KeyboardKit
//
// Created by Daniel Saidi on 2019-05-28.
// Copyright © 2021 Daniel Saidi. All rights reserved.
//
#if os(iOS) || os(tvOS)
import MockingKit
import UIKit
class MockCollectionViewLayout: UICollectionViewFlowLayout, Mockable {
lazy var invalidateLayoutRef = MockReference(invalidateLayout as () -> Void)
var mock = Mock()
override func invalidateLayout() {
call(invalidateLayoutRef, args: ())
}
}
#endif
| 20.958333 | 80 | 0.687873 |
1aabbe0dd279ce0a9633a4e796a279ca5c2d08ae | 65 | let a = ["foo", "bar", "baz"]
let b: Int = strings.first!.length
| 21.666667 | 34 | 0.584615 |
c1a82cf3fabf39097ee524367c92a3d8a35b7f40 | 5,876 | //
// SensorUIData.swift
// simple_service
//
// Created by SK Telecom on 2018. 1. 2..
// Copyright © 2018년 SK Telecom. All rights reserved.
//
import Foundation
import UIKit
public enum SensorCategory: UInt8 {
case SENSOR_MANAGER = 0
case BROADCAST
case LOCATION_MANAGER
case MEDIA_RECORDER
case ACTUATOR
}
class SensorUIData {
class Entry {
var sensorImage : UIImage
var sensorName : NSString
var sensorValueName : NSArray
var sensorCategory : SensorCategory
var sensorValueString : NSMutableArray
var sensorValueFormat : NSArray
var sensorIsActivated : Bool
var sensorIsSupport : Bool
init(sImage : UIImage, sName : NSString, sValueName : NSArray , sCategory :SensorCategory, sValueString : NSMutableArray, sValueFormat : NSArray , sActivated : Bool, sSupport : Bool) {
self.sensorImage = sImage
self.sensorName = sName
self.sensorValueName = sValueName
self.sensorCategory = sCategory
self.sensorValueString = sValueString
self.sensorValueFormat = sValueFormat
self.sensorIsActivated = sActivated
self.sensorIsSupport = sSupport
}
}
var Sensors = [
Entry(sImage: #imageLiteral(resourceName: "icon_batterygauge_big"), sName: "Battery", sValueName: ["batteryTemperature","batteryGuage"], sCategory: .BROADCAST, sValueString: ["0","0"], sValueFormat:[["Temperature", "℃"], ["Charge", "%"]], sActivated: false, sSupport: false),
Entry(sImage: #imageLiteral(resourceName: "icon_temperature_big"), sName: "Temperature", sValueName: ["temperature"], sCategory: .SENSOR_MANAGER, sValueString: ["0"], sValueFormat:[["Ambient temperature", "℃"]], sActivated: false, sSupport: false),
Entry(sImage: #imageLiteral(resourceName: "icon_humidity_big"), sName: "Humidity", sValueName: ["humidity"], sCategory: .SENSOR_MANAGER, sValueString: ["0"], sValueFormat:[["Air humidity", "%"]], sActivated: false, sSupport: false),
Entry(sImage: #imageLiteral(resourceName: "icon_noise_big"), sName: "Noise", sValueName: ["noise"], sCategory: .MEDIA_RECORDER, sValueString: ["0"], sValueFormat:[["Noise", "㏈"]], sActivated: false, sSupport: false),
Entry(sImage: #imageLiteral(resourceName: "icon_actuator_big"), sName: "GPS", sValueName: ["latitude", "longitude", "altitude"], sCategory: .LOCATION_MANAGER, sValueString: ["","",""], sValueFormat:[["Latitude", "˚"], ["Longitude","˚"], ["Altitude","˚"]], sActivated: false, sSupport: false),
Entry(sImage: #imageLiteral(resourceName: "icon_pressure_big"), sName: "Air Pressure", sValueName: ["airPressure"], sCategory: .SENSOR_MANAGER, sValueString: ["0"], sValueFormat:[["Pressure", "h㎩"]], sActivated: false, sSupport: false),
Entry(sImage: #imageLiteral(resourceName: "icon_light_big"), sName: "Light", sValueName: ["light"], sCategory: .SENSOR_MANAGER, sValueString: ["0"], sValueFormat:[["Level", "㏓"]], sActivated: false, sSupport: false),
Entry(sImage: #imageLiteral(resourceName: "icon_buzzer_big"), sName: "Buzzer", sValueName: ["buzzer"], sCategory: .ACTUATOR, sValueString: ["0"], sValueFormat:[["",""]], sActivated: false, sSupport: false),
Entry(sImage: #imageLiteral(resourceName: "icon_color_big"), sName: "Led", sValueName: ["led"], sCategory: .ACTUATOR, sValueString: ["0"], sValueFormat:[["",""]], sActivated: false, sSupport: false),
Entry(sImage: #imageLiteral(resourceName: "icon_peoplecount_big"), sName: "Proximity", sValueName: ["distance"], sCategory: .SENSOR_MANAGER, sValueString: [""], sValueFormat:[["Distance", "㎝"]], sActivated: false, sSupport: false),
Entry(sImage: #imageLiteral(resourceName: "icon_camera_big"), sName: "Camera", sValueName: ["camera"], sCategory: .ACTUATOR, sValueString: ["0"], sValueFormat:[["",""]], sActivated: false, sSupport: false),
Entry(sImage: #imageLiteral(resourceName: "icon_accelerometer_big"), sName: "Accelerometer", sValueName: ["accel_x", "accel_y", "accel_z"], sCategory: .SENSOR_MANAGER, sValueString: ["0","0","0"], sValueFormat:[["X", "㎨"], ["Y", "㎨"], ["Z", "㎨"]], sActivated: false, sSupport: false),
Entry(sImage: #imageLiteral(resourceName: "icon_windvane_big"), sName: "Orientation", sValueName: ["azi", "pitch", "roll"], sCategory: .SENSOR_MANAGER, sValueString: ["0","0","0"], sValueFormat:[["Azimuth", "˚"], ["Pitch", "˚"], ["Roll", "˚"]], sActivated: false, sSupport: false),
Entry(sImage: #imageLiteral(resourceName: "icon_weight_big"), sName: "Gravity", sValueName: ["grav_x", "grav_y", "grav_z"], sCategory: .SENSOR_MANAGER, sValueString: ["0","0","0"], sValueFormat:[["X", "㎨"], ["Y", "㎨"], ["Z", "㎨"]], sActivated: false, sSupport: false),
Entry(sImage: #imageLiteral(resourceName: "icon_rotaryangle_big"), sName: "Gyroscope", sValueName: ["gyro_x", "gyro_y", "gyro_z"], sCategory: .SENSOR_MANAGER, sValueString: ["0","0","0"], sValueFormat:[["X", "˚"], ["Y", "˚"], ["Z", "˚"]], sActivated: false, sSupport: false),
Entry(sImage: #imageLiteral(resourceName: "icon_vibration_big"), sName: "Magnetic Field", sValueName: ["magn_x", "magn_y", "magn_z"], sCategory: .SENSOR_MANAGER, sValueString: ["0","0","0"], sValueFormat:[["X", "µT"], ["Y", "µT"], ["Z", "µT"]], sActivated: false, sSupport: false),
Entry(sImage: #imageLiteral(resourceName: "icon_motion_on_big"), sName: "Step Detector", sValueName: ["stepDetection"], sCategory: .SENSOR_MANAGER, sValueString: ["0"], sValueFormat:[["Detection", ""]], sActivated: false, sSupport: false),
Entry(sImage: #imageLiteral(resourceName: "icon_motion_on_big"), sName: "Step Count", sValueName: ["stepCount"], sCategory: .SENSOR_MANAGER, sValueString: ["0"], sValueFormat:[["Count", "steps"]], sActivated: false, sSupport: false)
]
}
| 89.030303 | 300 | 0.669163 |
18187a7682ba784420c6a1f18d842f6822cdf54d | 16,981 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020-2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Swift
/// An asynchronous sequence generated from a closure that calls a continuation
/// to produce new elements.
///
/// `AsyncStream` conforms to `AsyncSequence`, providing a convenient way to
/// create an asynchronous sequence without manually implementing an
/// asynchronous iterator. In particular, an asynchronous stream is well-suited
/// to adapt callback- or delegation-based APIs to participate with
/// `async`-`await`.
///
/// You initialize an `AsyncStream` with a closure that receives an
/// `AsyncStream.Continuation`. Produce elements in this closure, then provide
/// them to the stream by calling the continuation's `yield(_:)` method. When
/// there are no further elements to produce, call the continuation's
/// `finish()` method. This causes the sequence iterator to produce a `nil`,
/// which terminates the sequence. The continuation conforms to `Sendable`, which permits
/// calling it from concurrent contexts external to the iteration of the
/// `AsyncStream`.
///
/// An arbitrary source of elements can produce elements faster than they are
/// consumed by a caller iterating over them. Because of this, `AsyncStream`
/// defines a buffering behavior, allowing the stream to buffer a specific
/// number of oldest or newest elements. By default, the buffer limit is
/// `Int.max`, which means the value is unbounded.
///
/// ### Adapting Existing Code to Use Streams
///
/// To adapt existing callback code to use `async`-`await`, use the callbacks
/// to provide values to the stream, by using the continuation's `yield(_:)`
/// method.
///
/// Consider a hypothetical `QuakeMonitor` type that provides callers with
/// `Quake` instances every time it detects an earthquake. To receive callbacks,
/// callers set a custom closure as the value of the monitor's
/// `quakeHandler` property, which the monitor calls back as necessary.
///
/// class QuakeMonitor {
/// var quakeHandler: ((Quake) -> Void)?
///
/// func startMonitoring() {…}
/// func stopMonitoring() {…}
/// }
///
/// To adapt this to use `async`-`await`, extend the `QuakeMonitor` to add a
/// `quakes` property, of type `AsyncStream<Quake>`. In the getter for this
/// property, return an `AsyncStream`, whose `build` closure -- called at
/// runtime to create the stream -- uses the continuation to perform the
/// following steps:
///
/// 1. Creates a `QuakeMonitor` instance.
/// 2. Sets the monitor's `quakeHandler` property to a closure that receives
/// each `Quake` instance and forwards it to the stream by calling the
/// continuation's `yield(_:)` method.
/// 3. Sets the continuation's `onTermination` property to a closure that
/// calls `stopMonitoring()` on the monitor.
/// 4. Calls `startMonitoring` on the `QuakeMonitor`.
///
/// ```
/// extension QuakeMonitor {
///
/// static var quakes: AsyncStream<Quake> {
/// AsyncStream { continuation in
/// let monitor = QuakeMonitor()
/// monitor.quakeHandler = { quake in
/// continuation.yield(quake)
/// }
/// continuation.onTermination = { @Sendable _ in
/// monitor.stopMonitoring()
/// }
/// monitor.startMonitoring()
/// }
/// }
/// }
/// ```
///
/// Because the stream is an `AsyncSequence`, the call point can use the
/// `for`-`await`-`in` syntax to process each `Quake` instance as the stream
/// produces it:
///
/// for await quake in QuakeMonitor.quakes {
/// print ("Quake: \(quake.date)")
/// }
/// print ("Stream finished.")
///
@available(SwiftStdlib 5.1, *)
public struct AsyncStream<Element> {
/// A mechanism to interface between synchronous code and an asynchronous
/// stream.
///
/// The closure you provide to the `AsyncStream` in
/// `init(_:bufferingPolicy:_:)` receives an instance of this type when
/// invoked. Use this continuation to provide elements to the stream by
/// calling one of the `yield` methods, then terminate the stream normally by
/// calling the `finish()` method.
///
/// - Note: Unlike other continuations in Swift, `AsyncStream.Continuation`
/// supports escaping.
public struct Continuation: Sendable {
/// A type that indicates how the stream terminated.
///
/// The `onTermination` closure receives an instance of this type.
public enum Termination {
/// The stream finished as a result of calling the continuation's
/// `finish` method.
case finished
/// The stream finished as a result of cancellation.
case cancelled
}
/// A type that indicates the result of yielding a value to a client, by
/// way of the continuation.
///
/// The various `yield` methods of `AsyncStream.Continuation` return this
/// type to indicate the success or failure of yielding an element to the
/// continuation.
public enum YieldResult {
/// The stream successfully enqueued the element.
///
/// This value represents the successful enqueueing of an element, whether
/// the stream buffers the element or delivers it immediately to a pending
/// call to `next()`. The associated value `remaining` is a hint that
/// indicates the number of remaining slots in the buffer at the time of
/// the `yield` call.
///
/// - Note: From a thread safety point of view, `remaining` is a lower bound
/// on the number of remaining slots. This is because a subsequent call
/// that uses the `remaining` value could race on the consumption of
/// values from the stream.
case enqueued(remaining: Int)
/// The stream didn't enqueue the element because the buffer was full.
///
/// The associated element for this case is the element dropped by the stream.
case dropped(Element)
/// The stream didn't enqueue the element because the stream was in a
/// terminal state.
///
/// This indicates the stream terminated prior to calling `yield`, either
/// because the stream finished normally or through cancellation.
case terminated
}
/// A strategy that handles exhaustion of a buffer’s capacity.
public enum BufferingPolicy {
/// Continue to add to the buffer, without imposing a limit on the number
/// of buffered elements.
case unbounded
/// When the buffer is full, discard the newly received element.
///
/// This strategy enforces keeping at most the specified number of oldest
/// values.
case bufferingOldest(Int)
/// When the buffer is full, discard the oldest element in the buffer.
///
/// This strategy enforces keeping at most the specified number of newest
/// values.
case bufferingNewest(Int)
}
let storage: _Storage
/// Resume the task awaiting the next iteration point by having it return
/// nomally from its suspension point with a given element.
///
/// - Parameter value: The value to yield from the continuation.
/// - Returns: A `YieldResult` that indicates the success or failure of the
/// yield operation.
///
/// If nothing is awaiting the next value, this method attempts to buffer the
/// result's element.
///
/// This can be called more than once and returns to the caller immediately
/// without blocking for any awaiting consumption from the iteration.
@discardableResult
public func yield(_ value: __owned Element) -> YieldResult {
storage.yield(value)
}
/// Resume the task awaiting the next iteration point by having it return
/// nil, which signifies the end of the iteration.
///
/// Calling this function more than once has no effect. After calling
/// finish, the stream enters a terminal state and doesn't produces any additional
/// elements.
public func finish() {
storage.finish()
}
/// A callback to invoke when canceling iteration of an asynchronous
/// stream.
///
/// If an `onTermination` callback is set, using task cancellation to
/// terminate iteration of an `AsyncStream` results in a call to this
/// callback.
///
/// Canceling an active iteration invokes the `onTermination` callback
/// first, then resumes by yielding `nil`. This means that you can perform
/// needed cleanup in the cancellation handler. After reaching a terminal
/// state as a result of cancellation, the `AsyncStream` sets the callback
/// to `nil`.
public var onTermination: (@Sendable (Termination) -> Void)? {
get {
return storage.getOnTermination()
}
nonmutating set {
storage.setOnTermination(newValue)
}
}
}
final class _Context {
let storage: _Storage?
let produce: () async -> Element?
init(storage: _Storage? = nil, produce: @escaping () async -> Element?) {
self.storage = storage
self.produce = produce
}
deinit {
storage?.cancel()
}
}
let context: _Context
/// Constructs an asynchronous stream for an element type, using the
/// specified buffering policy and element-producing closure.
///
/// - Parameters:
/// - elementType: The type of element the `AsyncStream` produces.
/// - bufferingPolicy: A `Continuation.BufferingPolicy` value to
/// set the stream's buffering behavior. By default, the stream buffers an
/// unlimited number of elements. You can also set the policy to buffer a
/// specified number of oldest or newest elements.
/// - build: A custom closure that yields values to the
/// `AsyncStream`. This closure receives an `AsyncStream.Continuation`
/// instance that it uses to provide elements to the stream and terminate the
/// stream when finished.
///
/// The `AsyncStream.Continuation` received by the `build` closure is
/// appropriate for use in concurrent contexts. It is thread safe to send and
/// finish; all calls to the continuation are serialized. However, calling
/// this from multiple concurrent contexts could result in out-of-order
/// delivery.
///
/// The following example shows an `AsyncStream` created with this
/// initializer that produces 100 random numbers on a one-second interval,
/// calling `yield(_:)` to deliver each element to the awaiting call point.
/// When the `for` loop exits, the stream finishes by calling the
/// continuation's `finish()` method.
///
/// let stream = AsyncStream<Int>(Int.self,
/// bufferingPolicy: .bufferingNewest(5)) { continuation in
/// Task.detached {
/// for _ in 0..<100 {
/// await Task.sleep(1 * 1_000_000_000)
/// continuation.yield(Int.random(in: 1...10))
/// }
/// continuation.finish()
/// }
/// }
///
/// // Call point:
/// for await random in stream {
/// print ("\(random)")
/// }
///
public init(
_ elementType: Element.Type = Element.self,
bufferingPolicy limit: Continuation.BufferingPolicy = .unbounded,
_ build: (Continuation) -> Void
) {
let storage: _Storage = .create(limit: limit)
context = _Context(storage: storage, produce: storage.next)
build(Continuation(storage: storage))
}
/// Constructs an asynchronous stream from a given element-producing
/// closure, with an optional closure to handle cancellation.
///
/// - Parameters:
/// - produce: A closure that asynchronously produces elements for the
/// stream.
/// - onCancel: A closure to execute when canceling the stream's task.
///
/// Use this convenience initializer when you have an asychronous function
/// that can produce elements for the stream, and don't want to invoke
/// a continuation manually. This initializer "unfolds" your closure into
/// an asynchronous stream. The created stream handles conformance
/// to the `AsyncSequence` protocol automatically, including termination
/// (either by cancellation or by returning `nil` from the closure to finish
/// iteration).
///
/// The following example shows an `AsyncStream` created with this
/// initializer that produces random numbers on a one-second interval. This
/// example uses the Swift multiple trailing closure syntax, which omits
/// the `unfolding` parameter label.
///
/// let stream = AsyncStream<Int> {
/// await Task.sleep(1 * 1_000_000_000)
/// return Int.random(in: 1...10)
/// }
/// onCancel: { @Sendable () in print ("Canceled.") }
/// )
///
/// // Call point:
/// for await random in stream {
/// print ("\(random)")
/// }
///
///
public init(
unfolding produce: @escaping () async -> Element?,
onCancel: (@Sendable () -> Void)? = nil
) {
let storage: _AsyncStreamCriticalStorage<Optional<() async -> Element?>>
= .create(produce)
context = _Context {
return await withTaskCancellationHandler {
guard let result = await storage.value?() else {
storage.value = nil
return nil
}
return result
} onCancel: {
storage.value = nil
onCancel?()
}
}
}
}
@available(SwiftStdlib 5.1, *)
extension AsyncStream: AsyncSequence {
/// The asynchronous iterator for iterating an asynchronous stream.
///
/// This type doesn't conform to `Sendable`. Don't use it from multiple
/// concurrent contexts. It is a programmer error to invoke `next()` from a
/// concurrent context that contends with another such call, which
/// results in a call to `fatalError()`.
public struct Iterator: AsyncIteratorProtocol {
let context: _Context
/// The next value from the asynchronous stream.
///
/// When `next()` returns `nil`, this signifies the end of the
/// `AsyncStream`.
///
/// It is a programmer error to invoke `next()` from a
/// concurrent context that contends with another such call, which
/// results in a call to `fatalError()`.
///
/// If you cancel the task this iterator is running in while `next()` is
/// awaiting a value, the `AsyncStream` terminates. In this case, `next()`
/// might return `nil` immediately, or return `nil` on subsequent calls.
public mutating func next() async -> Element? {
await context.produce()
}
}
/// Creates the asynchronous iterator that produces elements of this
/// asynchronous sequence.
public func makeAsyncIterator() -> Iterator {
return Iterator(context: context)
}
}
@available(SwiftStdlib 5.1, *)
extension AsyncStream.Continuation {
/// Resume the task awaiting the next iteration point by having it return
/// normally from its suspension point with a given result's success value.
///
/// - Parameter result: A result to yield from the continuation.
/// - Returns: A `YieldResult` that indicates the success or failure of the
/// yield operation.
///
/// If nothing is awaiting the next value, the method attempts to buffer the
/// result's element.
///
/// If you call this method repeatedly, each call returns immediately, without
/// blocking for any awaiting consumption from the iteration.
@discardableResult
public func yield(
with result: Result<Element, Never>
) -> YieldResult {
switch result {
case .success(let val):
return storage.yield(val)
}
}
/// Resume the task awaiting the next iteration point by having it return
/// normally from its suspension point.
///
/// - Returns: A `YieldResult` that indicates the success or failure of the
/// yield operation.
///
/// Use this method with `AsyncStream` instances whose `Element` type is
/// `Void`. In this case, the `yield()` call unblocks the awaiting
/// iteration; there is no value to return.
///
/// If you call this method repeatedly, each call returns immediately, without
/// blocking for any awaiting consumption from the iteration.
@discardableResult
public func yield() -> YieldResult where Element == Void {
return storage.yield(())
}
}
@available(SwiftStdlib 5.1, *)
extension AsyncStream: @unchecked Sendable where Element: Sendable { }
| 39.126728 | 95 | 0.649726 |
1a959a27038d1c6f53df9eac43baa4f068d70642 | 460 | class Solution {
func uniquePaths(_ m: Int, _ n: Int) -> Int {
var uniquePathMatrix = Array(repeating: Array(repeating: 1, count: n), count: m)
for row in 1..<uniquePathMatrix.count {
for column in 1..<uniquePathMatrix[0].count {
uniquePathMatrix[row][column] = uniquePathMatrix[row - 1][column] + uniquePathMatrix[row][column - 1]
}
}
return uniquePathMatrix[m - 1][n - 1]
}
} | 38.333333 | 117 | 0.582609 |
8f3581ca9d07123d67c28594085e38918f723732 | 969 | //
// PanelScrollView.swift
// Odyssey
//
// Created by CoolStar on 7/6/20.
// Copyright © 2020 coolstar. All rights reserved.
//
import UIKit
class PanelScrollView: UIScrollView, UIScrollViewDelegate, PanelView {
@IBInspectable var isRootView: Bool = false
@IBOutlet var parentView: (UIView & PanelView)!
@IBOutlet var viewController: ViewController!
override func awakeFromNib() {
super.awakeFromNib()
self.delegate = self
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
viewController.cancelPopTimer()
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if !decelerate {
viewController.resetPopTimer()
}
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
viewController.resetPopTimer()
}
func viewShown() {
self.flashScrollIndicators()
}
}
| 24.846154 | 96 | 0.667699 |
f9b7ff28d33f50bd1084824105649aaed1835cba | 5,526 | //
// Calculator.swift
// Grid_Example
//
// Created by Denis Obukhov on 20.05.2020.
// Copyright © 2020 Exyte. All rights reserved.
//
import SwiftUI
import ExyteGrid
struct Calculator: View {
enum Mode: CustomStringConvertible {
case system
case second
var description: String {
switch self {
case .system:
return "System"
case .second:
return "Alternative"
}
}
}
@Environment(\.verticalSizeClass) var verticalSizeClass: UserInterfaceSizeClass?
@Environment(\.horizontalSizeClass) var horizontalSizeClass: UserInterfaceSizeClass?
@State var mode: Mode = .system
var isPortrait: Bool {
let result = verticalSizeClass == .regular && horizontalSizeClass == .compact
return result
}
var digits: [MathOperation] {
(1..<10).map { .digit($0) } + [.digit(0)]
}
var body: some View {
GeometryReader { geometry in
ZStack {
Color.black
.edgesIgnoringSafeArea(.all)
VStack(alignment: .trailing, spacing: 0) {
self.modesPicker
Spacer()
Text("565 626")
.foregroundColor(.white)
.font(.custom("PingFang TC", size: 90))
.fontWeight(.light)
.minimumScaleFactor(0.01)
Grid(tracks: self.tracks, spacing: 10) {
self.mainArithmeticButtons
if self.mode == .system {
CalcButton(.percent)
.animation(nil)
CalcButton(.sign)
.animation(nil)
GridGroup(MathOperation.clear) {
CalcButton($0)
}
}
GridGroup(self.digits, id: \.self) {
if self.mode == .system && $0 == .digit(0) {
CalcButton($0)
.gridSpan(column: 2)
} else {
CalcButton($0)
}
}
GridGroup(MathOperation.point) {
CalcButton($0)
}
self.landscapeButtons
}
.gridContentMode(.fill)
.gridAnimation(.easeInOut)
.frame(width: self.proportionalSize(geometry: geometry).width,
height: self.proportionalSize(geometry: geometry).height)
}
}
}
.environment(\.colorScheme, .dark)
}
var tracks: [GridTrack] {
self.isPortrait ? (self.mode == .system ? 4 : 5) : (self.mode == .system ? 10 : 11)
}
var landscapeButtons: some View {
let funcCount = (self.mode == .system ? 30 : 24)
let functions: [MathOperation] = self.isPortrait ? [] : (0..<funcCount).map { .function($0) }
return GridGroup(functions, id: \.self) {
CalcButton($0)
.gridStart(column: (functions.firstIndex(of: $0)!) % 6)
.animation(nil)
}
}
let mainArithmeticOperations: [MathOperation] = [.divide, .multiply, .substract, .add, .equal]
@GridBuilder
var mainArithmeticButtons: some View {
switch self.mode {
case .system:
GridGroup(0..<mainArithmeticOperations.count) {
CalcButton(mainArithmeticOperations[$0])
.gridStart(column: self.tracks.count - 1)
}
case .second:
GridGroup(MathOperation.clear) {
CalcButton($0)
.gridStart(column: self.tracks.count - 1)
}
CalcButton(.divide)
.gridStart(column: self.tracks.count - 1)
CalcButton(.multiply)
.gridStart(column: self.tracks.count - 1)
CalcButton(.substract)
.gridStart(column: self.tracks.count - 2)
CalcButton(.add)
.gridStart(column: self.tracks.count - 2)
.gridSpan(row: 2)
CalcButton(.equal)
.gridStart(column: self.tracks.count - 3)
.gridSpan(column: 3)
}
}
func proportionalSize(geometry: GeometryProxy) -> CGSize {
let height: CGFloat
if self.isPortrait {
height = geometry.size.width * 5 / 4
} else {
height = geometry.size.width * 4 / 10
}
return CGSize(width: geometry.size.width,
height: height)
}
private var modesPicker: some View {
Picker("Mode", selection: $mode) {
ForEach([Mode.system, Mode.second], id: \.self) {
Text($0.description)
.tag($0)
}
}
.pickerStyle(SegmentedPickerStyle())
}
}
struct Calculator_Previews: PreviewProvider {
static var previews: some View {
Calculator()
.environment(\.verticalSizeClass, .regular)
.environment(\.horizontalSizeClass, .compact)
}
}
| 32.315789 | 101 | 0.468151 |
e008716b0159680074fa563b2f6ce97e2c281f55 | 2,176 | //
// AppDelegate.swift
// ArchSample
//
// Created by Paul Dmitryev on 26.04.2018.
// Copyright © 2018 MyOwnTeam. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.297872 | 285 | 0.755974 |
fe5debd642d0bbf0e333674e126351a6376b13ae | 483 | //
// ShowListCell.swift
// ARKit+CoreLocation
//
// Created by EMILENCE on 23/07/18.
// Copyright © 2018 Project Dent. All rights reserved.
//
import UIKit
class ShowListCell: UICollectionViewCell {
@IBOutlet weak var imgVw: AsyncImageView!
@IBOutlet weak var lblHeading: UILabel!
@IBOutlet weak var lblOffer: UILabel!
@IBOutlet weak var lblDistance: UILabel!
@IBOutlet weak var btnShopNow: UIButton!
@IBOutlet weak var btnShowDetail: UIButton!
}
| 24.15 | 55 | 0.716356 |
1d8cf859d8c7ddf6e11a9ab8e880cd98b0f3cd94 | 3,277 | //
// SAUserThreadViewController.swift
// Saralin
//
// Created by zhang on 2/9/16.
// Copyright © 2016 zaczh. All rights reserved.
//
import UIKit
struct MyThreadModel {
var json: [String:Any]?
}
struct OthersThreadModel {
var tid: String?
var title: String?
var createDate: String?
var authorName: String?
var replyCount: String?
}
struct ThreadSearchResultModel {
var tid: String?
var title: String?
var createDate: String?
var authorName: String?
var replyCount: String?
}
class SAUserThreadViewController<DataModel>: SABaseTableViewController {
var fetchedData: [DataModel]? {
didSet {
guard let _ = fetchedData else { return }
dispatch_async_main {
_ = self.view
self.reloadData()
}
}
}
var dataFiller: ((DataModel, SABoardTableViewCell, IndexPath) -> ())?
var dataInteractor: ((SAUserThreadViewController<DataModel>, DataModel, IndexPath) -> ())?
var themeUpdator: ((SAUserThreadViewController<DataModel>) -> ())?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
loadingController.emptyLabelTitle = "内容为空"
tableView.estimatedRowHeight = 100
tableView.register(SABoardTableViewCell.self, forCellReuseIdentifier: "cell")
tableView.tableFooterView?.frame = CGRect.zero
loadingController.setLoading()
}
override func getTableView() -> UITableView {
if UIDevice.current.userInterfaceIdiom == .mac {
return UITableView(frame: .zero, style: .insetGrouped)
}
return super.getTableView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewThemeDidChange(_ newTheme:SATheme) {
super.viewThemeDidChange(newTheme)
themeUpdator?(self)
}
override func handleUserLoggedIn() {
refreshTableViewCompletion(nil)
}
override func refreshTableViewCompletion(_ completion: ((SALoadingViewController.LoadingResult, NSError?) -> Void)?) {
// this is a one-time loader, does not support refresh
completion?(.newData, nil)
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return fetchedData?.count ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! SABoardTableViewCell
guard let data = fetchedData?[indexPath.row] else {
return cell
}
dataFiller?(data, cell, indexPath)
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
guard let data = fetchedData?[indexPath.row] else {
return
}
dataInteractor?(self, data, indexPath)
}
}
| 29.522523 | 122 | 0.632591 |
384cfb9aba659d8302d60facd39838c59f35454b | 556 | //
// TimeInterval+String.swift
// sbtuitestbrowser
//
// Created by Tomas Camin on 29/12/2017.
//
import Foundation
extension TimeInterval {
func formattedString() -> String {
let ms = Int(truncatingRemainder(dividingBy: 1) * 1000)
let formatter = DateComponentsFormatter()
formatter.zeroFormattingBehavior = .pad
formatter.allowedUnits = [.hour, .minute, .second]
let formattedString = formatter.string(from: self)! + ".\(ms)"
return String(formattedString.dropFirst(2))
}
}
| 25.272727 | 70 | 0.643885 |
fcbe444d1276208e2f4a7e440e1dfd47f53c87e6 | 2,120 | //
// MainViewController.swift
// NXCWB
//
// Created by nxc on 17/8/2.
// Copyright © 2017年 nxc. All rights reserved.
//
import UIKit
class MainViewController: UITabBarController {
fileprivate lazy var composeBtn: UIButton = UIButton(imageName: "tabbar_compose_icon_add", bgImageName: "tabbar_compose_button")
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
addChildViewController(HomeViewController(), "微博", "tabbar_home")
addChildViewController(MessageViewController(), "消息", "tabbar_message_center")
addChildViewController(ViewController(), "", "")
addChildViewController(DiscoverViewController(), "发现", "tabbar_discover")
addChildViewController(ProfileViewController(), "我", "tabbar_profile")
setUpComposeBtn()
}
override func viewDidAppear(_ animated: Bool) {
let item = tabBar.items![2]
item.isEnabled = false
}
}
// MARK: - ui界面
extension MainViewController {
fileprivate func setUpComposeBtn() {
tabBar.addSubview(composeBtn)
composeBtn.center = CGPoint(x: tabBar.center.x, y: tabBar.bounds.height * 0.5)
composeBtn.addTarget(self, action: #selector(composeBtnClick), for: .touchUpInside)
}
//swift 方法的重载
//方法的重载:方法名称相同,参数不同 1,个数不同 2,参数类型
//private 只能在本文件访问,不能在别的文件中访问
fileprivate func addChildViewController(_ childController: UIViewController, _ title: String, _ image: String) {
//1.设置字控制器的属性
childController.title = title
childController.tabBarItem.image = UIImage(named: image)
childController.tabBarItem.selectedImage = UIImage(named: image + "_highlighted")
//2,用navi控制器包裹
let navi: UINavigationController = UINavigationController(rootViewController: childController)
//3.添加控制器
addChildViewController(navi)
}
}
// MARK: - 时间监听
extension MainViewController {
@objc fileprivate func composeBtnClick() {
WBLog(message: "send")
}
}
| 29.444444 | 133 | 0.666509 |
1eb25f14ad87f31c7d26cf7ea6e4efdeaf484d71 | 1,426 | // Copyright 2021-present Xsolla (USA), Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at q
//
// 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 and permissions and
import Foundation
import XsollaSDKUtilities
struct InventoryAPIErrorModel: Codable
{
let errorCode: Int
let statusCode: Int
let errorMessage: String
enum CodingKeys: String, CodingKey
{
case errorCode
case statusCode
case errorMessage
}
init(from decoder: Decoder) throws
{
let values = try decoder.container(keyedBy: CodingKeys.self)
errorCode = try values.decode(Int.self, forKey: .errorCode)
statusCode = try values.decode(Int.self, forKey: .statusCode)
errorMessage = try values.decode(String.self, forKey: .errorMessage)
}
}
extension InventoryAPIErrorModel: APIDecodableErrorModelProtocol
{
var code: Int { errorCode }
var description: String { errorMessage }
var extendedDescription: String { errorMessage }
}
| 31.688889 | 76 | 0.715288 |
23d7681378e142673d4f69cf53477f0226d73848 | 1,266 | //
// RouterEnvironment.swift
// edX
//
// Created by Akiva Leffert on 11/30/15.
// Copyright © 2015 edX. All rights reserved.
//
import UIKit
@objc class RouterEnvironment: NSObject, OEXAnalyticsProvider, OEXConfigProvider, DataManagerProvider, OEXInterfaceProvider, NetworkManagerProvider, ReachabilityProvider, OEXRouterProvider, OEXSessionProvider, OEXStylesProvider {
let analytics: OEXAnalytics
let config: OEXConfig
let dataManager: DataManager
let reachability: Reachability
let interface: OEXInterface?
let networkManager: NetworkManager
weak var router: OEXRouter?
let session: OEXSession
let styles: OEXStyles
init(
analytics: OEXAnalytics,
config: OEXConfig,
dataManager: DataManager,
interface: OEXInterface?,
networkManager: NetworkManager,
reachability: Reachability,
session: OEXSession,
styles: OEXStyles
)
{
self.analytics = analytics
self.config = config
self.dataManager = dataManager
self.interface = interface
self.networkManager = networkManager
self.reachability = reachability
self.session = session
self.styles = styles
super.init()
}
}
| 28.772727 | 229 | 0.684834 |
16f2a9eab5b46cb4202111191e54adbc12b6bc62 | 5,893 | import UIKit
import SnapKit
import RxSwift
import RxCocoa
import ThemeKit
import ComponentKit
struct SendPriorityViewItem {
let title: String
let selected: Bool
}
struct SendFeeSliderViewItem {
let initialValue: Int
let range: ClosedRange<Int>
let unit: String
}
protocol ISendFeePriorityViewModel {
var priorityDriver: Driver<String> { get }
var openSelectPrioritySignal: Signal<[SendPriorityViewItem]> { get }
var feeSliderDriver: Driver<SendFeeSliderViewItem?> { get }
var warningOfStuckDriver: Driver<Bool> { get }
func openSelectPriority()
func selectPriority(index: Int)
func changeCustomPriority(value: Int)
}
protocol ISendFeePriorityCellDelegate: IDynamicHeightCellDelegate {
func open(viewController: UIViewController)
}
protocol IDynamicHeightCellDelegate: AnyObject {
func onChangeHeight()
}
class SendFeePriorityCell: UITableViewCell {
static private let warningOfStuckString = "send.stuck_warning".localized
weak var delegate: ISendFeePriorityCellDelegate?
private let viewModel: ISendFeePriorityViewModel
private let separator = UIView()
private let selectableValueView = C5Cell(style: .default, reuseIdentifier: nil)
private let feeSliderWrapper = FeeSliderWrapper()
private let warningOfStuckView = HighlightedDescriptionView()
private let disposeBag = DisposeBag()
var isVisible = true
init(viewModel: ISendFeePriorityViewModel) {
self.viewModel = viewModel
super.init(style: .default, reuseIdentifier: nil)
backgroundColor = .clear
selectionStyle = .none
clipsToBounds = true
addSubview(separator)
separator.snp.makeConstraints { maker in
maker.top.leading.trailing.equalToSuperview()
maker.height.equalTo(CGFloat.heightOnePixel)
}
separator.backgroundColor = .themeSteel20
contentView.addSubview(selectableValueView.contentView)
selectableValueView.contentView.snp.makeConstraints { maker in
maker.leading.top.trailing.equalToSuperview()
maker.height.equalTo(CGFloat.heightSingleLineCell)
}
selectableValueView.title = "send.tx_speed".localized
selectableValueView.titleImage = UIImage(named: "circle_information_20")?.withRenderingMode(.alwaysTemplate)
selectableValueView.titleImageTintColor = .themeJacob
selectableValueView.titleImageAction = { [weak self] in
self?.openFeeInfo()
}
selectableValueView.valueAction = { [weak self] in
self?.viewModel.openSelectPriority()
}
contentView.addSubview(feeSliderWrapper)
feeSliderWrapper.snp.makeConstraints { maker in
maker.top.equalTo(selectableValueView.contentView.snp.bottom)
maker.leading.trailing.equalToSuperview().inset(CGFloat.margin4x)
}
feeSliderWrapper.finishTracking = { [weak self] value in
self?.finishTracking(value: value)
}
contentView.addSubview(warningOfStuckView)
warningOfStuckView.snp.makeConstraints { maker in
maker.top.equalTo(feeSliderWrapper.snp.bottom).offset(CGFloat.margin16 + .margin12)
maker.leading.trailing.equalToSuperview().inset(CGFloat.margin4x)
}
warningOfStuckView.text = Self.warningOfStuckString
subscribe(disposeBag, viewModel.priorityDriver) { [weak self] priority in self?.selectableValueView.value = priority }
subscribe(disposeBag, viewModel.openSelectPrioritySignal) { [weak self] viewItems in self?.openSelectPriority(viewItems: viewItems) }
subscribe(disposeBag, viewModel.warningOfStuckDriver) { [weak self] in self?.show(warningOfStuck: $0) }
subscribe(disposeBag, viewModel.feeSliderDriver) { [weak self] viewItem in
if let viewItem = viewItem {
self?.feeSliderWrapper.set(value: viewItem.initialValue, range: viewItem.range, description: viewItem.unit)
self?.feeSliderWrapper.isHidden = false
} else {
self?.feeSliderWrapper.isHidden = true
}
self?.delegate?.onChangeHeight()
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func openFeeInfo() {
let infoController = InfoModule.viewController(dataSource: FeeInfoDataSource())
delegate?.open(viewController: ThemeNavigationController(rootViewController: infoController))
}
private func openSelectPriority(viewItems: [SendPriorityViewItem]) {
let alertController = AlertRouter.module(
title: "send.tx_speed".localized,
viewItems: viewItems.map { viewItem in
AlertViewItem(
text: viewItem.title,
selected: viewItem.selected
)
}
) { [weak self] index in
self?.viewModel.selectPriority(index: index)
}
delegate?.open(viewController: alertController)
}
private func finishTracking(value: Int) {
viewModel.changeCustomPriority(value: value)
}
private func show(warningOfStuck: Bool) {
warningOfStuckView.isHidden = !warningOfStuck
delegate?.onChangeHeight()
}
}
extension SendFeePriorityCell {
var cellHeight: CGFloat {
let feeSliderHeight: CGFloat = feeSliderWrapper.isHidden ? 0 : 29
let warningOfStuckHeight = warningOfStuckView.isHidden ? 0 : (HighlightedDescriptionView.height(containerWidth: warningOfStuckView.width, text: Self.warningOfStuckString) + .margin16 + .margin12)
return isVisible ? (CGFloat.heightSingleLineCell + feeSliderHeight + warningOfStuckHeight) : 0
}
}
| 35.932927 | 203 | 0.682335 |
50517b96855960dcec3e391410ff7c79d9057588 | 2,217 | //
// AppDelegate.swift
// FakeRunner
//
// Created by FakeRunner on 2019/7/25.
// Copyright © 2019 FakeRunner. All rights reserved.
//
import UIKit
import CoreLocation
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,CLLocationManagerDelegate {
var window: UIWindow?
let locationManager = CLLocationManager()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
// 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.
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
location()
return true
}
func location() {
locationManager.delegate = self
locationManager.allowsBackgroundLocationUpdates = true
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
}
| 38.224138 | 179 | 0.742445 |
116e96f5217314f3aa31d3dd219b59fd23dadebb | 15,029 | //
// CerealSerialization.swift
// Cereal
//
// Created by Sergey Galezdinov on 27.04.16.
// Copyright © 2016 Weebly. All rights reserved.
//
import Foundation
// MARK: Types
/// Recursive tree enum that represents data being encoded/decoded
internal indirect enum CoderTreeValue {
case StringValue(String)
case IntValue(Int)
case Int64Value(Int64)
case DoubleValue(Double)
case FloatValue(Float)
case BoolValue(Bool)
case NSDateValue(NSDate)
case NSURLValue(NSURL)
case PairValue(CoderTreeValue, CoderTreeValue)
case ArrayValue([CoderTreeValue])
case SubTree([CoderTreeValue])
case IdentifyingTree(String,[CoderTreeValue])
}
/// Byte header to identify CoderTreeValue in a byte array
internal enum CerealCoderTreeValueType: UInt8 {
case String = 1
case Int = 2
case Int64 = 3
case Double = 4
case Float = 5
case Bool = 6
case NSDate = 7
case NSURL = 8
case Pair = 9
case Array = 10
case SubTree = 11
case IdentifyingTree = 12
}
// MARK: Helpers
/// function takes a value of type `Type` and returns a byte array representation
private func toByteArray<Type>(value: Type) -> [UInt8] {
var unsafeValue = value
return withUnsafePointer(&unsafeValue) {
Array(UnsafeBufferPointer(start: UnsafePointer<UInt8>($0), count: sizeof(Type)))
}
}
/// function takes an array of bytes and returns a value of type `Type`
private func fromByteArray<Type>(value: [UInt8], _: Type.Type) -> Type {
return value.withUnsafeBufferPointer {
return UnsafePointer<Type>($0.baseAddress).memory
}
}
/// function reads an array of bytes and returns an integer value (Int, Int64 etc)
private func bytesToInteger<Type where Type: IntegerType>(from: [UInt8]) -> Type {
return from.withUnsafeBufferPointer({
UnsafePointer<Type>($0.baseAddress).memory
})
}
/// function returns a number of .StringValue entries inside an array of CoderTreeValue (including subtrees)
private func stringEntriesCount(array: [CoderTreeValue]) -> Int {
var result = 0
for item in array {
result += item.numberOfStringEntries
}
return result
}
/// function returns a byte array in format [length_in_bytes] + [number of array items] + [bytes of CoderTreeValue array]
/// this allows a decoder to set a capacity for an array of CoderTreeValue beign decoded from bytes
private func countCapacityBytes(array: [CoderTreeValue]) -> [UInt8] {
var stringMap = Dictionary<String, [UInt8]>(minimumCapacity: stringEntriesCount(array))
return countCapacityBytes(array, stringMap: &stringMap)
}
/// function returns a byte array in format [length_in_bytes] + [number of array items] + [bytes of CoderTreeValue array]
/// this allows a decoder to set a capacity for an array of CoderTreeValue beign decoded from bytes
/// - note: stringMap dictionary is used to improve string encoding speed, see `String.writeToBuffer`
private func countCapacityBytes(array: [CoderTreeValue], inout stringMap: [String: [UInt8]]) -> [UInt8] {
var result = [UInt8]()
for item in array {
item.writeToBuffer(&result, stringMap: &stringMap)
}
let count = toByteArray(result.count)
let capacity = toByteArray(array.count)
result.insertContentsOf(capacity, at: 0)
result.insertContentsOf(count, at: 0)
return result
}
// MARK: encoding extensions
private extension String {
func writeToBuffer(inout buffer: [UInt8], inout stringMap: [String: [UInt8]]) {
// if the string was already decoded, getting from a dictionary is a cheaper operation than getting utf8 view
if let bytes = stringMap[self] {
buffer.appendContentsOf(bytes)
return
}
var array = Array(self.utf8)
array.insertContentsOf(toByteArray(array.count), at: 0)
buffer.appendContentsOf(array)
stringMap.updateValue(array, forKey: self)
}
}
private extension CoderTreeValue {
var numberOfStringEntries: Int {
switch self {
case .StringValue, .NSURLValue:
return 1
case let .ArrayValue(items):
return stringEntriesCount(items)
case let .SubTree(items):
return stringEntriesCount(items)
case let .IdentifyingTree(_,items):
return 1 + stringEntriesCount(items)
default:
return 0
}
}
func writeToBuffer(inout buffer: [UInt8], inout stringMap: [String: [UInt8]]) {
switch self {
case .StringValue, .NSURLValue:
self.writeStringBytes(&buffer, stringMap: &stringMap)
case .IntValue, .Int64Value, .BoolValue:
self.writeIntBytes(&buffer)
case .DoubleValue, .FloatValue, .NSDateValue:
self.writeFloatBytes(&buffer)
case let .PairValue(key, value):
buffer.append(CerealCoderTreeValueType.Pair.rawValue)
key.writeToBuffer(&buffer, stringMap: &stringMap)
value.writeToBuffer(&buffer, stringMap: &stringMap)
case let .ArrayValue(array):
buffer.append(CerealCoderTreeValueType.Array.rawValue)
buffer.appendContentsOf(countCapacityBytes(array, stringMap: &stringMap))
case let .SubTree(items):
buffer.append(CerealCoderTreeValueType.SubTree.rawValue)
buffer.appendContentsOf(countCapacityBytes(items, stringMap: &stringMap))
case let .IdentifyingTree(key, items):
buffer.append(CerealCoderTreeValueType.IdentifyingTree.rawValue)
CoderTreeValue.StringValue(key).writeToBuffer(&buffer, stringMap: &stringMap)
buffer.appendContentsOf(countCapacityBytes(items, stringMap: &stringMap))
}
}
func writeStringBytes(inout buffer: [UInt8], inout stringMap: [String: [UInt8]]) {
switch self {
case let .StringValue(string):
buffer.append(CerealCoderTreeValueType.String.rawValue)
string.writeToBuffer(&buffer, stringMap: &stringMap)
case let .NSURLValue(url):
buffer.append(CerealCoderTreeValueType.NSURL.rawValue)
url.absoluteString.writeToBuffer(&buffer, stringMap: &stringMap)
default:
break
}
}
func writeIntBytes(inout buffer: [UInt8]) {
switch self {
case let .IntValue(int):
buffer.append(CerealCoderTreeValueType.Int.rawValue)
var array = toByteArray(int)
array.insertContentsOf(toByteArray(array.count), at: 0)
buffer.appendContentsOf(array)
case let .Int64Value(int64):
buffer.append(CerealCoderTreeValueType.Int64.rawValue)
var array = toByteArray(int64)
array.insertContentsOf(toByteArray(array.count), at: 0)
buffer.appendContentsOf(array)
case let .BoolValue(bool):
buffer.append(CerealCoderTreeValueType.Bool.rawValue)
buffer.appendContentsOf(toByteArray(1))
buffer.append(bool ? 1 : 0)
default:
break
}
}
func writeFloatBytes(inout buffer: [UInt8]) {
switch self {
case let .DoubleValue(double):
buffer.append(CerealCoderTreeValueType.Double.rawValue)
var array = toByteArray(double)
array.insertContentsOf(toByteArray(array.count), at: 0)
buffer.appendContentsOf(array)
case let .FloatValue(float):
buffer.append(CerealCoderTreeValueType.Float.rawValue)
var array = toByteArray(float)
array.insertContentsOf(toByteArray(array.count), at: 0)
buffer.appendContentsOf(array)
case let .NSDateValue(date):
let interval = date.timeIntervalSinceReferenceDate
buffer.append(CerealCoderTreeValueType.NSDate.rawValue)
var array = toByteArray(interval)
array.insertContentsOf(toByteArray(array.count), at: 0)
buffer.appendContentsOf(array)
default:
break
}
}
}
extension CoderTreeValue {
func toData() -> NSData {
let bytes = self.bytes()
return NSData(bytes: bytes, length: bytes.count)
}
func bytes() -> [UInt8] {
var result = [UInt8]()
result.reserveCapacity(20)
var stringMap = Dictionary<String, [UInt8]>(minimumCapacity: self.numberOfStringEntries)
self.writeToBuffer(&result, stringMap: &stringMap)
return result
}
}
// MARK: decoding extensions
// Credit to Mike Ash: https://www.mikeash.com/pyblog/friday-qa-2015-11-06-why-is-swifts-string-api-so-hard.html
private extension String {
#if swift(>=3.0)
init?<Seq: Sequence where Seq.Iterator.Element == UInt16>(utf16: Seq) {
self.init()
guard !transcode(utf16.makeIterator(), from: UTF16.self, to: UTF32.self, stoppingOnError: true, sendingOutputTo: { self.append(UnicodeScalar($0)) }) else { return nil }
}
init?<Seq: Sequence where Seq.Iterator.Element == UInt8>(utf8: Seq) {
self.init()
guard !transcode(utf8.makeIterator(), from: UTF8.self, to: UTF32.self, stoppingOnError: true, sendingOutputTo: { self.append(UnicodeScalar($0)) }) else { return nil }
}
#else
init?<Seq: SequenceType where Seq.Generator.Element == UInt16>(utf16: Seq) {
self.init()
guard transcode(UTF16.self,
UTF32.self,
utf16.generate(),
{ self.append(UnicodeScalar($0)) },
stopOnError: true)
== false else { return nil }
}
init?<Seq: SequenceType where Seq.Generator.Element == UInt8>(utf8: Seq) {
self.init()
guard transcode(UTF8.self,
UTF32.self,
utf8.generate(),
{ self.append(UnicodeScalar($0)) },
stopOnError: true)
== false else { return nil }
}
#endif
}
private extension CoderTreeValue {
static func readInt(inout bytes: [UInt8], inout offset: Int) -> Int? {
guard bytes.count >= offset + sizeof(Int) else { return nil }
let bytesForInt: [UInt8] = Array(bytes[offset..<offset + sizeof(Int)])
let value: Int = bytesToInteger(bytesForInt)
offset += sizeof(Int)
return value
}
static func readArray(inout bytes: [UInt8], inout offset: Int, capacity: Int, endOffset: Int) -> [CoderTreeValue]? {
var array = [CoderTreeValue]()
array.reserveCapacity(capacity)
while offset < endOffset {
guard let value = CoderTreeValue(bytes: &bytes, offset: &offset) else { return nil }
array.append(value)
}
return array
}
init?(inout bytes: [UInt8], inout offset: Int) {
guard bytes.count > offset + 1 else { return nil }
guard let type = CerealCoderTreeValueType(rawValue: bytes[offset]) else { return nil }
offset += 1
if type == .Pair {
guard let key = CoderTreeValue(bytes: &bytes, offset: &offset),
let value = CoderTreeValue(bytes: &bytes, offset: &offset) else { return nil }
self = .PairValue(key, value)
return
}
var identifier: CoderTreeValue? = nil
if type == .IdentifyingTree {
identifier = CoderTreeValue(bytes: &bytes, offset: &offset)
}
guard let count = CoderTreeValue.readInt(&bytes, offset: &offset) else { return nil }
guard bytes.count >= offset + count else { return nil }
let capacity: Int
if [CerealCoderTreeValueType.Array, CerealCoderTreeValueType.SubTree, CerealCoderTreeValueType.IdentifyingTree].contains(type) {
guard let capacityValue = CoderTreeValue.readInt(&bytes, offset: &offset) else { return nil }
capacity = capacityValue
} else {
capacity = 0
}
let startIndex = offset
let endIndex = offset + count
guard bytes.count >= endIndex else { return nil }
switch type {
case .String, .NSURL:
let valueBytes = bytes[startIndex..<endIndex]
guard let string = String(utf8: valueBytes) else { return nil }
if type == .String {
self = .StringValue(string)
} else {
guard let url = NSURL(string: string) else { return nil }
self = .NSURLValue(url)
}
case .Int:
let valueBytes = Array(bytes[startIndex..<endIndex])
let value = fromByteArray(valueBytes, Int.self)
self = .IntValue(value)
case .Int64:
let valueBytes = Array(bytes[startIndex..<endIndex])
let value = fromByteArray(valueBytes, Int64.self)
self = .Int64Value(value)
case .Bool:
let valueBytes = Array(bytes[startIndex..<endIndex])
let value = valueBytes[0]
self = .BoolValue(value == 1)
case .Float:
let valueBytes = Array(bytes[startIndex..<endIndex])
let value = fromByteArray(valueBytes, Float.self)
self = .FloatValue(value)
case .Double, .NSDate:
let valueBytes = Array(bytes[startIndex..<endIndex])
let value = fromByteArray(valueBytes, Double.self)
if type == .Double {
self = .DoubleValue(value)
} else {
let date = NSDate(timeIntervalSinceReferenceDate: value)
self = .NSDateValue(date)
}
case .Array, .SubTree:
guard let array = CoderTreeValue.readArray(&bytes, offset: &offset, capacity: capacity, endOffset: endIndex) else { return nil }
if type == .Array {
self = .ArrayValue(array)
} else {
self = .SubTree(array)
}
case .IdentifyingTree:
guard let id = identifier, case let .StringValue(string) = id else { return nil }
guard let array = CoderTreeValue.readArray(&bytes, offset: &offset, capacity: capacity, endOffset: endIndex) else { return nil }
self = .IdentifyingTree(string, array)
return
default:
return nil
}
offset = endIndex
}
}
extension CoderTreeValue {
init?(bytes: [UInt8]) {
var bytes = bytes
var offset = 0
self.init(bytes: &bytes, offset: &offset)
}
init?(data: NSData) {
let bytes = Array(UnsafeBufferPointer(start: UnsafePointer<UInt8>(data.bytes), count: data.length))
guard let result = CoderTreeValue(bytes: bytes) else {
return nil
}
self = result
}
}
| 34.549425 | 172 | 0.613614 |
287290aa86d5d059721559706fae9bcf84476754 | 3,555 | //
// VehicleBookings.swift
// Goget
//
// Created by Danish Aziz on 22/10/19.
// Copyright © 2019 Danish Aziz. All rights reserved.
//
import UIKit
// MARK: - Vehicles
struct VehicleBookings: Codable {
let vehicleBookings: [VehicleBooking]
enum CodingKeys: String, CodingKey {
case vehicleBookings = "vehicleBookings"
}
public init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
self.vehicleBookings = try values.decode([VehicleBooking].self, forKey: .vehicleBookings)
}
}
// MARK: - VehicleBooking
struct VehicleBooking: Codable {
let id: Int
let startTime, endTime: String
let vehicleID, podID: Int
let estimatedCost: Double
let fuelPin: String
let freeKmsTotal: Int
var startDate: String = ""
var endDate: String = ""
var startFullDate: String = ""
var endFullDate: String = ""
var duration: String = ""
enum CodingKeys: String, CodingKey {
case id, startTime, endTime
case vehicleID = "vehicleId"
case podID = "podId"
case estimatedCost, fuelPin, freeKmsTotal
}
public init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
self.id = try values.decode(Int.self, forKey: .id)
var timeString = try values.decode(String.self, forKey: .startTime)
var localStartDate = Date()
var localEndDate = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
if let dateFromString = dateFormatter.date(from: timeString) {
localStartDate = dateFromString
dateFormatter.dateFormat = "EEE d MMM"
self.startDate = dateFormatter.string(from: dateFromString)
dateFormatter.dateFormat = "h:mm a"
dateFormatter.locale = .current
self.startTime = dateFormatter.string(from: dateFromString)
dateFormatter.dateFormat = "EEEE d MMM, h:mm a"
self.startFullDate = dateFormatter.string(from: dateFromString)
} else {
self.startTime = ""
}
timeString = try values.decode(String.self, forKey: .endTime)
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
if let dateFromString = dateFormatter.date(from: timeString) {
localEndDate = dateFromString
dateFormatter.dateFormat = "EEE d MMM"
self.endDate = dateFormatter.string(from: dateFromString)
dateFormatter.dateFormat = "h:mm a"
dateFormatter.locale = .current
self.endTime = dateFormatter.string(from: dateFromString)
dateFormatter.dateFormat = "EEEE d MMM, h:mm a"
self.endFullDate = dateFormatter.string(from: dateFromString)
} else {
self.endTime = ""
}
let cal = Calendar.current
let components = cal.dateComponents([.hour], from: localStartDate, to: localEndDate)
if let diff = components.hour {
self.duration = "\(diff)"
}
self.vehicleID = try values.decode(Int.self, forKey: .vehicleID)
self.podID = try values.decode(Int.self, forKey: .podID)
self.estimatedCost = try values.decode(Double.self, forKey: .estimatedCost)
self.fuelPin = try values.decode(String.self, forKey: .fuelPin)
self.freeKmsTotal = try values.decode(Int.self, forKey: .freeKmsTotal)
}
}
| 36.27551 | 97 | 0.629817 |
fb82f173b9704b2700511b701f4cf3d7be988694 | 6,399 | //
// ALEvent.swift
// AirlyticsSDK
//
// Created by Yoav Ben-Yair on 14/11/2019.
// Copyright © 2019 IBM. All rights reserved.
//
import Foundation
import SwiftyJSON
public class ALEvent : NSObject, NSCoding {
public let id: String
public let name: String
public let time: Date
internal(set) public var attributes: [String:Any?]
internal(set) public var previousValues: [String:Any?]?
internal(set) public var customDimensions: [String:Any?]?
public let userId: String
public let sessionId: String
public let sessionStartTime: TimeInterval
public let schemaVersion: String?
public let productId: String
public let appVersion: String
public let outOfSession: Bool
public init(name: String, attributes: [String:Any?], previousValues: [String:Any?]? = nil, customDimensions: [String:Any?]? = nil, time: Date, eventId: String? = nil, userId: String, sessionId: String, sessionStartTime: TimeInterval, schemaVersion: String?, productId: String, appVersion: String, outOfSession: Bool = false) {
if let eventId = eventId {
self.id = eventId
} else {
self.id = UUID().uuidString
}
self.name = name
self.attributes = attributes
self.previousValues = previousValues
self.customDimensions = customDimensions
self.time = time
self.userId = userId
self.sessionId = sessionId
self.sessionStartTime = sessionStartTime
self.schemaVersion = schemaVersion
self.productId = productId
self.appVersion = appVersion
self.outOfSession = outOfSession
}
public func setPreviousValues(previousValues: [String:Any?]?) {
self.previousValues = previousValues
}
public func setCustomDimensions(customDimensions: [String:Any?]?) {
self.customDimensions = customDimensions
}
public required init?(coder: NSCoder) {
guard let notNullId = coder.decodeObject(forKey: "id") as? String else {
return nil
}
guard let notNullName = coder.decodeObject(forKey: "name") as? String else {
return nil
}
guard let notNullTime = coder.decodeObject(forKey: "time") as? Date else {
return nil
}
guard let notNullAttributes = coder.decodeObject(forKey: "attributes") as? [String:Any?] else {
return nil
}
guard let notNullUserId = coder.decodeObject(forKey: "userId") as? String else {
return nil
}
guard let notNullSessionId = coder.decodeObject(forKey: "sessionId") as? String else {
return nil
}
guard let notNullAppVersion = coder.decodeObject(forKey: "appVersion") as? String else {
return nil
}
guard let notNullProductId = coder.decodeObject(forKey: "productId") as? String else {
return nil
}
id = notNullId
name = notNullName
time = notNullTime
attributes = notNullAttributes
userId = notNullUserId
sessionId = notNullSessionId
appVersion = notNullAppVersion
productId = notNullProductId
previousValues = coder.decodeObject(forKey: "previousValues") as? [String:Any?]
customDimensions = coder.decodeObject(forKey: "customDimensions") as? [String:Any?]
schemaVersion = coder.decodeObject(forKey: "schemaVersion") as? String
let rawSessionStartTime = coder.decodeDouble(forKey: "sessionStartTime")
sessionStartTime = rawSessionStartTime != 0 ? rawSessionStartTime : Date.distantPast.epochMillis
outOfSession = coder.decodeBool(forKey: "outOfSession")
}
@objc public func encode(with coder: NSCoder) {
coder.encode(id, forKey:"id")
coder.encode(name, forKey:"name")
coder.encode(time, forKey: "time")
coder.encode(attributes, forKey: "attributes")
coder.encode(userId, forKey:"userId")
coder.encode(sessionId, forKey:"sessionId")
coder.encode(sessionStartTime, forKey:"sessionStartTime")
coder.encode(schemaVersion, forKey: "schemaVersion")
coder.encode(productId, forKey: "productId")
coder.encode(appVersion, forKey: "appVersion")
coder.encode(outOfSession, forKey: "outOfSession")
if self.previousValues != nil {
coder.encode(previousValues, forKey: "previousValues")
}
if self.customDimensions != nil {
coder.encode(customDimensions, forKey: "customDimensions")
}
}
public func json() -> JSON {
var eventjson: JSON
eventjson = ["name": self.name,
"eventId": self.id,
"eventTime": self.time.epochMillis,
"appVersion": self.appVersion,
"productId": self.productId,
"schemaVersion": self.schemaVersion as Any,
"platform": "ios",
"userId": self.userId]
if !outOfSession {
eventjson["sessionId"] = JSON(self.sessionId)
if sessionStartTime != Date.distantPast.epochMillis {
eventjson["sessionStartTime"] = JSON(self.sessionStartTime)
}
if let customDimensions = self.customDimensions {
eventjson["customDimensions"] = JSON(customDimensions)
}
}
var jsonAttributes: JSON = [:]
for (key, value) in self.attributes {
if let nonNullValue = value {
if case Optional<Any>.none = nonNullValue {
jsonAttributes[key] = JSON(NSNull.self)
} else {
jsonAttributes[key] = JSON(nonNullValue)
}
} else {
jsonAttributes[key] = JSON(NSNull.self)
}
}
eventjson["attributes"] = jsonAttributes
if let previousValues = self.previousValues {
eventjson["previousValues"] = JSON(previousValues)
}
return eventjson
}
}
| 34.777174 | 330 | 0.585717 |
f7177a92633332eb30bcb5c406d52a64efc36a4d | 926 | //
// OverlayingMenusTests.swift
// OverlayingMenusTests
//
// Created by Jon Manning on 14/01/2015.
// Copyright (c) 2015 Secret Lab. All rights reserved.
//
import UIKit
import XCTest
class OverlayingMenusTests: 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.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| 25.027027 | 111 | 0.62419 |
e69e29b5d73d1787ebe9153ba01ed60a7813b273 | 619 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-sil %s | %FileCheck %s
import ctypes
struct S {
let a: Int
let b: Int
let c: Int
}
struct T {
let v: StructWithBitfields
let s: S
init(v: StructWithBitfields, s: S) {
self.v = v
self.s = s
}
}
// CHECK-LABEL: sil hidden @$S42predictable_memopt_unreferenceable_storage1TV1v1sACSo19StructWithBitfieldsV_AA1SVtcfC
// CHECK: bb0(%0 : $StructWithBitfields, %1 : $S, %2 : $@thin T.Type):
// CHECK: [[RESULT:%.*]] = struct $T (%0 : $StructWithBitfields, %1 : $S)
// CHECK: return [[RESULT]]
| 29.47619 | 117 | 0.613893 |
f96243874b6319928e68c97710239068cedc1742 | 2,178 | //
// SignUpScreenViewController.swift
// SecondSprintApp
//
// Created by Svetlana Timofeeva on 09/11/2019.
// Copyright © 2019 jorge. All rights reserved.
//
import UIKit
class SignUpScreenViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
// Do any additional setup after loading the view.
let (x, y) = (view.center.x, view.center.y)
let textField = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 100))
textField.font = UIFont.systemFont(ofSize: 25.0)
textField.textAlignment = .center
textField.text = "Sorry, this option is unavailable."
textField.lineBreakMode = .byWordWrapping
textField.numberOfLines = 2
textField.center = CGPoint(x: x, y: y - 30)
textField.adjustsFontSizeToFitWidth = true
view.addSubview(textField)
let textField2 = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 100))
textField2.font = UIFont.systemFont(ofSize: 25.0)
textField2.textAlignment = .center
textField2.text = "Use webpage to log in."
textField2.lineBreakMode = .byWordWrapping
textField2.numberOfLines = 2
textField2.center = CGPoint(x: x, y: y + 30)
textField2.adjustsFontSizeToFitWidth = true
view.addSubview(textField2)
let backButton = UIBarButtonItem(title: "back", style: .plain, target: self, action: #selector(logout))
navigationItem.setLeftBarButton(backButton, animated: true)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
@objc
func logout() {
navigationController?.popViewController(animated: true)
}
override func viewWillAppear(_ animated: Bool) {
navigationController?.isNavigationBarHidden = false
}
}
| 35.129032 | 111 | 0.655647 |
90265feb4dc2c9ea912fd5f3dae58f1dd34322da | 1,501 | import Foundation
import xcodeproj
import XCTest
final class PBXFileElementSpec: XCTestCase {
var subject: PBXFileElement!
override func setUp() {
super.setUp()
subject = PBXFileElement(sourceTree: .absolute,
path: "path",
name: "name",
includeInIndex: false,
wrapsLines: true)
}
func test_isa_returnsTheCorrectValue() {
XCTAssertEqual(PBXFileElement.isa, "PBXFileElement")
}
func test_init_initializesTheFileElementWithTheRightAttributes() {
XCTAssertEqual(subject.sourceTree, .absolute)
XCTAssertEqual(subject.path, "path")
XCTAssertEqual(subject.name, "name")
XCTAssertEqual(subject.includeInIndex, false)
XCTAssertEqual(subject.wrapsLines, true)
}
func test_equal_returnsTheCorrectValue() {
let another = PBXFileElement(sourceTree: .absolute,
path: "path",
name: "name",
includeInIndex: false,
wrapsLines: true)
XCTAssertEqual(subject, another)
}
private func testDictionary() -> [String: Any] {
return [
"sourceTree": "absolute",
"path": "path",
"name": "name",
"includeInIndex": "0",
"wrapsLines": "1",
]
}
}
| 31.270833 | 70 | 0.52565 |
e2d063f0c8a7e5c26d40b0073ad3bc04ce11b441 | 6,695 | // MapKitTutorial
//
// Created by javedmultani16 on 15/10/2019.
// Copyright © Javed Multani. All rights reserved.
//
import UIKit
import MapKit
protocol HandleMapSearch {
func dropPinZoomIn(placemark:MKPlacemark)
}
class ViewController : UIViewController {
var myRoute : MKRoute?
var directionsRequest = MKDirections.Request()
var placemarks = [MKMapItem]()
var selectedPin:MKPlacemark? = nil
let locationManager = CLLocationManager()
var resultSearchController:UISearchController? = nil
@IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.requestLocation()
let locationSearchTable = storyboard!.instantiateViewController(withIdentifier: "LocationSearchTable") as! LocationSearchTable
locationSearchTable.handleMapSearchDelegate = self
resultSearchController = UISearchController(searchResultsController: locationSearchTable)
resultSearchController?.searchResultsUpdater = locationSearchTable
let searchBar = resultSearchController!.searchBar
searchBar.sizeToFit()
searchBar.placeholder = "Search for places"
navigationItem.titleView = resultSearchController?.searchBar
resultSearchController?.hidesNavigationBarDuringPresentation = false
resultSearchController?.dimsBackgroundDuringPresentation = true
definesPresentationContext = true
locationSearchTable.mapView = mapView
mapView.delegate = self
}
@objc func getDirections(){
if let selectedPin = selectedPin {
let mapItem = MKMapItem(placemark: selectedPin)
let launchOptions = [MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving]
mapItem.openInMaps(launchOptions: launchOptions)
}
}
}
extension ViewController : CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == .authorizedWhenInUse {
locationManager.requestLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.first {
let span = MKCoordinateSpan.init(latitudeDelta: 0.05, longitudeDelta: 0.05)
let region = MKCoordinateRegion(center: location.coordinate, span: span)
mapView.setRegion(region, animated: true)
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("error:: (error)")
}
}
extension ViewController: HandleMapSearch {
func dropPinZoomIn(placemark:MKPlacemark){
// cache the pin
selectedPin = placemark
// clear existing pins
mapView.removeAnnotations(mapView.annotations)
let annotation = MKPointAnnotation()
annotation.coordinate = placemark.coordinate
annotation.title = placemark.name
if let city = placemark.locality,
let state = placemark.administrativeArea {
annotation.subtitle = "\(city) \(state)"
}
placemarks.append(MKMapItem(placemark: placemark))
directionsRequest.transportType = MKDirectionsTransportType.automobile
//Draw polyline by using MKRoute so it follows the street roads...
for (k, item) in placemarks.enumerated() {
if k < (placemarks.count - 1) {
directionsRequest.source = item
directionsRequest.destination = placemarks[k+1]
var directions = MKDirections(request: directionsRequest)
directions.calculate { (response:MKDirections.Response!, error: Error!) -> Void in
if error == nil {
self.myRoute = response.routes[0] as? MKRoute
//self.mapView.addOverlay(self.myRoute?.polyline)
let geodesic:MKPolyline = self.myRoute!.polyline
self.mapView.addOverlay(geodesic)
}
}
}
}
mapView.addAnnotation(annotation)
let span = MKCoordinateSpan.init(latitudeDelta: 0.05, longitudeDelta: 0.05) //MKCoordinateSpanMake(0.05, 0.05)
let region = MKCoordinateRegion.init(center: placemark.coordinate, span: span)
mapView.setRegion(region, animated: true)
}
}
extension LocationSearchTable {
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
let selectedItem = matchingItems[indexPath.row].placemark
handleMapSearchDelegate?.dropPinZoomIn(placemark: selectedItem)
dismiss(animated: true, completion: nil)
}
}
extension ViewController : MKMapViewDelegate {
func mapView(_: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView?{
if annotation is MKUserLocation {
//return nil so map view draws "blue dot" for standard user location
let placemarkSource = MKPlacemark(coordinate: annotation.coordinate, addressDictionary: nil)
placemarks.append(MKMapItem(placemark: placemarkSource))
return nil
}
let reuseId = "pin"
var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) as? MKPinAnnotationView
pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
pinView?.pinTintColor = UIColor.orange
pinView?.canShowCallout = true
let smallSquare = CGSize(width: 30, height: 30)
let button = UIButton(frame: CGRect(origin: CGPoint(x: 0,y :0), size: smallSquare))
button.setBackgroundImage(UIImage(named: "car"), for: .normal)
button.addTarget(self, action: #selector(ViewController.getDirections), for: .touchUpInside)
pinView?.leftCalloutAccessoryView = button
return pinView
}
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
if overlay.isKind(of: MKPolyline.self){
var polylineRenderer = MKPolylineRenderer(overlay: overlay)
polylineRenderer.fillColor = UIColor.blue
polylineRenderer.strokeColor = UIColor.blue
polylineRenderer.lineWidth = 2
return polylineRenderer
}
return MKOverlayRenderer(overlay: overlay)
}
}
| 40.08982 | 134 | 0.672442 |
67d3f13c1b2712fcfacc10b93871ab5bbed76e97 | 4,735 | //
// Copyright Amazon.com Inc. or its affiliates.
// All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
import XCTest
import Amplify
@testable import AWSAPICategoryPlugin
class GraphQLErrorDecoderTests: XCTestCase {
func testDecodeErrors() throws {
let graphQLErrorJSON: JSONValue = [
"message": "Name for character with ID 1002 could not be fetched.",
"locations": [["line": 6, "column": 7]],
"path": ["hero", "heroFriends", 1, "name"]
]
let graphQLErrorJSON2: JSONValue = [
"message": "Name for character with ID 1002 could not be fetched.",
"locations": [["line": 6, "column": 7]],
"path": ["hero", "heroFriends", 1, "name"],
"extensions": [
"code": "CAN_NOT_FETCH_BY_ID",
"timestamp": "Fri Feb 9 14:33:09 UTC 2018"
]
]
let graphQLErrors = try GraphQLErrorDecoder
.decodeErrors(graphQLErrors: [graphQLErrorJSON, graphQLErrorJSON2])
XCTAssertEqual(graphQLErrors.count, 2)
let result = graphQLErrors[0]
XCTAssertEqual(result.message, "Name for character with ID 1002 could not be fetched.")
XCTAssertNotNil(result.locations)
XCTAssertNotNil(result.path)
XCTAssertNil(result.extensions)
let result2 = graphQLErrors[1]
XCTAssertEqual(result2.message, "Name for character with ID 1002 could not be fetched.")
XCTAssertNotNil(result2.locations)
XCTAssertNotNil(result2.path)
XCTAssertNotNil(result2.extensions)
}
/// Decoding the graphQL error into `GraphQLError` will merge fields which do not meet the GraphQL spec for error
/// fields ("message", "locations", "path", and "extensions") will be merged into extensions, without overwriting
/// what is currently there
///
/// - Given: GraphQL error JSON with extra fields ("errorInfo", "data", "errorType", "code"). "code" is duplicated
/// in extensions.
/// - When:
/// - Decode into `GraphQLError`
/// - Then:
/// - Extra fields are merged under `GraphQLError.extensions` without overwriting data, such as the "code" field
func testDecodeErrorWithExtensions() throws {
let graphQLErrorJSON: JSONValue = [
"message": "Name for character with ID 1002 could not be fetched.",
"locations": [["line": 6, "column": 7]],
"path": ["hero", "heroFriends", 1, "name"],
"extensions": [
"code": "CAN_NOT_FETCH_BY_ID",
"timestamp": "Fri Feb 9 14:33:09 UTC 2018"
],
"errorInfo": nil,
"data": [
"id": "EF48518C-92EB-4F7A-A64E-D1B9325205CF",
"title": "new3",
"content": "Original content from DataStoreEndToEndTests at 2020-03-26 21:55:47 +0000",
"_version": 2
],
"errorType": "ConflictUnhandled",
"code": 123
]
let graphQLErrors = try GraphQLErrorDecoder.decodeErrors(graphQLErrors: [graphQLErrorJSON])
XCTAssertEqual(graphQLErrors.count, 1)
let result = graphQLErrors[0]
XCTAssertEqual(result.message, "Name for character with ID 1002 could not be fetched.")
XCTAssertNotNil(result.locations)
XCTAssertNotNil(result.path)
guard let extensions = result.extensions else {
XCTFail("Missing extensions in result")
return
}
XCTAssertEqual(extensions.count, 5)
guard case let .string(code) = extensions["code"] else {
XCTFail("Missing code")
return
}
XCTAssertEqual(code, "CAN_NOT_FETCH_BY_ID")
guard case let .string(timeStamp) = extensions["timestamp"] else {
XCTFail("Missing timeStamp")
return
}
XCTAssertEqual(timeStamp, "Fri Feb 9 14:33:09 UTC 2018")
guard case .null = extensions["errorInfo"] else {
XCTFail("Missing errorInfo")
return
}
guard case let .object(data) = extensions["data"] else {
XCTFail("Missing data")
return
}
XCTAssertEqual(data["id"], "EF48518C-92EB-4F7A-A64E-D1B9325205CF")
XCTAssertEqual(data["title"], "new3")
XCTAssertEqual(data["content"],
"Original content from DataStoreEndToEndTests at 2020-03-26 21:55:47 +0000")
XCTAssertEqual(data["_version"], 2)
guard case let .string(errorType) = extensions["errorType"] else {
XCTFail("Missing errorType")
return
}
XCTAssertEqual(errorType, "ConflictUnhandled")
}
}
| 39.458333 | 119 | 0.596832 |
1469bb5c00ac96525aaebed0d44c2c0c806c9a91 | 1,530 | /**
* Solution to the problem: https://leetcode.com/problems/delete-node-in-a-bst/
*/
//Note: The number here denotes the problem id in leetcode. This is to avoid name conflict with other solution classes in the Swift playground.
public class Solution450 {
public init(){
}
public func deleteNode(_ root: TreeNode?, _ key: Int) -> TreeNode? {
if(root == nil){
return nil
}
if(key < (root?.val)!){
//Key smaller than the the current root, so find it in the left subtree
root?.left = deleteNode(root?.left, key)
}else if (key > (root?.val)!){
//Key larger than the the current root, so find it in the right subtree
root?.right = deleteNode(root?.right, key)
} else {
if(root?.left == nil){
//Key is in the current root and left branch is empty, delete the root and return the right as the new root
return root?.right
}else if(root?.right == nil) {
//Key is in the current root and right branch is empty, delete the root and return the left as the new root
return root?.left
}else{
//Key is in the current root and left and right are not empty. Find the min in the right subtree, copy the min to the root, and recursively delete that value from the right subtree
let node: TreeNode? = minNode(root?.right)
root?.val = (node?.val)!
root?.right = deleteNode(root?.right, (node?.val)!)
}
}
return root
}
func minNode(_ root: TreeNode?) -> TreeNode {
var node = root
while(node?.left != nil){
node = node?.left
}
return node!
}
}
| 30.6 | 184 | 0.664706 |
698eb9f7d5633a4c5cdad2afb6b2b26fba756d6e | 1,268 | //
// TipsterUITests.swift
// TipsterUITests
//
// Created by Aripirala, Sriram Santosh on 3/6/17.
// Copyright © 2017 Aripirala, Sriram Santosh. All rights reserved.
//
import XCTest
class TipsterUITests: XCTestCase {
override func setUp() {
super.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.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 34.27027 | 182 | 0.665615 |
1e7b98adbfcdaec56f955bd5b6f6d8273cc4f33c | 1,476 | //
// WalletRenameViewController.swift
// RaccoonWallet
//
// Created by Taizo Kusuda on 2018/08/28.
// Copyright © 2018年 T TECH, LIMITED LIABILITY CO. All rights reserved.
//
import UIKit
class WalletRenameViewController: BaseViewController {
var presenter: WalletRenamePresentation! { didSet { basePresenter = presenter } }
@IBOutlet weak var navigation: UINavigationBar!
@IBOutlet weak var name: UITextField!
@IBOutlet weak var cancel: UIBarButtonItem!
@IBOutlet weak var ok: UIBarButtonItem!
override func setup() {
super.setup()
navigation.topItem?.title = R.string.localizable.wallet_rename_title()
ok.customView = createBarButton(image: R.image.icon_check_green()!, size: Constant.barIconSize, action: #selector(onTouchedOk(_:)))
cancel.customView = createBarButton(image: R.image.icon_close()!, size: Constant.barIconSize, action: #selector(onTouchedCancel(_:)))
name.becomeFirstResponder()
}
@IBAction func onChangedName(_ sender: Any) {
if let text = name.text {
presenter.didChangeName(text)
}
}
@objc func onTouchedOk(_ sender: Any) {
presenter.didClickOk()
}
@objc func onTouchedCancel(_ sender: Any) {
presenter.didClickCancel()
}
}
extension WalletRenameViewController : WalletRenameView {
func enableOk() {
ok.isEnabled = true
}
func disableOk() {
ok.isEnabled = false
}
}
| 27.849057 | 141 | 0.675474 |
efadf8757522dba5331af92b305cc6a7cbb20308 | 444 | //
// Stream_itApp.swift
// Stream.it
//
// Created by Mark Howard on 26/09/2021.
//
import SwiftUI
@main
struct Stream_itApp: App {
var body: some Scene {
WindowGroup {
ContentView()
.frame(minWidth: 750, maxWidth: .infinity, minHeight: 400, maxHeight: .infinity)
}
Settings {
SettingsView()
}
.commands {
SidebarCommands()
}
}
}
| 17.76 | 96 | 0.527027 |
76d60f1adbceb1ac4eb8561feeefd387eeacccca | 652 | //
// AnimeEpisode.swift
// Twist For Mac
//
// Created by Aritro Paul on 11/07/20.
// Copyright © 2020 Aritro Paul. All rights reserved.
//
import Foundation
struct Episode: Codable {
var id: Int?
var source: String?
var number, animeID: Int?
var createdAt, updatedAt: String?
enum CodingKeys: String, CodingKey {
case id, source, number
case animeID = "anime_id"
case createdAt = "created_at"
case updatedAt = "updated_at"
}
func decodedURL() -> String {
return Twist.Anime.cdn + CryptoJS.AES.shared.decrypt(self.source ?? "", password: Twist.Constant.key)
}
}
| 22.482759 | 109 | 0.627301 |
200a855d4c5c56b2cddb73688657b28d346acc9b | 176 | import UIKit
class ViewController: UIViewController {
var myObject: MyObjectable = MyObject()
override func viewDidLoad() {
super.viewDidLoad()
_ = myObject.foo()
}
}
| 16 | 40 | 0.727273 |
ef45ff99234e7db0e74f43382c8b44fe9fe463dd | 1,919 | // The MIT License (MIT)
// Copyright © 2022 Ivan Vorobei ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
public struct ProfileDeviceModel: Equatable {
public let id: String
public let name: String
public let type: DeviceType
public let fcmToken: String?
public let languageCode: String
public let addedDate: Date
public init(id: String, name: String, type: DeviceType, fcmToken: String?, languageCode: String, addedDate: Date) {
self.id = id
self.name = name
self.type = type
self.fcmToken = fcmToken
self.languageCode = languageCode
self.addedDate = addedDate
}
// MARK: - Models
public enum DeviceType: String {
case phone
case pad
case desktop
public var id: String { rawValue }
}
}
| 36.207547 | 119 | 0.701928 |
619c3a02ee560196a582856366a3bafa2497ee99 | 2,303 | //
// GuestViewController.swift
// RockPaperScissors
//
// Created by Paweł Brzozowski on 20/12/2021.
//
import UIKit
class GuestViewController: UIViewController {
@IBOutlet weak var mainLabel: UILabel!
@IBOutlet weak var idTextField: UITextField!
@IBOutlet weak var joinButton: UIButton!
// Join id provided by user from textField
var joinID: String?
// Variable responsible for showing navigation bar when user is editing
// It make sure that trigering to show nav. bar will be fired only once.
var naviagtionControllerSetActive = false
override func viewDidLoad() {
super.viewDidLoad()
// Properly formated main label text:
mainLabel.text = "ROCK \n / PAPAER / \n SCISSORS"
// Set radius for both button and TextField:
joinButton.layer.cornerRadius = 10
idTextField.layer.cornerRadius = 20
}
// Hide anvigation bar on apearing
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: animated)
}
// Set nagiation bar viible again for next screen
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
navigationController?.setNavigationBarHidden(false, animated: animated)
}
// When GUEST is editing textField show him option to go back via navigation controller
@IBAction func edditingTextField(_ sender: Any) {
if !naviagtionControllerSetActive {
navigationController?.setNavigationBarHidden(false, animated: false)
naviagtionControllerSetActive = true
}
}
// Send provided JOIN id to chooseVC
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == Constants.JOIN_TO_CHOOSE {
if let chooseVC = segue.destination as? ChooseViewController {
// Send data about gameID and that the next screen have been triggered GUEST
chooseVC.ID = idTextField.text!
chooseVC.user = "GUEST"
}
}
}
// Code when GUEST press join button
@IBAction func joinButtonPressed(_ sender: Any) {
}
}
| 32.43662 | 92 | 0.661746 |
14335217914b949bc16b40d364548d548d7b0067 | 554 | // TODO: This particular interface should not exists or at least it should not duplicate other interfaces.
// However, we will need something like that to implement actions (ElementAction).
//
// It is a temporary workaround to pause current refactoring.
// Should be refactored further during implementation of Gray Box tests.
public protocol SnapshotForInteractionResolver: class {
func resolve(
minimalPercentageOfVisibleArea: CGFloat,
completion: @escaping (ElementSnapshot) -> (InteractionResult))
-> InteractionResult
}
| 46.166667 | 106 | 0.763538 |
d54c8ef43f2364b4451db101a0217c3acc65bba8 | 3,032 | //
// Copyright © 2020 NHSX. All rights reserved.
//
import Localization
import UIKit
public class PrimaryLinkButton: UIControl {
private var title: String
private var action: (() -> Void)?
public required init(
title: String,
action: (() -> Void)? = nil
) {
self.title = title
self.action = action
super.init(frame: .zero)
setUp()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setUp() {
backgroundColor = UIColor(.nhsBlue)
layer.cornerRadius = .buttonCornerRadius
isAccessibilityElement = true
accessibilityTraits = .link
accessibilityHint = localize(.link_accessibility_hint)
accessibilityLabel = title
heightAnchor.constraint(greaterThanOrEqualToConstant: .hitAreaMinHeight).isActive = true
let titleLabel = UILabel().set(text: title).styleAsHeading()
titleLabel.textColor = UIColor(.primaryButtonLabel)
titleLabel.adjustsFontForContentSizeCategory = true
titleLabel.numberOfLines = 0
titleLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
titleLabel.setContentHuggingPriority(.required, for: .vertical)
titleLabel.setContentHuggingPriority(.required, for: .horizontal)
let image = UIImage(.externalLink)
let imageView = UIImageView(image: image).color(.primaryButtonLabel)
imageView.adjustsImageSizeForAccessibilityContentSizeCategory = true
let aspectRatio = image.size.height / image.size.width
imageView.heightAnchor.constraint(equalTo: imageView.widthAnchor, multiplier: aspectRatio).isActive = true
imageView.setContentCompressionResistancePriority(.required, for: .horizontal)
imageView.setContentHuggingPriority(.required, for: .horizontal)
imageView.setContentHuggingPriority(.required, for: .vertical)
let stackView = UIStackView(arrangedSubviews: [titleLabel, imageView])
stackView.axis = .horizontal
stackView.alignment = .center
stackView.distribution = .fill
stackView.spacing = .linkIconSpacing
stackView.isUserInteractionEnabled = false
addAutolayoutSubview(stackView)
NSLayoutConstraint.activate([
stackView.heightAnchor.constraint(equalTo: heightAnchor, constant: -.doubleSpacing),
stackView.centerYAnchor.constraint(equalTo: centerYAnchor),
stackView.widthAnchor.constraint(lessThanOrEqualTo: widthAnchor, constant: -.doubleSpacing),
stackView.centerXAnchor.constraint(equalTo: centerXAnchor),
imageView.heightAnchor.constraint(lessThanOrEqualTo: titleLabel.heightAnchor),
])
addTarget(self, action: #selector(touchUpInside))
}
@objc private func touchUpInside() {
action?()
}
}
| 37.432099 | 114 | 0.671834 |
eb1d3592f6e4d02e7e18b23a39dff51a8eeba477 | 550 | //
// TopicTitle.swift
// docc2html
//
// Created by Helge Heß.
// Copyright © 2021 ZeeZide GmbH. All rights reserved.
//
//
import mustache
let TopicTitleTemplate = Mustache(
"""
<div class="topictitle">
<span class="eyebrow">{{eyebrow}}</span>
<h1 class="title">{{title}}</h1>
</div>
"""
)
extension DZRenderingContext {
func renderTopicTitle(eyebrow: String? = nil, title: String) -> String {
return templates.topicTitle(title : title,
eyebrow : eyebrow ?? labels.framework)
}
}
| 19.642857 | 74 | 0.610909 |
ff053145cb76498d833af45b004f351959a28d8d | 768 | //
// GitHubPullRequest.swift
// XBotBuilder
//
// Created by Geoffrey Nix on 10/7/14.
// Copyright (c) 2014 ModCloth. All rights reserved.
//
import Foundation
class GitHubPullRequest {
var status:GitHubCommitStatus?
var branch:String?
var sha:String?
var number:NSNumber?
var title:String?
init(gitHubDictionary:Dictionary<String,AnyObject>) {
if let head = gitHubDictionary["head"] as AnyObject? as Dictionary<String, AnyObject>? {
self.branch = head["ref"] as AnyObject? as String?
self.sha = head["sha"] as AnyObject? as String?
}
self.number = gitHubDictionary["number"] as AnyObject? as NSNumber?
self.title = gitHubDictionary["title"] as AnyObject? as String?
}
} | 27.428571 | 96 | 0.657552 |
f7b9a5d0af10bd5e3ea848e53a74622a2905ec43 | 2,356 | //
// SceneDelegate.swift
// AutomaticPackage
//
// Created by 李广斌 on 2020/7/22.
// Copyright © 2020 www.automaticpackage. 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.
}
}
| 43.62963 | 147 | 0.714771 |
8960a8a43cc31cf4ea10f85ba85d3fb37632f226 | 2,982 | //
// ScriptConverter.swift
// BitFreezer-BitcoinKit
//
// Created by Oleksii Shulzhenko on 26.03.2020.
//
import Foundation
public class ScriptConverter {
public init() {}
public func encode(script: Script) -> Data {
var scriptData = Data()
script.chunks.forEach { chunk in
if let data = chunk.data {
scriptData += OpCode.push(data)
} else {
scriptData += Data([chunk.opCode])
}
}
return scriptData
}
private func getPushRange(data: Data, it: Int) throws -> Range<Int> {
let opCode = data[it]
var bytesCount: Int?
var bytesOffset = 1
switch opCode {
case 0x01...0x4b: bytesCount = Int(opCode)
case 0x4c: // The next byte contains the number of bytes to be pushed onto the stack
bytesOffset += 1
guard data.count > 1 else {
throw ScriptError.wrongScriptLength
}
bytesCount = Int(data[1])
case 0x4d: // The next two bytes contain the number of bytes to be pushed onto the stack in little endian order
bytesOffset += 2
guard data.count > 2 else {
throw ScriptError.wrongScriptLength
}
bytesCount = Int(data[2]) << 8 + Int(data[1])
case 0x4e: // The next four bytes contain the number of bytes to be pushed onto the stack in little endian order
bytesOffset += 4
guard data.count > 5 else {
throw ScriptError.wrongScriptLength
}
var index = bytesOffset
var count = 0
while index >= 0 {
count += count << 8 + Int(data[1 + index])
index -= 1
}
bytesCount = count
default: break
}
guard let keyLength = bytesCount, data.count >= it + bytesOffset + keyLength else {
throw ScriptError.wrongScriptLength
}
return Range(uncheckedBounds: (lower: it + bytesOffset, upper: it + bytesOffset + keyLength))
}
}
extension ScriptConverter: IScriptConverter {
public func decode(data: Data) throws -> Script {
var chunks = [Chunk]()
var it = 0
while it < data.count {
let opCode = data[it]
switch opCode {
case 0x01...0x4e:
let range = try getPushRange(data: data, it: it)
chunks.append(Chunk(scriptData: data, index: it, payloadRange: range))
it = range.upperBound
default:
chunks.append(Chunk(scriptData: data, index: it, payloadRange: nil))
it += 1
}
}
return Script(with: data, chunks: chunks)
}
}
| 33.886364 | 153 | 0.51006 |
d549cc7ca5321067524a4d59128a69f8662ba1db | 20,736 | //
// KOPickerView.swift
// KOControls
//
// Copyright (c) 2018 Kuba Ostrowski
//
// 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: - Settings
/// Dialog action
public class KODialogActionModel: NSObject {
/// Title used for barView: left/right buttons or for titleLabel.text
public let title: String
/// Action that will be invoked
public let action: (KODialogViewController) -> Void
public init(title: String, action: @escaping (KODialogViewController) -> Void) {
self.title = title
self.action = action
super.init()
}
/// Action that will invoke a function and then dismiss the dialog
///
/// - Parameter title: title used for barView: left/right buttons or for titleLabel.text
public static func dismissAction<Parameter: KODialogViewController>(withTitle title: String, action: ((Parameter) -> Void)? = nil) -> KODialogActionModel {
return KODialogActionModel(title: title, action: { (dialog) in
action?(dialog as! Parameter)
dialog.dismiss(animated: true, completion: nil)
})
}
/// Action that will dismiss the dialog
///
/// - Parameter title: title used for barView: left/right buttons or for titleLabel.text
@available(*, deprecated, message: "This func will be removed in the next version, please use dismissAction instead")
public static func cancelAction(withTitle title: String = "Cancel") -> KODialogActionModel {
return dismissAction(withTitle: title, action: { _ in
})
}
/// Action that will invoke a function and then dismiss the dialog
///
/// - Parameter title: title used for barView: left/right buttons or for titleLabel.text
@available(*, deprecated, message: "This func will be removed in the next version, please use dismissAction instead")
public static func doneAction<Parameter: KODialogViewController>(withTitle title: String = "Done", action: @escaping (Parameter) -> Void) -> KODialogActionModel {
return dismissAction(withTitle: title, action: action)
}
}
/// Mode of 'barView' visibility
public enum KODialogBarModes {
case top
case bottom
case hidden
}
@objc public protocol KODialogViewControllerDelegate: NSObjectProtocol {
//developer is responsible for set a title on the button, after implemented one of these methods
/// Developer can create a button manually by implementing this function. Button will be created after setted leftBarButtonAction.
@objc optional func dialogViewControllerCreateLeftButton(_ dialogViewController: KODialogViewController) -> UIButton
/// Developer can create a button manually by implementing this function. Button will be created after setted rightBarButtonAction.
@objc optional func dialogViewControllerCreateRightButton(_ dialogViewController: KODialogViewController) -> UIButton
@objc optional func dialogViewControllerLeftButtonClicked(_ dialogViewController: KODialogViewController)
@objc optional func dialogViewControllerRightButtonClicked(_ dialogViewController: KODialogViewController)
// You can use events instead
@objc optional func dialogViewControllerInitialized(_ dialogViewController: KODialogViewController)
@objc optional func dialogViewControllerViewWillDisappear(_ dialogViewController: KODialogViewController)
@objc optional func dialogViewControllerViewDidDisappear(_ dialogViewController: KODialogViewController)
}
// MARK: - KODialogViewController
// swiftlint:disable type_body_length file_length
/// Dialog view with the bar and content view. Content can be changed by override function 'createContentView'. BarView title should be changed by assign text to the 'barView.titleLabel.text'. 'Left/Right BarButtonAction' should be used to get the result or dismiss.
open class KODialogViewController: UIViewController, UIGestureRecognizerDelegate {
// MARK: - Variables
//public
@IBOutlet public weak var delegate: KODialogViewControllerDelegate?
public var statusBarStyleWhenCapturesAppearance: UIStatusBarStyle = .lightContent
/// Custom view transition used when modalPresentationStyle is set to '.custom'
public var customTransition: KOCustomTransition? = KODimmingTransition() {
didSet {
transitioningDelegate = customTransition
}
}
/// Events that will be invoke
public var viewLoadedEvent: ((KODialogViewController) -> Void)?
public var viewWillDisappearEvent: ((KODialogViewController) -> Void)?
public var viewDidDisappearEvent: ((KODialogViewController) -> Void)?
// MARK: Main view
private weak var pMainView: KODialogMainView!
private var mainViewAllHorizontalConsts: [NSLayoutConstraint] = []
private var mainViewHorizontalConstraintsInsets: KOHorizontalConstraintsInsets!
private var mainViewAllVerticalConsts: [NSLayoutConstraint] = []
private var mainViewVerticalConstraintsInsets: KOVerticalConstraintsInsets!
private var dismissOnTapRecognizer: UITapGestureRecognizer!
//public
/// Main view of dialog, the view of viewController is the container for that view that fills the background
public var mainView: KODialogMainView! {
loadViewIfNeeded()
return pMainView
}
/// Is the dialog will be dismissed when user clicked at the view of viewController
public var dismissWhenUserTapAtBackground: Bool = true {
didSet {
refreshDismissOnTapRecognizer()
}
}
/// Vertical alignment of the main view in the view of viewController
public var mainViewVerticalAlignment: UIControl.ContentVerticalAlignment = .bottom {
didSet {
refreshMainViewVerticalAlignment()
}
}
/// Horizontal alignment of the main view in the view of viewController
public var mainViewHorizontalAlignment: UIControl.ContentHorizontalAlignment = .fill {
didSet {
refreshMainViewHorizontalAlignment()
}
}
/// This parameter will be reseted when alignments were refresh, so use it after viewDidLoad and refresh manually when you changed alignments
public var mainViewEdgesConstraintsInsets: KOEdgesConstraintsInsets!
/// After setted this action will be created the left button. This action should be setted to get the result or dismiss the dialog after button clicked.
public var leftBarButtonAction: KODialogActionModel? {
didSet {
refreshLeftBarButtonAction()
}
}
/// After setted this action will be created the right button. This action should be setted to get the result or dismiss the dialog after button clicked.
public var rightBarButtonAction: KODialogActionModel? {
didSet {
refreshRightBarButtonAction()
}
}
open var defaultBarButtonInsets: UIEdgeInsets {
return UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 8)
}
override open var preferredStatusBarStyle: UIStatusBarStyle {
return statusBarStyleWhenCapturesAppearance
}
// MARK: - Functions
// MARK: Initialization
override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
initTransition()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initTransition()
}
private func initTransition() {
modalPresentationStyle = .custom
transitioningDelegate = customTransition
}
override open func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
delegate?.dialogViewControllerViewWillDisappear?(self)
viewWillDisappearEvent?(self)
}
override open func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
delegate?.dialogViewControllerViewDidDisappear?(self)
viewDidDisappearEvent?(self)
}
override open func viewDidLoad() {
super.viewDidLoad()
initialize()
}
private func initialize() {
initializeView()
initializeMainView()
refreshLeftBarButtonAction()
refreshRightBarButtonAction()
initializeAppearance()
delegate?.dialogViewControllerInitialized?(self)
viewLoadedEvent?(self)
}
private func initializeView() {
dismissOnTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissOnTapRecognizerTap(gesture:)))
dismissOnTapRecognizer.delegate = self
refreshDismissOnTapRecognizer()
view.addGestureRecognizer(dismissOnTapRecognizer)
}
@objc private func dismissOnTapRecognizerTap(gesture: UITapGestureRecognizer) {
self.dismiss(animated: true, completion: nil)
}
private func refreshDismissOnTapRecognizer() {
guard isViewLoaded else {
return
}
dismissOnTapRecognizer.isEnabled = dismissWhenUserTapAtBackground
}
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
//prevent from close dialog by touching child views
return view.hitTest(touch.location(in: view), with: nil) == view
}
private func initializeMainView() {
let mainView = KODialogMainView(contentView: createContentView(), withInsets: defaultContentInsets)
mainView.translatesAutoresizingMaskIntoConstraints = false
self.pMainView = mainView
view.addSubview(mainView)
refreshMainViewVerticalAlignment()
refreshMainViewHorizontalAlignment()
}
//public
open func createContentView() -> UIView {
//method to overrride by subclasses
return UIView()
}
open var defaultContentInsets: UIEdgeInsets {
return UIEdgeInsets.zero
}
open func initializeAppearance() {
pMainView.backgroundColor = UIColor.Theme.dialogMainViewBackground
}
// MARK: Main view
private func refreshMainViewHorizontalAlignment() {
guard isViewLoaded else {
return
}
view.removeConstraints(mainViewAllHorizontalConsts)
switch mainViewHorizontalAlignment {
case .left:
createMainViewConstraintsForLeftHorizontalAllignment()
case .leading:
createMainViewConstraintsForLeadingHorizontalAllignment()
case .center:
createMainViewConstraintsForCenterHorizontalAllignment()
case .right:
createMainViewConstraintsForRightHorizontalAllignment()
case .trailing:
createMainViewConstraintsForTrailingHorizontalAllignment()
default:
createMainViewConstraintsForFillHorizontalAllignment()
}
}
private func createMainViewConstraintsForLeftHorizontalAllignment() {
let leftConst = pMainView.leftAnchor.constraint(equalTo: view.leftAnchor)
let rightConst = pMainView.rightAnchor.constraint(lessThanOrEqualTo: view.rightAnchor)
let allConsts = [leftConst, rightConst]
setMainViewConstraintsForHorizontalAllignment(leftConst: leftConst, rightConst: rightConst, allConsts: allConsts)
}
private func createMainViewConstraintsForLeadingHorizontalAllignment() {
let leftConst = pMainView.leadingAnchor.constraint(equalTo: view.leadingAnchor)
let rightConst = pMainView.trailingAnchor.constraint(lessThanOrEqualTo: view.trailingAnchor)
let allConsts = [leftConst, rightConst]
setMainViewConstraintsForHorizontalAllignment(leftConst: leftConst, rightConst: rightConst, allConsts: allConsts)
}
private func createMainViewConstraintsForCenterHorizontalAllignment() {
let leftConst = pMainView.leftAnchor.constraint(greaterThanOrEqualTo: view.leftAnchor)
let rightConst = pMainView.rightAnchor.constraint(lessThanOrEqualTo: view.rightAnchor)
let allConsts = [leftConst, rightConst, pMainView.centerXAnchor.constraint(equalTo: view.centerXAnchor)]
setMainViewConstraintsForHorizontalAllignment(leftConst: leftConst, rightConst: rightConst, allConsts: allConsts)
}
private func createMainViewConstraintsForRightHorizontalAllignment() {
let leftConst = pMainView.leftAnchor.constraint(greaterThanOrEqualTo: view.leftAnchor)
let rightConst = pMainView.rightAnchor.constraint(equalTo: view.rightAnchor)
let allConsts = [leftConst, rightConst]
setMainViewConstraintsForHorizontalAllignment(leftConst: leftConst, rightConst: rightConst, allConsts: allConsts)
}
private func createMainViewConstraintsForTrailingHorizontalAllignment() {
let leftConst = pMainView.leadingAnchor.constraint(greaterThanOrEqualTo: view.leadingAnchor)
let rightConst = pMainView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
let allConsts = [leftConst, rightConst]
setMainViewConstraintsForHorizontalAllignment(leftConst: leftConst, rightConst: rightConst, allConsts: allConsts)
}
private func createMainViewConstraintsForFillHorizontalAllignment() {
let leftConst = pMainView.leftAnchor.constraint(equalTo: view.leftAnchor)
let rightConst = pMainView.rightAnchor.constraint(equalTo: view.rightAnchor)
let allConsts = [leftConst, rightConst]
setMainViewConstraintsForHorizontalAllignment(leftConst: leftConst, rightConst: rightConst, allConsts: allConsts)
}
private func setMainViewConstraintsForHorizontalAllignment(leftConst: NSLayoutConstraint, rightConst: NSLayoutConstraint, allConsts: [NSLayoutConstraint]) {
view.addConstraints(allConsts)
mainViewAllHorizontalConsts = allConsts
mainViewHorizontalConstraintsInsets = KOHorizontalConstraintsInsets(leftConst: leftConst, rightConst: rightConst)
refreshMainViewEdgesConstraintsInsets()
}
private func refreshMainViewVerticalAlignment() {
guard isViewLoaded else {
return
}
view.removeConstraints(mainViewAllVerticalConsts)
switch mainViewVerticalAlignment {
case .top:
createMainViewConstraintsForTopVerticalAllignment()
case .center:
createMainViewConstraintsForCenterVerticalAllignment()
case .bottom:
createMainViewConstraintsForBottomVerticalAllignment()
default:
createMainViewConstraintsForDefaultVerticalAllignment()
}
}
private func createMainViewConstraintsForTopVerticalAllignment() {
let topConst = pMainView.topAnchor.constraint(equalTo: view.topAnchor)
let bottomConst = pMainView.bottomAnchor.constraint(lessThanOrEqualTo: view.bottomAnchor)
let allConsts = [topConst, bottomConst]
setMainViewConstraintsForVerticalAllignment(topConst: topConst, bottomConst: bottomConst, allConsts: allConsts)
}
private func createMainViewConstraintsForCenterVerticalAllignment() {
let topConst = pMainView.topAnchor.constraint(greaterThanOrEqualTo: view.topAnchor)
let bottomConst = pMainView.bottomAnchor.constraint(lessThanOrEqualTo: view.bottomAnchor)
let allConsts = [topConst, bottomConst, pMainView.centerYAnchor.constraint(equalTo: view.centerYAnchor)]
setMainViewConstraintsForVerticalAllignment(topConst: topConst, bottomConst: bottomConst, allConsts: allConsts)
}
private func createMainViewConstraintsForBottomVerticalAllignment() {
let topConst = pMainView.topAnchor.constraint(greaterThanOrEqualTo: view.topAnchor)
let bottomConst = pMainView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
let allConsts = [topConst, bottomConst]
setMainViewConstraintsForVerticalAllignment(topConst: topConst, bottomConst: bottomConst, allConsts: allConsts)
}
private func createMainViewConstraintsForDefaultVerticalAllignment() {
let topConst = pMainView.topAnchor.constraint(equalTo: view.topAnchor)
let bottomConst = pMainView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
let allConsts = [topConst, bottomConst]
setMainViewConstraintsForVerticalAllignment(topConst: topConst, bottomConst: bottomConst, allConsts: allConsts)
}
private func setMainViewConstraintsForVerticalAllignment(topConst: NSLayoutConstraint, bottomConst: NSLayoutConstraint, allConsts: [NSLayoutConstraint]) {
view.addConstraints(allConsts)
mainViewAllVerticalConsts = allConsts
mainViewVerticalConstraintsInsets = KOVerticalConstraintsInsets(topConst: topConst, bottomConst: bottomConst)
refreshMainViewEdgesConstraintsInsets()
}
private func refreshMainViewEdgesConstraintsInsets() {
guard mainViewHorizontalConstraintsInsets != nil && mainViewVerticalConstraintsInsets != nil else {
return
}
mainViewEdgesConstraintsInsets = KOEdgesConstraintsInsets(horizontal: mainViewHorizontalConstraintsInsets, vertical: mainViewVerticalConstraintsInsets)
}
// MARK: Bar Buttons
private func refreshRightBarButtonAction() {
guard isViewLoaded else {
return
}
guard let rightBarButtonAction = rightBarButtonAction else {
pMainView.barView.rightView = nil
return
}
createRightBarButton(fromAction: rightBarButtonAction)
}
private func createRightBarButton(fromAction action: KODialogActionModel) {
let rightBarButton: UIButton = (delegate?.dialogViewControllerCreateRightButton?(self)) ?? createDefaultBarButton(withTitle: action.title)
rightBarButton.addTarget(self, action: #selector(rightBarButtonClicked), for: .touchUpInside)
pMainView.barView.rightView = rightBarButton
pMainView.barView.rightViewEdgesConstraintsInset.insets = defaultBarButtonInsets
}
private func refreshLeftBarButtonAction() {
guard isViewLoaded else {
return
}
guard let leftBarButtonAction = leftBarButtonAction else {
pMainView.barView.leftView = nil
return
}
createLeftBarButton(fromAction: leftBarButtonAction)
}
private func createLeftBarButton(fromAction action: KODialogActionModel) {
let leftBarButton: UIButton = (delegate?.dialogViewControllerCreateLeftButton?(self)) ?? createDefaultBarButton(withTitle: action.title)
leftBarButton.addTarget(self, action: #selector(leftBarButtonClicked), for: .touchUpInside)
pMainView.barView.leftView = leftBarButton
pMainView.barView.leftViewEdgesConstraintsInset.insets = defaultBarButtonInsets
}
private func createDefaultBarButton(withTitle title: String) -> UIButton {
let button = UIButton(type: .system)
button.setTitle(title, for: .normal)
return button
}
@objc private func leftBarButtonClicked() {
leftBarButtonAction?.action(self)
delegate?.dialogViewControllerLeftButtonClicked?(self)
}
@objc private func rightBarButtonClicked() {
rightBarButtonAction?.action(self)
delegate?.dialogViewControllerRightButtonClicked?(self)
}
}
// MARK: KODialogViewController + Tests
extension KODialogViewController {
internal func testLeftBarButtonClicked() {
leftBarButtonClicked()
}
internal func testRightBarButtonClicked() {
rightBarButtonClicked()
}
}
| 42.491803 | 266 | 0.725116 |
3ab5c8ee56ec34e5e5a89bb8fda62761f686a459 | 1,457 | import Foundation
import MixboxTestsFoundation
import TestsIpc
@objc(PrincipalClass)
final class TestObservationEntryPoint: BaseTestObservationEntryPoint {
override func main() {
exportAvailableTestCasesIfNeeded()
setUpObservation()
}
private func exportAvailableTestCasesIfNeeded() {
guard let exportPath = env("EMCEE_RUNTIME_TESTS_EXPORT_PATH") else {
return
}
TestQuery(outputPath: exportPath).export()
}
private func setUpObservation() {
let testFailureRecorder = XcTestFailureRecorder(
currentTestCaseProvider: AutomaticCurrentTestCaseProvider(),
shouldNeverContinueTestAfterFailure: false
)
startObservation(
testLifecycleManagers: [
ReportingTestLifecycleManager(
reportingSystem: DevNullReportingSystem(),
stepLogsProvider: Singletons.stepLogsProvider,
stepLogsCleaner: Singletons.stepLogsCleaner,
testFailureRecorder: testFailureRecorder
),
MeasureableTimedActivityMetricSenderWaiterTestLifecycleManager()
]
)
}
private func env(_ envName: String) -> String? {
guard let value = ProcessInfo.processInfo.environment[envName], !value.isEmpty else {
return nil
}
return value
}
}
| 31 | 93 | 0.628689 |
bf0fce22ffd7d55818244ad511d76a54bf2efe5f | 5,899 | //
// Copyright RevenueCat Inc. All Rights Reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/MIT
//
// Offering.swift
//
// Created by Joshua Liebowitz on 7/9/21.
//
import Foundation
/**
* An offering is a collection of ``Package``s, and they let you control which products
* are shown to users without requiring an app update.
*
* Building paywalls that are dynamic and can react to different product
* configurations gives you maximum flexibility to make remote updates.
*
* #### Related Articles
* - [Displaying Products](https://docs.revenuecat.com/docs/displaying-products)
* - ``Offerings``
* - ``Package``
*/
@objc(RCOffering) public class Offering: NSObject {
/**
Unique identifier defined in RevenueCat dashboard.
*/
@objc public let identifier: String
/**
Offering description defined in RevenueCat dashboard.
*/
@objc public let serverDescription: String
/**
Array of ``Package`` objects available for purchase.
*/
@objc public let availablePackages: [Package]
/**
Lifetime ``Package`` type configured in the RevenueCat dashboard, if available.
*/
@objc private(set) public var lifetime: Package?
/**
Annual ``Package`` type configured in the RevenueCat dashboard, if available.
*/
@objc private(set) public var annual: Package?
/**
Six month ``Package`` type configured in the RevenueCat dashboard, if available.
*/
@objc private(set) public var sixMonth: Package?
/**
Three month ``Package`` type configured in the RevenueCat dashboard, if available.
*/
@objc private(set) public var threeMonth: Package?
/**
Two month ``Package`` type configured in the RevenueCat dashboard, if available.
*/
@objc private(set) public var twoMonth: Package?
/**
Monthly ``Package`` type configured in the RevenueCat dashboard, if available.
*/
@objc private(set) public var monthly: Package?
/**
Weekly ``Package`` type configured in the RevenueCat dashboard, if available.
*/
@objc private(set) public var weekly: Package?
public override var description: String {
return """
<Offering {\n\tidentifier=\(identifier)\n\tserverDescription=\(serverDescription)\n"
\tavailablePackages=\(valueOrEmpty(availablePackages))\n\tlifetime=\(valueOrEmpty(lifetime))\n
\tannual=\(valueOrEmpty(annual))\n\tsixMonth=\(valueOrEmpty(sixMonth))\n
\tthreeMonth=\(valueOrEmpty(threeMonth))\n\ttwoMonth=\(valueOrEmpty(twoMonth))\n
\tmonthly=\(valueOrEmpty(monthly))\n\tweekly=\(valueOrEmpty(weekly))\n}>
"""
}
/**
Retrieves a specific ``Package`` by identifier, use this to access custom package types configured in the
RevenueCat dashboard, e.g. `offering.package(identifier: "custom_package_id")` or
`offering["custom_package_id"]`.
*/
@objc public func package(identifier: String?) -> Package? {
guard let identifier = identifier else {
return nil
}
return availablePackages
.filter { $0.identifier == identifier }
.first
}
/// - Seealso: ``package(identifier:)``
@objc public subscript(key: String) -> Package? {
return package(identifier: key)
}
init(identifier: String, serverDescription: String, availablePackages: [Package]) {
self.identifier = identifier
self.serverDescription = serverDescription
self.availablePackages = availablePackages
for package in availablePackages {
switch package.packageType {
case .lifetime:
Self.checkForNilAndLogReplacement(package: self.lifetime, newPackage: package)
self.lifetime = package
case .annual:
Self.checkForNilAndLogReplacement(package: self.annual, newPackage: package)
self.annual = package
case .sixMonth:
Self.checkForNilAndLogReplacement(package: self.sixMonth, newPackage: package)
self.sixMonth = package
case .threeMonth:
Self.checkForNilAndLogReplacement(package: self.threeMonth, newPackage: package)
self.threeMonth = package
case .twoMonth:
Self.checkForNilAndLogReplacement(package: self.twoMonth, newPackage: package)
self.twoMonth = package
case .monthly:
Self.checkForNilAndLogReplacement(package: self.monthly, newPackage: package)
self.monthly = package
case .weekly:
Self.checkForNilAndLogReplacement(package: self.weekly, newPackage: package)
self.weekly = package
case .custom where package.storeProduct.productCategory == .nonSubscription:
// Non-subscription product, ignoring
break
case .unknown, .custom:
Logger.warn(
"Unknown subscription length for package '\(package.offeringIdentifier)': " +
"\(package.packageType). Ignoring."
)
}
}
}
private static func checkForNilAndLogReplacement(package: Package?, newPackage: Package) {
guard let package = package else {
return
}
Logger.warn("Package: \(package.identifier) already exists, overwriting with:\(newPackage.identifier)")
}
private func valueOrEmpty<T: CustomStringConvertible>(_ value: T?) -> String {
if let value = value {
return value.description
} else {
return ""
}
}
}
extension Offering: Identifiable {}
| 34.7 | 111 | 0.635531 |
116ebc8d0e71a438396f6ba8b9e46ef27a85a5cf | 1,176 | import SwiftUI
struct AnimatableGradientView: View {
@State private var gradientA: [Color] = [.white, .red]
@State private var gradientB: [Color] = [.white, .blue]
@State private var firstPlane: Bool = true
func setGradient(gradient: [Color]) {
if firstPlane {
gradientB = gradient
}
else {
gradientA = gradient
}
firstPlane = !firstPlane
}
var body: some View {
ZStack {
Rectangle()
.fill(LinearGradient(gradient: Gradient(colors: self.gradientA), startPoint: UnitPoint(x: 0, y: 0), endPoint: UnitPoint(x: 1, y: 1)))
Rectangle()
.fill(LinearGradient(gradient: Gradient(colors: self.gradientB), startPoint: UnitPoint(x: 0, y: 0), endPoint: UnitPoint(x: 1, y: 1)))
.opacity(self.firstPlane ? 0 : 1)
Button(action:{
withAnimation(.spring()) {
self.setGradient(gradient: [Color.random(), Color.random()])
}
})
{
Text("Change gradient")
}
}
}
}
struct AnimatableGradientView_Previews: PreviewProvider {
static var previews: some View {
AnimatableGradientView()
}
}
| 27.348837 | 145 | 0.595238 |
89ce3985d70caec9374dca5908c760cd554c7537 | 356 | //
// SDPRandomNumberParameterModuleInteractorOutput.swift
// Swift-data-processor
//
// Created by Dmytro Platov on 10/10/2018.
// Copyright © 2018 Dmytro Platov. All rights reserved.
//
import Foundation
protocol SDPRandomNumberParameterModuleInteractorOutput: class {
func set(state: SDPRandomParametersState?)
func invalidDataPassed()
}
| 22.25 | 64 | 0.769663 |
4bc3b30294e865a62a2fc294da4eb506a0875a01 | 2,151 | //
// BlockManager.swift
// TunnelPacketKit
//
// Created by Zhuhao Wang on 16/1/27.
// Copyright © 2016年 Zhuhao Wang. All rights reserved.
//
import Foundation
class BlockManager {
var blockList: LinkedList<TCPDataBlock>?
func addPacket(packet: IPPacket) {
var blockIter = blockList
while let cBlock = blockIter {
if cBlock.item.takeIn(packet) {
break
}
blockIter = cBlock.next
}
if blockIter == nil {
// no block takes this in
let block = TCPDataBlock(fromPacket: packet)
let listItem = LinkedList(item: block)
if blockList == nil {
blockList = listItem
return
}
if TCPUtils.sequenceLessThanOrEqualTo(block.startSequence, blockList!.item.startSequence) {
listItem.append(blockList!)
blockList = listItem
}
var blockIter = blockList!
while true {
if blockIter.next == nil {
blockIter.append(listItem)
return
}
if blockIter.next!.item.startSequence > block.endSequence {
// since next is after current block, it must be inserted now
blockIter.insertAfter(listItem)
return
}
blockIter = blockIter.next!
}
} else {
if let nextBlock = blockIter!.next {
if blockIter!.item.merge(nextBlock.item) {
blockIter!.takeOffNext()
}
}
}
}
func getData(sequenceNumber: UInt32) -> (NSData, Bool)? {
if let block = blockList?.item {
if TCPUtils.sequenceBetween(sequenceNumber, block.startSequence, block.endSequence) {
block.skipToSequenceNumber(sequenceNumber)
return (block.getData(), block.FIN)
}
}
return nil
}
} | 29.875 | 103 | 0.493724 |
18e81bf0e0b5657e1761dc95984d6286d2b5558d | 356 | // RUN: not --crash %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class S<T where B:A{
class a
enum T{
protocol d func d{
{
}
class D{class B{{
}class B<T where T:B
{var
b=d}func b{
class B{
var _=a
| 18.736842 | 87 | 0.710674 |
1ecfb9627ec10c6c7a046418357aad7e00e1caad | 5,889 | //
// PhoneNumberTests.swift
// StripeUICoreTests
//
// Created by Cameron Sabol on 10/11/21.
//
import XCTest
@_spi(STP) @testable import StripeUICore
class PhoneNumberTests: XCTestCase {
func testFormats() {
let cases: [(number: String, country: String, format: PhoneNumber.Format, formattedNumber: String)] = [
(
number: "",
country: "US",
format: .national,
formattedNumber: ""
),
(
number: "4",
country: "US",
format: .national,
formattedNumber: "(4"
),
(
number: "+",
country: "US",
format: .national,
formattedNumber: "" // doesn't include + in national format
),
(
number: "+",
country: "US",
format: .international,
formattedNumber: "" // empty input shouldn't get formatted
),
(
number: "a",
country: "US",
format: .national,
formattedNumber: ""
),
(
number: "(", // PhoneNumberFormat only formats digits, +, and •
country: "US",
format: .national,
formattedNumber: ""
),
(
number: "+49",
country: "DE",
format: .international,
formattedNumber: "+49 49" // never treats input as country code
),
(
number: "160 1234567",
country: "DE",
format: .international,
formattedNumber: "+49 160 1234567"
),
(
number: "5551231234",
country: "US",
format: .international,
formattedNumber: "+1 (555) 123-1234"
),
(
number: "(555) 123-1234",
country: "US",
format: .international,
formattedNumber: "+1 (555) 123-1234"
),
(
number: "555",
country: "US",
format: .international,
formattedNumber: "+1 (555"
),
(
number: "(555) a",
country: "US",
format: .international,
formattedNumber: "+1 (555"
),
(
number: "(403) 123-1234",
country: "CA",
format: .international,
formattedNumber: "+1 (403) 123-1234"
),
(
number: "(403) 123-1234",
country: "CA",
format: .national,
formattedNumber: "(403) 123-1234"
),
(
number: "4031231234",
country: "CA",
format: .national,
formattedNumber: "(403) 123-1234"
),
(
number: "6711231234",
country: "GU",
format: .international,
formattedNumber: "+1 (671) 123-1234"
),
(
number: "6711231234",
country: "GU",
format: .national,
formattedNumber: "(671) 123-1234"
),
];
for c in cases {
guard let phoneNumber = PhoneNumber(number: c.number, countryCode: c.country) else {
XCTFail("Could not create phone number for \(c.country), \(c.number)")
continue
}
XCTAssertEqual(phoneNumber.string(as: c.format), c.formattedNumber)
}
}
func teste164FormatDropsLeadingZeros() {
guard let phoneNumber = PhoneNumber(number: "08022223333", countryCode: "JP") else {
XCTFail("Could not create phone number")
return
}
XCTAssertEqual(phoneNumber.string(as: .e164), "+818022223333")
}
func teste164MaxLength() {
guard let phoneNumber = PhoneNumber(number: "123456789123456789", countryCode: "US") else {
XCTFail("Could not create phone number")
return
}
XCTAssertEqual(phoneNumber.string(as: .e164), "+112345678912345")
}
func testFromE164() {
let gbPhone = PhoneNumber.fromE164("+445555555555")
XCTAssertEqual(gbPhone?.countryCode, "GB")
XCTAssertEqual(gbPhone?.number, "5555555555")
let brPhone = PhoneNumber.fromE164("+5591155256325")
XCTAssertEqual(brPhone?.countryCode, "BR")
XCTAssertEqual(brPhone?.number, "91155256325")
}
func testFromE164_shouldHandleInvalidInput() {
XCTAssertNil(PhoneNumber.fromE164(""))
XCTAssertNil(PhoneNumber.fromE164("++"))
XCTAssertNil(PhoneNumber.fromE164("+13"))
XCTAssertNil(PhoneNumber.fromE164("1 (555) 555 5555"))
XCTAssertNil(PhoneNumber.fromE164("+1555555555555555")) // too long
}
func testFromE164_shouldDisambiguateUsingLocale() {
// This test number is very ambiguous, it can belong to ~25 countries/territories due to
// the "+1" calling code/prefix being shared by many countries.
let number = "+15555555555"
XCTAssertEqual(PhoneNumber.fromE164(number, locale: .init(identifier: "en_US"))?.countryCode, "US")
XCTAssertEqual(PhoneNumber.fromE164(number, locale: .init(identifier: "en_CA"))?.countryCode, "CA")
XCTAssertEqual(PhoneNumber.fromE164(number, locale: .init(identifier: "es_DO"))?.countryCode, "DO")
XCTAssertEqual(PhoneNumber.fromE164(number, locale: .init(identifier: "en_PR"))?.countryCode, "PR")
XCTAssertEqual(PhoneNumber.fromE164(number, locale: .init(identifier: "en_JM"))?.countryCode, "JM")
XCTAssertEqual(PhoneNumber.fromE164(number, locale: .init(identifier: "ja_JP"))?.countryCode, "US")
XCTAssertEqual(PhoneNumber.fromE164(number, locale: .init(identifier: "ar_LB"))?.countryCode, "US")
}
}
| 32.899441 | 111 | 0.525896 |
4aaa12bd4d54d5609f580fa0570c759729f7231f | 8,523 | //
// OnboardingView.swift
// Multiverse
//
// Created by temp on 2021/07/30.
//
import Foundation
import SwiftUI
//Onboarding
struct OnboardingView: View {
@Binding var shouldShowOnboarding: Bool
var body: some View{
TabView {
PageView(
title: "Welcome to MultiVerse",
subtitle: "Multiverse is your Rick and Morty Library at your fingertips",
imageName: "rickmorty3",
showsDismissButton: false,
shouldShowOnboarding: $shouldShowOnboarding
)
PageView2(
title: "Ultimate library of Rick and Morty",
numberChar: "671",
nameChar: "Characters",
numberLoc: "108",
nameLoc: "Locations",
numberEpi: "41",
nameEpi: "Episodes",
showsDismissButton: false,
shouldShowOnboarding: $shouldShowOnboarding
)
PageView3(
title: "Get ready to have your mind blown!",
subtitle: "Learn all the amazing details about the animated Tv show",
imageName: "rickmorty4",
showsDismissButton: true,
shouldShowOnboarding: $shouldShowOnboarding
)
}
.tabViewStyle(PageTabViewStyle())
.background(Color.black)
.edgesIgnoringSafeArea(/*@START_MENU_TOKEN@*/.all/*@END_MENU_TOKEN@*/)
}
}
//Onboarding Page View 1
struct PageView: View {
let title: String
let subtitle: String
let imageName: String
let showsDismissButton: Bool
@Binding var shouldShowOnboarding: Bool
var body: some View {
VStack {
HStack{
Text(title)
.font(.system(size: 32))
.fontWeight(/*@START_MENU_TOKEN@*/.bold/*@END_MENU_TOKEN@*/)
.foregroundColor(.white)
.multilineTextAlignment(.center)
}.padding()
Spacer()
HStack{
Image(imageName)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 265, height: 265, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/)
.padding()
}
HStack{
Text(subtitle)
.font(.system(size: 20))
.multilineTextAlignment(.center)
.foregroundColor(Color(.white))
.padding()
}
Spacer()
if showsDismissButton {
Button(action: {
shouldShowOnboarding.toggle()
}, label: {
Text("Get Schwifty!")
.bold()
.foregroundColor(Color.white)
.frame(width: 200, height: 50)
.background(Color.green)
.cornerRadius(6)
})
}
Spacer()
}
}
}
//Onboarding Page View 2
struct PageView2: View {
let title: String
let numberChar: String
let nameChar: String
let numberLoc: String
let nameLoc: String
let numberEpi: String
let nameEpi: String
let showsDismissButton: Bool
@Binding var shouldShowOnboarding: Bool
var body: some View {
VStack {
HStack{
Text(title)
.font(.system(size: 32))
.fontWeight(/*@START_MENU_TOKEN@*/.bold/*@END_MENU_TOKEN@*/)
.multilineTextAlignment(.center)
.foregroundColor(.white)
}.padding()
VStack {
Text(numberChar)
.frame(width: 40, height: 40, alignment: .center)
.font(.system(size: 20))
.foregroundColor(Color(.white))
.padding()
.overlay(
Circle()
.stroke(Color.orange, lineWidth: 4)
.padding(6)
)
Text(nameChar)
.font(.system(size: 20))
.fontWeight(/*@START_MENU_TOKEN@*/.bold/*@END_MENU_TOKEN@*/)
.multilineTextAlignment(.center)
.foregroundColor(Color(.white))
.padding()
}.padding()
VStack{
Text(numberLoc)
.frame(width: 40, height: 40, alignment: .center)
.font(.system(size: 20))
.foregroundColor(Color(.white))
.padding()
.overlay(
Circle()
.stroke(Color.orange, lineWidth: 4)
.padding(6)
)
Text(nameLoc)
.font(.system(size: 20))
.fontWeight(/*@START_MENU_TOKEN@*/.bold/*@END_MENU_TOKEN@*/)
.multilineTextAlignment(.center)
.foregroundColor(Color(.white))
.padding()
}.padding()
VStack{
Text(numberEpi)
.frame(width: 40, height: 40, alignment: .center)
.font(.system(size: 20))
.foregroundColor(Color(.white))
.padding()
.overlay(
Circle()
.stroke(Color.orange, lineWidth: 4)
.padding(6)
)
Text(nameEpi)
.font(.system(size: 20))
.fontWeight(/*@START_MENU_TOKEN@*/.bold/*@END_MENU_TOKEN@*/)
.multilineTextAlignment(.center)
.foregroundColor(Color(.white))
.padding()
}.padding()
Spacer()
if showsDismissButton {
Button(action: {
shouldShowOnboarding.toggle()
}, label: {
Text("Get Schwifty!")
.bold()
.foregroundColor(Color.white)
.frame(width: 200, height: 50)
.background(Color.green)
.cornerRadius(6)
})
}
Spacer()
}
}
}
//Onboarding Page View 3
struct PageView3: View {
let title: String
let subtitle: String
let imageName: String
let showsDismissButton: Bool
@Binding var shouldShowOnboarding: Bool
var body: some View {
VStack {
HStack{
Text(title)
.font(.system(size: 32))
.fontWeight(/*@START_MENU_TOKEN@*/.bold/*@END_MENU_TOKEN@*/)
.multilineTextAlignment(.center)
.foregroundColor(.white)
}.padding()
HStack{
Image(imageName)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 300, height: 300, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/)
.padding()
}
HStack{
Text(subtitle)
.font(.system(size: 20))
.multilineTextAlignment(.center)
.foregroundColor(Color(.white))
.padding()
}
if showsDismissButton {
Button(action: {
shouldShowOnboarding.toggle()
}, label: {
Text("Get Schwifty!")
.bold()
.foregroundColor(Color.white)
.frame(width: 200, height: 50)
.background(Color.green)
.cornerRadius(6)
})
.accessibilityIdentifier("schwiftyButton")
}
Spacer()
}
}
}
| 31.105839 | 113 | 0.426962 |
d5ca599f3240e2ffb0fa7d36e0a50d184ea466c6 | 123 | // RUN: %target-swift-ide-test -code-completion -code-completion-token=A -source-filename=%s
// REQUIRES: asserts
t=0.#^A^# | 41 | 92 | 0.715447 |
7a7dacaf9f91dd96a547c512da445b0492e83982 | 1,176 | //
// ScoreTableViewController.swift
// TicTacToe
//
// Created by Susmita Horrow on 11/01/16.
// Copyright © 2016 Ashutosh. All rights reserved.
//
import UIKit
class ScoreViewController: UIViewController {
var matches = [GameHistory]()
override func viewDidLoad() {
super.viewDidLoad()
}
}
extension ScoreViewController: UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let history = matches[section]
return history.gameResults.count
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return matches.count
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return String("Match \(section)")
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("scoreCell")
let history = matches[indexPath.section]
let gameInfo = history.gameResults[indexPath.row]
let info = String("Game# \(indexPath.row) \(gameInfo.stringForResult) against \(history.opponentName)")
cell?.textLabel?.text = info
return cell!
}
}
| 26.727273 | 107 | 0.751701 |
188fa405b012701b986f2f5f4fb4a96d15ef2af5 | 6,347 | //
// SpeechEngine.swift
// testspeech
//
// Created by Nick Brook on 17/09/2016.
// Copyright © 2016 NickBrook. All rights reserved.
//
import UIKit
import Speech
import AVFoundation
protocol SpeechEngineDelegate: class {
func speechEngineDidStart(speechEngine: SpeechEngine)
func speechEngine(_ speechEngine: SpeechEngine, didHypothesizeTranscription transcription: SFTranscription, withTranscriptionIdentifier identifier: UUID)
func speechEngine(_ speechEngine: SpeechEngine, didFinishTranscription transcription: SFTranscription, withTranscriptionIdentifier identifier: UUID)
}
@available(iOS 10.0, *)
class SpeechEngine: NSObject {
weak var delegate: SpeechEngineDelegate? = nil
fileprivate var capture: AVCaptureSession?
fileprivate var speechRequest: SFSpeechAudioBufferRecognitionRequest?
fileprivate var recognizer: SFSpeechRecognizer?
fileprivate var recognitionTask: SFSpeechRecognitionTask?
fileprivate var transcriptionIdentifier: UUID?
fileprivate var recognitionTimeoutTimer: Timer? {
didSet {
oldValue?.invalidate()
}
}
var active: Bool = false {
didSet {
if active {
self.startRecognizer()
} else {
self.endRecognizer()
}
}
}
var recognitionTimeout: TimeInterval = 1
fileprivate func startTask() {
self.recognitionTask?.finish()
self.transcriptionIdentifier = UUID()
self.speechRequest = SFSpeechAudioBufferRecognitionRequest()
self.recognitionTask = self.recognizer?.recognitionTask(with: self.speechRequest!, delegate: self)
}
fileprivate func startRecognizer() {
SFSpeechRecognizer.requestAuthorization { (status) in
switch status {
case .authorized:
print("Authorized, starting recognizer")
self.recognizer = SFSpeechRecognizer(locale: Locale.current)
print("Initial available: \(self.recognizer?.isAvailable ?? false)")
DispatchQueue.main.async {
self.startTask()
self.startCapture()
self.delegate?.speechEngineDidStart(speechEngine: self)
}
case .denied:
fallthrough
case .notDetermined:
fallthrough
case.restricted:
print("User Autorization Issue.")
}
}
}
fileprivate func endRecognizer() {
print("Ending recognizer")
self.endCapture()
self.speechRequest?.endAudio()
self.recognitionTask?.cancel()
}
private func startCapture() {
print("Starting capture")
self.capture = AVCaptureSession()
guard let audioDev = AVCaptureDevice.default(for: AVMediaType.audio) else {
print("Could not get capture device.")
return
}
guard let audioIn = try? AVCaptureDeviceInput(device: audioDev) else {
print("Could not create input device.")
return
}
guard self.capture!.canAddInput(audioIn) else {
print("Could not add input device")
return
}
self.capture?.addInput(audioIn)
let audioOut = AVCaptureAudioDataOutput()
audioOut.setSampleBufferDelegate(self, queue: DispatchQueue.main)
guard self.capture!.canAddOutput(audioOut) else {
print("Could not add audio output")
return
}
self.capture!.addOutput(audioOut)
audioOut.connection(with: AVMediaType.audio)
self.capture!.startRunning()
print("Capture running")
}
private func endCapture() {
if true == self.capture?.isRunning {
self.capture?.stopRunning()
}
print("Ended capture")
}
}
extension SpeechEngine: AVCaptureAudioDataOutputSampleBufferDelegate {
func captureOutput(_ captureOutput: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
self.speechRequest?.appendAudioSampleBuffer(sampleBuffer)
}
}
extension SpeechEngine: SFSpeechRecognizerDelegate {
func speechRecognizer(_ speechRecognizer: SFSpeechRecognizer, availabilityDidChange available: Bool) {
if available {
print("Available")
} else {
print("Not available")
}
}
}
extension SpeechEngine: SFSpeechRecognitionTaskDelegate {
func speechRecognitionDidDetectSpeech(_ task: SFSpeechRecognitionTask) {
print("Detection began")
}
func speechRecognitionTask(_ task: SFSpeechRecognitionTask, didHypothesizeTranscription transcription: SFTranscription) {
print("Hypothesised) \(transcription)")
self.delegate?.speechEngine(self, didHypothesizeTranscription: transcription, withTranscriptionIdentifier: self.transcriptionIdentifier!)
if self.recognitionTimeout > 0 {
self.recognitionTimeoutTimer = Timer.scheduledTimer(withTimeInterval: self.recognitionTimeout, repeats: false, block: { (timer) in
task.finish()
})
}
}
func speechRecognitionTask(_ task: SFSpeechRecognitionTask, didFinishRecognition recognitionResult: SFSpeechRecognitionResult) {
print("Recognition result \(recognitionResult.bestTranscription)")
if recognitionResult.isFinal {
self.delegate?.speechEngine(self, didFinishTranscription: recognitionResult.bestTranscription, withTranscriptionIdentifier: self.transcriptionIdentifier!)
self.startTask()
}
}
func speechRecognitionTask(_ task: SFSpeechRecognitionTask, didFinishSuccessfully successfully: Bool) {
print("Did finish successfully: \(successfully)")
if !successfully && task.error != nil {
print("Error: \(task.error!)")
}
self.startTask()
}
func speechRecognitionTaskWasCancelled(_ task: SFSpeechRecognitionTask) {
print("cancelled")
}
func speechRecognitionTaskFinishedReadingAudio(_ task: SFSpeechRecognitionTask) {
print("Finished reading audio")
}
}
| 33.941176 | 166 | 0.645974 |
fe0091fa76ba27662a7fea058d3c06e4babd3f1c | 4,982 | //
// ViewController.swift
// MovieDB
//
// Created by Anil Kukadeja on 30/04/18.
// Copyright © 2018 Anil Kukadeja. All rights reserved.
//
import UIKit
import Alamofire
import ObjectMapper
import Kingfisher
import SVProgressHUD
class MoviesListViewController: UIViewController {
@IBOutlet weak var tableViewMovieList: UITableView!
var currentPage = 1
var totalPage = 1
var moviesList = [MovieList]()
override func viewDidLoad() {
super.viewDidLoad()
if let movies = DBManager.shared.getMoviesFromDB(), movies.count > 0 {
let mappedMovies = Mapper<MovieList>().mapArray(JSONArray: movies)
self.moviesList = mappedMovies
reloadTableView()
} else {
getMovieList(currentPage: currentPage)
}
}
override func viewWillAppear(_ animated: Bool) {
UIApplication.shared.statusBarStyle = .default
}
}
// MARK: Custom Methods
extension MoviesListViewController{
func reloadTableView(){
tableViewMovieList.reloadData()
}
}
// MARK: Webservice Call Methods
extension MoviesListViewController{
func getMovieList(currentPage : Int){
// Add URL parameters
let urlParams = [
WebServiceAPIConstants.apiKey: "201f3add5604b108ffe6d1d53dd54a87",
WebServiceAPIConstants.page: currentPage
] as [String : Any]
SVProgressHUD.setDefaultMaskType(.black)
SVProgressHUD.show()
// Fetch Request
Alamofire.request(WebServiceAPIConstants.nowPlayingMovies, method: .get, parameters: urlParams)
.validate(statusCode: 200..<300)
.responseJSON { response in
SVProgressHUD.dismiss()
if (response.result.error == nil) {
if let resultDictonary = response.result.value as? [String:Any] {
if let mappedModel = Mapper<ResponseModel>().map(JSON: resultDictonary){
if let totalPage = mappedModel.total_pages {
self.totalPage = totalPage
}
if let movies = mappedModel.results, movies.count > 0 {
self.moviesList.append(contentsOf: movies)
DBManager.shared.insertMoviesToDB(movies: movies)
}
self.reloadTableView()
}
}
}
else {
}
}
}
}
// MARK: UITableViewDataSource & Delegate Methods Methods
extension MoviesListViewController : UITableViewDataSource,UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if(moviesList.count == 0){
tableView.setEmptyMessage("No data found. Check your internet connection")
}else{
tableView.restore()
}
return moviesList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "MoviesListTableViewCell", for: indexPath) as? MoviesListTableViewCell else{
return UITableViewCell()
}
cell.labelMovieName.text = moviesList[indexPath.row].title ?? "Default Title"
cell.labelReleaseDate.text = moviesList[indexPath.row].releaseDate ?? "Default Date"
if let imageUrl = moviesList[indexPath.row].posterPath{
cell.imgMovieThumbnail.kf.setImage(with: URL(string: WebServiceAPIConstants.imageURL + imageUrl))
}else{
cell.imgMovieThumbnail.image = nil
}
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 95
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let movieDetailViewControllerObj = self.storyboard?.instantiateViewController(withIdentifier: "MovieDetailViewController") as? MovieDetailViewController else { return }
movieDetailViewControllerObj.movieDetails = moviesList[indexPath.row]
self.navigationController?.pushViewController(movieDetailViewControllerObj, animated: true)
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if(indexPath.row == (moviesList.count) - 1){
if(currentPage <= totalPage){
getMovieList(currentPage: currentPage)
currentPage += 1
}
}
}
}
| 32.141935 | 182 | 0.600562 |
d58ade4b95dcf59c2e79c886c8397cb3ab66c218 | 2,153 | //
// AppDelegate.swift
// ASDKPlainNodeTest
//
// Created by Adlai Holler on 12/4/15.
// Copyright © 2015 Adlai Holler. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 45.808511 | 285 | 0.754761 |
ed24a48d3947490a1562dc8d8a0e5a53161e4183 | 2,320 | //
// ViewController.swift
// Custom-AVFoundation-Camera
//
// Created by Edward Prokopik on 3/24/20.
// Copyright © 2020 Edward Prokopik. All rights reserved.
//
import UIKit
import AVFoundation
class ViewController: UIViewController {
let session = AVCaptureSession()
var camera: AVCaptureDevice?
var cameraPreviewLayer: AVCaptureVideoPreviewLayer?
var cameraCaptureOutput: AVCapturePhotoOutput?
@IBOutlet weak var previewImage: UIImageView!
@IBAction func takePictureButton(_ sender: UIButton) {
let settings = AVCapturePhotoSettings()
cameraCaptureOutput?.capturePhoto(with: settings, delegate: self)
}
override func viewDidLoad() {
super.viewDidLoad()
initCaptureSession()
}
func initCaptureSession() {
session.sessionPreset = AVCaptureSession.Preset.high
camera = AVCaptureDevice.default(for: AVMediaType.video)
do {
if let availableCamera = camera {
let cameraCaptureInput = try AVCaptureDeviceInput(device: availableCamera)
cameraCaptureOutput = AVCapturePhotoOutput()
session.addInput(cameraCaptureInput)
session.addOutput(cameraCaptureOutput!)
} else {
print("no available camera")
}
} catch {
print(error.localizedDescription)
}
cameraPreviewLayer = AVCaptureVideoPreviewLayer(session: session)
cameraPreviewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
let bounds = CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height / 1.5)
cameraPreviewLayer?.frame = bounds
if let layer = cameraPreviewLayer {
view.layer.insertSublayer(layer, at: 0)
}
session.startRunning()
}
}
extension ViewController: AVCapturePhotoCaptureDelegate {
func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
if let unwrappedError = error {
print(unwrappedError.localizedDescription)
} else {
print("image captured")
let image = photo.fileDataRepresentation()
previewImage.image = UIImage(data: image!)
}
}
}
| 30.12987 | 117 | 0.653448 |
e24ee64e4b085ab6a50cb7875be6cfbe1edf3fac | 1,403 | // RUN: %target-typecheck-verify-swift -verify-ignore-unknown -swift-version 4 -enable-experimental-enum-codable-derivation
// Simple enums where Codable conformance is added in extensions should derive
// conformance.
enum SimpleEnum {
case a(x: Int, y: Double)
case b(z: String)
func foo() {
// They should receive a synthesized CodingKeys enum.
let _ = SimpleEnum.CodingKeys.self
let _ = SimpleEnum.ACodingKeys.self
let _ = SimpleEnum.BCodingKeys.self
// The enum should have a case for each of the cases.
let _ = SimpleEnum.CodingKeys.a
let _ = SimpleEnum.CodingKeys.b
// The enum should have a case for each of the vars.
let _ = SimpleEnum.ACodingKeys.x
let _ = SimpleEnum.ACodingKeys.y
let _ = SimpleEnum.BCodingKeys.z
}
}
extension SimpleEnum : Codable {
}
// They should receive synthesized init(from:) and an encode(to:).
let _ = SimpleEnum.init(from:)
let _ = SimpleEnum.encode(to:)
// The synthesized CodingKeys type should not be accessible from outside the
// enum.
let _ = SimpleEnum.CodingKeys.self // expected-error {{'CodingKeys' is inaccessible due to 'private' protection level}}
let _ = SimpleEnum.ACodingKeys.self // expected-error {{'ACodingKeys' is inaccessible due to 'private' protection level}}
let _ = SimpleEnum.BCodingKeys.self // expected-error {{'BCodingKeys' is inaccessible due to 'private' protection level}}
| 35.974359 | 123 | 0.730577 |
cc18fc02b07d2d0eb7dea53ee6394c81fd06398b | 1,924 | // Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
// This file was auto-autogenerated by scripts and templates at http://github.com/AudioKit/AudioKitDevTools/
import AVFoundation
import CAudioKit
/// Table-lookup panning with linear interpolation
public class AutoPanner: Node {
let input: Node
/// Connected nodes
public var connections: [Node] { [input] }
/// Underlying AVAudioNode
public var avAudioNode = instantiate(effect: "apan")
// MARK: - Parameters
/// Specification details for frequency
public static let frequencyDef = NodeParameterDef(
identifier: "frequency",
name: "Frequency (Hz)",
address: akGetParameterAddress("AutoPannerParameterFrequency"),
defaultValue: 10.0,
range: 0.0 ... 100.0,
unit: .hertz)
/// Frequency (Hz)
@Parameter(frequencyDef) public var frequency: AUValue
/// Specification details for depth
public static let depthDef = NodeParameterDef(
identifier: "depth",
name: "Depth",
address: akGetParameterAddress("AutoPannerParameterDepth"),
defaultValue: 1.0,
range: 0.0 ... 1.0,
unit: .generic)
/// Depth
@Parameter(depthDef) public var depth: AUValue
// MARK: - Initialization
/// Initialize this auto panner node
///
/// - Parameters:
/// - input: Input node to process
/// - frequency: Frequency (Hz)
/// - depth: Depth
/// - waveform: Shape of the curve
///
public init(
_ input: Node,
frequency: AUValue = frequencyDef.defaultValue,
depth: AUValue = depthDef.defaultValue,
waveform: Table = Table(.positiveSine)
) {
self.input = input
setupParameters()
au.setWavetable(waveform.content)
self.frequency = frequency
self.depth = depth
}
}
| 27.485714 | 108 | 0.635655 |
ab859200b39b76780e0ac29e384d59e03076dee0 | 2,744 | //
// AzMEInAppNotificationView.swift
// Engagement
//
// Created by Microsoft on 18/02/2016.
// Copyright © 2016 Microsoft. All rights reserved.
//
import UIKit
/// Local Fake InApp AzME notification
class AzMEInAppNotificationView: UIView {
@IBOutlet var ibRootView: UIView!
@IBOutlet weak var ibTitleLabel: UILabel!
@IBOutlet weak var ibMessageLabel: UILabel!
@IBOutlet weak var ibContentView: UIView!
@IBOutlet weak var ibCloseButton: UIButton!
private var announcementVM: AnnouncementViewModel?
//MARK: Initialization
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
init(announcement: AnnouncementViewModel){
self.announcementVM = announcement
super.init(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
self.commonInit()
}
func commonInit() {
NSBundle.mainBundle().loadNibNamed("AzMEInAppNotificationView", owner: self, options: nil)
self.frame = self.ibRootView.frame
self.addSubview(self.ibRootView)
ibTitleLabel.textColor = UIColor(named: UIColor.Name.GeneralText)
ibTitleLabel.font = UIFont(named: UIFont.AppFont.Medium, size: 17)
ibMessageLabel.textColor = UIColor(named: UIColor.Name.SecondaryText)
ibMessageLabel.font = UIFont(named: UIFont.AppFont.Regular, size: 15)
self.ibTitleLabel.text = self.announcementVM?.title
self.ibMessageLabel.text = self.announcementVM?.body
ibCloseButton.setImage(AzIcon.iconClose(18).imageWithSize(CGSize(width: 18, height: 18)).imageWithRenderingMode(.AlwaysTemplate),
forState: .Normal)
ibCloseButton.tintColor = UIColor(named: UIColor.Name.SmallMentions)
}
func applyShadow(){
self.ibContentView.layer.cornerRadius = 5
self.ibContentView.layer.shadowOpacity = 1
self.ibContentView.layer.shadowRadius = 5
self.ibContentView.layer.shadowOffset = CGSizeZero
self.ibContentView.layer.shadowColor = UIColor.blackColor().CGColor
self.ibContentView.layer.masksToBounds = false
self.ibContentView.layer.shadowPath = UIBezierPath(rect: self.ibContentView.bounds).CGPath
}
//MARK: Actions
@IBAction func didTapCloseButton(sender: AnyObject) {
UIView.animateWithDuration(0.3,
animations: { () -> Void in
self.alpha = 0
}){ (completed) -> Void in
self.removeFromSuperview()
}
}
@IBAction func didTapActionButton(sender: AnyObject)
{
UIView.animateWithDuration(0.3,
animations: { () -> Void in
self.alpha = 0
}){ (completed) -> Void in
self.announcementVM?.action?()
self.removeFromSuperview()
}
}
}
| 30.153846 | 133 | 0.702259 |
03a1b8a7194704ced04ce826d8627ccaf8ae3f1d | 11,923 | //
// ThumbnailLinkCell.swift
// reddift
//
// Created by sonson on 2016/10/05.
// Copyright © 2016年 sonson. All rights reserved.
//
class ThumbnailLinkCell: LinkCell, ImageDownloadable, ImageViewAnimator {
var titleTextViewHeightConstraint: NSLayoutConstraint?
let thumbnailImageView = UIImageView(frame: CGRect.zero)
let activityIndicatorViewOnThumbnail = UIActivityIndicatorView(activityIndicatorStyle: .gray)
let titleAndThumbnailBaseView = UIView(frame: CGRect.zero)
static let horizontalLeftMargin = CGFloat(8)
static let horizontalCenterMargin = CGFloat(8)
static let horizontalRightMargin = CGFloat(8)
static let thumbnailWidth = CGFloat(88)
static let thumbnailHeight = CGFloat(88)
func targetImageView(thumbnail: Thumbnail) -> UIImageView? {
return self.container?.link.id == thumbnail.parentID ? thumbnailImageView : nil
}
func imageViews() -> [UIImageView] {
return [thumbnailImageView]
}
static func textAreaWidth(_ width: CGFloat) -> CGFloat {
return width - thumbnailWidth - horizontalLeftMargin - horizontalCenterMargin - horizontalRightMargin
}
override class func estimateTitleSize(attributedString: NSAttributedString, withBountWidth: CGFloat, margin: UIEdgeInsets) -> CGSize {
let constrainedWidth = ThumbnailLinkCell.textAreaWidth(withBountWidth)
return UZTextView.size(for: attributedString, withBoundWidth: constrainedWidth, margin: UIEdgeInsets.zero)
}
override class func estimateHeight(titleHeight: CGFloat) -> CGFloat {
let thumbnailHeight = ThumbnailLinkCell.thumbnailHeight
let h = titleHeight > thumbnailHeight ? titleHeight : thumbnailHeight
return ThumbnailLinkCell.verticalTopMargin + h + ThumbnailLinkCell.verticalBotttomMargin + ContentInfoView.height + ContentToolbar.height
}
func updateTitleTextViewHeightConstraintWith(_ height: CGFloat) {
if let t = titleTextViewHeightConstraint {
t.constant = height
} else {
let heightConstraint = NSLayoutConstraint(item: titleTextView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: height)
titleTextView.addConstraint(heightConstraint)
titleTextViewHeightConstraint = heightConstraint
}
}
override var container: LinkContainable? {
didSet {
if let container = container as? ThumbnailLinkContainer {
updateTitleTextViewHeightConstraintWith(container.titleSize.height)
self.setNeedsUpdateConstraints()
setImage(of: container
.thumbnailURL)
}
}
}
// MARK: - UIViewController
override func awakeFromNib() {
super.awakeFromNib()
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setup()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setup()
}
override func prepareForReuse() {
super.prepareForReuse()
thumbnailImageView.image = nil
activityIndicatorViewOnThumbnail.isHidden = false
activityIndicatorViewOnThumbnail.startAnimating()
activityIndicatorViewOnThumbnail.isHidden = false
activityIndicatorViewOnThumbnail.startAnimating()
}
// MARK: - Setup
func setupTitleAndThumbnailBaseViewConstraints() {
titleTextView.translatesAutoresizingMaskIntoConstraints = false
thumbnailImageView.translatesAutoresizingMaskIntoConstraints = false
activityIndicatorViewOnThumbnail.translatesAutoresizingMaskIntoConstraints = false
let views = [
"thumbnailImageView": thumbnailImageView,
"titleTextView": titleTextView
] as [String: Any]
let metrics = [
"horizontalCenterMargin": ThumbnailLinkCell.horizontalCenterMargin
]
self.contentView.addConstraints (
NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[titleTextView]-horizontalCenterMargin-[thumbnailImageView]-0-|", options: NSLayoutFormatOptions(), metrics: metrics, views: views)
)
do {
let centerx = NSLayoutConstraint(item: thumbnailImageView, attribute: .centerX, relatedBy: .equal, toItem: activityIndicatorViewOnThumbnail, attribute: .centerX, multiplier: 1, constant: 0)
titleAndThumbnailBaseView.addConstraint(centerx)
let centery = NSLayoutConstraint(item: thumbnailImageView, attribute: .centerY, relatedBy: .equal, toItem: activityIndicatorViewOnThumbnail, attribute: .centerY, multiplier: 1, constant: 0)
titleAndThumbnailBaseView.addConstraint(centery)
}
do {
let centery = NSLayoutConstraint(item: titleAndThumbnailBaseView, attribute: .centerY, relatedBy: .equal, toItem: titleTextView, attribute: .centerY, multiplier: 1, constant: 0)
titleAndThumbnailBaseView.addConstraint(centery)
}
do {
let widthConstraint = NSLayoutConstraint(item: thumbnailImageView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: ThumbnailLinkCell.thumbnailWidth)
thumbnailImageView.addConstraint(widthConstraint)
let heightConstraint = NSLayoutConstraint(item: thumbnailImageView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: ThumbnailLinkCell.thumbnailHeight)
thumbnailImageView.addConstraint(heightConstraint)
let centery = NSLayoutConstraint(item: titleAndThumbnailBaseView, attribute: .centerY, relatedBy: .equal, toItem: thumbnailImageView, attribute: .centerY, multiplier: 1, constant: 0)
titleAndThumbnailBaseView.addConstraint(centery)
}
}
func setupTitleAndThumbnailBaseView() {
titleAndThumbnailBaseView.addSubview(titleTextView)
titleAndThumbnailBaseView.addSubview(thumbnailImageView)
titleAndThumbnailBaseView.addSubview(activityIndicatorViewOnThumbnail)
activityIndicatorViewOnThumbnail.startAnimating()
}
override func setupConstraints() {
contentInfoView.translatesAutoresizingMaskIntoConstraints = false
contentToolbar.translatesAutoresizingMaskIntoConstraints = false
titleAndThumbnailBaseView.translatesAutoresizingMaskIntoConstraints = false
let views = [
"titleAndThumbnailBaseView": titleAndThumbnailBaseView,
"contentInfoView": contentInfoView,
"contentToolbar": contentToolbar
]
let metric = [
"horizontalLeftMargin": ThumbnailLinkCell.horizontalLeftMargin,
"horizontalRightMargin": ThumbnailLinkCell.horizontalRightMargin,
"verticalTopMargin": LinkCell.verticalTopMargin,
"verticalBottomMargin": LinkCell.verticalBotttomMargin,
"contentInfoViewHeight": ContentInfoView.height,
"contentToolbarHeight": ContentToolbar.height
]
["contentInfoView", "contentToolbar"].forEach({
self.contentView.addConstraints (
NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[\($0)]-0-|", options: NSLayoutFormatOptions(), metrics: nil, views: views)
)
})
self.contentView.addConstraints (
NSLayoutConstraint.constraints(withVisualFormat: "H:|-horizontalLeftMargin-[titleAndThumbnailBaseView]-horizontalRightMargin-|", options: NSLayoutFormatOptions(), metrics: metric, views: views)
)
self.contentView.addConstraints (
NSLayoutConstraint.constraints(withVisualFormat: "V:|-verticalTopMargin-[titleAndThumbnailBaseView]-verticalBottomMargin-[contentInfoView(==contentInfoViewHeight)]-0-[contentToolbar(==contentToolbarHeight)]-0-|", options: NSLayoutFormatOptions(), metrics: metric, views: views)
)
}
override func setupDispatching() {
super.setupDispatching()
let rec = UITapGestureRecognizer(target: self, action: #selector(ThumbnailLinkCell.didTapGesture(recognizer:)))
titleAndThumbnailBaseView.addGestureRecognizer(rec)
}
override func setupViews() {
selectionStyle = .none
layoutMargins = UIEdgeInsets.zero
separatorInset = UIEdgeInsets.zero
thumbnailImageView.clipsToBounds = true
thumbnailImageView.contentMode = .scaleAspectFill
titleTextView.isUserInteractionEnabled = false
titleTextView.backgroundColor = UIColor.clear
titleAndThumbnailBaseView.backgroundColor = UIColor.clear
self.contentView.addSubview(titleAndThumbnailBaseView)
self.contentView.addSubview(contentInfoView)
self.contentView.addSubview(contentToolbar)
}
override func setup() {
setupViews()
setupConstraints()
setupTitleAndThumbnailBaseView()
setupTitleAndThumbnailBaseViewConstraints()
setupDispatching()
setupTitleAndThumbnailBaseView()
NotificationCenter.default.addObserver(self, selector: #selector(ThumbnailLinkCell.didFinishDownloading(notification:)), name: ImageDownloadableDidFinishDownloadingName, object: nil)
}
// MARK: - Action
@objc func didTapGesture(recognizer: UITapGestureRecognizer) {
if let container = container as? ThumbnailLinkContainer {
let userInfo: [String: Any] = ["link": container.link, "thumbnail": container.thumbnails[0], "view": thumbnailImageView]
NotificationCenter.default.post(name: LinkCellDidTapThumbnailNotification, object: nil, userInfo: userInfo)
}
}
// MARK: - 3D touch
override func urlAt(_ location: CGPoint, peekView: UIView) -> (URL, CGRect)? {
return nil
}
override func thumbnailAt(_ location: CGPoint, peekView: UIView) -> (Thumbnail, CGRect, LinkContainable, Int)? {
if let container = container {
let p = peekView.convert(location, to: titleAndThumbnailBaseView)
if titleAndThumbnailBaseView.frame.contains(p) {
let sourceRect = titleAndThumbnailBaseView.convert(thumbnailImageView.frame, to: peekView)
return (container.thumbnails[0], sourceRect, container, 0)
}
}
return nil
}
// MARK: - ImageDownloadable
func setImage(of url: URL) {
do {
let image = try self.cachedImageInCache(of: url)
thumbnailImageView.contentMode = .scaleAspectFill
thumbnailImageView.image = image
activityIndicatorViewOnThumbnail.isHidden = true
activityIndicatorViewOnThumbnail.stopAnimating()
} catch {
}
}
func setErrorImage() {
thumbnailImageView.contentMode = .center
thumbnailImageView.image = UIImage(named: "error")
activityIndicatorViewOnThumbnail.isHidden = true
activityIndicatorViewOnThumbnail.stopAnimating()
}
@objc func didFinishDownloading(notification: NSNotification) {
if let userInfo = notification.userInfo, let _ = userInfo[ImageDownloadableSenderKey], let url = userInfo[ImageDownloadableUrlKey] as? URL {
if let container = container as? ThumbnailLinkContainer {
if container.thumbnailURL == url {
if let _ = userInfo[ImageDownloadableErrorKey] as? NSError {
setErrorImage()
} else {
setImage(of: container.thumbnailURL)
}
}
}
}
}
}
| 45.681992 | 289 | 0.683217 |
2389a1711e89c18e39c405d88f4757ecd32fff9e | 6,947 | //
// ViewController.swift
// xDebug Toggler
//
// Created by Yunus Emre Deligöz on 14.06.2020.
// Copyright © 2020 Yunus Emre Deligöz. All rights reserved.
//
import Cocoa
import MASShortcut
class ViewController: NSViewController {
var callbackClosure: (() -> Void)?
@IBOutlet weak var showNotification: NSButton!
@IBOutlet weak var shortcutView: MASShortcutView!
@IBOutlet weak var xDebugFilePath: NSTextField!
@IBOutlet weak var phpService: NSButton!
@IBOutlet weak var php74Service: NSButton!
@IBOutlet weak var nginxService: NSButton!
@IBOutlet weak var redisService: NSButton!
@IBOutlet weak var mysqlService: NSButton!
@IBOutlet weak var dnsmasqService: NSButton!
@IBOutlet weak var allServices: NSButton!
override func viewDidLoad() {
super.viewDidLoad()
xDebugFilePath.stringValue = UserDefaults.standard.string(forKey: "xDebugFilePath") ?? ""
self.getShortcut()
self.watchShortcutKeyChanges()
self.getServiceRestarts()
self.getShowNotification()
}
override func viewDidDisappear() {
self.callbackClosure?()
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
@IBAction func findXDebugFile(_ sender: Any) {
let openPanel = NSOpenPanel()
openPanel.allowsMultipleSelection = false
openPanel.canChooseDirectories = false
openPanel.canCreateDirectories = false
openPanel.canChooseFiles = true
openPanel.directoryURL = XDebugManager.probableXDebugFileURL()
openPanel.begin { (result) -> Void in
if result == NSApplication.ModalResponse.OK {
self.xDebugFilePath.stringValue = openPanel.url!.path
}
}
}
@IBAction func saveSettings(_ sender: Any) {
if xDebugFilePath.stringValue.contains("ext-xdebug.ini") &&
(FileManager.default.isReadableFile(atPath: self.xDebugFilePath.stringValue) ||
FileManager.default.isReadableFile(atPath: self.xDebugFilePath.stringValue + ".disabled")) {
// Check for disabled state
if xDebugFilePath.stringValue.contains(".disabled") {
UserDefaults.standard.set(self.xDebugFilePath.stringValue.replacingOccurrences(of: ".disabled", with: ""), forKey: "xDebugFilePath")
} else {
UserDefaults.standard.set(self.xDebugFilePath.stringValue, forKey: "xDebugFilePath")
}
// Save shortcut
self.saveShortcut()
// Save service restarts
self.saveServiceRestarts()
// Save show notification
self.saveNotification()
self.closeSettings(sender)
} else {
XDebugManager.alertSetFilePath()
}
}
@IBAction func closeSettings(_ sender: Any) {
self.view.window?.performClose(sender)
}
func saveShortcut() {
if let shortcut = self.shortcutView.shortcutValue {
XDebugManager.saveShortcut(useModifier: Int(shortcut.modifierFlags.rawValue), useKeyCode: shortcut.keyCode)
}
}
func getShortcut() {
self.shortcutView.shortcutValue = XDebugManager.getShortcut()
}
func watchShortcutKeyChanges() {
let appDelegate: AppDelegate? = NSApplication.shared.delegate as? AppDelegate
self.shortcutView.shortcutValueChange = { (sender) in
if self.shortcutView.shortcutValue != nil {
MASShortcutMonitor.shared().register(self.shortcutView.shortcutValue, withAction: appDelegate?.toggleXDebug)
} else {
MASShortcutMonitor.shared()?.unregisterAllShortcuts()
XDebugManager.removeShortcut()
}
}
}
func saveServiceRestarts() {
// Check if all services should have restarted
UserDefaults.standard.set(self.allServices.state.rawValue, forKey:"serviceAll")
if self.allServices.state == .on {
UserDefaults.standard.set(NSControl.StateValue.off.rawValue, forKey:"servicePhp")
UserDefaults.standard.set(NSControl.StateValue.off.rawValue, forKey:"serviceNginx")
UserDefaults.standard.set(NSControl.StateValue.off.rawValue, forKey:"serviceRedis")
UserDefaults.standard.set(NSControl.StateValue.off.rawValue, forKey:"serviceMysql")
UserDefaults.standard.set(NSControl.StateValue.off.rawValue, forKey:"serviceDnsmasq")
} else {
UserDefaults.standard.set(self.phpService.state.rawValue, forKey:"servicePhp")
UserDefaults.standard.set(self.php74Service.state.rawValue, forKey: "servicePhp74")
UserDefaults.standard.set(self.nginxService.state.rawValue, forKey:"serviceNginx")
UserDefaults.standard.set(self.redisService.state.rawValue, forKey:"serviceRedis")
UserDefaults.standard.set(self.mysqlService.state.rawValue, forKey:"serviceMysql")
UserDefaults.standard.set(self.dnsmasqService.state.rawValue, forKey:"serviceDnsmasq")
}
}
func getServiceRestarts() {
self.allServices.state = NSControl.StateValue(UserDefaults.standard.integer(forKey:"serviceAll"))
self.phpService.state = NSControl.StateValue(UserDefaults.standard.integer(forKey:"servicePhp"))
self.php74Service.state = NSControl.StateValue(UserDefaults.standard.integer(forKey: "servicePhp74"))
self.nginxService.state = NSControl.StateValue(UserDefaults.standard.integer(forKey:"serviceNginx"))
self.redisService.state = NSControl.StateValue(UserDefaults.standard.integer(forKey:"serviceRedis"))
self.mysqlService.state = NSControl.StateValue(UserDefaults.standard.integer(forKey:"serviceMysql"))
self.dnsmasqService.state = NSControl.StateValue(UserDefaults.standard.integer(forKey:"serviceDnsmasq"))
}
@IBAction func toggleServices(_ sender: Any) {
if self.allServices.state == .on {
self.phpService.state = NSControl.StateValue.off
self.php74Service.state = NSControl.StateValue.off
self.nginxService.state = NSControl.StateValue.off
self.redisService.state = NSControl.StateValue.off
self.mysqlService.state = NSControl.StateValue.off
self.dnsmasqService.state = NSControl.StateValue.off
}
}
func saveNotification() {
UserDefaults.standard.set(self.showNotification.state.rawValue, forKey:"showNotification")
}
func getShowNotification() {
self.showNotification.state = NSControl.StateValue(UserDefaults.standard.integer(forKey:"showNotification"))
}
}
| 39.925287 | 148 | 0.656686 |
fea3c9496d232c5a6cb40cb429998af79c46de2b | 5,160 | //
// MastodonCompactPollViewController.swift
//
// iMast https://github.com/cinderella-project/iMast
//
// Created by rinsuki on 2019/07/26.
//
// ------------------------------------------------------------------------
//
// Copyright 2017-2019 rinsuki and other contributors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
import Mew
import Ikemen
import SnapKit
import iMastiOSCore
class MastodonCompactPollViewController: UIViewController, Instantiatable, Injectable {
typealias Input = MastodonPost
typealias Environment = MastodonUserToken
let environment: Environment
var input: Input
let titleLabel = UILabel() ※ { v in
v.text = "投票"
}
let expireLabel = UILabel() ※ { v in
v.text = "n票 / あとn日ぐらい"
v.setContentHuggingPriority(UILayoutPriority(251), for: .horizontal)
}
let descriptionLabel = UILabel() ※ { v in
v.text = "4択の中から1つ: 選択肢1 / 選択肢2 / 選択肢3 / 選択肢4"
}
var paddingConstraint: Constraint!
required init(with input: Input, environment: Environment) {
self.input = input
self.environment = environment
super.init(nibName: nil, bundle: Bundle(for: type(of: self)))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
view.layer.cornerRadius = 8
view.layer.borderWidth = 1 / UIScreen.main.scale
view.layer.borderColor = UIColor.gray.cgColor
let stackView = UIStackView(arrangedSubviews: [
UIStackView(arrangedSubviews: [
titleLabel,
expireLabel,
]) ※ { v in
v.axis = .horizontal
},
descriptionLabel,
]) ※ { v in
v.axis = .vertical
v.spacing = 4
v.isUserInteractionEnabled = false
}
self.view.addSubview(stackView)
stackView.snp.makeConstraints { snp in
self.paddingConstraint = snp.width.height.equalToSuperview().offset(-16).constraint
snp.centerX.centerY.equalToSuperview()
}
self.input(input)
}
override func loadView() {
let view = UIButton(type: .custom)
view.addTarget(self, action: #selector(self.onTapped), for: .touchUpInside)
self.view = view
}
func input(_ input: Input) {
self.input = input
guard let poll = input.poll else {
self.view.isHidden = true
return
}
self.view.isHidden = false
self.titleLabel.font = UIFont.boldSystemFont(ofSize: CGFloat(Defaults[.timelineTextFontsize]))
self.expireLabel.font = UIFont.systemFont(ofSize: CGFloat(Defaults[.timelineTextFontsize]))
self.descriptionLabel.font = UIFont.systemFont(ofSize: CGFloat(Defaults[.timelineTextFontsize]))
self.paddingConstraint.update(offset: -Defaults[.timelineTextFontsize])
var expireLabelComponents = ["\(poll.votes_count)票"]
if poll.expired {
expireLabelComponents.append("締め切り済み")
} else if let expires = poll.expires_at {
let trueRemains = expires.timeIntervalSinceNow
let remains = fabs(trueRemains)
let finished = trueRemains < 0
var remainsString: String
if remains > (24 * 60 * 60 * 1.5) {
remainsString = "\(Int(remains / (24 * 60 * 60)))日"
} else if remains > (60 * 60 * 1.5) {
remainsString = "\(Int(remains / (60 * 60)))時間"
} else if remains > (60 * 1.5) {
remainsString = "\(Int(remains / 60))分"
} else {
if finished {
remainsString = "ちょっと"
} else {
remainsString = "もうすぐ"
}
}
expireLabelComponents.append(finished ? "\(remainsString)前に終わるはずだった" : "あと\(remainsString)ぐらい")
} else {
expireLabelComponents.append("期限不定")
}
expireLabel.text = expireLabelComponents.joined(separator: " / ")
descriptionLabel.text = "\(poll.options.count)択の中から\(poll.multiple ? "複数" : "一個")選択 : \(poll.options.map { $0.title }.joined(separator: " / "))"
}
@objc func onTapped() {
let newVC = MastodonPostDetailViewController.instantiate(self.input, environment: self.environment)
self.navigationController?.pushViewController(newVC, animated: true)
}
}
| 36.338028 | 152 | 0.601744 |
14a0c74a64418f4b724081f5bef77dbe7b96de76 | 1,483 | // Copyright © 2020 Mark Moeykens. All rights reserved. | @BigMtnStudio
import SwiftUI
struct MGE_WhatCouldGoWrong_PositioningSolution: View {
@State private var showView2 = false
@Namespace var namespace
var body: some View {
VStack(spacing: 20.0) {
TitleText("MatchedGeometryEffect")
SubtitleText("Positioning Solution")
BannerText("Keep positioning modifiers below the matchedGeometryEffect for more predictable results.", backColor: .green, textColor: .black)
Spacer()
if showView2 {
RoundedRectangle(cornerRadius: 25)
.fill(Color.green)
.overlay(Text("View 2"))
.matchedGeometryEffect(id: "change", in: namespace)
.onTapGesture { showView2.toggle() }
} else {
RoundedRectangle(cornerRadius: 25)
.fill(Color.green)
.overlay(Text("View 1"))
.matchedGeometryEffect(id: "change", in: namespace)
.offset(x: -130)
.frame(width: 100, height: 100)
.onTapGesture { showView2.toggle() }
}
}
.animation(.default)
.font(.title)
}
}
struct MGE_WhatCouldGoWrong_PositioningSolution_Previews: PreviewProvider {
static var previews: some View {
MGE_WhatCouldGoWrong_PositioningSolution()
}
}
| 35.309524 | 152 | 0.567768 |
26e19edccb7142bc05354ad528e6cf62a4040335 | 1,693 | import UsercentricsUI
extension ButtonLayout {
static func from(dict: [[NSDictionary]]?, fallbackFont: UIFont?, assetProvider: FlutterAssetProvider) -> ButtonLayout? {
guard let dict = dict else { return nil }
return .grid(buttons: dict.map { $0.compactMap { button in ButtonSettings(from: button, fallbackFont: fallbackFont, assetProvider: assetProvider) }})
}
}
extension ButtonSettings {
init?(from dict: NSDictionary?, fallbackFont: UIFont?, assetProvider: FlutterAssetProvider) {
guard
let dict = dict,
let buttonTypeValue = dict["type"] as? String,
let buttonType = ButtonType.from(enumString: buttonTypeValue)
else { return nil }
let font = UIFont.initialize(from: dict["fontAssetPath"] as? String,
fontSizeValue: dict["textSize"] as? CGFloat,
fallbackFont: fallbackFont,
assetProvider: assetProvider)
self.init(type: buttonType,
font: font,
textColor: UIColor(unsafeHex: dict["textColor"] as? String),
backgroundColor: UIColor(unsafeHex: dict["backgroundColor"] as? String),
cornerRadius: dict["cornerRadius"] as? CGFloat)
}
}
extension ButtonType {
static func from(enumString: String) -> ButtonType? {
switch enumString {
case "ACCEPT_ALL":
return .acceptAll
case "DENY_ALL":
return .denyAll
case "MORE":
return .more
case "SAVE":
return .save
default:
return nil
}
}
}
| 35.270833 | 157 | 0.579445 |
7a857c0af53a74d5ffb0c9a3d599cc8e6bb865d3 | 350 | //
// XCTestManifests.swift
// Swiftgres
//
// Copyright © 2016 David Piper, @_dpiper
//
// This software may be modified and distributed under the terms
// of the MIT license. See the LICENSE file for details.
//
#if !os(macOS)
import XCTest
public func allTests() -> [XCTestCaseEntry] {
return [
testCase(ASmokeTest.allTests)
]
}
#endif
| 18.421053 | 64 | 0.697143 |
9be4858082761fb61966c3faeca50e53a640b06c | 653 | // RendererAction.swift
// Copyright (c) 2020 Dylan Gattey
import Foundation
import Metal
/// All possible actions the renderer has to respond to
enum RendererAction {
/// Evicts one chunk from the list of existing chunks
case evictChunk(Chunk)
/// Generates one chunk in the list of existing chunks
case generateChunk(Chunk)
/// Updates the user position to a new position in a drawable size
case updateUserPosition(to: MTLViewport, inDrawableSize: CGSize)
/// Updates the visible region to a new chunk region
case updateVisibleRegion(to: ChunkRegion)
/// Just redraws whatever's in range
case redrawMap
}
| 27.208333 | 70 | 0.732006 |
39d9db2725041d737336ee349f2f29aa58febad8 | 3,158 | //
// UIImageViewRotationTests.swift
// ViaSwiftUtils
//
// Copyright 2017 Viacom, 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.
@testable import ViaSwiftUtils
import XCTest
class UIImageViewRotationTests: XCTestCase {
func testIsRotating() {
// Given, When
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
// Then
XCTAssertFalse(imageView.isRotating, "Expected imageView to not be rotating before starts")
}
func testStartRotating() {
// Given, When
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
// When
imageView.startRotating()
// Then
XCTAssertTrue(imageView.isRotating, "Expected imageView to be rotating after startRotating")
}
func testStopRotating() {
// Given, When
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
// When
imageView.startRotating()
imageView.stopRotating()
// Then
XCTAssertFalse(imageView.isRotating, "Expected imageView to not be rotating after stopRotating")
}
func testSlowIsSlowerThanNormal() {
// Given, When
let slow = UIImageView.AnimationDuration.slow
let normal = UIImageView.AnimationDuration.normal
// Then
XCTAssertGreaterThan(slow.duration, normal.duration, "Expected slow duration to be slower than normal duration")
}
func testNormalIsSlowerThanFast() {
// Given, When
let normal = UIImageView.AnimationDuration.normal
let fast = UIImageView.AnimationDuration.fast
// Then
XCTAssertGreaterThan(normal.duration, fast.duration, "Expected normal duration to be slower than fast duration")
}
func testCustomIsWhatYouGiveIt() {
// Given, When
let custom = UIImageView.AnimationDuration.custom(time: 0.2)
// Then
XCTAssertEqual(custom.duration, 0.2, "Expected custom duration to be exactly what you give it")
}
func testIsRemovedOnCompletion() {
// Given
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
// When
imageView.startRotating(isRemovedOnCompletion: false)
// Then
if let animation = imageView.layer.animation(forKey: RotationAnimation.key) {
XCTAssertFalse(animation.isRemovedOnCompletion)
} else {
XCTFail("imageView is missing animation for \(RotationAnimation.key)")
}
}
}
| 32.556701 | 120 | 0.649145 |
14c5a51b31989164bb74277600ed58d5af7ec157 | 2,797 | ////
/// ProfileGeneratorSpec.swift
//
@testable import Ello
import Quick
import Nimble
class ProfileGeneratorSpec: QuickSpec {
class MockProfileDestination: StreamDestination {
var placeholderItems: [StreamCellItem] = []
var headerItems: [StreamCellItem] = []
var postItems: [StreamCellItem] = []
var otherPlaceholderLoaded = false
var user: User?
var responseConfig: ResponseConfig?
var isPagingEnabled: Bool = false
func setPlaceholders(items: [StreamCellItem]) {
placeholderItems = items
}
func replacePlaceholder(
type: StreamCellType.PlaceholderType,
items: [StreamCellItem],
completion: @escaping Block
) {
switch type {
case .profileHeader:
headerItems = items
case .streamItems:
postItems = items
default:
otherPlaceholderLoaded = true
}
}
func setPrimary(jsonable: Model) {
guard let user = jsonable as? User else { return }
self.user = user
}
func primaryModelNotFound() {
}
func setPagingConfig(responseConfig: ResponseConfig) {
self.responseConfig = responseConfig
}
}
override func spec() {
describe("ProfileGenerator") {
var destination: MockProfileDestination!
var currentUser: User!
var subject: ProfileGenerator!
beforeEach {
destination = MockProfileDestination()
currentUser = User.stub(["id": "42"])
subject = ProfileGenerator(
currentUser: currentUser,
userParam: "42",
user: currentUser,
destination: destination
)
}
describe("load()") {
it("sets 2 placeholders") {
subject.load()
expect(destination.placeholderItems.count) == 2
}
it("replaces only ProfileHeader and ProfilePosts") {
subject.load()
expect(destination.headerItems.count) > 0
expect(destination.postItems.count) > 0
expect(destination.otherPlaceholderLoaded) == false
}
it("sets the primary jsonable") {
subject.load()
expect(destination.user).toNot(beNil())
}
it("sets the config response") {
subject.load()
expect(destination.responseConfig).toNot(beNil())
}
}
}
}
}
| 29.135417 | 71 | 0.512335 |
16d08c8588a43b40e27f570abb616e72f75507e0 | 1,990 | /**
This file is part of the YBSlantedCollectionViewLayout package.
Copyright (c) 2016 Yassir Barchi <[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
/// :nodoc:
open class YBSlantedCollectionViewLayoutAttributes : UICollectionViewLayoutAttributes {
/// :nodoc:
open var slantedLayerMask :CAShapeLayer?
/// :nodoc:
override open func copy(with zone: NSZone?) -> Any {
let attributesCopy = super.copy(with: zone) as! YBSlantedCollectionViewLayoutAttributes
attributesCopy.slantedLayerMask = self.slantedLayerMask
return attributesCopy
}
/// :nodoc:
override open func isEqual(_ object: Any?) -> Bool {
if let o = object as? YBSlantedCollectionViewLayoutAttributes {
if self.slantedLayerMask != o.slantedLayerMask {
return false
}
return super.isEqual(object)
}
return false
}
}
| 36.851852 | 95 | 0.717085 |
758ec28fe54c458ec27e77fd11d47331714c3185 | 367 | import ComposableArchitecture
import Foundation
struct AudioPlayerClient {
var play: (AnyHashable, URL) -> Effect<Action, Failure>
var stop: (AnyHashable) -> Effect<Never, Never>
enum Action: Equatable {
case didFinishPlaying(successfully: Bool)
}
enum Failure: Error, Equatable {
case couldntCreateAudioPlayer
case decodeErrorDidOccur
}
}
| 21.588235 | 57 | 0.741144 |
72b83ebfd0f7fda9ee24b73ab1e6772eff4f0bcc | 7,463 | ///
/// TextFetcher_Configuration_Tests.swift
/// Created on 7/21/20
/// Copyright © 2020 Eric Reedy. All rights reserved.
///
import XCTest
@testable import TextFetcher
// MARK: - Setup / Cleanup...
///
/// TextFetcher Unit Tests - Configuration
///
class TextFetcher_Configuration_Tests: XCTestCase {
var mockTextManager: Mock_TextManager!
func resetTextFetcher(withSessionID sessionID: String) {
mockTextManager = .init()
textFetcher?.clearCaches()
textFetcher = .init(withSessionID: sessionID,
textManager: mockTextManager)
}
var textFetcher: TextFetcher!
override func tearDown() {
super.tearDown()
textFetcher?.clearCaches()
}
}
// MARK: - Tests...
///
/// Covering the following functions:
///
/// public func setResourceBundle(to bundle: Bundle)
/// public func setResourceTimeout(to timeout: TimeInterval)
/// public func setVersionSource(_ versionSource: VersionSource, withCompletion completion: (()->Void)? = nil)
///
extension TextFetcher_Configuration_Tests {
// MARK: - T - Set Resource Bundle
///
/// TextFetcher Unit Test
///
/// Tests the function:
///
/// public func setResourceBundle(to bundle: Bundle)
///
/// The following behavior is expected:
/// 1. The TextFetcher's TextManager should have its setResourceBundle(...) method called one time, with the provided bundle passed in
///
func test_setResourceBundle() {
resetTextFetcher(withSessionID: "\(Self.self).\(#function)")
var bundle: Bundle
// Pre-Behavior:
XCTAssertEqual(mockTextManager.mock_setBundleCount, 0)
// Behavior #1 - 1:
bundle = Bundle(for: Self.self)
textFetcher.setResourceBundle(to: bundle)
XCTAssertEqual(mockTextManager.mock_setBundleCount, 1)
XCTAssertTrue(mockTextManager.mock_bundle === bundle)
// Behavior #1 - 2:
bundle = Bundle.main
textFetcher.setResourceBundle(to: bundle)
XCTAssertEqual(mockTextManager.mock_setBundleCount, 2)
XCTAssertTrue(mockTextManager.mock_bundle === bundle)
}
// MARK: - T - Set Resource Timeout
///
/// TextFetcher Unit Test
///
/// Tests the function:
///
/// public func setResourceTimeout(to timeout: TimeInterval)
///
/// The following behavior is expected:
/// 1. The TextFetcher's TextManager should have its setResourceTimeout(...) method called one time, with the provided TimeInterval passed in
///
func test_setResourceTimeout() {
resetTextFetcher(withSessionID: "\(Self.self).\(#function)")
var newTimeout: TimeInterval = 1234
// Pre-Behavior:
XCTAssertEqual(mockTextManager.mock_setResourceTimeoutCount, 0)
XCTAssertNotEqual(mockTextManager.mock_resourceTimeout, newTimeout)
// Behavior #1:
textFetcher.setResourceTimeout(to: newTimeout)
XCTAssertEqual(mockTextManager.mock_setResourceTimeoutCount, 1)
XCTAssertEqual(mockTextManager.mock_resourceTimeout, newTimeout)
// Behavior #2:
newTimeout = 432423
textFetcher.setResourceTimeout(to: newTimeout)
XCTAssertEqual(mockTextManager.mock_setResourceTimeoutCount, 2)
XCTAssertEqual(mockTextManager.mock_resourceTimeout, newTimeout)
}
// MARK: - T - Set Version Source
///
/// TextFetcher Unit Test
///
/// Tests the function:
///
/// public func setVersionSource(_ versionSource: VersionSource, withCompletion completion: (()->Void)? = nil)
///
/// The following behavior is expected:
/// 1. The TextFetcher's TextManager should have its setVersionSource(...) method called one time, with the provided VersionSource passed in
///
func test_setVersionSource() {
resetTextFetcher(withSessionID: "\(Self.self).\(#function)")
var newVersionSource: VersionSource
// Pre-Behavior:
XCTAssertEqual(mockTextManager.mock_setVersionSourceCount, 0)
XCTAssertNil(mockTextManager.mock_versionSource)
XCTAssertNil(mockTextManager.mock_versionSourceCompletion)
// Behavior #1 - 1:
newVersionSource = .init(bundleFile: .init(fileName: "dfdfgdffg", fileExtension: "dff"), remoteFile: .init(urlString: "sdfdfsdf"))
textFetcher.setVersionSource(to: newVersionSource, withCompletion: {})
XCTAssertEqual(mockTextManager.mock_setVersionSourceCount, 1)
XCTAssertEqual(mockTextManager.mock_versionSource?.bundleFile?.fileName, newVersionSource.bundleFile?.fileName)
XCTAssertEqual(mockTextManager.mock_versionSource?.bundleFile?.fileExtension, newVersionSource.bundleFile?.fileExtension)
XCTAssertEqual(mockTextManager.mock_versionSource?.remoteFile.urlString, newVersionSource.remoteFile.urlString)
XCTAssertNotNil(mockTextManager.mock_versionSourceCompletion)
// Behavior #1 - 2:
newVersionSource = .init(bundleFile: .init(fileName: "fghfgh", fileExtension: "htrhrth"), remoteFile: .init(urlString: "ww4w4t"))
textFetcher.setVersionSource(to: newVersionSource, withCompletion: {})
XCTAssertEqual(mockTextManager.mock_setVersionSourceCount, 2)
XCTAssertEqual(mockTextManager.mock_versionSource?.bundleFile?.fileName, newVersionSource.bundleFile?.fileName)
XCTAssertEqual(mockTextManager.mock_versionSource?.bundleFile?.fileExtension, newVersionSource.bundleFile?.fileExtension)
XCTAssertEqual(mockTextManager.mock_versionSource?.remoteFile.urlString, newVersionSource.remoteFile.urlString)
XCTAssertNotNil(mockTextManager.mock_versionSourceCompletion)
}
}
// MARK: - Mock Classes
extension TextFetcher_Configuration_Tests {
class Mock_TextManager: TextManager_TextFetcherInterface {
var mock_setBundleCount: Int = 0
var mock_bundle: Bundle?
func setResourceBundle(to bundle: Bundle) {
mock_setBundleCount += 1
mock_bundle = bundle
}
var mock_setResourceTimeoutCount: Int = 0
var mock_resourceTimeout: TimeInterval?
func setResourceTimeout(to timeout: TimeInterval) {
mock_setResourceTimeoutCount += 1
mock_resourceTimeout = timeout
}
var mock_setVersionSourceCount: Int = 0
var mock_versionSource: VersionSource?
var mock_versionSourceCompletion: (()->Void)?
func setVersionSource(to versionSource: VersionSource, withCompletion completion: (()->Void)?) {
mock_setVersionSourceCount += 1
mock_versionSource = versionSource
mock_versionSourceCompletion = completion
completion?()
}
// Unused
func setDelegate(to delegate: TextManagerDelegate?) {}
func registerTextSource(_ textSource: TextSource) {}
func cachedText(forResource resourceID: ResourceID, completion: @escaping TextRequestCompletion) {}
func latestText(forResource resourceID: ResourceID, completion: @escaping TextRequestCompletion) {}
func clearCaches() {}
}
}
| 39.909091 | 145 | 0.66354 |
643bac945ae38c4c9697b877960eb0566d6ba1a7 | 3,570 | //
// ConditionalModifier.swift
// ZamzamUI
//
// Created by Basem Emara on 2020-09-20.
// https://fivestars.blog/swiftui/conditional-modifiers.html
// https://forums.swift.org/t/conditionally-apply-modifier-in-swiftui
//
// Copyright © 2020 Zamzam Inc. All rights reserved.
//
import SwiftUI
public extension View {
/// Applies a modifier to a view conditionally.
///
/// someView
/// .modifier(if: model == nil) {
/// $0.redacted(reason: .placeholder )
/// }
///
/// - Parameters:
/// - condition: The condition to determine if the content should be applied.
/// - content: The modifier to apply to the view.
/// - Returns: The modified view.
@ViewBuilder func modifier<T: View>(
if condition: Bool,
then content: (Self) -> T
) -> some View {
if condition {
content(self)
} else {
self
}
}
/// Applies a modifier to a view conditionally.
///
/// someView
/// .modifier(if: model == nil) {
/// $0.redacted(reason: .placeholder )
/// } else: {
/// $0.unredacted()
/// }
///
/// - Parameters:
/// - condition: The condition to determine the content to be applied.
/// - trueContent: The modifier to apply to the view if the condition passes.
/// - falseContent: The modifier to apply to the view if the condition fails.
/// - Returns: The modified view.
@ViewBuilder func modifier<TrueContent: View, FalseContent: View>(
if condition: Bool,
then trueContent: (Self) -> TrueContent,
else falseContent: (Self) -> FalseContent
) -> some View {
if condition {
trueContent(self)
} else {
falseContent(self)
}
}
}
public extension View {
/// Applies a modifier to a view if an optional item can be unwrapped.
///
/// someView
/// .modifier(let: model) {
/// $0.background(BackgroundView(model.bg))
/// }
///
/// - Parameters:
/// - condition: The optional item to determine if the content should be applied.
/// - content: The modifier and unwrapped item to apply to the view.
/// - Returns: The modified view.
@ViewBuilder func modifier<T: View, Item>(
`let` item: Item?,
then content: (Self, Item) -> T
) -> some View {
if let item = item {
content(self, item)
} else {
self
}
}
/// Applies a modifier to a view if an optional item can be unwrapped.
///
/// someView
/// .modifier(let: model) {
/// $0.background(BackgroundView(model.bg))
/// } else: {
/// $0.background(Color.black)
/// }
///
/// - Parameters:
/// - condition: The optional item to determine if the content should be applied.
/// - trueContent: The modifier and unwrapped item to apply to the view.
/// - falseContent: The modifier to apply to the view if the condition fails.
/// - Returns: The modified view.
@ViewBuilder func modifier<Item, TrueContent: View, FalseContent: View>(
`let` item: Item?,
then trueContent: (Self, Item) -> TrueContent,
else falseContent: (Self) -> FalseContent
) -> some View {
if let item = item {
trueContent(self, item)
} else {
falseContent(self)
}
}
}
| 31.59292 | 87 | 0.545938 |
bf4e325829c7b06a912ec48f900e2726c66dc6eb | 399 | //
// LabelComponent.swift
// UIComponents
//
import UIKit
open class LabelComponent: InitView, LabelContainer {
// MARK: - UI elements
open var label: UILabel = UILabel() {
didSet {
oldValue.removeFromSuperview()
addSubview(label)
}
}
// MARK: - Init configure
open override func initConfigure() {
super.initConfigure()
addSubview(label)
}
}
| 15.346154 | 53 | 0.636591 |
f5412397657563413411df2f8da3182d99030c9b | 1,289 | ////
//// MKScrollController.swift
//// MiaoKiit
////
//// Created by miaokii on 2021/5/19.
////
//
//import UIKit
//
//class MKScrollController: UIViewController {
//
// /// 滑动视图,懒加载
// public lazy var scrollView: UIScrollView = {
// let scrollView = UIScrollView.init()
// scrollView.backgroundColor = .clear
// scrollView.bounces = true
// scrollView.alwaysBounceVertical = true
// view.addSubview(scrollView)
// scrollView.snp.makeConstraints { (make) in
// make.edges.equalToSuperview()
// }
// return scrollView
// }()
//
// /// 懒加载 滑动视图的内容视图,所有的子元素都放在这里面
// ///
// /// 子元素布局首尾相接,就会撑开整个视图,从而滑动
// /// 如果布局设置正确,scrollView的cotentsize就会自动计算,不需重手动设置
// public lazy var scrollContainer: UIView = {
// let container = UIView()
// container.backgroundColor = .clear
// scrollView.addSubview(container)
// container.snp.makeConstraints { (make) in
// make.edges.equalTo(0)
// make.width.equalTo(screenWidth)
// }
// return container
// }()
//
// open override func viewDidLoad() {
// super.viewDidLoad()
// addScrollSubViews()
// }
//
// /// 在该方法添加子视图
// open func addScrollSubViews() {
//
// }
//}
//
| 25.27451 | 54 | 0.577192 |
ed01a1ed181266eecb60a5526605219b7c5c65a9 | 6,738 | //
// BaseSubscriptionCell.swift
// Rocket.Chat
//
// Created by Samar Sunkaria on 7/18/18.
// Copyright © 2018 Rocket.Chat. All rights reserved.
//
import UIKit
protocol SubscriptionCellProtocol {
var subscription: Subscription? { get set }
}
class BaseSubscriptionCell: UITableViewCell, SubscriptionCellProtocol {
internal let defaultBackgroundColor = UIColor.white
internal let selectedBackgroundColor = #colorLiteral(red: 0.4980838895, green: 0.4951269031, blue: 0.5003594756, alpha: 0.19921875)
internal let highlightedBackgroundColor = #colorLiteral(red: 0.4980838895, green: 0.4951269031, blue: 0.5003594756, alpha: 0.09530179799)
var subscription: Subscription? {
didSet {
guard let subscription = subscription, !subscription.isInvalidated else { return }
updateSubscriptionInformation()
}
}
@IBOutlet weak var viewStatus: UIView! {
didSet {
viewStatus.backgroundColor = .RCInvisible()
viewStatus.layer.masksToBounds = true
viewStatus.layer.cornerRadius = 5
}
}
weak var avatarView: AvatarView!
@IBOutlet weak var avatarViewContainer: UIView! {
didSet {
avatarViewContainer.layer.cornerRadius = 4
avatarViewContainer.layer.masksToBounds = true
if let avatarView = AvatarView.instantiateFromNib() {
avatarView.frame = avatarViewContainer.bounds
avatarViewContainer.addSubview(avatarView)
self.avatarView = avatarView
}
}
}
@IBOutlet weak var labelUnreadRightSpacingConstraint: NSLayoutConstraint! {
didSet {
labelUnreadRightSpacingConstraint.constant = UIDevice.current.userInterfaceIdiom == .pad ? 8 : 0
}
}
@IBOutlet weak var iconRoom: UIImageView!
@IBOutlet weak var labelName: UILabel!
@IBOutlet weak var labelUnread: UILabel!
@IBOutlet weak var viewUnread: UIView! {
didSet {
viewUnread.layer.cornerRadius = 4
}
}
override func prepareForReuse() {
super.prepareForReuse()
avatarView.prepareForReuse()
labelName.text = nil
labelUnread.text = nil
viewUnread.isHidden = true
}
func updateSubscriptionInformation() {
guard let subscription = self.subscription else { return }
var user: User?
if subscription.type == .directMessage {
user = subscription.directMessageUser
}
updateStatus(subscription: subscription, user: user)
if let user = user {
avatarView.subscription = nil
avatarView.user = user
} else {
avatarView.user = nil
avatarView.subscription = subscription
}
labelName.text = subscription.displayName()
if subscription.unread > 0 || subscription.alert {
updateViewForAlert(with: subscription)
} else {
updateViewForNoAlert(with: subscription)
}
}
func updateViewForAlert(with subscription: Subscription) {
labelName.font = UIFont.systemFont(ofSize: labelName.font.pointSize, weight: .semibold)
labelUnread.font = UIFont.boldSystemFont(ofSize: labelUnread.font.pointSize)
if subscription.unread > 0 {
viewUnread.isHidden = false
if subscription.groupMentions > 0 || subscription.userMentions > 0 {
labelUnread.text = "@\(subscription.unread)"
} else {
labelUnread.text = "\(subscription.unread)"
}
} else {
viewUnread.isHidden = false
labelUnread.text = "!"
}
}
func updateViewForNoAlert(with subscription: Subscription) {
labelName.font = UIFont.systemFont(ofSize: labelName.font.pointSize, weight: .medium)
viewUnread.isHidden = true
labelUnread.text = nil
}
var userStatus: UserStatus? {
didSet {
if let userStatus = userStatus {
switch userStatus {
case .online: viewStatus.backgroundColor = .RCOnline()
case .busy: viewStatus.backgroundColor = .RCBusy()
case .away: viewStatus.backgroundColor = .RCAway()
case .offline: viewStatus.backgroundColor = .RCInvisible()
}
}
}
}
fileprivate func updateStatus(subscription: Subscription, user: User?) {
if subscription.type == .directMessage {
viewStatus.isHidden = false
iconRoom.isHidden = true
if let user = user {
userStatus = user.status
}
} else {
iconRoom.isHidden = false
viewStatus.isHidden = true
if subscription.type == .channel {
iconRoom.image = UIImage(named: "Cell Subscription Hashtag")
} else {
iconRoom.image = UIImage(named: "Cell Subscription Lock")
}
}
}
}
extension BaseSubscriptionCell {
override func setSelected(_ selected: Bool, animated: Bool) {
let transition = {
switch selected {
case true:
self.backgroundColor = self.theme?.bannerBackground ?? self.selectedBackgroundColor
case false:
self.backgroundColor = self.theme?.backgroundColor ?? self.defaultBackgroundColor
}
}
if animated {
UIView.animate(withDuration: 0.18, animations: transition)
} else {
transition()
}
}
override func setHighlighted(_ highlighted: Bool, animated: Bool) {
let transition = {
switch highlighted {
case true:
self.backgroundColor = self.theme?.auxiliaryBackground ?? self.highlightedBackgroundColor
case false:
self.backgroundColor = self.theme?.backgroundColor ?? self.defaultBackgroundColor
}
}
if animated {
UIView.animate(withDuration: 0.18, animations: transition)
} else {
transition()
}
}
}
// MARK: Themeable
extension BaseSubscriptionCell {
override func applyTheme() {
super.applyTheme()
guard let theme = theme else { return }
labelName.textColor = theme.titleText
viewUnread.backgroundColor = theme.tintColor
labelUnread.backgroundColor = theme.tintColor
labelUnread.textColor = theme.backgroundColor
iconRoom.tintColor = theme.auxiliaryText
setSelected(isSelected, animated: false)
setHighlighted(isHighlighted, animated: false)
}
}
| 31.194444 | 141 | 0.610122 |
893a5c6d95e6df749b2f689f6de24927ddd1b99d | 1,127 | //
// TaskEstimateTableCellView.swift
// FocusPlan
//
// Created by Vojtech Rinik on 4/26/17.
// Copyright © 2017 Median. All rights reserved.
//
import Foundation
import AppKit
import ReactiveSwift
import ReactiveCocoa
import NiceKit
class TaskEstimateTableCellView: EditableTableCellView {
var task = MutableProperty<Task?>(nil)
override func awakeFromNib() {
super.awakeFromNib()
guard let field = textField else { return }
field.font = NSFont.systemFont(ofSize: 13, weight: NSFontWeightRegular)
field.textColor = NSColor(hexString: "9099A3")
field.drawsBackground = false
field.backgroundColor = NSColor.clear
let minutesLabel = task.producer.pick({ $0.reactive.estimatedMinutesFormatted.producer })
field.reactive.stringValue <~ minutesLabel.map({ $0 ?? "" })
}
override func controlTextDidEndEditing(_ obj: Notification) {
super.controlTextDidEndEditing(obj)
let value = textField?.stringValue ?? ""
self.task.value?.setEstimate(fromString: value)
}
}
| 28.175 | 97 | 0.665484 |
7a83bc8b4b515a98c50e1dcd0c24cd568a902691 | 40,290 | /*
* Copyright (c) 2019, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
import Foundation
public class MeshNetworkManager {
/// Mesh Network data.
private var meshData: MeshData
/// The Network Layer handler.
private var networkManager: NetworkManager?
/// Storage to keep the app data.
private let storage: Storage
/// A queue to handle incoming and outgoing messages.
internal let queue: DispatchQueue
/// A queue to call delegate methods on.
internal let delegateQueue: DispatchQueue
/// The Proxy Filter state.
public internal(set) var proxyFilter: ProxyFilter?
/// The logger delegate will be called whenever a new log entry is created.
public weak var logger: LoggerDelegate?
/// The delegate will receive callbacks whenever a complete
/// Mesh Message has been received and reassembled.
public weak var delegate: MeshNetworkDelegate?
/// The sender object should send PDUs created by the manager
/// using any Bearer.
public weak var transmitter: Transmitter?
// MARK: - Network Manager properties
/// The Default TTL will be used for sending messages, if the value has
/// not been set in the Provisioner's Node. By default it is set to 5,
/// which is a reasonable value. The TTL shall be in range 2...127.
public var defaultTtl: UInt8 = 5
/// The timeout after which an incomplete segmented message will be
/// abandoned. The timer is restarted each time a segment of this
/// message is received.
///
/// The incomplete timeout should be set to at least 10 seconds.
public var incompleteMessageTimeout: TimeInterval = 10.0
/// The amount of time after which the lower transport layer sends a
/// Segment Acknowledgment message after receiving a segment of a
/// multi-segment message where the destination is a Unicast Address
/// of the Provisioner's Element.
///
/// The acknowledgment timer shall be set to a minimum of
/// 150 + 50 * TTL milliseconds. The TTL dependent part is added
/// automatically, and this value shall specify only the constant part.
public var acknowledgmentTimerInterval: TimeInterval = 0.150
/// The time within which a Segment Acknowledgment message is
/// expected to be received after a segment of a segmented message has
/// been sent. When the timer is fired, the non-acknowledged segments
/// are repeated, at most `retransmissionLimit` times.
///
/// The transmission timer shall be set to a minimum of
/// 200 + 50 * TTL milliseconds. The TTL dependent part is added
/// automatically, and this value shall specify only the constant part.
///
/// If the bearer is using GATT, it is recommended to set the transmission
/// interval longer than the connection interval, so that the acknowledgment
/// had a chance to be received.
public var transmissionTimerInteral: TimeInterval = 0.200
/// Number of times a non-acknowledged segment of a segmented message
/// will be retransmitted before the message will be cancelled.
///
/// The limit may be decreased with increasing of `transmissionTimerInterval`
/// as the target Node has more time to reply with the Segment
/// Acknowledgment message.
public var retransmissionLimit: Int = 5
/// If the Element does not receive a response within a period of time known
/// as the acknowledged message timeout, then the Element may consider the
/// message has not been delivered, without sending any additional messages.
///
/// The `meshNetworkManager(_:failedToSendMessage:from:to:error)`
/// callback will be called on timeout.
///
/// The acknowledged message timeout should be set to a minimum of 30 seconds.
public var acknowledgmentMessageTimeout: TimeInterval = 30.0
/// The base time after which the acknowledgmed message will be repeated.
///
/// The repeat timer will be set to the base time + 50 * TTL milliseconds +
/// 50 * segment count. The TTL and segment count dependent parts are added
/// automatically, and this value shall specify only the constant part.
public var acknowledgmentMessageInterval: TimeInterval = 2.0
/// According to Bluetooth Mesh Profile 1.0.1, section 3.10.5, if the IV Index of the mesh
/// network increased by more than 42 since the last connection (which can take at least
/// 48 weeks), the Node should be reprovisioned. However, as this library can be used to
/// provision other Nodes, it should not be blocked from sending messages to the network
/// only because the phone wasn't connected to the network for that time. This flag can
/// disable this check, effectively allowing such connection.
///
/// The same can be achieved by clearing the app data (uninstalling and reinstalling the
/// app) and importing the mesh network. With no "previous" IV Index, the library will
/// accept any IV Index received in the Secure Network beacon upon connection to the
/// GATT Proxy Node.
public var allowIvIndexRecoveryOver42: Bool = false
/// IV Update Test Mode enables efficient testing of the IV Update procedure.
/// The IV Update test mode removes the 96-hour limit; all other behavior of the device
/// are unchanged.
///
/// - seeAlso: Bluetooth Mesh Profile 1.0.1, section 3.10.5.1.
public var ivUpdateTestMode: Bool = false
// MARK: - Computed properties
/// Returns the MeshNetwork object.
public var meshNetwork: MeshNetwork? {
return meshData.meshNetwork
}
/// Returns `true` if Mesh Network has been created, `false` otherwise.
public var isNetworkCreated: Bool {
return meshData.meshNetwork != nil
}
// MARK: - Constructors
/// Initializes the MeshNetworkManager.
///
/// If storage is not provided, a local file will be used instead.
///
/// - important: Aafter the manager has been initialized, the
/// `localElements` property must be set . Otherwise,
/// none of status messages will be parsed correctly
/// and they will be returned to the delegate as
/// `UnknownMessage`s.
///
/// - parameters:
/// - storage: The storage to use to save the network configuration.
/// - queue: The DispatQueue to process reqeusts on. By default
/// the a global background queue will be used.
/// - delegateQueue: The DispatQueue to call delegate methods on.
/// By default the global main queue will be used.
/// - seeAlso: `LocalStorage`
public init(using storage: Storage = LocalStorage(),
queue: DispatchQueue = DispatchQueue.global(qos: .background),
delegateQueue: DispatchQueue = DispatchQueue.main) {
self.storage = storage
self.meshData = MeshData()
self.queue = queue
self.delegateQueue = delegateQueue
}
/// Initializes the MeshNetworkManager. It will use the `LocalStorage`
/// with the given file name.
///
/// - parameter fileName: File name to keep the configuration.
/// - seeAlso: `LocalStorage`
public convenience init(using fileName: String) {
self.init(using: LocalStorage(fileName: fileName))
}
}
// MARK: - Mesh Network API
public extension MeshNetworkManager {
/// Generates a new Mesh Network configuration with default values.
/// This method will override the existing configuration, if such exists.
/// The mesh network will contain one Provisioner with given name.
///
/// Network Keys and Application Keys must be added manually
/// using `add(networkKey:name)` and `add(applicationKey:name)`.
///
/// - parameters:
/// - name: The user given network name.
/// - provisionerName: The user given local provisioner name.
func createNewMeshNetwork(withName name: String, by provisionerName: String) -> MeshNetwork {
return createNewMeshNetwork(withName: name, by: Provisioner(name: provisionerName))
}
/// Generates a new Mesh Network configuration with default values.
/// This method will override the existing configuration, if such exists.
/// The mesh network will contain one Provisioner with given name.
///
/// Network Keys and Application Keys must be added manually
/// using `add(networkKey:name)` and `add(applicationKey:name)`.
///
/// - parameters:
/// - name: The user given network name.
/// - provisioner: The default Provisioner.
func createNewMeshNetwork(withName name: String, by provisioner: Provisioner) -> MeshNetwork {
let network = MeshNetwork(name: name)
// Add a new default provisioner.
try! network.add(provisioner: provisioner)
meshData.meshNetwork = network
networkManager = NetworkManager(self)
proxyFilter = ProxyFilter(self)
return network
}
/// An array of Elements of the local Node.
///
/// Use this property if you want to extend the capabilities of the local
/// Node with additional Elements and Models. For example, you may add an
/// additional Element with Generic On/Off Client Model if you support this
/// feature in your app. Make sure there is enough addresses for all the
/// Elements created. If a collision is found, the coliding Elements will
/// be ignored.
///
/// The Element with all mandatory Models (Configuration Server and Client
/// and Health Server and Client) will be added automatically at index 0,
/// and should be skipped when setting.
///
/// The mesh network must be created or loaded before setting this field,
/// otherwise it has no effect.
var localElements: [Element] {
get {
return meshNetwork?.localElements ?? []
}
set {
meshNetwork?.localElements = newValue
}
}
}
// MARK: - Provisioning
public extension MeshNetworkManager {
/// This method returns the Provisioning Manager that can be used
/// to provision the given device.
///
/// - parameter unprovisionedDevice: The device to be added to mes network.
/// - parameter bearer: The Provisioning Bearer to be used for sending
/// provisioning PDUs.
/// - returns: The Provisioning manager that should be used to continue
/// provisioning process after identification.
/// - throws: This method throws when the mesh network has not been created.
func provision(unprovisionedDevice: UnprovisionedDevice,
over bearer: ProvisioningBearer) throws -> ProvisioningManager {
guard let meshNetwork = meshNetwork else {
print("Error: Mesh Network not created")
throw MeshNetworkError.noNetwork
}
return ProvisioningManager(for: unprovisionedDevice, over: bearer, in: meshNetwork)
}
}
// MARK: - Send / Receive Mesh Messages
public extension MeshNetworkManager {
/// This method should be called whenever a PDU has been received
/// from the mesh network using any bearer.
/// When a complete Mesh Message is received and reassembled, the
/// delegate's `meshNetwork(:didDeliverMessage:from)` will be called.
///
/// For easier integration with Bearers use
/// `bearer(didDeliverData:ofType)` instead, and set the manager
/// as Bearer's `dataDelegate`.
///
/// - parameters:
/// - data: The PDU received.
/// - type: The PDU type.
func bearerDidDeliverData(_ data: Data, ofType type: PduType) {
guard let networkManager = networkManager else {
return
}
queue.async {
networkManager.handle(incomingPdu: data, ofType: type)
}
}
/// This method tries to publish the given message using the
/// publication information set in the Model.
///
/// - parameters:
/// - message: The message to be sent.
/// - model: The model from which to send the message.
/// - initialTtl: The initial TTL (Time To Live) value of the message.
/// If `nil`, the default Node TTL will be used.
func publish(_ message: MeshMessage, fromModel model: Model,
withTtl initialTtl: UInt8? = nil) -> MessageHandle? {
guard let publish = model.publish,
let localElement = model.parentElement,
let applicationKey = meshNetwork?.applicationKeys[publish.index] else {
return nil
}
return try? send(message, from: localElement, to: publish.publicationAddress,
withTtl: initialTtl, using: applicationKey)
}
/// Encrypts the message with the Application Key and a Network Key
/// bound to it, and sends to the given destination address.
///
/// This method does not send nor return PDUs to be sent. Instead,
/// for each created segment it calls transmitter's `send(:ofType)`,
/// which should send the PDU over the air. This is in order to support
/// retransmittion in case a packet was lost and needs to be sent again
/// after block acknowlegment was received.
///
/// A `delegate` method will be called when the message has been sent,
/// delivered, or failed to be sent.
///
/// - parameters:
/// - message: The message to be sent.
/// - localElement: The source Element. If `nil`, the primary
/// Element will be used. The Element must belong
/// to the local Provisioner's Node.
/// - destination: The destination address.
/// - initialTtl: The initial TTL (Time To Live) value of the message.
/// If `nil`, the default Node TTL will be used.
/// - applicationKey: The Application Key to sign the message.
/// - throws: This method throws when the mesh network has not been created,
/// the local Node does not have configuration capabilities
/// (no Unicast Address assigned), or the given local Element
/// does not belong to the local Node.
/// - returns: Message handle that can be used to cancel sending.
func send(_ message: MeshMessage,
from localElement: Element? = nil, to destination: MeshAddress,
withTtl initialTtl: UInt8? = nil, using applicationKey: ApplicationKey) throws -> MessageHandle {
guard let networkManager = networkManager, let meshNetwork = meshNetwork else {
print("Error: Mesh Network not created")
throw MeshNetworkError.noNetwork
}
guard let localNode = meshNetwork.localProvisioner?.node,
let source = localElement ?? localNode.elements.first else {
print("Error: Local Provisioner has no Unicast Address assigned")
throw AccessError.invalidSource
}
guard source.parentNode == localNode else {
print("Error: The Element does not belong to the local Node")
throw AccessError.invalidElement
}
guard initialTtl == nil || initialTtl == 0 || (2...127).contains(initialTtl!) else {
print("Error: TTL value \(initialTtl!) is invalid")
throw AccessError.invalidTtl
}
queue.async {
networkManager.send(message, from: source, to: destination,
withTtl: initialTtl, using: applicationKey)
}
return MessageHandle(for: message, sentFrom: source.unicastAddress,
to: destination.address, using: self)
}
/// Encrypts the message with the Application Key and a Network Key
/// bound to it, and sends to the given Group.
///
/// A `delegate` method will be called when the message has been sent,
/// or failed to be sent.
///
/// - parameters:
/// - message: The message to be sent.
/// - localElement: The source Element. If `nil`, the primary
/// Element will be used. The Element must belong
/// to the local Provisioner's Node.
/// - group: The target Group.
/// - initialTtl: The initial TTL (Time To Live) value of the message.
/// If `nil`, the default Node TTL will be used.
/// - applicationKey: The Application Key to sign the message.
/// - throws: This method throws when the mesh network has not been created,
/// the local Node does not have configuration capabilities
/// (no Unicast Address assigned), or the given local Element
/// does not belong to the local Node.
/// - returns: Message handle that can be used to cancel sending.
func send(_ message: MeshMessage,
from localElement: Element? = nil, to group: Group,
withTtl initialTtl: UInt8? = nil, using applicationKey: ApplicationKey) throws -> MessageHandle {
return try send(message, from: localElement, to: group.address,
withTtl: initialTtl, using: applicationKey)
}
/// Encrypts the message with the first Application Key bound to the given
/// Model and a Network Key bound to it, and sends it to the Node
/// to which the Model belongs to.
///
/// A `delegate` method will be called when the message has been sent,
/// delivered, or fail to be sent.
///
/// - parameters:
/// - message: The message to be sent.
/// - localElement: The source Element. If `nil`, the primary
/// Element will be used. The Element must belong
/// to the local Provisioner's Node.
/// - model: The destination Model.
/// - initialTtl: The initial TTL (Time To Live) value of the message.
/// If `nil`, the default Node TTL will be used.
/// - applicationKey: The Application Key to sign the message.
/// - throws: This method throws when the mesh network has not been created,
/// the target Model does not belong to any Element, or has
/// no Application Key bound to it, or when
/// the local Node does not have configuration capabilities
/// (no Unicast Address assigned), or the given local Element
/// does not belong to the local Node.
/// - returns: Message handle that can be used to cancel sending.
func send(_ message: MeshMessage,
from localElement: Element? = nil, to model: Model,
withTtl initialTtl: UInt8? = nil) throws -> MessageHandle {
guard let element = model.parentElement else {
print("Error: Element does not belong to a Node")
throw AccessError.invalidDestination
}
guard let firstKeyIndex = model.bind.first,
let meshNetwork = meshNetwork,
let applicationKey = meshNetwork.applicationKeys[firstKeyIndex] else {
print("Error: Model is not bound to any Application Key")
throw AccessError.modelNotBoundToAppKey
}
return try send(message, from: localElement, to: MeshAddress(element.unicastAddress),
withTtl: initialTtl, using: applicationKey)
}
/// Encrypts the message with the common Application Key bound to both given
/// Models and a Network Key bound to it, and sends it to the Node
/// to which the target Model belongs to.
///
/// A `delegate` method will be called when the message has been sent,
/// delivered, or fail to be sent.
///
/// - parameters:
/// - message: The message to be sent.
/// - localElement: The source Element. If `nil`, the primary
/// Element will be used. The Element must belong
/// to the local Provisioner's Node.
/// - model: The destination Model.
/// - initialTtl: The initial TTL (Time To Live) value of the message.
/// If `nil`, the default Node TTL will be used.
/// - throws: This method throws when the mesh network has not been created,
/// the local or target Model do not belong to any Element, or have
/// no common Application Key bound to them, or when
/// the local Node does not have configuration capabilities
/// (no Unicast Address assigned), or the given local Element
/// does not belong to the local Node.
/// - returns: Message handle that can be used to cancel sending.
func send(_ message: MeshMessage,
from localModel: Model, to model: Model,
withTtl initialTtl: UInt8? = nil) throws -> MessageHandle {
guard let meshNetwork = meshNetwork else {
print("Error: Mesh Network not created")
throw MeshNetworkError.noNetwork
}
guard let element = model.parentElement else {
print("Error: Element does not belong to a Node")
throw AccessError.invalidDestination
}
guard let localElement = localModel.parentElement else {
print("Error: Source Model does not belong to an Element")
throw AccessError.invalidSource
}
guard let commonKeyIndex = model.bind.first(where: { localModel.bind.contains($0) }),
let applicationKey = meshNetwork.applicationKeys[commonKeyIndex] else {
print("Error: Models are not bound to any common Application Key")
throw AccessError.modelNotBoundToAppKey
}
return try send(message, from: localElement, to: MeshAddress(element.unicastAddress),
withTtl: initialTtl, using: applicationKey)
}
/// Sends Configuration Message to the Node with given destination Address.
/// The `destination` must be a Unicast Address, otherwise the method
/// does nothing.
///
/// A `delegate` method will be called when the message has been sent,
/// delivered, or fail to be sent.
///
/// - parameters:
/// - message: The message to be sent.
/// - destination: The destination Unicast Address.
/// - initialTtl: The initial TTL (Time To Live) value of the message.
/// If `nil`, the default Node TTL will be used.
/// - throws: This method throws when the mesh network has not been created,
/// the local Node does not have configuration capabilities
/// (no Unicast Address assigned), or the destination address
/// is not a Unicast Address or it belongs to an unknown Node.
/// Error `AccessError.cannotDelete` is sent when trying to
/// delete the last Network Key on the device.
/// - returns: Message handle that can be used to cancel sending.
func send(_ message: ConfigMessage, to destination: Address,
withTtl initialTtl: UInt8? = nil) throws -> MessageHandle {
guard let networkManager = networkManager, let meshNetwork = meshNetwork else {
print("Error: Mesh Network not created")
throw MeshNetworkError.noNetwork
}
guard let localProvisioner = meshNetwork.localProvisioner,
let source = localProvisioner.unicastAddress else {
print("Error: Local Provisioner has no Unicast Address assigned")
throw AccessError.invalidSource
}
guard destination.isUnicast else {
print("Error: Address: 0x\(destination.hex) is not a Unicast Address")
throw MeshMessageError.invalidAddress
}
guard let node = meshNetwork.node(withAddress: destination) else {
print("Error: Unknown destination Node")
throw AccessError.invalidDestination
}
guard let _ = node.networkKeys.first else {
print("Fatal Error: The target Node does not have Network Key")
throw AccessError.invalidDestination
}
if message is ConfigNetKeyDelete {
guard node.networkKeys.count > 1 else {
print("Error: Cannot remove last Network Key")
throw AccessError.cannotDelete
}
}
guard initialTtl == nil || initialTtl == 0 || (2...127).contains(initialTtl!) else {
print("Error: TTL value \(initialTtl!) is invalid")
throw AccessError.invalidTtl
}
queue.async {
networkManager.send(message, to: destination, withTtl: initialTtl)
}
return MessageHandle(for: message, sentFrom: source,
to: destination, using: self)
}
/// Sends Configuration Message to the given Node.
///
/// A `delegate` method will be called when the message has been sent,
/// delivered, or fail to be sent.
///
/// - parameters:
/// - message: The message to be sent.
/// - node: The destination Node.
/// - initialTtl: The initial TTL (Time To Live) value of the message.
/// If `nil`, the default Node TTL will be used.
/// - throws: This method throws when the mesh network has not been created,
/// the local Node does not have configuration capabilities
/// (no Unicast Address assigned), or the destination address
/// is not a Unicast Address or it belongs to an unknown Node.
/// - returns: Message handle that can be used to cancel sending.
func send(_ message: ConfigMessage, to node: Node,
withTtl initialTtl: UInt8? = nil) throws -> MessageHandle {
return try send(message, to: node.unicastAddress, withTtl: initialTtl)
}
/// Sends Configuration Message to the given Node.
///
/// A `delegate` method will be called when the message has been sent,
/// delivered, or fail to be sent.
///
/// - parameters:
/// - message: The message to be sent.
/// - element: The destination Element.
/// - initialTtl: The initial TTL (Time To Live) value of the message.
/// If `nil`, the default Node TTL will be used.
/// - throws: This method throws when the mesh network has not been created,
/// the local Node does not have configuration capabilities
/// (no Unicast Address assigned), or the target Element does not
/// belong to any known Node.
/// - returns: Message handle that can be used to cancel sending.
func send(_ message: ConfigMessage, to element: Element,
withTtl initialTtl: UInt8? = nil) throws -> MessageHandle {
guard let node = element.parentNode else {
print("Error: Element does not belong to a Node")
throw AccessError.invalidDestination
}
return try send(message, to: node, withTtl: initialTtl)
}
/// Sends Configuration Message to the given Node.
///
/// A `delegate` method will be called when the message has been sent,
/// delivered, or fail to be sent.
///
/// - parameters:
/// - message: The message to be sent.
/// - model: The destination Model.
/// - initialTtl: The initial TTL (Time To Live) value of the message.
/// If `nil`, the default Node TTL will be used.
/// - throws: This method throws when the mesh network has not been created,
/// the local Node does not have configuration capabilities
/// (no Unicast Address assigned), or the target Element does
/// not belong to any known Node.
/// - returns: Message handle that can be used to cancel sending.
func send(_ message: ConfigMessage, to model: Model,
withTtl initialTtl: UInt8? = nil) throws -> MessageHandle {
guard let element = model.parentElement else {
print("Error: Model does not belong to an Element")
throw AccessError.invalidDestination
}
return try send(message, to: element, withTtl: initialTtl)
}
/// Sends the Proxy Configuration Message to the connected Proxy Node.
///
/// This method will only work if the bearer uses is GATT Proxy.
/// The message will be encrypted and sent to the `transported`, which
/// should deliver the PDU to the connected Node.
///
/// - parameters:
/// - message: The Proxy Configuration message to be sent.
/// - initialTtl: The initial TTL (Time To Live) value of the message.
/// If `nil`, the default Node TTL will be used.
/// - throws: This method throws when the mesh network has not been created.
func send(_ message: ProxyConfigurationMessage) throws {
guard let networkManager = networkManager else {
print("Error: Mesh Network not created")
throw MeshNetworkError.noNetwork
}
queue.async {
networkManager.send(message)
}
}
/// Cancels sending the message with the given identifier.
///
/// - parameter messageId: The message identifier.
func cancel(_ messageId: MessageHandle) throws {
guard let networkManager = networkManager else {
print("Error: Mesh Network not created")
throw MeshNetworkError.noNetwork
}
queue.async {
networkManager.cancel(messageId)
}
}
}
// MARK: - Helper methods for Bearer support
extension MeshNetworkManager: BearerDataDelegate {
public func bearer(_ bearer: Bearer, didDeliverData data: Data, ofType type: PduType) {
bearerDidDeliverData(data, ofType: type)
}
}
// MARK: - Managing sequence numbers.
public extension MeshNetworkManager {
/// This method sets the next outgoing sequence number of the given Element on local Node.
/// This 24-bit number will be set in the next message sent by this Element. The sequence
/// number is increased by 1 every time the Element sends a message.
///
/// Mind, that the sequence number is the least significant 24-bits of a SeqAuth, where
/// the 32 most significant bits are called IV Index. The sequence number resets to 0
/// when the device re-enters IV Index Normal Operation after 96-144 hours of being
/// in IV Index Update In Progress phase. The current IV Index is obtained from the
/// Secure Network beacon upon connection to Proxy Node. Setting too low sequence
/// number will effectively block the Element from sending messages to the network,
/// until it will increase enough not to be discarded by other nodes.
///
/// - important: This method should not be used, unless you need to reuse the same
/// Provisioner's Unicast Address on another device, or a device where the
/// app was uninstalled and reinstalled. Even then the use of it is not recommended.
/// The sequence number is an internal parameter of the Element and is
/// managed automatically by the library. Instead, each device (phone) should
/// use a separate Provisioner with unique set of Unicast Addresses, which
/// should not change on export/import.
///
/// - parameters:
/// - sequence: The new sequence number.
/// - element: The Element of a Node associated with the local Provisioner.
func setSequenceNumber(_ sequence: UInt32, forLocalElement element: Element) {
guard let meshNetwork = meshNetwork,
element.parentNode?.isLocalProvisioner == true,
let defaults = UserDefaults(suiteName: meshNetwork.uuid.uuidString) else {
return
}
defaults.set(sequence & 0x00FFFFFF, forKey: "S\(element.unicastAddress.hex)")
}
/// Returns the next sequence number that would be used by the given Element on local Node.
///
/// - important: The sequence number is an internal parameter of an Element.
/// Apps should not use this method unless necessary. It is recommended
/// to create a new Provisioner with a unique Unicast Address instead.
///
/// - parameter element: The local Element to get sequence number of.
/// - returns: The next sequence number, or `nil` if the Element does not belong
/// to the local Element or the mesh network does not exist.
func getSequenceNumber(ofLocalElement element: Element) -> UInt32? {
guard let meshNetwork = meshNetwork,
element.parentNode?.isLocalProvisioner == true,
let defaults = UserDefaults(suiteName: meshNetwork.uuid.uuidString) else {
return nil
}
return UInt32(defaults.integer(forKey: "S\(element.unicastAddress.hex)"))
}
}
// MARK: - Save / Load
public extension MeshNetworkManager {
/// Loads the Mesh Network configuration from the storage.
/// If storage is not given, a local file will be used.
///
/// If the storage is empty, this method tries to migrate the
/// database from the nRF Mesh 1.0.x to the new format. This
/// is useful when the library or the Sample App has been updated.
/// For fresh installs, when the storage is empty and the
/// legacy version was not found this method returns `false`.
///
/// - returns: `True` if the network settings were loaded,
/// `false` otherwise.
/// - throws: If loading configuration failed.
func load() throws -> Bool {
if let data = storage.load() {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
meshData = try decoder.decode(MeshData.self, from: data)
guard let meshNetwork = meshData.meshNetwork else {
return false
}
// Restore the last IV Index. The last IV Index is stored since version 2.2.2.
if let defaults = UserDefaults(suiteName: meshNetwork.uuid.uuidString),
let map = defaults.object(forKey: IvIndex.indexKey) as? [String : Any],
let ivIndex = IvIndex.fromMap(map) {
meshNetwork.ivIndex = ivIndex
}
networkManager = NetworkManager(self)
proxyFilter = ProxyFilter(self)
return true
} else if let legacyState = MeshStateManager.load() {
// The app has been updated from version 1.0.x to 2.0.
// Time to migrate the data to the new format.
let network = MeshNetwork(name: legacyState.name)
try! network.add(provisioner: legacyState.provisioner,
withAddress: legacyState.provisionerUnicastAddress)
let provisionerNode = network.localProvisioner!.node!
provisionerNode.defaultTTL = legacyState.provisionerDefaultTtl
network.ivIndex = legacyState.ivIndex
network.networkKeys.removeAll()
let networkKey = legacyState.networkKey
network.add(networkKey: networkKey)
legacyState.applicationKeys(boundTo: networkKey).forEach {
network.add(applicationKey: $0)
}
legacyState.groups.forEach {
try? network.add(group: $0)
}
legacyState.nodes(provisionedUsingNetworkKey: networkKey).forEach {
try? network.add(node: $0)
}
// Restore the sequence number from the legacy version.
let defaultsKey = "nRFMeshSequenceNumber"
let oldDefaults = UserDefaults.standard
let oldSequence = UInt32(oldDefaults.integer(forKey: defaultsKey))
let newDefaults = UserDefaults(suiteName: network.uuid.uuidString)!
// The version 1.0.x had only one local Element, so there is no need to
// update sequence numbers for other possible local Elements.
newDefaults.set(oldSequence + 1, forKey: "S\(legacyState.provisionerUnicastAddress.hex)")
// Clean up.
oldDefaults.removeObject(forKey: defaultsKey)
MeshStateManager.cleanup()
meshData.meshNetwork = network
networkManager = NetworkManager(self)
proxyFilter = ProxyFilter(self)
return save()
}
return false
}
/// Saves the Mesh Network configuration in the storage.
/// If storage is not given, a local file will be used.
///
/// - returns: `True` if the network settings was saved, `false` otherwise.
func save() -> Bool {
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .iso8601
let data = try! encoder.encode(meshData)
return storage.save(data)
}
}
// MARK: - Export / Import
public extension MeshNetworkManager {
/// Returns the exported Mesh Network configuration as JSON Data.
/// The returned Data can be transferred to another application and
/// imported. The JSON is compatible with Bluetooth Mesh scheme.
///
/// - returns: The mesh network configuration as JSON Data.
func export() -> Data {
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .iso8601
return try! encoder.encode(meshData.meshNetwork)
}
/// Imports the Mesh Network configuration from the given Data.
/// The data must contain valid JSON with Bluetooth Mesh scheme.
///
/// - parameter data: JSON as Data.
/// - returns: The imported mesh network.
/// - throws: This method throws an error if import or adding
/// the local Provisioner failed.
func `import`(from data: Data) throws -> MeshNetwork {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
let meshNetwork = try decoder.decode(MeshNetwork.self, from: data)
meshData.meshNetwork = meshNetwork
// Restore the last IV Index. The last IV Index is stored since version 2.2.2.
if let defaults = UserDefaults(suiteName: meshNetwork.uuid.uuidString),
let map = defaults.object(forKey: IvIndex.indexKey) as? [String : Any],
let ivIndex = IvIndex.fromMap(map) {
meshNetwork.ivIndex = ivIndex
}
networkManager = NetworkManager(self)
proxyFilter = ProxyFilter(self)
return meshNetwork
}
}
| 47.4 | 111 | 0.639191 |
185ee2db25e26daff80914b45ec012fcbae5dae9 | 2,493 | //
// ViewController.swift
// MVVMState Example
//
// Created by Ivan Foong Kwok Keong on 15/9/17.
// Copyright © 2017 ivanfoong. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var textField: UITextField!
@IBOutlet weak var button: UIButton!
var viewModel = ViewModel(state: .timerStopped(AppData(secondsRemaining: 100, initialSecondsRemaining: 100))) {
didSet {
switch self.viewModel.state {
case .timerStarted(_):
CountdownTimer.sharedInstace.start()
default:
CountdownTimer.sharedInstace.stop()
}
self.updateUI()
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
CountdownTimer.sharedInstace.handler = { [weak self] in
self?.handleTick()
}
self.textField.addTarget(self, action: #selector(textFieldDidBeginEditing(textField:)), for: .editingDidBegin)
self.textField.addTarget(self, action: #selector(textFieldDidEndEditing(textField:)), for: .editingDidEnd)
self.updateUI()
}
deinit {
CountdownTimer.sharedInstace.handler = nil
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func buttonTapped(_ sender: UIButton) {
if self.textField.isEditing {
self.textField.resignFirstResponder()
}
self.viewModel = self.viewModel.buttonTapped()
}
@objc func textFieldDidBeginEditing(textField: UITextField) {
if let text = textField.text, let initialSecondsRemaining = Int(text) {
self.viewModel = self.viewModel.reset(with: initialSecondsRemaining)
} else {
self.viewModel = self.viewModel.reset(with: 0)
}
}
@objc func textFieldDidEndEditing(textField: UITextField) {
if let text = textField.text, let initialSecondsRemaining = Int(text) {
self.viewModel = self.viewModel.reset(with: initialSecondsRemaining)
}
}
private func updateUI() {
self.textField.text = self.viewModel.textFieldText
self.button.setTitle(self.viewModel.buttonText, for: .normal)
}
private func handleTick() {
self.viewModel = self.viewModel.tick()
}
}
| 31.556962 | 118 | 0.637786 |
76502c1b5542434770dd29118a53479c782561dc | 3,182 | //
// FlickrClient.swift
// Learn2Tune
//
// Created by gam on 6/10/20.
// Copyright © 2020 gam. All rights reserved.
//
import Foundation
import Foundation
import UIKit
class FlickrClient {
struct Auth {
static var apiKey = "API KEY HERE"
}
enum Endpoints {
static let flickrBase = "https://www.flickr.com/services/rest/?method=flickr.photos.search&api_key=\(Auth.apiKey)&lat={lat}&lon={long}&radius={radius}&per_page={perpage}&page={page}&format=json&nojsoncallback=1"
static let imageBase = "https://farm{farmId}.staticflickr.com/{serverId}/{id}_{secret}_z.jpg"
case getImageLinks(FlickrImageLocation)
case getImage(FlickrURL)
var stringValue: String {
switch self {
case .getImageLinks(let flickrImageLocs):
let link = Endpoints.flickrBase.replacingOccurrences(of: "{lat}", with: flickrImageLocs.lat).replacingOccurrences(of: "{long}", with: flickrImageLocs.long).replacingOccurrences(of: "{radius}", with: flickrImageLocs.radius).replacingOccurrences(of: "{perpage}", with: flickrImageLocs.perpage).replacingOccurrences(of: "{page}", with: flickrImageLocs.page)
return link
case .getImage(let flickrUrl):
let link = Endpoints.imageBase.replacingOccurrences(of: "{farmId}", with: "\(flickrUrl.farm)").replacingOccurrences(of: "{serverId}", with: flickrUrl.server).replacingOccurrences(of: "{id}", with: flickrUrl.id).replacingOccurrences(of: "{secret}", with: flickrUrl.secret)
return link
}
}
var url: URL {
return URL(string: stringValue)!
}
}
class func handleDataProcess(data: Data) -> Data {
let range = 5..<data.count
return data.subdata(in: range)
}
class func getImages(imageLocation: String, completion: @escaping (Data?) -> Void) {
let url = URL(string: imageLocation)!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
DispatchQueue.main.async {
completion(data)
}
}
task.resume()
}
class func getImageLinks(imageLoc: FlickrImageLocation, completion: @escaping (ImageLinks?, Error?) -> Void) {
//print("linksurl \(Endpoints.getImageLinks(imageLoc).url)")
let url = Endpoints.getImageLinks(imageLoc).url
print("get Image Links url: \(url)")
HttpMethods.taskForGETRequest(url: url, response: FlickrImageResult.self, dataProcess: nil) { (response, error) in
guard let response = response, let links = response.photos else {
completion(nil, error)
return
}
if response.stat != "ok" {return completion(nil, error)}
var imageLinks = ImageLinks(links: [String](), totalNoOfLinks: response.photos!.total)
for link in links.photo {
let imageLink = Endpoints.getImage(link).stringValue
imageLinks.links.append(imageLink)
}
completion(imageLinks, nil)
}
}
}
| 39.775 | 370 | 0.616593 |
f8f02f3edea0ef43910deba6210a62a131b7db06 | 13,049 | //
// SHSearchBar.swift
// SHSearchBar
//
// Created by Stefan Herold on 01/08/16.
// Copyright © 2016 StefanHerold. All rights reserved.
//
import UIKit
/**
* The central searchbar class of this framework.
* You must initialize this class using an instance of SHSearchBarConfig which is also changable later.
*/
public class SHSearchBar: UIView, SHSearchBarDelegate {
/// The content of this property is used to restore the textField text after cancellation
var textBeforeEditing: String?
/// Constraint that shows the cancel button when active
var bgToCancelButtonConstraint: NSLayoutConstraint!
/// Constraint that hides the cancel button when active
var bgToParentConstraint: NSLayoutConstraint!
/// The background image view which is responsible for displaying the rounded corners.
let backgroundView: UIImageView = UIImageView()
/// The cancel button under the right side of the searhcbar.
let cancelButton: UIButton = UIButton(type: .custom)
// MARK: - Public Properties
/// This textfield is currently the central element of the searchbar.
/// In future it could be possible that this view is exchanged by something different.
/// So at some time it will maybe become an internal property.
public let textField: UITextField
/// The central SHSearchBarConfig instance which configures all searchbar parameters.
public var config: SHSearchBarConfig {
didSet {
if let textField = textField as? SHSearchBarTextField {
textField.config = config
}
updateUserInterface()
updateViewConstraints()
}
}
/// You can set the searchbar as inactive with this property. Currently this only dims the text color slightly.
public var isActive: Bool = true {
didSet {
updateUserInterface()
}
}
/// The text of the searchbar. Defaults to nil.
public var text: String? {set {textField.text = newValue} get {return textField.text}}
/// The placeholder of the searchbar. Defaults to nil.
public var placeholder: String? {set {textField.placeholder = newValue} get {return textField.placeholder}}
/// The text alignment of the searchbar.
public var textAlignment: NSTextAlignment {set {textField.textAlignment = newValue} get {return textField.textAlignment}}
/// The enabled state of the searchbar.
public var isEnabled: Bool {set {textField.isEnabled = newValue} get {return textField.isEnabled}}
/// The delegate which informs the user about important events.
public weak var delegate: SHSearchBarDelegate?
// MARK: - Lifecycle
/**
* The designated initializer to initialize the searchbar.
* - parameter config: The initial SHSearchBarConfig object.
*/
public init(config: SHSearchBarConfig) {
self.config = config
self.textField = SHSearchBarTextField(config: config)
super.init(frame: CGRect.zero)
self.delegate = self
translatesAutoresizingMaskIntoConstraints = false
setupBackgroundView(withConfig: config)
setupTextField(withConfig: config)
setupCancelButton(withConfig: config)
backgroundView.addSubview(textField)
addSubview(cancelButton)
addSubview(backgroundView)
updateViewConstraints()
updateUserInterface()
}
func setupBackgroundView(withConfig config: SHSearchBarConfig) {
backgroundView.translatesAutoresizingMaskIntoConstraints = false
backgroundView.isUserInteractionEnabled = true
updateBackgroundImage(withRadius: 0, corners: .allCorners, color: UIColor.white)
}
func setupTextField(withConfig config: SHSearchBarConfig) {
textField.translatesAutoresizingMaskIntoConstraints = false
textField.delegate = self
textField.autocorrectionType = .default
textField.autocapitalizationType = .none
textField.spellCheckingType = .no
textField.adjustsFontSizeToFitWidth = false
textField.clipsToBounds = true
textField.addTarget(self, action: #selector(didChangeTextField(_:)), for: .editingChanged)
}
func setupCancelButton(withConfig config: SHSearchBarConfig) {
cancelButton.translatesAutoresizingMaskIntoConstraints = false
cancelButton.alpha = 0.0
cancelButton.setContentHuggingPriority(.required, for: .horizontal)
cancelButton.reversesTitleShadowWhenHighlighted = true
cancelButton.adjustsImageWhenHighlighted = true
cancelButton.addTarget(self, action: #selector(pressedCancelButton(_:)), for: .touchUpInside)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func updateViewConstraints() {
let isInitialUpdate = backgroundView.constraints.isEmpty
let isTextFieldInEditMode = bgToCancelButtonConstraint?.isActive ?? false
bgToParentConstraint?.isActive = false
bgToCancelButtonConstraint?.isActive = false
if isInitialUpdate {
let constraints = [
backgroundView.leadingAnchor.constraint(equalTo: leadingAnchor),
backgroundView.topAnchor.constraint(equalTo: topAnchor),
backgroundView.bottomAnchor.constraint(equalTo: bottomAnchor),
textField.leadingAnchor.constraint(equalTo: backgroundView.leadingAnchor),
textField.trailingAnchor.constraint(equalTo: backgroundView.trailingAnchor),
textField.topAnchor.constraint(equalTo: backgroundView.topAnchor),
textField.bottomAnchor.constraint(equalTo: backgroundView.bottomAnchor),
cancelButton.trailingAnchor.constraint(equalTo: trailingAnchor),
cancelButton.topAnchor.constraint(equalTo: topAnchor),
cancelButton.bottomAnchor.constraint(equalTo: bottomAnchor),
]
NSLayoutConstraint.activate(constraints)
bgToParentConstraint = backgroundView.trailingAnchor.constraint(equalTo: trailingAnchor)
bgToCancelButtonConstraint = backgroundView.trailingAnchor.constraint(equalTo: cancelButton.leadingAnchor, constant: -config.rasterSize)
}
bgToCancelButtonConstraint.constant = -config.rasterSize
if isTextFieldInEditMode && !isInitialUpdate && config.useCancelButton {
bgToCancelButtonConstraint.isActive = true
} else {
bgToParentConstraint.isActive = true
}
}
// MARK: - First Responder Handling
public override var isFirstResponder: Bool {
return textField.isFirstResponder
}
@discardableResult
public override func resignFirstResponder() -> Bool {
return textField.resignFirstResponder()
}
@discardableResult
public override func becomeFirstResponder() -> Bool {
return textField.becomeFirstResponder()
}
public override var canResignFirstResponder: Bool {
return textField.canResignFirstResponder
}
public override var canBecomeFirstResponder: Bool {
return textField.canBecomeFirstResponder
}
// MARK: - UI Updates
func updateUserInterface() {
var textColor = config.textAttributes[.foregroundColor] as? UIColor ?? SHSearchBarConfig.defaultTextForegroundColor
// Replace normal color with a lighter color so the text looks disabled
if !isActive { textColor = textColor.withAlphaComponent(0.5) }
textField.tintColor = textColor // set cursor color
textField.textColor = textColor
textField.leftView = config.leftView
textField.leftViewMode = config.leftViewMode
textField.rightView = config.rightView
textField.rightViewMode = config.rightViewMode
textField.clearButtonMode = config.clearButtonMode
var textAttributes = config.textAttributes
textAttributes[.foregroundColor] = textColor
textField.defaultTextAttributes = SHSearchBarConfig.convert(textAttributes: textAttributes)
let normalAttributes = config.cancelButtonTextAttributes
cancelButton.setAttributedTitle(NSAttributedString(string: config.cancelButtonTitle, attributes: normalAttributes), for: .normal)
var highlightedAttributes = config.cancelButtonTextAttributes
let highlightColor = highlightedAttributes[.foregroundColor] as? UIColor ?? SHSearchBarConfig.defaultTextForegroundColor
highlightedAttributes[.foregroundColor] = highlightColor.withAlphaComponent(0.75)
cancelButton.setAttributedTitle(NSAttributedString(string: config.cancelButtonTitle, attributes: highlightedAttributes), for: .highlighted)
if #available(iOS 10.0, *) {
if let textContentType = config.textContentType {
textField.textContentType = UITextContentType(rawValue: textContentType)
}
}
}
/**
* Use this function to specify the views corner radii. They will be applied to the background
* image view that spans the whole search bar. The backgroundColor of this view must remain clear to
* make the corner radius visible.
* - parameter withRadius: The radius in pt to apply to the given corners.
* - parameter corners: The corners to apply the radius to.
* - parameter color: The solid color of the background image.
*/
public func updateBackgroundImage(withRadius radius: CGFloat, corners: UIRectCorner, color: UIColor) {
let insets = UIEdgeInsets(top: radius, left: radius, bottom: radius, right: radius)
let imgSize = CGSize(width: radius*2 + 1, height: radius*2 + 1)
var img = UIImage.imageWithSolidColor(color, size: imgSize)
img = img.roundedImage(with: radius, cornersToRound: corners)
img = img.resizableImage(withCapInsets: insets)
backgroundView.image = img
backgroundColor = UIColor.clear
}
open func resetTextField() {
textField.text = ""
delegate?.searchBar(self, textDidChange: "")
}
// MARK: - Cancel Button Management
public func cancelSearch() {
let shouldCancel = delegate?.searchBarShouldCancel(self) ?? searchBarShouldCancel(self)
if shouldCancel {
resetTextField()
updateCancelButtonVisibility(makeVisible: false)
textField.resignFirstResponder()
}
}
@objc func pressedCancelButton(_ sender: AnyObject) {
cancelSearch()
}
func updateCancelButtonVisibility(makeVisible show: Bool) {
// This 'complex' if-else avoids constraint warnings in the console
if show && config.useCancelButton {
bgToParentConstraint.isActive = false
bgToCancelButtonConstraint.isActive = true
} else {
bgToCancelButtonConstraint.isActive = false
bgToParentConstraint.isActive = true
}
UIView.animate(withDuration: config.animationDuration, delay: 0, options: [], animations: {
self.layoutIfNeeded()
self.cancelButton.alpha = show ? 1 : 0
}, completion: nil)
}
// MARK: - Handle Text Changes
@objc func didChangeTextField(_ textField: UITextField) {
let newText = textField.text ?? ""
delegate?.searchBar(self, textDidChange: newText)
}
}
// MARK: - UITextFieldDelegate
extension SHSearchBar: UITextFieldDelegate {
public func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
let shouldBegin = delegate?.searchBarShouldBeginEditing(self) ?? searchBarShouldBeginEditing(self)
if shouldBegin {
updateCancelButtonVisibility(makeVisible: true)
}
return shouldBegin
}
public func textFieldDidBeginEditing(_ textField: UITextField) {
textBeforeEditing = textField.text
delegate?.searchBarDidBeginEditing(self)
}
public func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
return delegate?.searchBarShouldEndEditing(self) ?? searchBarShouldEndEditing(self)
}
public func textFieldDidEndEditing(_ textField: UITextField) {
delegate?.searchBarDidEndEditing(self)
}
public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let shouldChange = delegate?.searchBar(self, shouldChangeCharactersIn: range, replacementString: string) ?? searchBar(self, shouldChangeCharactersIn: range, replacementString: string)
return shouldChange
}
public func textFieldShouldClear(_ textField: UITextField) -> Bool {
let shouldClear = delegate?.searchBarShouldClear(self) ?? searchBarShouldClear(self)
return shouldClear
}
public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
let shouldReturn = delegate?.searchBarShouldReturn(self) ?? searchBarShouldReturn(self)
return shouldReturn
}
}
| 39.068862 | 191 | 0.70151 |
642e1307cf902401daf57f04212b735553f92b1e | 1,218 | //
// CarsMapMockController.swift
// CarsMapTests
//
// Created by Antonio Ruffolo on 14/08/2019.
// Copyright © 2019 AR. All rights reserved.
//
import UIKit
@testable import CarsMap
class CarsMapMockController: UIViewController, CarsMapViewProtocol
{
var coordinate: (lat: Double, lng: Double)?
var carsViewData: [CarLocationViewData]?
var carsItemData: [CarListItemDataView]?
var scrollIndex: Int?
var erroMessage: String?
override func viewDidLoad()
{
super.viewDidLoad()
}
func zoomToLocation(coordinate: (lat: Double, lng: Double))
{
self.coordinate = coordinate
}
func addPoisToMap(carsViewData: [CarLocationViewData])
{
self.carsViewData = carsViewData
}
func goTolist(carsItemData: [CarListItemDataView])
{
self.carsItemData = carsItemData
}
func showErrorForDataFailure(title: String, message: String, buttonLabel: String)
{
self.erroMessage = message
}
func fillCollectionView(carsItemData: [CarListItemDataView])
{
// nothing to do here
}
func scrollCollectionTo(index: Int)
{
self.scrollIndex = index
}
func showError(title: String, message: String, buttonLabel: String)
{
// nothing to do here
}
}
| 19.645161 | 83 | 0.70936 |
11a4d76f93ff477801509ea85e99c51519cd789a | 5,633 | //
// SendViewControllerTests.swift
// AlphaWalletTests
//
// Created by Vladyslav Shepitko on 05.03.2021.
//
import UIKit
@testable import AlphaWallet
import XCTest
import BigInt
class SendViewControllerTests: XCTestCase {
private let storage = FakeTokensDataStore()
private let balanceCoordinator = FakeBalanceCoordinator()
private let nativeCryptocurrencyTransactionType: TransactionType = {
let token = TokenObject(contract: AlphaWallet.Address.make(), server: .main, value: "0", type: .nativeCryptocurrency)
return .nativeCryptocurrency(token, destination: nil, amount: nil)
}()
private lazy var session: WalletSession = .make(balanceCoordinator: balanceCoordinator)
func testNativeCryptocurrencyAllFundsValueSpanish() {
let vc = createSendViewControllerAndSetLocale(locale: .spanish, transactionType: nativeCryptocurrencyTransactionType)
XCTAssertEqual(vc.amountTextField.value, "")
let testValue = BigInt("10000000000000000000000")
balanceCoordinator.balance = .some(.init(value: testValue))
vc.allFundsSelected()
XCTAssertEqual(vc.amountTextField.value, "10000")
//Reset language to default
Config.setLocale(AppLocale.system)
}
func testNativeCryptocurrencyAllFundsValueEnglish() {
let vc = createSendViewControllerAndSetLocale(locale: .japanese, transactionType: nativeCryptocurrencyTransactionType)
XCTAssertEqual(vc.amountTextField.value, "")
let testValue = BigInt("10000000000000000000000")
balanceCoordinator.balance = .some(.init(value: testValue))
vc.allFundsSelected()
XCTAssertEqual(vc.amountTextField.value, "10000")
XCTAssertNotNil(vc.shortValueForAllFunds)
XCTAssertTrue((vc.shortValueForAllFunds ?? "").nonEmpty)
Config.setLocale(AppLocale.system)
}
func testNativeCryptocurrencyAllFundsValueEnglish2() {
let vc = createSendViewControllerAndSetLocale(locale: .english, transactionType: nativeCryptocurrencyTransactionType)
XCTAssertEqual(vc.amountTextField.value, "")
let testValue = BigInt("10000000000000")
balanceCoordinator.balance = .some(.init(value: testValue))
vc.allFundsSelected()
XCTAssertEqual(vc.amountTextField.value, "0.00001")
XCTAssertNotNil(vc.shortValueForAllFunds)
XCTAssertTrue((vc.shortValueForAllFunds ?? "").nonEmpty)
Config.setLocale(AppLocale.system)
}
func testERC20AllFunds() {
let token = TokenObject(contract: AlphaWallet.Address.make(), server: .main, decimals: 18, value: "2000000020224719101120", type: .erc20)
let vc = createSendViewControllerAndSetLocale(locale: .spanish, transactionType: .ERC20Token(token, destination: .none, amount: nil))
XCTAssertEqual(vc.amountTextField.value, "")
vc.allFundsSelected()
XCTAssertEqual(vc.amountTextField.value, "2000")
XCTAssertNotNil(vc.shortValueForAllFunds)
XCTAssertTrue((vc.shortValueForAllFunds ?? "").nonEmpty)
Config.setLocale(AppLocale.system)
}
func testERC20AllFundsSpanish() {
let token = TokenObject(contract: AlphaWallet.Address.make(), server: .main, decimals: 18, value: "2020224719101120", type: .erc20)
let vc = createSendViewControllerAndSetLocale(locale: .spanish, transactionType: .ERC20Token(token, destination: .none, amount: nil))
XCTAssertEqual(vc.amountTextField.value, "")
vc.allFundsSelected()
XCTAssertEqual(vc.amountTextField.value, "0,002")
XCTAssertNotNil(vc.shortValueForAllFunds)
XCTAssertTrue((vc.shortValueForAllFunds ?? "").nonEmpty)
Config.setLocale(AppLocale.system)
}
func testERC20AllFundsEnglish() {
let token = TokenObject(contract: AlphaWallet.Address.make(), server: .main, decimals: 18, value: "2020224719101120", type: .erc20)
let vc = createSendViewControllerAndSetLocale(locale: .english, transactionType: .ERC20Token(token, destination: .none, amount: nil))
XCTAssertEqual(vc.amountTextField.value, "")
vc.allFundsSelected()
XCTAssertEqual(vc.amountTextField.value, "0.002")
XCTAssertNotNil(vc.shortValueForAllFunds)
XCTAssertTrue((vc.shortValueForAllFunds ?? "").nonEmpty)
Config.setLocale(AppLocale.system)
}
func testERC20English() {
let token = TokenObject(contract: AlphaWallet.Address.make(), server: .main, decimals: 18, value: "2020224719101120", type: .erc20)
let vc = createSendViewControllerAndSetLocale(locale: .english, transactionType: .ERC20Token(token, destination: .none, amount: nil))
XCTAssertEqual(vc.amountTextField.value, "")
XCTAssertNil(vc.shortValueForAllFunds)
XCTAssertFalse((vc.shortValueForAllFunds ?? "").nonEmpty)
Config.setLocale(AppLocale.system)
}
private func createSendViewControllerAndSetLocale(locale: AppLocale, transactionType: TransactionType) -> SendViewController {
Config.setLocale(locale)
let vc = SendViewController(session: session,
storage: storage,
account: .make(),
transactionType: nativeCryptocurrencyTransactionType,
cryptoPrice: Subscribable<Double>.init(nil),
assetDefinitionStore: AssetDefinitionStore())
vc.configure(viewModel: .init(transactionType: transactionType, session: session, storage: storage))
return vc
}
}
| 38.060811 | 145 | 0.695899 |
d5fb93f1f3186ea368092e0dc50cd97f08084f02 | 54,588 | //
// AtoZViewController.swift
// Aah to Zzz
//
// Created by David Fierstein on 2/18/16.
// Copyright © 2016 David Fierstein. All rights reserved.
//
import UIKit
import CoreData
import Alamofire
class AtoZViewController: UIViewController {
//TODO: should weak optional vars be used for delegates? Probably yes, to avoid retain cycles
// AtoZ VC is not releasing
let tableViewsDelegate = AtoZTableViewDelegates()
weak var uiDynamicsDelegate: AtoZUIDynamicsDelegate?
weak var gestureDelegate: AtoZGestureDelegate?
var model = AtoZModel.sharedInstance //why not let?
var letters: [Letter]! //TODO: why not ? instead of !
var wordlist = [String]()
var positions: [Position]?
var wordHolderCenter: CGPoint?
var mainGradient: CAGradientLayer?
var game: Game?
var currentLetterSet: LetterSet?
var currentWords: [Word]?
var currentNumberOfWords: Int?
var currentNumberOfActiveWords: Int?
var fillingInBlanks: Bool = false // flag for configuring cells when Fill in the Blanks button is touched
var lettertiles: [Tile]! // created in code so that autolayout doesn't interfere with UI Dynamcis
var tilesToSwap: [Tile]? // an array to temporarilly hold the tiles waiting to be swapped
var maxTilesToSwap: Int = 0 // temp. diagnostic
var blurredViews: [BlurViewController] = []
var animatingStatusHeight: Bool = false
var arrowEndPoints: [CGPoint] = []
//MARK:- IBOutlets
@IBOutlet weak var progressLabl: UILabel!
@IBOutlet weak var wordInProgress: UILabel!
@IBOutlet weak var startNewList: UIButton!
@IBOutlet weak var wordTableHolderView: UIView!
@IBOutlet weak var wordTableHeaderView: UIView!
@IBOutlet weak var wordTableHeaderCover: UIView!
@IBOutlet weak var wordTableHeaderCoverHeight: NSLayoutConstraint!
@IBOutlet weak var wordTableFooterCoverHeight: NSLayoutConstraint!
@IBOutlet weak var wordTable: UITableView!
@IBOutlet weak var proxyTable: ProxyTable!
@IBOutlet weak var proxyTableArrow: UIImageView!
@IBOutlet weak var toolbar: UIToolbar!
@IBOutlet weak var topConstraint: NSLayoutConstraint!
@IBOutlet weak var bottomConstraint: NSLayoutConstraint!
@IBOutlet weak var inProgressLeading: NSLayoutConstraint!
@IBOutlet weak var statusBgHeight: NSLayoutConstraint!
@IBOutlet weak var blurredViewHeight: NSLayoutConstraint!
@IBOutlet weak var statusBg: ShapeView!
@IBOutlet weak var downButton: UIButton!
//MARK:- IBActions
// Unwind segue from Progress view
@IBAction func cancelToProgressViewController(_ segue:UIStoryboardSegue) {
}
@IBAction func returnTiles(_ sender: AnyObject) {
returnTiles()
}
@IBAction func fillWordList(_ sender: AnyObject) {
fillInTheBlanks()
}
@IBAction func autoFillWords(_ sender: AnyObject) {
fillInWords("Auto Found the words")
}
@IBAction func autoFillMultiple(_ sender: AnyObject) {
for i in 0 ..< 100 {
fillInWords("AutoFind x \(i+1)")
generateNewWordlist()
}
}
// helper for autoFill
func fillInWords(_ message: String) {
if fillingInBlanks == false {
// For each word in the word list, mark each one as found, etc
for wordObject: Word in currentWords! {
if wordObject.active == true {
wordObject.found = true
}
}
saveContext()
updateProgress("Auto Found the words")
}
}
//MARK:- vars for UIDynamics
let gravity = UIGravityBehavior()
lazy var center: CGPoint = {
return CGPoint(x: self.view.frame.midX, y: self.view.frame.midY)
}()
fileprivate var animator: UIDynamicAnimator!
// Two different collision behaviors being used (One of them seems to have different gravity?)
fileprivate var collisionBehavior = UICollisionBehavior()
lazy var collider:UICollisionBehavior = {
let lazyCollider = UICollisionBehavior()
// This line makes the boundaries of our reference view a boundary
// for the added items to collide with.
lazyCollider.translatesReferenceBoundsIntoBoundary = true
return lazyCollider
}()
lazy var dynamicItemBehavior:UIDynamicItemBehavior = {
let lazyBehavior = UIDynamicItemBehavior()
lazyBehavior.elasticity = 0.5
lazyBehavior.allowsRotation = true
lazyBehavior.friction = 0.3
lazyBehavior.resistance = 0.5
return lazyBehavior
}()
lazy var uiDynamicItemBehavior:UIDynamicItemBehavior = {
let lazyBehavior = UIDynamicItemBehavior()
lazyBehavior.elasticity = 0.0
lazyBehavior.allowsRotation = false
lazyBehavior.density = 5500.0
lazyBehavior.friction = 5110.00
lazyBehavior.resistance = 5110.0
return lazyBehavior
}()
@IBAction func jumbleTiles(_ sender: AnyObject) {
//Find current positions of the letters. Randomize the positions of the letters. Later, snap to those positions
let sevenRandomizedInts = model.randomize7()
for j in 0 ..< 7 {
// There are 10 Positions, not 7. Tiles in the upper positions (7,8,9) will be returned to lower positions
letters[j].position = positions![sevenRandomizedInts[j]]
}
saveContext() // TODO: Need dispatch async?
for tile in lettertiles {
// To give a bit of a 3D effect, vary the tiles' scale, depending on how high they are in the view hierarchy. Their tags range from 1000 to 1007, so convert that to a range between 0.5 and 1. Numbers < 1 scale the tiles bigger.
let scaleFactor = (CGFloat(tile.tag - 1000) / 14.0) + 0.5
let s = CGAffineTransform(scaleX: scaleFactor, y: scaleFactor)
tile.layer.shadowOpacity = 0.95
tile.layer.shadowRadius = 24.0
tile.layer.shadowColor = UIColor.black.cgColor
UIView.animate(withDuration: 1.0, delay: 0.0, options: UIView.AnimationOptions.curveEaseIn, animations: { () -> Void in
tile.transform = s
}, completion: { (finished: Bool) -> Void in
tile.layer.shadowOpacity = 0.0 // remove the shadow when back in a box
})
}
jumbleTiles()
}
func jumbleTiles() {
//animator.setValue(true, forKey: "debugEnabled") // uncomment to see dynamics reference lines
animator.removeAllBehaviors() // reset the animator
uiDynamicItemBehavior.addItem(toolbar)
animator.addBehavior(gravity)
animator.addBehavior(collider)
animator.addBehavior(dynamicItemBehavior)
animator.addBehavior(uiDynamicItemBehavior)
// add the scroll view that holds the word list as a collider
collider.addItem(toolbar)
// Need to turn off gravity after awhile, otherwise it moves the tiles out of position
let gravityTimer = 1.0
let gravityDelay = gravityTimer * Double(NSEC_PER_SEC)
let gravityTime = DispatchTime.now() + Double(Int64(gravityDelay)) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: gravityTime) {
self.animator.removeBehavior(self.gravity)
}
// Delay snapping tiles back to positions until after the tiles have departed
var timer = 0.2
let delay = timer * Double(NSEC_PER_SEC)
let time = DispatchTime.now() + Double(Int64(delay)) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: time) {
timer = 0.1
for tile in self.lettertiles {
timer += 0.1
let delay = timer * Double(NSEC_PER_SEC)
let time = DispatchTime.now() + Double(Int64(delay)) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: time) {
tile.snapBehavior = UISnapBehavior(item: tile, snapTo: (tile.letter?.position?.position)!)
// // To do an action on every frame
// tile.snapBehavior?.action = {
// () -> Void in
// print("action")
// }
self.animator.addBehavior(tile.snapBehavior!)
self.collider.removeItem(tile) // keeps the letters from getting stuck on each other.
self.saveContext()
}
}
}
// for tile in lettertiles {
for i in 0 ..< lettertiles.count {
// add a push in a random but up direction
// taking into account that 0 (in radians) pushes to the right, and we want to vary between about 90 degrees (-1.57 radians) to the left, and to the right
// direction should be between ~ -3 and 0. or maybe ~ -.5 and -2.5 (needs fine tuning)
let direction = -1.5 * drand48() - 0.9
let push = UIPushBehavior(items: [lettertiles[i]], mode: .instantaneous)
push.angle = CGFloat(direction)
push.magnitude = CGFloat(7.0 * drand48() + 7.0)
animator.addBehavior(push)
// add gravity to each tile
collider.addItem(lettertiles[i])
gravity.addItem(lettertiles[i])
dynamicItemBehavior.addItem(lettertiles[i])
}
}
// MARK: - NSFetchedResultsController vars
lazy var sharedContext = {
CoreDataStackManager.sharedInstance().managedObjectContext
}()
lazy var fetchedResultsController: NSFetchedResultsController<NSFetchRequestResult> = {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Word")
//TODO: next line causing crash after upgrrde to swift 4. But commenting out line leaves the word feedback box blank
// fetchRequest.predicate = NSPredicate(format: "inCurrentList == %@", true as CVarArg)
fetchRequest.predicate = NSPredicate(format: "inCurrentList == %@", NSNumber(value: true))
//fetchRequest.predicate = NSPredicate(format: "inCurrentList == true")
// Add Sort Descriptors
let sortDescriptor = NSSortDescriptor(key: "word", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor]
let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.sharedContext, sectionNameKeyPath: nil, cacheName: nil)
fetchedResultsController.delegate = tableViewsDelegate
return fetchedResultsController
}()
// MARK:- Notifications
// Present definition when a word is tapped
@objc func presentDefinition(_ notification: Notification) {
if let pop = notification.userInfo?["item"] as? DefinitionPopoverVC {
self.present(pop, animated: true, completion: nil)
}
}
@objc func updateCurrentNumberOfWords(_ notification: Notification) {
if let cnow = notification.userInfo?["item"] as? Int {
currentNumberOfWords = cnow
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
print (":::::::A TO Z VC INIT:::::::")
}
//MARK:- View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector (presentDefinition(_:)), name: NSNotification.Name(rawValue: "PresentDefinition"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector (updateCurrentNumberOfWords(_:)), name: NSNotification.Name(rawValue: "UpdateCNOW"), object: nil)
//tableViewsDelegate = AtoZTableViewDelegates()
wordTable.delegate = tableViewsDelegate
proxyTable.delegate = tableViewsDelegate
wordTable.dataSource = tableViewsDelegate
proxyTable.dataSource = tableViewsDelegate
tableViewsDelegate.wordTable = wordTable
tableViewsDelegate.wordTableHeaderCoverHeight = wordTableHeaderCoverHeight
tableViewsDelegate.wordTableFooterCoverHeight = wordTableFooterCoverHeight
tableViewsDelegate.proxyTable = proxyTable
tableViewsDelegate.proxyTableArrow = proxyTableArrow
tableViewsDelegate.fetchedResultsController = fetchedResultsController
proxyTable.proxyTableArrow = proxyTableArrow
//wordTable.tableHeaderView = wordTableHeaderView
tableViewsDelegate.wordTableHeaderCover = wordTableHeaderCover
tableViewsDelegate.gradient = mainGradient
do {
try fetchedResultsController.performFetch()
} catch {
let fetchError = error as NSError
print("\(fetchError), \(fetchError.localizedDescription)")
}
game = model.game
// save the center of the wordTableHolderView, so that it can be used as snap position, to keep the wordTableHolderView in place after it is jostled by moving tiles.
wordHolderCenter = wordTableHolderView.center
// constants allow the tiles to be anchored at desired location
// vary vertiShift based on view height, to adjust per device
// for 4s: -475 480
// for 5s: -500 568
// for 6: -530 667
// for 6s plus: -540 736
// for X? -588
// TODO: also fine tune horiz. position
//let vertiShift = -475 - ((view.frame.size.height - 480) * 0.25)
let safeHeight = view.frame.size.height
// check and adjust for iPhone X (height affected by notch, and safe areas are not set until ViewDidAppear)
//if safeHeight > 800.0 { safeHeight = 734.0 } // won't work til ViewDidAppear
let vertiShift: CGFloat = (-0.25 * safeHeight) - 355
let vertiShiftX: CGFloat = 43.5 // adjustment for iPhone X
var vertiShiftUpperPositions: CGFloat = 120.0
var letterShiftX: CGFloat = 0.0
// adjustments for iPhone X
if safeHeight > 800.0 {
vertiShiftUpperPositions += vertiShiftX
letterShiftX = 30.0
bottomConstraint.constant = 34.0 // aligns table holder to bottom in iPhone X
} else {
bottomConstraint.constant = 0.0
}
print ("VERTIFSHIFT: \(vertiShift)")
print(view.frame.size.height)
print(safeHeight)
// if #available(iOS 11.0, *) {
// let guide = view.safeAreaLayoutGuide
// let height = guide.layoutFrame.size.height
// print (height)
// } else {
// // Fallback on earlier versions
// }
// var anchorPointShiftX: CGFloat = 90.0
// if view.frame.size.width < 321.0 { anchorPointShiftX = 104.5 } // shift for iPhone 5s, SE
let wordTableWidth = wordTableHolderView.frame.size.width + 3.0 // There's a 3 px inset from left
let tilesAnchorPoint = model.calculateAnchor(view.frame.size.width - wordTableWidth,
areaHeight: safeHeight,
vertiShift: vertiShift,
horizShift: wordTableWidth)
model.updateLetterPositions(letterShiftX: letterShiftX) // needed to get the view bounds first, and then go back to the model to update the Positions
// Set positions here, to the sorted array position from the model
//(Confusing because model.game.positions is a Set
positions = model.positions
// Adjust the constraints for the Tile UI background elements
topConstraint.constant = tilesAnchorPoint.y + CGFloat(120.0) - 0.5 * wordInProgress.frame.height
inProgressLeading.constant = tilesAnchorPoint.x - 0.5 * wordInProgress.frame.width
//scrollingSlider.transform = CGAffineTransformMakeRotation(CGFloat(M_PI * 0.5))
lettertiles = [Tile]()
tilesToSwap = [Tile]()
// Set Delegates
animator = UIDynamicAnimator(referenceView: view)
animator.delegate = uiDynamicsDelegate
//let bgImage = UIImage(named: "tile_bg") as UIImage?
for i in 0 ..< 7 {
//TODO: move some of this stuff to init for Tile
//TODO: use the eventual tile positions
if let tilePos = positions?[i].position {
let tile = Tile(frame: CGRect(x: tilePos.x, y: tilePos.y * CGFloat(i), width: 50, height: 50))
//let bgView = UIImageView(image: bgImage)
let bgView = TileHolderView(numTiles: 1, tileWidth: 50, borderWidth: 4.2, blurriness: 0.1, shadowWidth: 1.5, isTheTitleHolder: false)
bgView.tag = 2000 + i
bgView.center = tilePos
tile.setTitle("Q", for: UIControl.State()) // Q is placeholder value
tile.tag = 1000 + i
lettertiles.append(tile)
setupGestureRecognizers(tile)
view.addSubview(bgView)
view.addSubview(tile)
}
}
let upperPositionsView = TileHolderView(numTiles: 3, tileWidth: 50, borderWidth: 10.0, blurriness: 0.5, shadowWidth: 3.5, isTheTitleHolder: false)
upperPositionsView.center = CGPoint(x: tilesAnchorPoint.x, y: tilesAnchorPoint.y + vertiShiftUpperPositions)
self.view.addSubview(upperPositionsView)
/*
// add shadow
// finish, and use, getShadowMask
let upperPositionsShadow = ShapeView(numTiles: 3, tileWidth: 50, borderWidth: 10)
upperPositionsShadow.center = CGPoint(x: tilesAnchorPoint.x, y: tilesAnchorPoint.y + 120)
view.addSubview(upperPositionsShadow)
*/
/*
let upperPositionsBg = UIImage(named: "upper_positions_bg") as UIImage?
let upperPositionsView = UIImageView(image: upperPositionsBg)
upperPositionsView.alpha = 0.75
upperPositionsView.center = CGPoint(x: tilesAnchorPoint.x, y: tilesAnchorPoint.y + 120)
view.addSubview(upperPositionsView)
*/
// Make sure all tiles have higher z index than all bg's. Also when tapped
for t in lettertiles {
view.bringSubviewToFront(t)
}
// reference for memory leak bug, and fix:
// http://stackoverflow.com/questions/34075326/swift-2-iboutlet-collection-uibutton-leaks-memory
//TODO: check for memory leak here
checkForExistingLetters()
updateTiles()
generateWordList()
startNewList.alpha = 0
startNewList.isHidden = true
mainGradient = model.yellowPinkBlueGreenGradient()
mainGradient?.frame = view.bounds
mainGradient?.zPosition = -1
mainGradient?.name = "mainGradientLayer"
view.layer.addSublayer(mainGradient!)
//tableViewsDelegate.gradient = mainGradient
//let indexPath = IndexPath(row: 0, section: 0)
//wordTableHeaderView.layer.addSublayer(mainGradient!)
collisionBehavior = UICollisionBehavior(items: [])
for tile in lettertiles {
if (tile.boundingPath) != nil {
collisionBehavior.addBoundary(withIdentifier: "tile" as NSCopying, for: tile.boundingPath!)
}
}
animator.addBehavior(collisionBehavior)
setupDownButton()
}
// Helper for ViewDidLoad
func setupDownButton() {
let downButtonShape = TriangleView(frame: downButton.bounds, direction: .down, blurriness: 0.5, shadowWidth: 0.0)
downButtonShape.isUserInteractionEnabled = false
downButton.addSubview(downButtonShape)
}
// func updateSizeForHeaderView(inTableView tableView : UITableView) {
// let size = wordTableHeaderView.systemLayoutSizeFitting(wordTable.frame.size, withHorizontalFittingPriority: UILayoutPriority.required, verticalFittingPriority: UILayoutPriority.defaultLow)
// wordTableHeaderView.frame.size = size
// print(size)
// }
//
// override func viewWillLayoutSubviews() {
// super.viewWillLayoutSubviews()
// updateSizeForHeaderView(inTableView: wordTable)
// }
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
uiDynamicsDelegate?.lettertiles = lettertiles
//setUpProxyTable()
}
func setUpProxyTable () {
let arrowImage = UIImage(named: "icon_newlist")
let imageView = UIImageView(image: arrowImage)
proxyTable.addSubview(imageView)
imageView.contentMode = .redraw
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
print(view.frame.size.height)
if #available(iOS 11.0, *) {
let guide = view.safeAreaLayoutGuide
let height = guide.layoutFrame.size.height
print (height)
} else {
// Fallback on earlier versions
}
if game?.data?.fillingInBlanks == true {
fillingInBlanks = true
updateProgress("Filled")
wordListCompleted()
} else {
updateProgress(nil)
}
// credit to Aaron Douglas for showing how to turn on the fields of lines that visualize UIFieldBehaviors
// https://astralbodi.es/2015/07/16/uikit-dynamics-turning-on-debug-mode/
//animator.setValue(true, forKey: "debugEnabled")
// Disable the Tutorial until bugs are fixed (appears at correct times, and animation backgrounds are fixed)
/*
// When first loading, add a basic info panel about the game, with a dismiss button
// TODO: enable dismiss by tapping anywhere
// TODO: customize the info vc animation
// TODO: blur the background behind the info view controller
if game?.data?.gameState == 0 || game?.data?.gameState == 1 { // 1 allows showing every time, for testing
//animator.removeAllBehaviors()
game?.data?.gameState = 1 // set to state where info window is not shown
saveContext()
/*
let infoViewController = storyboard?.instantiateViewController(withIdentifier: "Intro") as! IntroViewController
// pass end points of arrows in
infoViewController.modalPresentationStyle = .overCurrentContext
infoViewController.arrowEndPoints = arrowEndPoints
self.present(infoViewController, animated: true)
*/
// TO Implement here: Instantiate TutorialViewController (on first open, and user request)
// and pass in the arrowEndPoints
let tutorial = TutorialViewController()
tutorial.buttonCenter = downButton.center.x
tutorial.modalPresentationStyle = .overCurrentContext
tutorial.arrowEndPoints = setArrowPoints()
self.present(tutorial, animated: true)
}
*/
}
func setArrowPoints() -> [CGPoint] {
// call in viewDidLayoutSubviews, to get arrow endpoints for tutorial
arrowEndPoints.removeAll()
if let ps = positions {
arrowEndPoints.append((ps[6].position))
}
let offset = toolbar.bounds.width * 0.18
arrowEndPoints.append(CGPoint(x: wordInProgress.center.x, y: wordInProgress.center.y) )
arrowEndPoints.append(CGPoint(x: wordTable.center.x + 50, y: 90.0))
arrowEndPoints.append(CGPoint(x: wordTable.center.x, y: 90.0))
arrowEndPoints.append(CGPoint(x: wordTable.center.x, y: wordTable.center.y))
arrowEndPoints.append(CGPoint(x: UIScreen.main.bounds.width - 12, y: wordTable.center.y))
arrowEndPoints.append(CGPoint(x: toolbar.center.x - offset, y: toolbar.center.y - 12.0))
arrowEndPoints.append(CGPoint(x: toolbar.center.x, y: toolbar.center.y - 12.0))
arrowEndPoints.append(CGPoint(x: toolbar.center.x + offset, y: toolbar.center.y - 12.0))
arrowEndPoints.append(CGPoint(x: toolbar.center.x + 2 * offset, y: toolbar.center.y - 12.0))
return arrowEndPoints
}
override func viewDidLayoutSubviews() {
// create arrow end points here (for use in tutorial)
// Is there a way to make this conditional, or to call only when the tutorial is requested?
// Tutorial only happens first time, or when user requests by tapping button
// viewDidLayoutSubviews gets called multiple times -- how to make it call only once?
arrowEndPoints = setArrowPoints() // need to avoid runnung multiple times
}
// note: as of ios 9, supposed to be that observers will be removed automatically
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
//NotificationCenter.default.removeObserver(self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
saveContext()
}
deinit {
print("AtoZ De-init")
}
//MARK:- Tile Swapping
// Each letter should have a position
func swapTile(_ tile: Tile) {
animator.removeAllBehaviors()
for anyTile in lettertiles {
animator.addBehavior(anyTile.snapBehavior!)
}
// add slight delay to give time for the positions to be updated and saved to context
// TODO: use completion handler instead of a delay every single time
//delay(0.15) { // still sometimes moves to a lower pos when an upper is open, and should be moved to
let newPosition = self.findVacancy(tile)
if newPosition != nil { // if newPosition is nil, then all spaces are occupied, and nothing happens
// update the Positions
let previousPosition = tile.letter?.position
previousPosition?.letter = nil // the previous position is now vacant
tile.letter?.position = newPosition
// Tiles drop slightly from gravity unless it's removed here. Gravity is added each time the tiles are jumbled anyway.
self.animator.removeBehavior(self.gravity)
//self.saveContext() // safest to save the context here, after every letter swap
self.saveContext() { success in
if success {
tile.snapBehavior?.snapPoint = (newPosition?.position)!
self.checkUpperPositionsForWord() // moved here from tileTapped, so it runs after the delay
}
}
}
}
// TODO: safer unwrapping
func swapTile() {
let tile = tilesToSwap![0]
tilesToSwap?.removeFirst()
animator.removeAllBehaviors()
for anyTile in lettertiles {
animator.addBehavior(anyTile.snapBehavior!)
}
let newPosition = self.findVacancy(tile)
if newPosition != nil { // if newPosition is nil, then all spaces are occupied, and nothing happens
// update the Positions
let previousPosition = tile.letter?.position
previousPosition?.letter = nil // the previous position is now vacant
tile.letter?.position = newPosition
// Tiles drop slightly from gravity unless it's removed here. Gravity is added each time the tiles are jumbled anyway.
self.animator.removeBehavior(self.gravity)
//self.saveContext() // safest to save the context here, after every letter swap
self.saveContext() { success in
if success {
guard let pos = newPosition?.position else {
// handle error
return
}
tile.snapBehavior?.snapPoint = pos//(newPosition?.position)!
self.checkUpperPositionsForWord()
if (self.tilesToSwap?.count)! > self.maxTilesToSwap {
self.maxTilesToSwap = (self.tilesToSwap?.count)!
}
// in case another tile is in the Q to swap, run this func again
//TODO: check whether this is ever called
if (self.tilesToSwap?.count)! > 0 {
self.swapTile()
}
}
}
}
}
//TODO: refactor the 3 swap tile funcs to not repeat code
// in the case that we already know the position
func swapTileToKnownPosition(_ tile: Tile, pos: Position) {
// update the Positions
let previousPosition = tile.letter?.position
previousPosition?.letter = nil // the previous position is now vacant
tile.letter?.position = pos
tile.snapBehavior?.snapPoint = pos.position
saveContext() // safest to save the context here, after every letter swap
}
func findVacancy(_ tile: Tile) -> Position? {
if tile.letter != nil { // tile.letter should never be nil, so this is an extra, possibly unneeded, safeguard. Which doesn't seem to work anyway.
// tile is in lower position, so look for vacancy in the uppers
if (tile.letter?.position!.index)! < 7 {
for i in 7 ..< 10 {
if self.positions![i].letter == nil {
self.collisionBehavior.addItem(tile) // enable collisions only for tiles when they are in 7 8 or 9
return positions![i]
}
}
return nil
} else { // must be in the upper positions, so look for a vacancy in the lowers
//TODO: verify that .stride is working correctly
// for var i=6; i>=0; i -= 1 {
for i in stride(from: 6, through: 0, by: -1) {
//for i in (0 ..< 6).reversed() {
if self.positions![i].letter == nil {
self.collisionBehavior.removeItem(tile)
return positions![i]
}
}
return nil
}
} else {
print ("was nil")
return nil
}
}
// added paramater 'first' only so #selector is recognized above - compiler can't disambiguate parameterless method
@objc func dismiss(first: Bool) {
self.dismiss(animated: true, completion: nil)
}
//MARK:-Tests
// print out a diagram to see the state of the Tiles and Positions
func printTileDiagram() {
for i in 0 ..< lettertiles.count {
//print("\(i): \(lettertiles[i].titleLabel!.text!) \(lettertiles[i].letter!.position!.index) \(lettertiles[i].letter!.position!.position) \(lettertiles[i].snapBehavior!.snapPoint)")
print(" \(lettertiles[i].letter!.position!.index) \(lettertiles[i].letter!.position!.position) \(lettertiles[i].snapBehavior!.snapPoint)")
}
print("====================================")
print("")
print("")
}
// Progress update //TODO: should these vars be stored to avoid recalc each word?
func updateProgress(_ message: String?) {
progressLabl.alpha = 1.0
if message != nil {
progressLabl.text = message
} else {
let numFound = currentNumFound()
if currentNumberOfWords != nil && model.inactiveCount != nil {
if numFound == currentNumberOfWords! - model.inactiveCount! {
// TODO: make wordListCompleted func
wordListCompleted()
// animateStatusHeight(80.0)
// progressLabl.text = "Word List Completed!"
// animateNewListButton()
} else {
progressLabl.text = "\(numFound) of \(currentNumberOfWords! - model.inactiveCount!) words found"
print("progressLabl.text: \(String(describing: progressLabl.text))")
}
print("progressLabl.text: \(progressLabl.text ?? "default")")
print(progressLabl.alpha)
}
}
UIView.animate(withDuration: 2.35, delay: 0.25, options: UIView.AnimationOptions.curveEaseOut, animations: { () -> Void in
self.progressLabl.alpha = 0.85
}, completion: { (finished: Bool) -> Void in
})
}
func wordListCompleted () {
statusBg.animateShape()
//animateStatusHeight(80.0)
progressLabl.text = "Word List Completed!"
animateNewListButton()
}
// each time a word is found, calculate how many have been found to show to the player
func currentNumFound() -> Int {
var numWordsFound: Int16 = 0
for aWord in (fetchedResultsController.fetchedObjects)! {
let w = aWord as? Word
if w?.found == true {
numWordsFound += 1
}
}
return Int(numWordsFound)
}
//MARK:- Actions
@IBAction func generateNewWordlist(_ sender: AnyObject) {
generateNewWordlist()
}
// This is where stats for a word are tracked (numTimesFound, numTimesPlayed)
//TODO:-- move tracking to separate func?
func generateNewWordlist() {
// still needed here? calling again later
game?.data?.level = model.calculateLevel()
// print("levelFromModel: \(String(describing: game?.data?.level))")
startNewList.alpha = 0
startNewList.isHidden = true
returnTiles() // if any tiles are in the upper positions, return them
// Generating a new list, so first, set all the previous Words 'found' property to false
// and, if the found property is true, first add 1 to the numTimesFound property
for i in 0 ..< fetchedResultsController.fetchedObjects!.count {
let indexPath = IndexPath(row: i, section: 0)
if let word = fetchedResultsController.object(at: indexPath) as? Word {
// check for active or not
if word.active == true {
word.numTimesPlayed += 1 // the # times the game has put that word into play
if word.found == true { // should work whether or no fillingInBlanks
word.numTimesFound += 1
}
} else { // Word was inactive for this round
print("Word was inactive: Level for \(word.word!): \(word.level)")
// Inactive words add to neither numTimesPlayed nor numTimesFound
word.active = true // reset all inactive words to inactive -- changes with each round
}
// reset values as the previous words are removed from the current list
word.found = false
word.inCurrentList = false
}
}
fillingInBlanks = false
game?.data?.fillingInBlanks = fillingInBlanks
saveContext()
// TODO: needed to set here? // fillingInBlanks = false // reset to false
// Now that the results of the previous round have been saved, create a new set of letters
currentLetterSet = model.generateLetterSet() // new set of letters created and saved to context
// converting the new LetterSet to an array, for use in this class
letters = currentLetterSet?.letters?.allObjects as? [Letter]
updateTiles()
//printTileDiagram()
currentWords = model.generateWords(letters)
// save the current # of words for use later in checkForValidWord
currentNumberOfWords = currentWords?.count
updateProgress(nil)
animateStatusHeight(52.0)
let levelFromModel = model.calculateLevel()
game?.data?.level = levelFromModel
print("levelFromModel: \(levelFromModel)")
saveContext()
let percentage = model.percentageFound()
print("percentage: \(percentage)")
let numListsPlayed = model.numListsPlayed()
var numWordsFound = 0
if let numWords = model.numWordsFound() {
numWordsFound = numWords
}
reportScores(levelFromModel, percentage: percentage, numberOfLists: numListsPlayed, numberOfWords: numWordsFound)
}
//MARK:-Tile Tapped
// replaces addLetterToWordInProgress(sender: Tile)
//TODO: instead of swapping the tile right away, check if a flag for a previous tileTap is true, if so, save the tile, wait until the context has been saved in swapTile, and then swap this new tile
// Create an array of Tiles to hold any tiles that are tapped, and waiting in line to be swapped
@IBAction func tileTapped(_ gesture: UIGestureRecognizer) {
if let tile = gesture.view as? Tile {
tilesToSwap?.append(tile)
// add the new letter to the word in progress
// if the flag that last tile has been finished is true, then:
//swapTile(tile) // swapping whichever tile is tapped
// otherwise, add a very slight delay first
swapTile()
// then, check for a valid word
// but iff 7 8 and 9 are occupado, then check for valid word
// checkUpperPositionsForWord() // moved to findVacancy(), so it can be inside the delay
// TODO: use a completion handler, so this line can be moved back to here
}
}
// need to incorporate this into func above this one (and consolidate with checkForValidWord)
func checkUpperPositionsForWord () {
if fillingInBlanks == false { // Check if the user has tapped Fill in the Blanks button
if positions![7].letter != nil && positions![8].letter != nil && positions![9].letter != nil {
let wordToCheck = (positions![7].letter?.letter)! + (positions![8].letter?.letter)! + (positions![9].letter?.letter)!
let wordIsValid = checkForValidWord(wordToCheck)
if wordIsValid { // return the letters to the letter pool
let time = DispatchTime.now() + 0.35
DispatchQueue.main.asyncAfter(deadline: time) {
//TODO: might be better to track which tiles have positions at 7 8 and 9 and checking those 3
// rather than checking all 7 tiles
self.returnTiles()
}
} else {
//word is *not* valid. Do nothing in that case (except show a message). The penalty to the user for playing an invalid word is that the flow of their game is interupted. They will have to return the letters manually (by tapping on a button)
updateProgress("That's not a word!")
}
}
}
}
func checkForValidWord(_ wordToCheck: String) -> Bool {
var wordIsNew = false
guard let numberOfWords = currentNumberOfWords else {
return false
}
for i in 0 ..< numberOfWords {
let indexPath = IndexPath(row: i, section: 0)
let aValidWord = fetchedResultsController.object(at: indexPath) as! Word
if wordToCheck == aValidWord.word {
// 3 cases:
// 1. word is inactive word.found==false && word.active==false
// 2. word has already been found word.found==true && word.active==true
// 3. word has been found for the first time word.found==false && word.active==true
if aValidWord.found == true { // case 2
updateProgress("Already found \(wordToCheck)")
} else if aValidWord.active == false { // case 1
updateProgress("\(wordToCheck) – already mastered!")
} else { // case 3
aValidWord.found = true
wordIsNew = true
saveContext()
}
// Needed to wait until after .found was set before updateProgress, otherwise the newly found word isn't counted
// But conditional, so we don't overwrite the "Already found.." message
if wordIsNew == true {
updateProgress(nil)
}
wordTable.scrollToRow(at: indexPath, at: UITableView.ScrollPosition.middle, animated: true)
proxyTable.scrollToRow(at: indexPath, at: UITableView.ScrollPosition.middle, animated: true)
return true
}
}
return false
}
// Check all 7 tiles over each position to find which ones to return
func returnTiles () {
for t in self.lettertiles {
if let _ = t.letter?.position {
if t.letter!.position!.index > 6 {
self.swapTile(t)
}
} else {
t.layer.opacity = 0.3 // a visual cue that something is not working correctly
}
}
}
//TODO: a function to check and reset positions to maintain integrity of model
func resetPositions() {
// There should be 7 positions with a letter, and 3 without
// All 7 Letter's should have a Position (and vice-versa)
// (Possibly these rules have been violated if their was a crash after the model has been changed, but before it was saved?)
}
// Pass text info to blurred background VC's
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let bubble = segue.destination as? BlurViewController else {
return
}
if segue.identifier == "BlurredStatusBG" {
blurredViews.append(bubble)
// Since we do not know in which order the controllers are added to blurredViews,
// set the index to the element just added to the array
let index = blurredViews.count - 1
blurredViews[index].shadowRadius = 2.4
blurredViews[index].shadowOpacity = 0.6
blurredViews[index].borderWidth = 0.2
}
}
func checkForExistingLetters () {
// if there is a saved letterset, then use that instead of a new one
game = model.fetchGame()
if let fib = game?.data?.fillingInBlanks {
fillingInBlanks = fib
}
if game?.data?.currentLetterSetID == nil {
currentLetterSet = model.generateLetterSet()
} else {
// there is a currentLetterSet, so let's find it
let lettersetURI = URL(string: (game?.data?.currentLetterSetID)!)
let id = sharedContext.persistentStoreCoordinator?.managedObjectID(forURIRepresentation: lettersetURI!)
do {
currentLetterSet = try sharedContext.existingObject(with: id!) as? LetterSet
// the Letter's are saved in Core Data as an NSSet, so convert to array
//letters = currentLetterSet?.letters?.allObjects as! [Letter]
} catch {
print("Error in getting current Letterset: \(error)")
}
}
}
func generateWordList() {
wordlist = model.generateWordlist(currentLetterSet?.letters?.allObjects as! [Letter])
currentWords = model.createOrUpdateWords(wordlist)
}
func updateTiles () {
// convert the LetterSet into an array
letters = currentLetterSet?.letters?.allObjects as? [Letter]
// Safeguard in case the correct number of letters has not been saved properly
if letters.count != lettertiles.count {
currentLetterSet = model.generateLetterSet()
saveContext()
letters = currentLetterSet?.letters?.allObjects as? [Letter]
}
// Possible fonts
//BanglaSangamMN-Bold //EuphemiaUCAS-Bold //GillSans-SemiBold //Copperplate-Bold
let attributes: [NSAttributedString.Key: Any] = [.font: UIFont(name: "EuphemiaUCAS-Bold", size: 30.0)!,
.foregroundColor: Colors.midBrown,
.strokeWidth: -3.0 as AnyObject,
.strokeColor: UIColor.black]
for i in 0 ..< lettertiles.count {
// TODO: set the attributed title in Tile.swift instead
let title = NSAttributedString(string: letters[i].letter!, attributes: attributes)
lettertiles[i].setAttributedTitle(title, for: UIControl.State())
lettertiles[i].letter = letters[i]
lettertiles[i].position = letters[i].position?.position
lettertiles[i].letter!.position = positions![i]
if lettertiles[i].snapBehavior != nil {
// update the snapPoint
lettertiles[i].snapBehavior?.snapPoint = (lettertiles[i].letter?.position?.position)!
} else { // Add snap behavior to Tile, but only if it doesn't already have one
//if lettertiles[i].snapBehavior == nil {
lettertiles[i].snapBehavior = UISnapBehavior(item: lettertiles[i], snapTo: lettertiles[i].letter!.position!.position)
lettertiles[i].snapBehavior?.damping = 0.6
animator.addBehavior(lettertiles[i].snapBehavior!)
}
}
saveContext() // Tile is not in the context, but letter.position is
}
func fillInTheBlanks() {
fillingInBlanks = true
// 'Cheat' function, to fill in unanswered words
//for var i=0; i<currentNumberOfWords; i += 1 {
for i in 0 ..< currentNumberOfWords! { //TODO: unwrap currentNumberOfWords safely
let indexPath = IndexPath(row: i, section: 0)
let aValidWord = fetchedResultsController.object(at: indexPath) as! Word
if aValidWord.found == false {
// fill in the word with red tiles
aValidWord.found = true // need to switch this to something else that will trigger configureCell
aValidWord.found = false
} else {
}
}
animateStatusHeight(80.0)
progressLabl.text = "\(currentNumFound()) of \(currentNumberOfWords! - model.inactiveCount!) words found"
animateNewListButton()
game?.data?.fillingInBlanks = true
saveContext()
}
// //TODO: layout the Tiles which are not using autolayout
// override func layoutSubviews() {
// super.layoutSubviews()
//
// }
//MARK:- Tapping and Panning for Tiles
func setupGestureRecognizers(_ tile: Tile) {
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(tileTapped(_:)))
let panRecognizer = UIPanGestureRecognizer(target: self, action: #selector(panTile(_:)))
tapRecognizer.delegate = gestureDelegate
panRecognizer.delegate = gestureDelegate
tile.addGestureRecognizer(tapRecognizer)
tile.addGestureRecognizer(panRecognizer)
panRecognizer.require(toFail: tapRecognizer)
}
//TODO:-set up custom behaviors as separate classes
@objc func panTile(_ pan: UIPanGestureRecognizer) {
animator.removeAllBehaviors()
let t = pan.view as! Tile
let location = pan.location(in: self.view)
// let startingLocation = location
// let sensitivity: Float = 10.0
switch pan.state {
case .began:
print("Began pan")
//animator?.removeBehavior(t.snapBehavior!) //TODO: behavior not being removed, and fighting with pan.
//TODO:-- each remove behavior, and/or, use attachment behavior instead of pan, as in WWDC video
t.superview?.bringSubviewToFront(t) // Make this Tile float above the other tiles
t.layer.shadowOpacity = 0.85
let scale = CGAffineTransform(scaleX: 1.25, y: 1.25)
let move = CGAffineTransform(translationX: 0.0, y: -58.0)
UIView.animate(withDuration: 0.15, delay: 0.0, options: UIView.AnimationOptions.curveEaseIn, animations: { () -> Void in
t.transform = scale.concatenating(move)
}, completion: { (finished: Bool) -> Void in
//hasFinishedBeganAnimation = finished
//print("ani done")
})
case .changed:
t.center = location
case .ended:
//TODO: make a completion block where 1st this code, then when velocity is below a set point, add the snap behavior
// let velocity = pan.velocityInView(self.view) // doesn't seem to be needed for a snap behavior
//
// collisionBehavior = UICollisionBehavior(items: [t])
// collisionBehavior.translatesReferenceBoundsIntoBoundary = true
//
// itemBehavior = UIDynamicItemBehavior(items: [t])
// itemBehavior.resistance = 5.5
// itemBehavior.angularResistance = 2
// itemBehavior.elasticity = 1.1
// animator?.addBehavior(itemBehavior)
// animator?.addBehavior(collisionBehavior)
// itemBehavior.addLinearVelocity(velocity, forItem: t)
// interesting. is Position not an optional type, but then closestOpenPosition could still be a nil?
// check for the nearest unoccupied position, and snap to that
//TODO:- if tile is moved only very very slightly, move it back to original position
// but problem: no way to determine if user meant to move and let it snap back, or if user meant to tap
// hypothesis: if movement is tiny, user meant to tap, so should move to upper/lower position
// if movement is small but not tiny, indicates intention to start to pan, and then decided to stop
// so move back to original position
if let closestOpenPosition = model.findClosestPosition(location, positionArray: positions!) {
swapTileToKnownPosition(t, pos: closestOpenPosition)
checkUpperPositionsForWord()
}
// seemed to have extra snapping behaviors interfering, so removed all behaviors, and added back here.
for tile in lettertiles {
animator.addBehavior(tile.snapBehavior!)
}
t.layer.shadowOpacity = 0.0
t.transform = CGAffineTransform.identity
default:
break
}
}
//MARK:- Animations
func animateTile(_ sender: AnyObject) {
_ = [UIView.animate(withDuration: 5.0, delay: 0.0, options: [.curveLinear, .allowUserInteraction], animations: {
}, completion: nil)]
}
func animateStatusHeight(_ ht: CGFloat) {
animatingStatusHeight = true
// if self.blurredViews.count > 0 {
// blurredViews[0].animatingStatusHeight = true
// }
UIView.animate(withDuration: 0.4 , animations: {
self.statusBgHeight.constant = ht
self.blurredViewHeight.constant = ht
self.view.layoutIfNeeded()
}, completion: {completion in
// self.animatingStatusHeight = false
// print(self.animatingStatusHeight)
// if self.blurredViews.count > 0 {
// self.blurredViews[0].animatingStatusHeight = false
// }
})
}
func animateNewListButton() {
UIView.animate(withDuration: 0.9, animations: {
self.startNewList.isHidden = false
self.startNewList.alpha = 1.0
self.view.layoutIfNeeded()
})
}
// MARK: - Core Data Saving support
func saveContext () {
if sharedContext.hasChanges {
do {
try sharedContext.save()
} catch {
let nserror = error as NSError
print("Could not save the Managed Object Context")
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
// save context with completion handler
func saveContext (_ completion: (_ success: Bool)-> Void) {
if sharedContext.hasChanges {
do {
try sharedContext.save()
completion(true)
} catch {
let nserror = error as NSError
print("Could not save the Managed Object Context")
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
completion(false)
}
}
}
// MARK:- Delay function
//http://www.globalnerdy.com/2015/09/30/swift-programming-tip-how-to-execute-a-block-of-code-after-a-specified-delay/
func delay(_ delay: Double, closure: @escaping ()->()) {
DispatchQueue.main.asyncAfter(
deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC),
execute: closure
)
}
}
| 42.881383 | 260 | 0.594874 |
f782a91e60e82e0dfbd10073c4f287604668a0dc | 3,032 | //
// BaseAllLivingVC.swift
// XMTV
//
// Created by Mac on 2017/1/18.
// Copyright © 2017年 Mac. All rights reserved.
//
import UIKit
class BaseAllLivingVC: BaseVC {
var baseVM: BaseVM!
lazy var collectionView : UICollectionView = {[unowned self] in
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: kNormalItemW, height: kNormalItemH)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = kItemMargin
layout.sectionInset = UIEdgeInsets(top: kItemMargin, left: kItemMargin, bottom: 0, right: kItemMargin)
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.backgroundColor = UIColor.white
collectionView.dataSource = self
collectionView.delegate = self
collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
collectionView.register(UINib(nibName: "CollectionNormalCell", bundle: nil), forCellWithReuseIdentifier: NormalCellID)
return collectionView
}()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
loadData()
}
}
// MARK: -
extension BaseAllLivingVC {
override func setupUI() {
contentView = collectionView
view.addSubview(collectionView)
super.setupUI()
}
}
// MARK: - loadData
extension BaseAllLivingVC {
func loadData() {}
}
// MARK: - UICollectionView代理数据源方法
extension BaseAllLivingVC : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if baseVM.anchorGroups.count > 0 {
return baseVM.anchorGroups[section].anchors.count
} else {
return 0
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NormalCellID, for: indexPath) as! CollectionNormalCell
cell.anchor = baseVM.anchorGroups[indexPath.section].anchors[indexPath.item]
return cell
}
}
extension BaseAllLivingVC : UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// let anchor = baseVM.anchorGroups[indexPath.section].anchors[indexPath.item]
// anchor.isVertical == 0 ? pushNormalRoomVc(anchor) : presentShowRoomVc(anchor)
}
// private func presentShowRoomVc(_ anchor : AnchorModel) {
// let showVc = ShowRoomVC()
// showVc.anchor = anchor
// present(showVc, animated: true, completion: nil)
// }
//
// private func pushNormalRoomVc(_ anchor : AnchorModel) {
// let normalVc = NormalRoomVC()
// normalVc.anchor = anchor
// navigationController?.pushViewController(normalVc, animated: true)
// }
}
| 33.318681 | 129 | 0.667876 |
0a23086d30ba45efe3830c7e2760eb671e78f611 | 2,795 | //
// ViewSelectionViewController.swift
// FlexLayout
//
// Created by anthann on 2019/5/4.
// Copyright © 2019 anthann. All rights reserved.
//
import UIKit
import SnapKit
class ViewSelectionViewController: UIViewController {
var candidates: [ViewCandidateModel]?
var completeBlock: ((Int) -> Void)?
var dismissBlock: (() -> Void)?
lazy var collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.minimumLineSpacing = 20
layout.itemSize = CGSize(width: 240, height: 90)
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.contentInset = UIEdgeInsets(top: 20, left: 0, bottom: 20, right: 0)
collectionView.delegate = self
collectionView.dataSource = self
collectionView.backgroundColor = .white
collectionView.register(CandidateCollectionViewCell.self, forCellWithReuseIdentifier: "candidate cell")
return collectionView
}()
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.preferredContentSize = CGSize(width: 240.0, height: 400.0)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
view.addSubview(collectionView)
collectionView.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
}
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
dismissBlock?()
}
}
extension ViewSelectionViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
guard let candidates = self.candidates else {
return 0
}
return candidates.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let candidates = self.candidates else {
fatalError()
}
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "candidate cell", for: indexPath) as! CandidateCollectionViewCell
cell.model = candidates[indexPath.item]
return cell
}
}
extension ViewSelectionViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
dismissBlock = nil
dismiss(animated: true) {
self.completeBlock?(indexPath.item)
}
}
}
| 33.674699 | 140 | 0.678712 |
e6520578c6e6f0abaa0cdd622cb103097598a182 | 2,238 | // Telegrammer - Telegram Bot Swift SDK.
// This file is autogenerated by API/generate_wrappers.rb script.
public extension Bot {
/// Parameters container struct for `forwardMessage` method
struct ForwardMessageParams: JSONEncodable {
/// Unique identifier for the target chat or username of the target channel (in the format @channelusername)
var chatId: ChatId
/// Unique identifier for the chat where the original message was sent (or channel username in the format @channelusername)
var fromChatId: ChatId
/// Sends the message silently. Users will receive a notification with no sound.
var disableNotification: Bool?
/// Message identifier in the chat specified in from_chat_id
var messageId: Int
/// Custom keys for coding/decoding `ForwardMessageParams` struct
enum CodingKeys: String, CodingKey {
case chatId = "chat_id"
case fromChatId = "from_chat_id"
case disableNotification = "disable_notification"
case messageId = "message_id"
}
public init(chatId: ChatId, fromChatId: ChatId, disableNotification: Bool? = nil, messageId: Int) {
self.chatId = chatId
self.fromChatId = fromChatId
self.disableNotification = disableNotification
self.messageId = messageId
}
}
/**
Use this method to forward messages of any kind. On success, the sent Message is returned.
SeeAlso Telegram Bot API Reference:
[ForwardMessageParams](https://core.telegram.org/bots/api#forwardmessage)
- Parameters:
- params: Parameters container, see `ForwardMessageParams` struct
- Throws: Throws on errors
- Returns: Future of `Message` type
*/
@discardableResult
func forwardMessage(params: ForwardMessageParams) throws -> Future<Message> {
let body = try httpBody(for: params)
let headers = httpHeaders(for: params)
return try client
.request(endpoint: "forwardMessage", body: body, headers: headers)
.flatMapThrowing { (container) -> Message in
return try self.processContainer(container)
}
}
}
| 36.688525 | 131 | 0.660411 |
673adbe20aac86ada2faef275f1ae90da3c5cb3b | 4,489 | //
// MoveCategoryAPI.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
#if canImport(AnyCodable)
import AnyCodable
#endif
open class MoveCategoryAPI {
/**
- parameter limit: (query) (optional)
- parameter offset: (query) (optional)
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the data and the error objects
*/
@discardableResult
open class func moveCategoryList(limit: Int? = nil, offset: Int? = nil, apiResponseQueue: DispatchQueue = OpenAPIClientAPI.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) -> RequestTask {
return moveCategoryListWithRequestBuilder(limit: limit, offset: offset).execute(apiResponseQueue) { result in
switch result {
case let .success(response):
completion(response.body, nil)
case let .failure(error):
completion(nil, error)
}
}
}
/**
- GET /api/v2/move-category/
- parameter limit: (query) (optional)
- parameter offset: (query) (optional)
- returns: RequestBuilder<String>
*/
open class func moveCategoryListWithRequestBuilder(limit: Int? = nil, offset: Int? = nil) -> RequestBuilder<String> {
let localVariablePath = "/api/v2/move-category/"
let localVariableURLString = OpenAPIClientAPI.basePath + localVariablePath
let localVariableParameters: [String: Any]? = nil
var localVariableUrlComponents = URLComponents(string: localVariableURLString)
localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([
"limit": limit?.encodeToJSON(),
"offset": offset?.encodeToJSON(),
])
let localVariableNillableHeaders: [String: Any?] = [
:
]
let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
let localVariableRequestBuilder: RequestBuilder<String>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder()
return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters)
}
/**
- parameter id: (path)
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the data and the error objects
*/
@discardableResult
open class func moveCategoryRead(id: Int, apiResponseQueue: DispatchQueue = OpenAPIClientAPI.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) -> RequestTask {
return moveCategoryReadWithRequestBuilder(id: id).execute(apiResponseQueue) { result in
switch result {
case let .success(response):
completion(response.body, nil)
case let .failure(error):
completion(nil, error)
}
}
}
/**
- GET /api/v2/move-category/{id}/
- parameter id: (path)
- returns: RequestBuilder<String>
*/
open class func moveCategoryReadWithRequestBuilder(id: Int) -> RequestBuilder<String> {
var localVariablePath = "/api/v2/move-category/{id}/"
let idPreEscape = "\(APIHelper.mapValueToPathItem(id))"
let idPostEscape = idPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? ""
localVariablePath = localVariablePath.replacingOccurrences(of: "{id}", with: idPostEscape, options: .literal, range: nil)
let localVariableURLString = OpenAPIClientAPI.basePath + localVariablePath
let localVariableParameters: [String: Any]? = nil
let localVariableUrlComponents = URLComponents(string: localVariableURLString)
let localVariableNillableHeaders: [String: Any?] = [
:
]
let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
let localVariableRequestBuilder: RequestBuilder<String>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder()
return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters)
}
}
| 42.349057 | 229 | 0.689463 |
f727b2ae964e7b31ef5706c40d0e53ec1166130a | 5,914 | //: Playground - noun: a place where people can play
import Cocoa
// LinkedList Node
class Node<T> {
var key: T
var next: Node?
init(key: T) {
self.key = key
}
}
// LinkedList for Queue
class LinkedList<T> {
public var head: Node<T>?
public var count: Int {
guard head != nil else {return 0}
var currentNode = head
var count = 0
while currentNode != nil {
count += 1
currentNode = currentNode?.next
}
return count
}
public var isEmpty: Bool {return self.head == nil}
public func append(element node: Node<T>) {
guard head != nil else {
head = node
return
}
var currentNode = head
while currentNode?.next != nil {
currentNode = currentNode?.next
}
currentNode?.next = node
}
public func dropFirst() -> T? {
guard let oldHead = head else {return nil}
self.head = oldHead.next
return oldHead.key
}
}
// Queue for Breadth first traversal
struct Queue<T> {
private var arr = LinkedList<T>()
public var count: Int {return arr.count}
public var isEmpty: Bool {return arr.isEmpty}
public mutating func enQueue(_ element: T) {
arr.append(element: Node(key: element))
}
public mutating func deQueue() -> T? {
guard !arr.isEmpty else {return nil}
return arr.dropFirst()
}
public func peek() -> T? {
return arr.head?.key
}
}
// Binary Tree
enum Order {
case inOrder
case preOrder
case postOrder
}
class NumberTreeNode {
var key: Int
var left: NumberTreeNode?
var right: NumberTreeNode?
init(key: Int) {
self.key = key
}
public func insert(_ value: Int) {
if value <= key { // left side
if left == nil {left = NumberTreeNode(key: value)} else {left?.insert(value)}}
else { //value > key, right side
if right == nil {right = NumberTreeNode(key: value)}
else {right?.insert(value)}}
}
public func contains(value: Int) -> Bool {
if value == key { return true } else if value < key {
if left == nil { return false }
else {return left!.contains(value: value)}} // go down a level on left
else { //value less than key
if right == nil {return false}
else {return right!.contains(value:value)}} // go down a level on right
}
public func printInOrder(order: Order) {
//preorder
switch order {
case .preOrder:
print(key)
left?.printInOrder(order: .preOrder)
right?.printInOrder(order: .preOrder)
case .inOrder:
left?.printInOrder(order: .inOrder)
print(key)
right?.printInOrder(order: .inOrder)
case .postOrder:
left?.printInOrder(order: .postOrder)
right?.printInOrder(order: .postOrder)
print(key)
}
}
}
class BinaryTreeNode<T> {
var key: T
var left: BinaryTreeNode?
var right: BinaryTreeNode?
init(key: T) {
self.key = key
}
public func preOrderDepthFirstTraversal() {
print(key)
left?.preOrderDepthFirstTraversal()
right?.preOrderDepthFirstTraversal()
}
public func inOrderDepthFirstTraversal() {
left?.inOrderDepthFirstTraversal()
print(key)
right?.inOrderDepthFirstTraversal()
}
public func postOrderDepthFirstTraversal() {
left?.postOrderDepthFirstTraversal()
right?.postOrderDepthFirstTraversal()
print(key)
}
}
class BinaryTree<T> {
var root: BinaryTreeNode<T>?
var numRoot: NumberTreeNode?
public func breadthFirstTraversal() {
guard let root = self.root else {return}
var processQueue = Queue<BinaryTreeNode<T>>()
processQueue.enQueue(root) // enQueue root node to execute loop
while !processQueue.isEmpty {
let currentNode = processQueue.deQueue()! // returns BinaryTreeNode of each level from left to right
print(currentNode.key)
if let leftNode = currentNode.left { // if there is more left node
processQueue.enQueue(leftNode)
}
if let rightNode = currentNode.right { // if there is more right node
processQueue.enQueue(rightNode)
}
}
}
public func depthFirstTraversal(in order: Order) {
guard let root = root else {return}
switch order {
case .preOrder:
root.preOrderDepthFirstTraversal()
case .inOrder:
root.inOrderDepthFirstTraversal()
case .postOrder:
root.postOrderDepthFirstTraversal()
}
}
}
//BinaryTreeNode
let tree = BinaryTree<Int>()
let root = BinaryTreeNode(key: 0)
let nodeOne = BinaryTreeNode(key: 1)
let nodeTwo = BinaryTreeNode(key: 2)
let nodeThree = BinaryTreeNode(key: 3)
let nodeFour = BinaryTreeNode(key: 4)
let nodeFive = BinaryTreeNode(key: 5)
let nodeSix = BinaryTreeNode(key: 6)
tree.root = root
root.left = nodeOne
root.right = nodeTwo
nodeOne.left = nodeThree
nodeOne.right = nodeFour
nodeFour.right = nodeSix
nodeTwo.right = nodeFive
tree.breadthFirstTraversal()
//print()
//tree.depthFirstTraversal(in: .inOrder)
/************************************/
//NumberTreeNode that contain only Integers
//Call insert function to automatically insert in sorted order of BST
let numTree = BinaryTree<Int>()
let numRoot = NumberTreeNode(key: 1)
numTree.numRoot = numRoot
numTree.numRoot?.insert(2)
numTree.numRoot?.insert(3)
numTree.numRoot?.insert(6)
numTree.numRoot?.insert(4)
numTree.numRoot?.insert(9)
numTree.numRoot?.insert(11)
//
//numTree.numRoot?.contains(value: 9)
//print("numTree")
//numTree.numRoot?.printInOrder(order: .inOrder)
| 28.296651 | 112 | 0.607203 |
e62062415de6eea67296e35c9ec19735ceb95a01 | 10,382 | //
// ChatViewController.swift
// XWallet
//
// Created by HeiHua BaiHua on 2020/3/9.
// Copyright © 2020 Andy.Chan 6K. All rights reserved.
//
import WKKit
import RxSwift
import FunctionX
import SwiftyJSON
import TrustWalletCore
extension WKWrapper where Base == ChatViewController {
var view: ChatViewController.View { return base.view as! ChatViewController.View }
}
extension ChatViewController {
override class func instance(with context: [String : Any] = [:]) -> UIViewController? {
guard let receiver = context["receiver"] as? SmsUser,
let wallet = context["wallet"] as? FxWallet else { return nil }
return ChatViewController(receiver: receiver, wallet: wallet)
}
}
class ChatViewController: WKViewController {
required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") }
init(receiver: SmsUser, wallet: FxWallet) {
self.viewModel = ViewModel(receiver: receiver, wallet: wallet)
super.init(nibName: nil, bundle: nil)
}
let viewModel: ViewModel
var wallet: FxWallet { viewModel.wallet }
var receiver: SmsUser { viewModel.service.receiver }
fileprivate lazy var listBinder = WKTableViewBinder<CellViewModel>(view: wk.view.listView)
fileprivate lazy var snapshotBinder = SnapshotBinder()
fileprivate var sendTextAction: Action<String, JSON>!
override func loadView() { self.view = View(frame: ScreenBounds) }
override func viewDidLoad() {
super.viewDidLoad()
logWhenDeinit()
bindNavBar()
bindListView()
bindSentText()
bindKeyboard()
bindTextInputPanel()
fetchData()
}
private func fetchData() {
listBinder.refresh()
}
override func bindNavBar() {
navigationBar.isHidden = true
weak var welf = self
wk.view.nameLabel.text = receiver.name
wk.view.navBar.backButton.rx.tap.subscribe(onNext: { (_) in
welf?.navigationController?.popViewController(animated: true)
}).disposed(by: defaultBag)
wk.view.navBar.rightButton.rx.tap.subscribe(onNext: { (_) in
Router.showChatMessageEncryptedTipAlert()
}).disposed(by: defaultBag)
viewModel.lastUpdateDate
.bind(to: wk.view.updateDateLabel.rx.text)
.disposed(by: defaultBag)
// let item = UIBarButtonItem(customView: wk.view.navLeftView)
// navigationBar.navigationItem.leftBarButtonItems?.append(item)
// navigationBar.action(.right, imageName: "Chat.Lock") { () in
// Router.showChatMessageEncryptedTipAlert()
// }?.config(config: { $0?.tintColor = HDA(0x14ff66) })
}
private func bindListView() {
weak var welf = self
let listView = wk.view.listView
listView.viewModels = { section in
guard let this = welf else { return section }
for vm in this.viewModel.items {
section.push(Cell.cls(for: vm), m: vm)
}
return section
}
// viewModel.refreshItems.errors.subscribe(onNext: { [] (error) in
// if error.isNoData { return }
// welf?.hud?.text(m: error.asWKError().msg)
// }).disposed(by: defaultBag)
viewModel.firstLoadFinished
.filter{$0}
.delay(RxTimeInterval.milliseconds(300), scheduler: MainScheduler.instance)
.subscribe(onNext: { _ in listView.scrollToBottom(true) })
.disposed(by: defaultBag)
viewModel.needReload
.delay(RxTimeInterval.milliseconds(200), scheduler: MainScheduler.instance)
.subscribe(onNext: { _ in
listView.reloadData()
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2) {
listView.scrollToBottom(true)
}
})
.disposed(by: defaultBag)
listBinder.bindListError = {}
listBinder.bindListFooter = {}
listBinder.refreshWithHUD = false
listBinder.bind(viewModel)
}
private func bindSentText() {
weak var welf = self
let textInputTV = wk.view.textInputTV
let hasInput = textInputTV.interactor.rx.text.map{ $0?.count != 0 }
sendTextAction = Action(workFactory: { (text) -> Observable<JSON> in
guard let this = welf else { return Observable.empty() }
return this.viewModel.service.send(sms: text)
})
_ = sendTextAction.elements.subscribe(onNext: { (_) in }) //hold the sending signal
Observable.combineLatest(hasInput, sendTextAction.executing)
.map{ $0.0 && !$0.1}
.bind(to: wk.view.textInputPanel.sendTextButton.rx.isEnabled)
.disposed(by: defaultBag)
wk.view.textInputPanel.sendTextButton.rx.tap.subscribe(onNext: { (_) in
guard textInputTV.text.isNotEmpty else { return }
welf?.sendTextAction.execute(textInputTV.text)
textInputTV.text = ""
}).disposed(by: defaultBag)
}
private func bindTextInputPanel() {
weak var welf = self
let textInputPanel = wk.view.textInputPanel
textInputPanel.sendGiftButton.rx.tap.subscribe(onNext: { (_) in
guard let this = welf else { return }
Router.presentSendCryptoGift(receiver: this.receiver, wallet: this.wallet)
}).disposed(by: defaultBag)
//textInputTV.height
let padding = 8
wk.view.textInputTV.interactor.rx.text.subscribe(onNext: { (value) in
let text = value ?? ""
var height: CGFloat = 40
let inputWidth = textInputPanel.inputWidth
if text.count > 12 {
height = text.height(ofWidth: inputWidth, attributes: [.font: XWallet.Font(ofSize: 16)]) + 12
height = max(40, height)
height = min(100, height)
}
height += CGFloat(padding * 2)
if textInputPanel.height != height {
textInputPanel.snp.updateConstraints { (make) in
make.height.equalTo(height)
}
}
}).disposed(by: defaultBag)
let listView = wk.view.listView
listView.rx.didEndDragging.subscribe(onNext: { (_) in
guard textInputPanel.textInputTV.interactor.isFirstResponder,
listView.panGestureRecognizer.translation(in: listView.superview).y > 0 else {
return
}
welf?.view.endEditing(true)
}).disposed(by: defaultBag)
}
override func router(event: String, context: [String : Any]) {
guard let cell = context[eventSender] as? Cell,
let sms = cell.getViewModel() else { return }
if event == Cell.longTapEvent {
showSnapshot(cell: cell, sms: sms.rawValue)
} else if event == Cell.resendTapEvent {
_ = viewModel.service.resend(sms: sms).subscribe()
}
}
private func showSnapshot(cell: Cell, sms: SmsMessage) {
weak var welf = self
let text = cell.snapshotText()
let onClickCopy = {
UIPasteboard.general.string = text
welf?.view.hud?.text(m: TR("Copied"))
}
let onClickInfo = {
guard let this = welf else { return }
Router.presentChatMessageInfo(receiver: this.receiver, wallet: this.wallet, sms: sms)
}
snapshotBinder.show(snapshot: cell, inView: self.view, onClickCopy: onClickCopy, onClickInfo: onClickInfo)
}
var offsetBeforeInput: CGPoint?
private func bindKeyboard() {
NotificationCenter.default.rx
.notification(UIResponder.keyboardWillShowNotification)
.takeUntil(self.rx.deallocated)
.subscribe(onNext: { [weak self] notif in
guard let this = self, this.navigationController?.topViewController == this else { return }
this.wk.view.textInputTV.layer.borderColor = UIColor.white.withAlphaComponent(0.5).cgColor
let duration = notif.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as! TimeInterval
let endFrame = (notif.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
let margin = UIScreen.main.bounds.height - endFrame.origin.y
this.wk.view.contentView.snp.updateConstraints( { (make) in
make.bottom.equalTo(this.view).offset(-margin)
})
if this.offsetBeforeInput == nil {
let listView = this.wk.view.listView
this.offsetBeforeInput = listView.contentOffset
listView.setContentOffset(CGPoint(x: 0, y: listView.contentOffset.y + margin), animated: listView.isDecelerating)
}
UIView.animate(withDuration: duration) {
this.view.layoutIfNeeded()
}
}).disposed(by: defaultBag)
NotificationCenter.default.rx
.notification(UIResponder.keyboardWillHideNotification)
.takeUntil(self.rx.deallocated)
.subscribe(onNext: { [weak self] notif in
guard let this = self, this.navigationController?.topViewController == this else { return }
this.offsetBeforeInput = nil
this.wk.view.textInputTV.layer.borderColor = UIColor.white.withAlphaComponent(0.25).cgColor
let duration = notif.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as! TimeInterval
this.wk.view.contentView.snp.updateConstraints( { (make) in
make.bottom.equalTo(this.view)
})
UIView.animate(withDuration: duration) {
this.view.layoutIfNeeded()
}
}).disposed(by: defaultBag)
}
}
| 38.169118 | 133 | 0.587459 |
c1a83f855eabd0153682cb438bdb6c34f6078cd2 | 290 | //
// Weak.swift
// Walkie Talkie
//
// Created by Sebastien Menozzi on 01/01/2020.
// Copyright © 2020 Sebastien Menozzi. All rights reserved.
//
import Foundation
/// A box that allows us to weakly hold on to an object
struct Weak<Object: AnyObject> {
weak var value: Object?
}
| 19.333333 | 60 | 0.693103 |
08004e74509ea790d1f37b55491a6aaee6b2d15a | 626 | //
// PXContainedLabelComponent.swift
// MercadoPagoSDK
//
// Created by AUGUSTO COLLERONE ALFONSO on 1/23/18.
// Copyright © 2018 MercadoPago. All rights reserved.
//
import UIKit
internal class PXContainedLabelComponent: PXComponentizable {
public func render() -> UIView {
return PXContainedLabelRenderer().render(self)
}
var props: PXContainedLabelProps
init(props: PXContainedLabelProps) {
self.props = props
}
}
internal class PXContainedLabelProps {
var labelText: NSAttributedString
init(labelText: NSAttributedString) {
self.labelText = labelText
}
}
| 20.866667 | 61 | 0.70607 |
e5c2f6c3f5720e509265eb820cb46bde239980e0 | 3,900 | //
// LeftTypeSixViewController.swift
// AnimatedDropdownMenu
//
// Created by JonyFang on 17/3/3.
// Copyright © 2017年 JonyFang. All rights reserved.
//
import UIKit
import AnimatedDropdownMenu
class LeftTypeSixViewController: UIViewController {
// MARK: - Properties
fileprivate let dropdownItems: [AnimatedDropdownMenu.Item] = [
AnimatedDropdownMenu.Item.init("From | Photography", nil, nil),
AnimatedDropdownMenu.Item.init("From | Artwork", nil, nil),
AnimatedDropdownMenu.Item.init("Others", nil, nil)
]
fileprivate var selectedStageIndex: Int = 0
fileprivate var lastStageIndex: Int = 0
fileprivate var dropdownMenu: AnimatedDropdownMenu!
// MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
setupAnimatedDropdownMenu()
view.backgroundColor = .white
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
resetNavigationBarColor()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
dropdownMenu.show()
}
// MARK: - Private Methods
fileprivate func setupAnimatedDropdownMenu() {
let dropdownMenu = AnimatedDropdownMenu(navigationController: navigationController, containerView: view, selectedIndex: selectedStageIndex, items: dropdownItems)
dropdownMenu.cellBackgroundColor = UIColor.menuPurpleColor()
dropdownMenu.menuTitleColor = UIColor.menuLightTextColor()
dropdownMenu.menuArrowTintColor = UIColor.menuLightTextColor()
dropdownMenu.cellTextColor = UIColor.init(white: 1.0, alpha: 0.3)
dropdownMenu.cellTextSelectedColor = UIColor.menuLightTextColor()
dropdownMenu.cellSeparatorColor = UIColor.init(white: 1.0, alpha: 0.1)
dropdownMenu.cellTextAlignment = .left
dropdownMenu.didSelectItemAtIndexHandler = {
[weak self] selectedIndex in
guard let strongSelf = self else {
return
}
strongSelf.lastStageIndex = strongSelf.selectedStageIndex
strongSelf.selectedStageIndex = selectedIndex
guard strongSelf.selectedStageIndex != strongSelf.lastStageIndex else {
return
}
//Configure Selected Action
strongSelf.selectedAction()
}
self.dropdownMenu = dropdownMenu
navigationItem.titleView = dropdownMenu
}
private func selectedAction() {
print("\(dropdownItems[selectedStageIndex].title)")
}
fileprivate func resetNavigationBarColor() {
navigationController?.navigationBar.barStyle = .black
navigationController?.navigationBar.barTintColor = UIColor.menuPurpleColor()
let textAttributes: [String: Any] = [
convertFromNSAttributedStringKey(NSAttributedString.Key.foregroundColor): UIColor.menuLightTextColor(),
convertFromNSAttributedStringKey(NSAttributedString.Key.font): UIFont.navigationBarTitleFont()
]
navigationController?.navigationBar.titleTextAttributes = convertToOptionalNSAttributedStringKeyDictionary(textAttributes)
}
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertFromNSAttributedStringKey(_ input: NSAttributedString.Key) -> String {
return input.rawValue
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertToOptionalNSAttributedStringKeyDictionary(_ input: [String: Any]?) -> [NSAttributedString.Key: Any]? {
guard let input = input else { return nil }
return Dictionary(uniqueKeysWithValues: input.map { key, value in (NSAttributedString.Key(rawValue: key), value)})
}
| 34.821429 | 169 | 0.674872 |
e23203b120d3c2ed74210f90fe08f489b89ed718 | 17,974 | //
// UserAPI.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Alamofire
import RxSwift
public class UserAPI: APIBase {
/**
Create user
- parameter body: (body) Created user object (optional)
- parameter completion: completion handler to receive the data and the error objects
*/
public class func createUser(body body: User? = nil, completion: ((error: ErrorType?) -> Void)) {
createUserWithRequestBuilder(body: body).execute { (response, error) -> Void in
completion(error: error);
}
}
/**
Create user
- parameter body: (body) Created user object (optional)
- returns: Observable<Void>
*/
public class func createUser(body body: User? = nil) -> Observable<Void> {
return Observable.create { observer -> Disposable in
createUser(body: body) { error in
if let error = error {
observer.on(.Error(error as ErrorType))
} else {
observer.on(.Next())
}
observer.on(.Completed)
}
return NopDisposable.instance
}
}
/**
Create user
- POST /user
- This can only be done by the logged in user.
- parameter body: (body) Created user object (optional)
- returns: RequestBuilder<Void>
*/
public class func createUserWithRequestBuilder(body body: User? = nil) -> RequestBuilder<Void> {
let path = "/user"
let URLString = PetstoreClientAPI.basePath + path
let parameters = body?.encodeToJSON() as? [String:AnyObject]
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true)
}
/**
Creates list of users with given input array
- parameter body: (body) List of user object (optional)
- parameter completion: completion handler to receive the data and the error objects
*/
public class func createUsersWithArrayInput(body body: [User]? = nil, completion: ((error: ErrorType?) -> Void)) {
createUsersWithArrayInputWithRequestBuilder(body: body).execute { (response, error) -> Void in
completion(error: error);
}
}
/**
Creates list of users with given input array
- parameter body: (body) List of user object (optional)
- returns: Observable<Void>
*/
public class func createUsersWithArrayInput(body body: [User]? = nil) -> Observable<Void> {
return Observable.create { observer -> Disposable in
createUsersWithArrayInput(body: body) { error in
if let error = error {
observer.on(.Error(error as ErrorType))
} else {
observer.on(.Next())
}
observer.on(.Completed)
}
return NopDisposable.instance
}
}
/**
Creates list of users with given input array
- POST /user/createWithArray
-
- parameter body: (body) List of user object (optional)
- returns: RequestBuilder<Void>
*/
public class func createUsersWithArrayInputWithRequestBuilder(body body: [User]? = nil) -> RequestBuilder<Void> {
let path = "/user/createWithArray"
let URLString = PetstoreClientAPI.basePath + path
let parameters = body?.encodeToJSON() as? [String:AnyObject]
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true)
}
/**
Creates list of users with given input array
- parameter body: (body) List of user object (optional)
- parameter completion: completion handler to receive the data and the error objects
*/
public class func createUsersWithListInput(body body: [User]? = nil, completion: ((error: ErrorType?) -> Void)) {
createUsersWithListInputWithRequestBuilder(body: body).execute { (response, error) -> Void in
completion(error: error);
}
}
/**
Creates list of users with given input array
- parameter body: (body) List of user object (optional)
- returns: Observable<Void>
*/
public class func createUsersWithListInput(body body: [User]? = nil) -> Observable<Void> {
return Observable.create { observer -> Disposable in
createUsersWithListInput(body: body) { error in
if let error = error {
observer.on(.Error(error as ErrorType))
} else {
observer.on(.Next())
}
observer.on(.Completed)
}
return NopDisposable.instance
}
}
/**
Creates list of users with given input array
- POST /user/createWithList
-
- parameter body: (body) List of user object (optional)
- returns: RequestBuilder<Void>
*/
public class func createUsersWithListInputWithRequestBuilder(body body: [User]? = nil) -> RequestBuilder<Void> {
let path = "/user/createWithList"
let URLString = PetstoreClientAPI.basePath + path
let parameters = body?.encodeToJSON() as? [String:AnyObject]
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true)
}
/**
Delete user
- parameter username: (path) The name that needs to be deleted
- parameter completion: completion handler to receive the data and the error objects
*/
public class func deleteUser(username username: String, completion: ((error: ErrorType?) -> Void)) {
deleteUserWithRequestBuilder(username: username).execute { (response, error) -> Void in
completion(error: error);
}
}
/**
Delete user
- parameter username: (path) The name that needs to be deleted
- returns: Observable<Void>
*/
public class func deleteUser(username username: String) -> Observable<Void> {
return Observable.create { observer -> Disposable in
deleteUser(username: username) { error in
if let error = error {
observer.on(.Error(error as ErrorType))
} else {
observer.on(.Next())
}
observer.on(.Completed)
}
return NopDisposable.instance
}
}
/**
Delete user
- DELETE /user/{username}
- This can only be done by the logged in user.
- parameter username: (path) The name that needs to be deleted
- returns: RequestBuilder<Void>
*/
public class func deleteUserWithRequestBuilder(username username: String) -> RequestBuilder<Void> {
var path = "/user/{username}"
path = path.stringByReplacingOccurrencesOfString("{username}", withString: "\(username)", options: .LiteralSearch, range: nil)
let URLString = PetstoreClientAPI.basePath + path
let nillableParameters: [String:AnyObject?] = [:]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true)
}
/**
Get user by user name
- parameter username: (path) The name that needs to be fetched. Use user1 for testing.
- parameter completion: completion handler to receive the data and the error objects
*/
public class func getUserByName(username username: String, completion: ((data: User?, error: ErrorType?) -> Void)) {
getUserByNameWithRequestBuilder(username: username).execute { (response, error) -> Void in
completion(data: response?.body, error: error);
}
}
/**
Get user by user name
- parameter username: (path) The name that needs to be fetched. Use user1 for testing.
- returns: Observable<User>
*/
public class func getUserByName(username username: String) -> Observable<User> {
return Observable.create { observer -> Disposable in
getUserByName(username: username) { data, error in
if let error = error {
observer.on(.Error(error as ErrorType))
} else {
observer.on(.Next(data!))
}
observer.on(.Completed)
}
return NopDisposable.instance
}
}
/**
Get user by user name
- GET /user/{username}
-
- examples: [{contentType=application/json, example={
"firstName" : "firstName",
"lastName" : "lastName",
"password" : "password",
"userStatus" : 6,
"phone" : "phone",
"id" : 0,
"email" : "email",
"username" : "username"
}}, {contentType=application/xml, example=<User>
<id>123456789</id>
<username>aeiou</username>
<firstName>aeiou</firstName>
<lastName>aeiou</lastName>
<email>aeiou</email>
<password>aeiou</password>
<phone>aeiou</phone>
<userStatus>123</userStatus>
</User>}]
- examples: [{contentType=application/json, example={
"firstName" : "firstName",
"lastName" : "lastName",
"password" : "password",
"userStatus" : 6,
"phone" : "phone",
"id" : 0,
"email" : "email",
"username" : "username"
}}, {contentType=application/xml, example=<User>
<id>123456789</id>
<username>aeiou</username>
<firstName>aeiou</firstName>
<lastName>aeiou</lastName>
<email>aeiou</email>
<password>aeiou</password>
<phone>aeiou</phone>
<userStatus>123</userStatus>
</User>}]
- parameter username: (path) The name that needs to be fetched. Use user1 for testing.
- returns: RequestBuilder<User>
*/
public class func getUserByNameWithRequestBuilder(username username: String) -> RequestBuilder<User> {
var path = "/user/{username}"
path = path.stringByReplacingOccurrencesOfString("{username}", withString: "\(username)", options: .LiteralSearch, range: nil)
let URLString = PetstoreClientAPI.basePath + path
let nillableParameters: [String:AnyObject?] = [:]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<User>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true)
}
/**
Logs user into the system
- parameter username: (query) The user name for login (optional)
- parameter password: (query) The password for login in clear text (optional)
- parameter completion: completion handler to receive the data and the error objects
*/
public class func loginUser(username username: String? = nil, password: String? = nil, completion: ((data: String?, error: ErrorType?) -> Void)) {
loginUserWithRequestBuilder(username: username, password: password).execute { (response, error) -> Void in
completion(data: response?.body, error: error);
}
}
/**
Logs user into the system
- parameter username: (query) The user name for login (optional)
- parameter password: (query) The password for login in clear text (optional)
- returns: Observable<String>
*/
public class func loginUser(username username: String? = nil, password: String? = nil) -> Observable<String> {
return Observable.create { observer -> Disposable in
loginUser(username: username, password: password) { data, error in
if let error = error {
observer.on(.Error(error as ErrorType))
} else {
observer.on(.Next(data!))
}
observer.on(.Completed)
}
return NopDisposable.instance
}
}
/**
Logs user into the system
- GET /user/login
-
- examples: [{contentType=application/json, example=""}, {contentType=application/xml, example=aeiou}]
- examples: [{contentType=application/json, example=""}, {contentType=application/xml, example=aeiou}]
- parameter username: (query) The user name for login (optional)
- parameter password: (query) The password for login in clear text (optional)
- returns: RequestBuilder<String>
*/
public class func loginUserWithRequestBuilder(username username: String? = nil, password: String? = nil) -> RequestBuilder<String> {
let path = "/user/login"
let URLString = PetstoreClientAPI.basePath + path
let nillableParameters: [String:AnyObject?] = [
"username": username,
"password": password
]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<String>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false)
}
/**
Logs out current logged in user session
- parameter completion: completion handler to receive the data and the error objects
*/
public class func logoutUser(completion: ((error: ErrorType?) -> Void)) {
logoutUserWithRequestBuilder().execute { (response, error) -> Void in
completion(error: error);
}
}
/**
Logs out current logged in user session
- returns: Observable<Void>
*/
public class func logoutUser() -> Observable<Void> {
return Observable.create { observer -> Disposable in
logoutUser() { error in
if let error = error {
observer.on(.Error(error as ErrorType))
} else {
observer.on(.Next())
}
observer.on(.Completed)
}
return NopDisposable.instance
}
}
/**
Logs out current logged in user session
- GET /user/logout
-
- returns: RequestBuilder<Void>
*/
public class func logoutUserWithRequestBuilder() -> RequestBuilder<Void> {
let path = "/user/logout"
let URLString = PetstoreClientAPI.basePath + path
let nillableParameters: [String:AnyObject?] = [:]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true)
}
/**
Updated user
- parameter username: (path) name that need to be deleted
- parameter body: (body) Updated user object (optional)
- parameter completion: completion handler to receive the data and the error objects
*/
public class func updateUser(username username: String, body: User? = nil, completion: ((error: ErrorType?) -> Void)) {
updateUserWithRequestBuilder(username: username, body: body).execute { (response, error) -> Void in
completion(error: error);
}
}
/**
Updated user
- parameter username: (path) name that need to be deleted
- parameter body: (body) Updated user object (optional)
- returns: Observable<Void>
*/
public class func updateUser(username username: String, body: User? = nil) -> Observable<Void> {
return Observable.create { observer -> Disposable in
updateUser(username: username, body: body) { error in
if let error = error {
observer.on(.Error(error as ErrorType))
} else {
observer.on(.Next())
}
observer.on(.Completed)
}
return NopDisposable.instance
}
}
/**
Updated user
- PUT /user/{username}
- This can only be done by the logged in user.
- parameter username: (path) name that need to be deleted
- parameter body: (body) Updated user object (optional)
- returns: RequestBuilder<Void>
*/
public class func updateUserWithRequestBuilder(username username: String, body: User? = nil) -> RequestBuilder<Void> {
var path = "/user/{username}"
path = path.stringByReplacingOccurrencesOfString("{username}", withString: "\(username)", options: .LiteralSearch, range: nil)
let URLString = PetstoreClientAPI.basePath + path
let parameters = body?.encodeToJSON() as? [String:AnyObject]
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "PUT", URLString: URLString, parameters: convertedParameters, isBody: true)
}
}
| 36.02004 | 150 | 0.627629 |
bf20546cc9339605589a3c5ed906bc2eba1a7ffd | 763 | //
// MessageTransfer+Update.swift
// JivoMobile
//
// Created by Stan Potemkin on 04.09.2020.
// Copyright © 2020 JivoSite. All rights reserved.
//
import Foundation
import JMCodingKit
extension MessageTransfer {
public func performApply(inside context: IDatabaseContext, with change: BaseModelChange) {
if let c = change as? MessageTransferGeneralChange {
_agentID = c.agentID
_comment = c.comment
}
}
}
public final class MessageTransferGeneralChange: BaseModelChange {
public let agentID: Int
public let comment: String?
required public init( json: JsonElement) {
agentID = json["agent_id"].intValue
comment = json["text"].valuable
super.init(json: json)
}
}
| 24.612903 | 94 | 0.671035 |
284822c6c3b6a46faa3e2ac1302c4d3466e5f33a | 21,136 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#if _runtime(_ObjC)
/// A Swift Array or Dictionary of types conforming to
/// `_ObjectiveCBridgeable` can be passed to Objective-C as an NSArray or
/// NSDictionary, respectively. The elements of the resulting NSArray
/// or NSDictionary will be the result of calling `_bridgeToObjectiveC`
/// on each element of the source container.
public protocol _ObjectiveCBridgeable {
associatedtype _ObjectiveCType : AnyObject
/// Convert `self` to Objective-C.
func _bridgeToObjectiveC() -> _ObjectiveCType
/// Bridge from an Objective-C object of the bridged class type to a
/// value of the Self type.
///
/// This bridging operation is used for forced downcasting (e.g.,
/// via as), and may defer complete checking until later. For
/// example, when bridging from `NSArray` to `Array<Element>`, we can defer
/// the checking for the individual elements of the array.
///
/// - parameter result: The location where the result is written. The optional
/// will always contain a value.
static func _forceBridgeFromObjectiveC(
_ source: _ObjectiveCType,
result: inout Self?
)
/// Try to bridge from an Objective-C object of the bridged class
/// type to a value of the Self type.
///
/// This conditional bridging operation is used for conditional
/// downcasting (e.g., via as?) and therefore must perform a
/// complete conversion to the value type; it cannot defer checking
/// to a later time.
///
/// - parameter result: The location where the result is written.
///
/// - Returns: `true` if bridging succeeded, `false` otherwise. This redundant
/// information is provided for the convenience of the runtime's `dynamic_cast`
/// implementation, so that it need not look into the optional representation
/// to determine success.
@discardableResult
static func _conditionallyBridgeFromObjectiveC(
_ source: _ObjectiveCType,
result: inout Self?
) -> Bool
/// Bridge from an Objective-C object of the bridged class type to a
/// value of the Self type.
///
/// This bridging operation is used for unconditional bridging when
/// interoperating with Objective-C code, either in the body of an
/// Objective-C thunk or when calling Objective-C code, and may
/// defer complete checking until later. For example, when bridging
/// from `NSArray` to `Array<Element>`, we can defer the checking
/// for the individual elements of the array.
///
/// \param source The Objective-C object from which we are
/// bridging. This optional value will only be `nil` in cases where
/// an Objective-C method has returned a `nil` despite being marked
/// as `_Nonnull`/`nonnull`. In most such cases, bridging will
/// generally force the value immediately. However, this gives
/// bridging the flexibility to substitute a default value to cope
/// with historical decisions, e.g., an existing Objective-C method
/// that returns `nil` to for "empty result" rather than (say) an
/// empty array. In such cases, when `nil` does occur, the
/// implementation of `Swift.Array`'s conformance to
/// `_ObjectiveCBridgeable` will produce an empty array rather than
/// dynamically failing.
static func _unconditionallyBridgeFromObjectiveC(_ source: _ObjectiveCType?)
-> Self
}
//===--- Bridging for metatypes -------------------------------------------===//
/// A stand-in for a value of metatype type.
///
/// The language and runtime do not yet support protocol conformances for
/// structural types like metatypes. However, we can use a struct that contains
/// a metatype, make it conform to _ObjectiveCBridgeable, and its witness table
/// will be ABI-compatible with one that directly provided conformance to the
/// metatype type itself.
@_fixed_layout
public struct _BridgeableMetatype: _ObjectiveCBridgeable {
internal var value: AnyObject.Type
public typealias _ObjectiveCType = AnyObject
public func _bridgeToObjectiveC() -> AnyObject {
return value
}
public static func _forceBridgeFromObjectiveC(
_ source: AnyObject,
result: inout _BridgeableMetatype?
) {
result = _BridgeableMetatype(value: source as! AnyObject.Type)
}
public static func _conditionallyBridgeFromObjectiveC(
_ source: AnyObject,
result: inout _BridgeableMetatype?
) -> Bool {
if let type = source as? AnyObject.Type {
result = _BridgeableMetatype(value: type)
return true
}
result = nil
return false
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: AnyObject?)
-> _BridgeableMetatype {
var result: _BridgeableMetatype?
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
//===--- Bridging facilities written in Objective-C -----------------------===//
// Functions that must discover and possibly use an arbitrary type's
// conformance to a given protocol. See ../runtime/Metadata.cpp for
// implementations.
//===----------------------------------------------------------------------===//
/// Bridge an arbitrary value to an Objective-C object.
///
/// - If `T` is a class type, it is always bridged verbatim, the function
/// returns `x`;
///
/// - otherwise, if `T` conforms to `_ObjectiveCBridgeable`,
/// returns the result of `x._bridgeToObjectiveC()`;
///
/// - otherwise, we use **boxing** to bring the value into Objective-C.
/// The value is wrapped in an instance of a private Objective-C class
/// that is `id`-compatible and dynamically castable back to the type of
/// the boxed value, but is otherwise opaque.
///
/// COMPILER_INTRINSIC
public func _bridgeAnythingToObjectiveC<T>(_ x: T) -> AnyObject {
if _fastPath(_isClassOrObjCExistential(T.self)) {
return unsafeBitCast(x, to: AnyObject.self)
}
return _bridgeAnythingNonVerbatimToObjectiveC(x)
}
/// COMPILER_INTRINSIC
@_silgen_name("_swift_bridgeAnythingNonVerbatimToObjectiveC")
public func _bridgeAnythingNonVerbatimToObjectiveC<T>(_ x: T) -> AnyObject
/// Convert a purportedly-nonnull `id` value from Objective-C into an Any.
///
/// Since Objective-C APIs sometimes get their nullability annotations wrong,
/// this includes a failsafe against nil `AnyObject`s, wrapping them up as
/// a nil `AnyObject?`-inside-an-`Any`.
///
/// COMPILER_INTRINSIC
public func _bridgeAnyObjectToAny(_ possiblyNullObject: AnyObject?) -> Any {
if let nonnullObject = possiblyNullObject {
return nonnullObject // AnyObject-in-Any
}
return possiblyNullObject as Any
}
/// Convert `x` from its Objective-C representation to its Swift
/// representation.
///
/// - If `T` is a class type:
/// - if the dynamic type of `x` is `T` or a subclass of it, it is bridged
/// verbatim, the function returns `x`;
/// - otherwise, if `T` conforms to `_ObjectiveCBridgeable`:
/// + if the dynamic type of `x` is not `T._ObjectiveCType`
/// or a subclass of it, trap;
/// + otherwise, returns the result of `T._forceBridgeFromObjectiveC(x)`;
/// - otherwise, trap.
public func _forceBridgeFromObjectiveC<T>(_ x: AnyObject, _: T.Type) -> T {
if _fastPath(_isClassOrObjCExistential(T.self)) {
return x as! T
}
var result: T?
_bridgeNonVerbatimFromObjectiveC(x, T.self, &result)
return result!
}
/// Convert `x` from its Objective-C representation to its Swift
/// representation.
@_silgen_name("_forceBridgeFromObjectiveC_bridgeable")
public func _forceBridgeFromObjectiveC_bridgeable<T:_ObjectiveCBridgeable> (
_ x: T._ObjectiveCType,
_: T.Type
) -> T {
var result: T?
T._forceBridgeFromObjectiveC(x, result: &result)
return result!
}
/// Attempt to convert `x` from its Objective-C representation to its Swift
/// representation.
///
/// - If `T` is a class type:
/// - if the dynamic type of `x` is `T` or a subclass of it, it is bridged
/// verbatim, the function returns `x`;
/// - otherwise, if `T` conforms to `_ObjectiveCBridgeable`:
/// + otherwise, if the dynamic type of `x` is not `T._ObjectiveCType`
/// or a subclass of it, the result is empty;
/// + otherwise, returns the result of
/// `T._conditionallyBridgeFromObjectiveC(x)`;
/// - otherwise, the result is empty.
public func _conditionallyBridgeFromObjectiveC<T>(
_ x: AnyObject,
_: T.Type
) -> T? {
if _fastPath(_isClassOrObjCExistential(T.self)) {
return x as? T
}
var result: T?
_ = _bridgeNonVerbatimFromObjectiveCConditional(x, T.self, &result)
return result
}
/// Attempt to convert `x` from its Objective-C representation to its Swift
/// representation.
@_silgen_name("_conditionallyBridgeFromObjectiveC_bridgeable")
public func _conditionallyBridgeFromObjectiveC_bridgeable<T:_ObjectiveCBridgeable>(
_ x: T._ObjectiveCType,
_: T.Type
) -> T? {
var result: T?
T._conditionallyBridgeFromObjectiveC (x, result: &result)
return result
}
@_silgen_name("_swift_bridgeNonVerbatimFromObjectiveC")
func _bridgeNonVerbatimFromObjectiveC<T>(
_ x: AnyObject,
_ nativeType: T.Type,
_ result: inout T?
)
/// Helper stub to upcast to Any and store the result to an inout Any?
/// on the C++ runtime's behalf.
// COMPILER_INTRINSIC
@_silgen_name("_swift_bridgeNonVerbatimFromObjectiveCToAny")
public func _bridgeNonVerbatimFromObjectiveCToAny(
_ x: AnyObject,
_ result: inout Any?
) {
result = x as Any
}
/// Helper stub to upcast to Optional on the C++ runtime's behalf.
// COMPILER_INTRINSIC
@_silgen_name("_swift_bridgeNonVerbatimBoxedValue")
public func _bridgeNonVerbatimBoxedValue<NativeType>(
_ x: UnsafePointer<NativeType>,
_ result: inout NativeType?
) {
result = x.pointee
}
/// Runtime optional to conditionally perform a bridge from an object to a value
/// type.
///
/// - parameter result: Will be set to the resulting value if bridging succeeds, and
/// unchanged otherwise.
///
/// - Returns: `true` to indicate success, `false` to indicate failure.
@_silgen_name("_swift_bridgeNonVerbatimFromObjectiveCConditional")
func _bridgeNonVerbatimFromObjectiveCConditional<T>(
_ x: AnyObject,
_ nativeType: T.Type,
_ result: inout T?
) -> Bool
/// Determines if values of a given type can be converted to an Objective-C
/// representation.
///
/// - If `T` is a class type, returns `true`;
/// - otherwise, returns whether `T` conforms to `_ObjectiveCBridgeable`.
public func _isBridgedToObjectiveC<T>(_: T.Type) -> Bool {
if _fastPath(_isClassOrObjCExistential(T.self)) {
return true
}
return _isBridgedNonVerbatimToObjectiveC(T.self)
}
@_silgen_name("_swift_isBridgedNonVerbatimToObjectiveC")
func _isBridgedNonVerbatimToObjectiveC<T>(_: T.Type) -> Bool
/// A type that's bridged "verbatim" does not conform to
/// `_ObjectiveCBridgeable`, and can have its bits reinterpreted as an
/// `AnyObject`. When this function returns true, the storage of an
/// `Array<T>` can be `unsafeBitCast` as an array of `AnyObject`.
public func _isBridgedVerbatimToObjectiveC<T>(_: T.Type) -> Bool {
return _isClassOrObjCExistential(T.self)
}
/// Retrieve the Objective-C type to which the given type is bridged.
public func _getBridgedObjectiveCType<T>(_: T.Type) -> Any.Type? {
if _fastPath(_isClassOrObjCExistential(T.self)) {
return T.self
}
return _getBridgedNonVerbatimObjectiveCType(T.self)
}
@_silgen_name("_swift_getBridgedNonVerbatimObjectiveCType")
func _getBridgedNonVerbatimObjectiveCType<T>(_: T.Type) -> Any.Type?
// -- Pointer argument bridging
@_transparent
internal var _nilNativeObject: AnyObject? {
return nil
}
/// A mutable pointer-to-ObjC-pointer argument.
///
/// This type has implicit conversions to allow passing any of the following
/// to a C or ObjC API:
///
/// - `nil`, which gets passed as a null pointer,
/// - an inout argument of the referenced type, which gets passed as a pointer
/// to a writeback temporary with autoreleasing ownership semantics,
/// - an `UnsafeMutablePointer<Pointee>`, which is passed as-is.
///
/// Passing pointers to mutable arrays of ObjC class pointers is not
/// directly supported. Unlike `UnsafeMutablePointer<Pointee>`,
/// `AutoreleasingUnsafeMutablePointer<Pointee>` must reference storage that
/// does not own a reference count to the referenced
/// value. UnsafeMutablePointer's operations, by contrast, assume that
/// the referenced storage owns values loaded from or stored to it.
///
/// This type does not carry an owner pointer unlike the other C*Pointer types
/// because it only needs to reference the results of inout conversions, which
/// already have writeback-scoped lifetime.
@_fixed_layout
public struct AutoreleasingUnsafeMutablePointer<Pointee /* TODO : class */>
: Equatable, _Pointer {
public let _rawValue: Builtin.RawPointer
@_transparent
public // COMPILER_INTRINSIC
init(_ _rawValue: Builtin.RawPointer) {
self._rawValue = _rawValue
}
/// Access the `Pointee` instance referenced by `self`.
///
/// - Precondition: the pointee has been initialized with an instance of type
/// `Pointee`.
public var pointee: Pointee {
/// Retrieve the value the pointer points to.
@_transparent get {
// We can do a strong load normally.
return UnsafePointer(self).pointee
}
/// Set the value the pointer points to, copying over the previous value.
///
/// AutoreleasingUnsafeMutablePointers are assumed to reference a
/// value with __autoreleasing ownership semantics, like 'NSFoo**'
/// in ARC. This autoreleases the argument before trivially
/// storing it to the referenced memory.
@_transparent nonmutating set {
// Autorelease the object reference.
typealias OptionalAnyObject = AnyObject?
let newAnyObject = unsafeBitCast(newValue, to: OptionalAnyObject.self)
Builtin.retain(newAnyObject)
Builtin.autorelease(newAnyObject)
// Trivially assign it as an OpaquePointer; the pointer references an
// autoreleasing slot, so retains/releases of the original value are
// unneeded.
typealias OptionalUnmanaged = Unmanaged<AnyObject>?
UnsafeMutablePointer<Pointee>(_rawValue).withMemoryRebound(
to: OptionalUnmanaged.self, capacity: 1) {
if let newAnyObject = newAnyObject {
// could be passed out of Swift, so mustBeConservativeMakeSafe_dmu_
$0.pointee = Unmanaged.passUnretained( mustBeConservativeMakeSafe_dmu_( newAnyObject ) )
}
else {
$0.pointee = nil
}
}
}
}
/// Access the `i`th element of the raw array pointed to by
/// `self`.
///
/// - Precondition: `self != nil`.
public subscript(i: Int) -> Pointee {
@_transparent
get {
// We can do a strong load normally.
return (UnsafePointer<Pointee>(self) + i).pointee
}
}
/// Explicit construction from an UnsafeMutablePointer.
///
/// This is inherently unsafe; UnsafeMutablePointer assumes the
/// referenced memory has +1 strong ownership semantics, whereas
/// AutoreleasingUnsafeMutablePointer implies +0 semantics.
///
/// - Warning: Accessing `pointee` as a type that is unrelated to
/// the underlying memory's bound type is undefined.
@_transparent public
init<U>(_ from: UnsafeMutablePointer<U>) {
self._rawValue = from._rawValue
}
/// Explicit construction from an UnsafeMutablePointer.
///
/// Returns nil if `from` is nil.
///
/// This is inherently unsafe; UnsafeMutablePointer assumes the
/// referenced memory has +1 strong ownership semantics, whereas
/// AutoreleasingUnsafeMutablePointer implies +0 semantics.
///
/// - Warning: Accessing `pointee` as a type that is unrelated to
/// the underlying memory's bound type is undefined.
@_transparent public
init?<U>(_ from: UnsafeMutablePointer<U>?) {
guard let unwrapped = from else { return nil }
self.init(unwrapped)
}
/// Explicit construction from a UnsafePointer.
///
/// This is inherently unsafe because UnsafePointers do not imply
/// mutability.
///
/// - Warning: Accessing `pointee` as a type that is unrelated to
/// the underlying memory's bound type is undefined.
@_transparent
init<U>(_ from: UnsafePointer<U>) {
self._rawValue = from._rawValue
}
/// Explicit construction from a UnsafePointer.
///
/// Returns nil if `from` is nil.
///
/// This is inherently unsafe because UnsafePointers do not imply
/// mutability.
///
/// - Warning: Accessing `pointee` as a type that is unrelated to
/// the underlying memory's bound type is undefined.
@_transparent
init?<U>(_ from: UnsafePointer<U>?) {
guard let unwrapped = from else { return nil }
self.init(unwrapped)
}
}
extension UnsafeMutableRawPointer {
/// Creates a new raw pointer from an `AutoreleasingUnsafeMutablePointer`
/// instance.
///
/// - Parameter other: The pointer to convert.
@_transparent
public init<T>(_ other: AutoreleasingUnsafeMutablePointer<T>) {
_rawValue = other._rawValue
}
/// Creates a new raw pointer from an `AutoreleasingUnsafeMutablePointer`
/// instance.
///
/// - Parameter other: The pointer to convert. If `other` is `nil`, the
/// result is `nil`.
@_transparent
public init?<T>(_ other: AutoreleasingUnsafeMutablePointer<T>?) {
guard let unwrapped = other else { return nil }
self.init(unwrapped)
}
}
extension UnsafeRawPointer {
/// Creates a new raw pointer from an `AutoreleasingUnsafeMutablePointer`
/// instance.
///
/// - Parameter other: The pointer to convert.
@_transparent
public init<T>(_ other: AutoreleasingUnsafeMutablePointer<T>) {
_rawValue = other._rawValue
}
/// Creates a new raw pointer from an `AutoreleasingUnsafeMutablePointer`
/// instance.
///
/// - Parameter other: The pointer to convert. If `other` is `nil`, the
/// result is `nil`.
@_transparent
public init?<T>(_ other: AutoreleasingUnsafeMutablePointer<T>?) {
guard let unwrapped = other else { return nil }
self.init(unwrapped)
}
}
extension AutoreleasingUnsafeMutablePointer : CustomDebugStringConvertible {
/// A textual representation of `self`, suitable for debugging.
public var debugDescription: String {
return _rawPointerToString(_rawValue)
}
}
@_transparent
public func == <Pointee>(
lhs: AutoreleasingUnsafeMutablePointer<Pointee>,
rhs: AutoreleasingUnsafeMutablePointer<Pointee>
) -> Bool {
return Bool(Builtin.cmp_eq_RawPointer(lhs._rawValue, rhs._rawValue))
}
internal struct _CocoaFastEnumerationStackBuf {
// Clang uses 16 pointers. So do we.
internal var _item0: UnsafeRawPointer?
internal var _item1: UnsafeRawPointer?
internal var _item2: UnsafeRawPointer?
internal var _item3: UnsafeRawPointer?
internal var _item4: UnsafeRawPointer?
internal var _item5: UnsafeRawPointer?
internal var _item6: UnsafeRawPointer?
internal var _item7: UnsafeRawPointer?
internal var _item8: UnsafeRawPointer?
internal var _item9: UnsafeRawPointer?
internal var _item10: UnsafeRawPointer?
internal var _item11: UnsafeRawPointer?
internal var _item12: UnsafeRawPointer?
internal var _item13: UnsafeRawPointer?
internal var _item14: UnsafeRawPointer?
internal var _item15: UnsafeRawPointer?
@_transparent
internal var count: Int {
return 16
}
internal init() {
_item0 = nil
_item1 = _item0
_item2 = _item0
_item3 = _item0
_item4 = _item0
_item5 = _item0
_item6 = _item0
_item7 = _item0
_item8 = _item0
_item9 = _item0
_item10 = _item0
_item11 = _item0
_item12 = _item0
_item13 = _item0
_item14 = _item0
_item15 = _item0
_sanityCheck(MemoryLayout.size(ofValue: self) >=
MemoryLayout<Optional<UnsafeRawPointer>>.size * count)
}
}
extension AutoreleasingUnsafeMutablePointer {
@available(*, unavailable, renamed: "Pointee")
public typealias Memory = Pointee
@available(*, unavailable, renamed: "pointee")
public var memory: Pointee {
Builtin.unreachable()
}
@available(*, unavailable, message: "Removed in Swift 3. Please use nil literal instead.")
public init() {
Builtin.unreachable()
}
}
/// Get the ObjC type encoding for a type as a pointer to a C string.
///
/// This is used by the Foundation overlays. The compiler will error if the
/// passed-in type is generic or not representable in Objective-C
@_transparent
public func _getObjCTypeEncoding<T>(_ type: T.Type) -> UnsafePointer<Int8> {
// This must be `@_transparent` because `Builtin.getObjCTypeEncoding` is
// only supported by the compiler for concrete types that are representable
// in ObjC.
return UnsafePointer(Builtin.getObjCTypeEncoding(type))
}
#endif
| 34.877888 | 98 | 0.707229 |
de6d872c1b8488fe0053026f6f94ff4a07e7130d | 3,705 | //
// Copyright © 2020 Optimize Fitness Inc.
// Licensed under the MIT license
// https://github.com/OptimizeFitness/Minerva/blob/master/LICENSE
//
import Combine
import Foundation
import UIKit
extension DataManager {
public func combineUsers() -> Future<[User], Error> {
asSingle(loadUsers(completion:))
}
public func combineUser(withID userID: String) -> Future<User?, Error> {
let curried = curry(loadUser(withID:completion:))
return asSingle(curried(userID))
}
public func combineUpdate(_ user: User) -> Future<Void, Error> {
let curried = curry(update(user:completion:))
return asSingle(curried(user))
}
public func combineDeleteUser(withUserID userID: String) -> Future<Void, Error> {
let curried = curry(delete(userID:completion:))
return asSingle(curried(userID))
}
public func combineCreateUser(
withEmail email: String,
password: String,
dailyCalories: Int32,
role: UserRole
) -> Future<Void, Error> {
Future { promise in
self.create(withEmail: email, password: password, dailyCalories: dailyCalories, role: role) {
error in
if let error = error {
promise(.failure(error))
} else {
promise(.success(()))
}
}
}
}
public func combineWorkouts(forUserID userID: String) -> Future<[Workout], Error> {
let curried = curry(loadWorkouts(forUserID:completion:))
return asSingle(curried(userID))
}
public func combineStore(_ workout: Workout) -> Future<Void, Error> {
let curried = curry(store(workout:completion:))
return asSingle(curried(workout))
}
public func combineDelete(_ workout: Workout) -> Future<Void, Error> {
let curried = curry(delete(workout:completion:))
return asSingle(curried(workout))
}
public func combineImage(forWorkoutID workoutID: String) -> Future<UIImage?, Error> {
let curried = curry(loadImage(forWorkoutID:completion:))
return asSingle(curried(workoutID))
}
public func combineObserveWorkouts(for userID: String) -> PassthroughSubject<
Result<[Workout], Error>, Error
> {
let curried = curry(subscribeToWorkoutChanges(for:callback:))
return observe(curried(userID))
}
public func combineObserveUsers() -> PassthroughSubject<Result<[User], Error>, Error> {
observe(subscribeToUserChanges(callback:))
}
// MARK: - Private
private func observe<T>(
_ block: @escaping (@escaping (T, Error?) -> Void) -> SubscriptionID
) -> PassthroughSubject<Result<T, Error>, Error> {
let subject = PassthroughSubject<Result<T, Error>, Error>()
// TODO: This never cancels the connection. Need to update this to use the cancelID to support unsubscribe.
_ = block { result, error in
if let error = error {
subject.send(.failure(error))
} else {
subject.send(.success(result))
}
}
return subject
}
private func asSingle(_ block: @escaping (@escaping (Error?) -> Void) -> Void) -> Future<
Void, Error
> {
Future { promise in
block { error in
if let error = error {
promise(.failure(error))
} else {
promise(.success(()))
}
}
}
}
private func asSingle<T>(_ block: @escaping (@escaping (T, Error?) -> Void) -> Void) -> Future<
T, Error
> {
Future { promise in
block { result, error in
if let error = error {
promise(.failure(error))
} else {
promise(.success(result))
}
}
}
}
private func curry<A, B, C>(
_ f: @escaping (A, B) -> C
) -> ((A) -> ((B) -> C)) {
{ (a: A) -> ((B) -> C) in
{ (b: B) -> C in
f(a, b)
}
}
}
}
| 27.444444 | 111 | 0.626991 |
79e01ed562295daa9b9af74a86f8feea16c744da | 201 | //
// StorageKit.swift
// StorageKit
//
// Created by Gustavo Perdomo on 4/16/18.
// Copyright © 2018 Gustavo Perdomo. All rights reserved.
//
struct StorageKit {
var text = "Hello, World!"
}
| 16.75 | 58 | 0.656716 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.