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
|
---|---|---|---|---|---|
e979863d4a4c634535ec938bba26b305beca675c | 5,339 | import Quick
import Nimble
#if USE_COMBINE
import Combine
#else
import CombineX
#endif
class CombineLatestSpec: QuickSpec {
override func spec() {
afterEach {
TestResources.release()
}
// MARK: - Relay
describe("Relay") {
// MARK: 1.1 should combine latest of 2
it("should combine latest of 2") {
let subject0 = PassthroughSubject<String, TestError>()
let subject1 = PassthroughSubject<String, TestError>()
let pub = subject0.combineLatest(subject1, +)
let sub = makeTestSubscriber(String.self, TestError.self, .unlimited)
pub.subscribe(sub)
subject0.send("0")
subject0.send("1")
subject1.send("a")
subject0.send("2")
subject1.send("b")
subject1.send("c")
let expected = ["1a", "2a", "2b", "2c"].map { TestSubscriberEvent<String, TestError>.value($0) }
expect(sub.events).to(equal(expected))
}
// MARK: 1.2 should combine latest of 3
it("should combine latest of 3") {
let subject0 = PassthroughSubject<String, TestError>()
let subject1 = PassthroughSubject<String, TestError>()
let subject2 = PassthroughSubject<String, TestError>()
let pub = subject0.combineLatest(subject1, subject2, { $0 + $1 + $2 })
let sub = makeTestSubscriber(String.self, TestError.self, .max(10))
pub.subscribe(sub)
subject0.send("0")
subject0.send("1")
subject0.send("2")
subject1.send("a")
subject1.send("b")
subject2.send("A")
subject0.send("3")
subject1.send("c")
subject1.send("d")
subject2.send("B")
subject2.send("C")
subject2.send("D")
let expected = ["2bA", "3bA", "3cA", "3dA", "3dB", "3dC", "3dD"].map { TestSubscriberEvent<String, TestError>.value($0) }
expect(sub.events).to(equal(expected))
}
// MARK: 1.3 should finish when one sends an error
it("should finish when one sends an error") {
let subjects = Array.make(count: 4, make: PassthroughSubject<Int, TestError>())
let pub = subjects[0].combineLatest(subjects[1], subjects[2], subjects[3]) {
$0 + $1 + $2 + $3
}
let sub = makeTestSubscriber(Int.self, TestError.self, .unlimited)
pub.subscribe(sub)
10.times {
subjects[$0 % 4].send($0)
}
subjects[3].send(completion: .failure(.e0))
let valueEvents = [6, 10, 14, 18, 22, 26, 30].map { TestSubscriberEvent<Int, TestError>.value($0) }
let expected = valueEvents + [.completion(.failure(.e0))]
expect(sub.events).to(equal(expected))
}
// MARK: 1.4 should send as many as demands
it("should send as many as demands") {
let subject0 = PassthroughSubject<String, TestError>()
let subject1 = PassthroughSubject<String, TestError>()
var counter = 0
let pub = subject0.combineLatest(subject1, +)
let sub = TestSubscriber<String, TestError>(receiveSubscription: { (s) in
s.request(.max(10))
}, receiveValue: { v in
defer { counter += 1}
return [0, 10].contains(counter) ? .max(1) : .none
}, receiveCompletion: { c in
})
pub.subscribe(sub)
100.times {
[subject0, subject1].randomElement()!.send("\($0)")
}
expect(sub.events.count).to(equal(12))
}
}
// MARK: - Backpressure sync
describe("Backpressure sync") {
// MARK: 2.1
it("should always return none from sync backpressure") {
let subject0 = TestSubject<Int, TestError>()
let subject1 = TestSubject<Int, TestError>()
let pub = subject0.combineLatest(subject1, +)
let sub = makeTestSubscriber(Int.self, TestError.self, .max(10))
pub.subscribe(sub)
100.times {
[subject0, subject1].randomElement()!.send($0)
}
let records0 = subject0.subscription.syncDemandRecords
let records1 = subject1.subscription.syncDemandRecords
expect(records0.allSatisfy({ $0 == .none })).to(beTrue())
expect(records1.allSatisfy({ $0 == .none })).to(beTrue())
}
}
}
}
| 38.410072 | 137 | 0.467129 |
21865e39fbcb052f2c1249fd640d34ddf66697f5 | 970 | //
// FanTextComponent.swift
// eul
//
// Created by Gao Sun on 2020/12/1.
// Copyright © 2020 Gao Sun. All rights reserved.
//
import SwiftUI
import SwiftyJSON
struct FanTextComponent: Hashable {
var id: Int
var isAverage: Bool {
id == -1
}
}
extension FanTextComponent: CaseIterable {
static var allCases: [Self]
= defaultComponents + [FanTextComponent(id: -1)]
static var defaultComponents: [Self] {
SmcControl.shared.fans.map { FanTextComponent(id: $0.id) }
}
}
extension FanTextComponent: JSONCodabble {
init?(json: JSON) {
guard let id = json["id"].int else {
return nil
}
self.id = id
}
var json: JSON {
JSON([
"id": id,
])
}
}
extension FanTextComponent: LocalizedStringConvertible {
var localizedDescription: String {
id == -1 ? "text_component.average".localized() : "fan".localized() + " \(id + 1)"
}
}
| 19.795918 | 90 | 0.591753 |
629ba0a495a3242a1ad75b736a2211c542a6897f | 876 | //
// XYZHUD_MBProgress.swift
// XYZHUD
//
// Created by 张子豪 on 2019/8/2.
// Copyright © 2019 张子豪. All rights reserved.
//
//import UIKit
class XYZHUD_MBProgress: NSObject {
}
import UIKit
import MBProgressHUD
public extension XYZHUDObject{
func HUD窗口(LabelText:String,添加到的窗口:UIView,加载时间:Double = 3){
MBpopedView.hide(animated: true)
MBpopedView = MBProgressHUD.showAdded(to: 添加到的窗口, animated: true)
MBpopedView.label.text = LabelText
MBpopedView.hide(animated: true, afterDelay: 加载时间)
}
func HudBadNetwork(title:String = "网络不好",on ViewX:UIView) {
HUD窗口(LabelText: title, 添加到的窗口: ViewX)
}
func HudonLoading(title:String = "正在加载ing",on ViewX:UIView) {
HUD窗口(LabelText: title, 添加到的窗口: ViewX)
}
//和Hide一样
func dismissMBpopedView() {
MBpopedView.hide(animated: true)
}
}
| 23.052632 | 73 | 0.666667 |
3312b5c56cc9672e38f2af6fee2e6e90ff3bd8c8 | 8,245 | //
// MoviesViewController.swift
// MovieViewer
//
// Created by Shakeel Daswani on 2/1/16.
// Copyright © 2016 Shakeel Daswani. All rights reserved.
//
import UIKit
import AFNetworking
import MBProgressHUD
class MoviesViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate {
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var TableView: UITableView!
var movies: [NSDictionary]?
var filteredData: [NSDictionary]?
var endpoint: String!
@IBOutlet weak var collectionView: UICollectionView!
let totalColors: Int = 100
func colorForIndexPath(indexPath: NSIndexPath) -> UIColor {
if indexPath.row >= totalColors {
return UIColor.blackColor() // return black if we get an unexpected row index
}
var hueValue: CGFloat = CGFloat(indexPath.row) / CGFloat(totalColors)
return UIColor(hue: hueValue, saturation: 1.0, brightness: 1.0, alpha: 1.0)
}
func refreshControlAction(refreshControl: UIRefreshControl) {
self.TableView.reloadData()
let apiKey = "a07e22bc18f5cb106bfe4cc1f83ad8ed"
let url = NSURL(string: "https://api.themoviedb.org/3/movie/\(endpoint)?api_key=\(apiKey)")
let request = NSURLRequest(
URL: url!,
cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData,
timeoutInterval: 10)
let session = NSURLSession(
configuration: NSURLSessionConfiguration.defaultSessionConfiguration(),
delegate: nil,
delegateQueue: NSOperationQueue.mainQueue()
)
let task: NSURLSessionDataTask = session.dataTaskWithRequest(request,
completionHandler: { (dataOrNil, response, error) in
if let data = dataOrNil {
if let responseDictionary = try! NSJSONSerialization.JSONObjectWithData(
data, options:[]) as? NSDictionary {
print("response: \(responseDictionary)")
self.movies = responseDictionary["results"] as! [NSDictionary]
self.TableView.reloadData()
refreshControl.endRefreshing()
}
}
})
task.resume()
}
override func viewDidLoad() {
super.viewDidLoad()
// collectionView.dataSource = self as! UICollectionViewDataSource
self.navigationItem.title = "Movies"
if let navigationBar = navigationController?.navigationBar {
//navigationBar.setBackgroundImage(UIImage(named: "filmstrip"), forBarMetrics: .Default)
navigationBar.tintColor = UIColor.blackColor()
let shadow = NSShadow()
// shadow.shadowColor = UIColor.whiteColor().colorWithAlphaComponent(0.8)
shadow.shadowOffset = CGSizeMake(2, 2);
shadow.shadowBlurRadius = 2;
navigationBar.titleTextAttributes = [
// NSFontAttributeName : UIFont.fontNamesForFamilyName("Copperplate"),
NSFontAttributeName : UIFont.boldSystemFontOfSize(22),
NSForegroundColorAttributeName : UIColor.blackColor(),
NSShadowAttributeName : shadow
]
}
self.TableView.reloadData()
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: "refreshControlAction:", forControlEvents: UIControlEvents.ValueChanged)
TableView.insertSubview(refreshControl, atIndex: 0)
TableView.dataSource = self
TableView.delegate = self
// searchBar.delegate = self
filteredData = movies
let apiKey = "a07e22bc18f5cb106bfe4cc1f83ad8ed"
let url = NSURL(string: "https://api.themoviedb.org/3/movie/now_playing?api_key=\(apiKey)")
let request = NSURLRequest(
URL: url!,
cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData,
timeoutInterval: 10)
let session = NSURLSession(
configuration: NSURLSessionConfiguration.defaultSessionConfiguration(),
delegate: nil,
delegateQueue: NSOperationQueue.mainQueue()
)
MBProgressHUD.showHUDAddedTo(self.view, animated: true)
let task: NSURLSessionDataTask = session.dataTaskWithRequest(request,
completionHandler: { (dataOrNil, response, error) in
if let data = dataOrNil {
if let responseDictionary = try! NSJSONSerialization.JSONObjectWithData(
data, options:[]) as? NSDictionary {
print("response: \(responseDictionary)")
self.movies = responseDictionary["results"] as! [NSDictionary]
self.TableView.reloadData()
MBProgressHUD.hideHUDForView(self.view, animated: true)
}
}
})
task.resume()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let movies = movies {
return movies.count
//return filteredData.count
}
else {
return 0
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("MovieCell", forIndexPath: indexPath) as! MovieCell
let movie = movies![indexPath.row]
let title = movie["title"] as! String
let overview = movie["overview"] as! String
let backgroundView = UIView()
backgroundView.backgroundColor = UIColor.redColor()
cell.selectedBackgroundView = backgroundView
// cell.textLabel?.text = title[indexPath.row]
cell.titleLabel.text = title
cell.overviewLabel.text = overview
cell.overviewLabel.sizeToFit()
let baseUrl = "http://image.tmdb.org/t/p/w500"
if let posterPath = movie["poster_path"] as? String {
let imageUrl = NSURL(string: baseUrl + posterPath)
cell.posterView.setImageWithURL(imageUrl!)
}
print("row \(indexPath.row)")
return cell
}
/*
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
movies = searchText.isEmpty ? movies : movies!.filter({(dataString: String) -> Bool in
return dataString.rangeOfString(searchText, options: .CaseInsensitiveSearch) != nil
})
}
*/
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue:
UIStoryboardSegue, sender: AnyObject?) {
let cell = sender as! UITableViewCell
let indexPath = TableView.indexPathForCell(cell)
let movie = movies![indexPath!.row]
let detailViewController = segue.destinationViewController as! DetailViewController
detailViewController.movie = movie
print("prepare for segue called")
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
} | 34.354167 | 119 | 0.577926 |
8a638881c8f095f37cc9ee807ccad74645768aba | 2,942 | //
// AppDelegate.swift
// SmartcarAuth
//
// Created by Ziyu Zhang on 1/6/17.
// Copyright © 2017 Smartcar Inc. All rights reserved.
//
import UIKit
import SmartcarAuth
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var smartCarSDK: SmartcarAuth?
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:.
}
/**
Intercepts callback from OAuth Safari view determined by the custom URI
*/
func application(_ application: UIApplication, handleOpen url: URL) -> Bool {
window!.rootViewController?.presentedViewController?.dismiss(animated: true , completion: nil)
do {
let code = try smartCarSDK!.resumeAuthorizationFlow(with: url)
if window?.rootViewController! is ViewController {
var vc = window?.rootViewController! as! ViewController
vc.accessCodeReceived(code: code)
}
} catch {
print("Error caught")
}
return true
}
}
| 45.261538 | 285 | 0.708702 |
713479ab26a66dd3ae3f8e96170b9509e1c392c2 | 7,904 | //
// AutocompleteField.swift
// Example
//
// Created by Filip Stefansson on 05/11/15.
// Copyright © 2015 Filip Stefansson. All rights reserved.
//
import Foundation
import UIKit
public enum AutocompleteType {
case word
case sentence
}
@IBDesignable public class AutocompleteField: UITextField
{
// MARK: - public properties
// left/right padding
@IBInspectable public var padding : CGFloat = 0
// the color of the suggestion. Matches the default placeholder color
@IBInspectable public var completionColor : UIColor = UIColor(white: 0, alpha: 0.22)
// Array of suggestions
public var suggestions : [String] = [""]
// The current suggestion shown. Can also be used to force a suggestion
public var suggestion : String? {
didSet {
if let val = suggestion {
setLabelContent(val)
}
}
}
// Move the suggestion label up or down. Sometimes there's a small difference, and this can be used to fix it.
public var pixelCorrection : CGFloat = 0
// Update the suggestion when the text is changed using 'field.text'
override public var text : String? {
didSet {
if let text = text {
self.setLabelContent(text)
}
}
}
// The type of autocomplete that should be used
public var autocompleteType : AutocompleteType = .word
// MARK: - private properties
// the suggestion label
private var label = UILabel()
// MARK: - init functions
override public init(frame: CGRect)
{
super.init(frame: frame)
createNotification()
setupLabel()
}
required public init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
createNotification()
setupLabel()
}
/**
Create an instance of a AutocompleteField.
- parameter
frame: The fields frame
suggestion: Array of autocomplete strings
*/
public init(frame: CGRect, suggestions: [String])
{
super.init(frame: frame)
self.suggestions = suggestions
createNotification()
setupLabel()
}
// ovverride to set frame of the suggestion label whenever the textfield frame changes.
public override func layoutSubviews()
{
self.label.frame = CGRect(x: self.padding, y: self.pixelCorrection, width: self.frame.width - (self.padding * 2), height: self.frame.height)
super.layoutSubviews()
}
// MARK: - public methods
public func currentSuggestion() -> String?
{
return self.suggestion
}
// MARK: - private methods
/**
Create a notification whenever the text of the field changes.
*/
private func createNotification()
{
NotificationCenter.default.addObserver(
self,
selector: #selector(AutocompleteField.textChanged(_:)),
name: NSNotification.Name.UITextFieldTextDidChange,
object: self)
}
/**
Sets up the suggestion label with the same font styling and alignment as the textfield.
*/
private func setupLabel()
{
setLabelContent()
self.label.lineBreakMode = .byClipping
// If the textfield has one of the default styles, we need to create some padding
// otherwise there will be a offset in x-led.
switch self.borderStyle
{
case .roundedRect, .bezel, .line:
self.padding = 8
break;
default:
break;
}
self.addSubview(self.label)
}
/**
Set content of the suggestion label.
- parameter text: Suggestion text
*/
private func setLabelContent(_ inputText : String = "")
{
var text = inputText
// label string
if(text.characters.count < 1) {
label.attributedText = nil
return
}
// only return first word if in word mode
if self.autocompleteType == .word {
let words = self.text!.components(separatedBy: " ")
let suggestionWords = text.components(separatedBy: " ")
var string : String = ""
for i in 0 ..< words.count {
string = string + suggestionWords[i] + " "
}
text = string
}
// create an attributed string instead of the regular one.
// In this way we can hide the letters in the suggestion that the user has already written.
let attributedString = NSMutableAttributedString(
string: text,
attributes: [
NSFontAttributeName:UIFont(
name: self.font!.fontName,
size: self.font!.pointSize
)!,
NSForegroundColorAttributeName: self.completionColor
]
)
// Hide the letters that are under the fields text.
// If the suggestion is abcdefgh and the user has written abcd
// we want to hide those letters from the suggestion.
if let inputText = self.text
{
attributedString.addAttribute(NSForegroundColorAttributeName,
value: UIColor.clear,
range: NSRange(location:0, length:inputText.characters.count)
)
}
label.attributedText = attributedString
label.textAlignment = self.textAlignment
}
/**
Scans through the suggestions array and finds a suggestion that
matches the searchTerm.
- parameter searchTerm: What to search for
- returns A string or nil
*/
private func suggestionToShow(_ searchTerm : String) -> String
{
var returnString = ""
for suggestion in self.suggestions
{
// Search the suggestion array. User lowercase on both to get a match.
// Also, if the match is exact we move on.
if( (suggestion != searchTerm) &&
suggestion.lowercased().hasPrefix(searchTerm.lowercased()))
{
var suggestionToReturn = searchTerm
suggestionToReturn = suggestionToReturn + suggestion.substring(with: suggestion.characters.index(suggestion.startIndex, offsetBy: searchTerm.characters.count) ..< suggestion.endIndex)
returnString = suggestionToReturn
break
}
}
self.suggestion = returnString
return returnString
}
// MARK: - Events
/**
Triggered whenever the field text changes.
- parameter notification: The NSNotifcation attached to the event
*/
func textChanged(_ notification: Notification)
{
if let text = self.text
{
let suggestion = suggestionToShow(text)
setLabelContent(suggestion)
}
}
// ovverride to set padding
public override func textRect(forBounds bounds: CGRect) -> CGRect
{
return CGRect(x: bounds.origin.x + self.padding, y: bounds.origin.y,
width: bounds.size.width - (self.padding * 2), height: bounds.size.height);
}
// ovverride to set padding
public override func editingRect(forBounds bounds: CGRect) -> CGRect
{
return self.textRect(forBounds: bounds)
}
// ovverride to set padding on placeholder
public override func placeholderRect(forBounds bounds: CGRect) -> CGRect
{
return self.textRect(forBounds: bounds)
}
// remove observer on deinit
deinit {
NotificationCenter.default.removeObserver(self)
}
}
| 29.274074 | 199 | 0.582237 |
898a9424e1ec18df15cbcc96aba9153dbe064f21 | 2,599 | //
// CollectionViewCellType1.swift
// ExampleViewController
//
// Created by hanwe on 2020/08/06.
// Copyright © 2020 hanwe. All rights reserved.
//
import UIKit
import SwiftyJSON
import SDWebImage
class CollectionViewCellType1: UICollectionViewCell {
//MARK: IBOutlet
@IBOutlet weak var mainContainerView: UIView!
@IBOutlet weak var imgContainerView: UIView!
@IBOutlet weak var imgView: UIImageView!
@IBOutlet weak var textContainerView: UIView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var priceLabel: UILabel!
@IBOutlet weak var shippingPriceContainerView: UIView!
@IBOutlet weak var shippingPriceLabel: UILabel!
//MARK: property
var infoData:JSON = JSON.null {
didSet {
self.titleLabel.text = infoData["title"].stringValue
if infoData["shipping_price"].intValue == 0 {
self.shippingPriceLabel.text = "무료배송"
}
else {
self.shippingPriceLabel.text = "\(infoData["shipping_price"].intValue) 원"
}
self.priceLabel.text = "\(infoData["price"].intValue) 원"
self.imgView.sd_setImage(with: URL(string: infoData["image_url"].stringValue), placeholderImage: nil, options: .lowPriority, completed: nil)
}
}
//MARK: lifeCycle
override func awakeFromNib() {
super.awakeFromNib()
initUI()
}
//MARK: function
func initUI() {
self.mainContainerView.backgroundColor = .white
self.imgContainerView.backgroundColor = .clear
self.imgContainerView.layer.borderWidth = 1
self.imgContainerView.layer.borderColor = UIColor.lightGray.cgColor
self.imgContainerView.layer.cornerRadius = 3
self.textContainerView.backgroundColor = .clear
self.titleLabel.font = UIFont(name: "HelveticaNeue", size: 10)
self.titleLabel.textColor = .darkGray
self.priceLabel.font = UIFont(name: "HelveticaNeue", size: 10)
self.priceLabel.textColor = .gray
self.shippingPriceContainerView.backgroundColor = .clear
self.shippingPriceContainerView.layer.borderWidth = 1
self.shippingPriceContainerView.layer.borderColor = UIColor.lightGray.cgColor
self.shippingPriceContainerView.layer.cornerRadius = 3
self.shippingPriceLabel.font = UIFont(name: "HelveticaNeue", size: 10)
self.shippingPriceLabel.textColor = .lightGray
}
//MARK: action
}
| 30.576471 | 153 | 0.644863 |
cccd8a661ecdfb28bddb29381458045d1908dcb3 | 1,314 | import XCTest
import SwiftUI
@testable import ViewInspector
#if os(iOS) || os(tvOS)
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
final class DelayedPreferenceViewTests: XCTestCase {
func testUnwrapDelayedPreferenceView() throws {
let view = NavigationView {
Text("Test")
.backgroundPreferenceValue(Key.self) { _ in EmptyView() }
}
// Not supported
//swiftlint:disable line_length
XCTAssertThrows(
try view.inspect().navigationView().text(0),
"ViewInspector: 'PreferenceValue' modifiers are currently not supported. Consider extracting the enclosed view for direct inspection.")
//swiftlint:enable line_length
}
func testRetainsModifiers() throws {
/* Disabled until supported
let view = Text("Test")
.padding()
.backgroundPreferenceValue(Key.self) { _ in EmptyView() }
.padding().padding()
let sut = try view.inspect().text()
XCTAssertEqual(sut.content.modifiers.count, 3)
*/
}
struct Key: PreferenceKey {
static var defaultValue: String = "test"
static func reduce(value: inout String, nextValue: () -> String) {
value = nextValue()
}
}
}
#endif
| 29.863636 | 147 | 0.605784 |
f95991379aeb81d5601e63b520dbee31b686a8c6 | 976 | extension BaseApp {
public final class QueryRouter: Cosmos.QueryRouter {
private var routes: [String: Querier] = [:]
// NewQueryRouter returns a reference to a new QueryRouter.
init() {}
// AddRoute adds a query path to the router with a given Querier. It will panic
// if a duplicate route is given. The route must be alphanumeric.
public func addRoute(path: String, querier: @escaping Querier) {
guard path.isAlphaNumeric else {
fatalError("route expressions can only contain alphanumeric characters")
}
guard routes[path] == nil else {
fatalError("route \(path) has already been initialized")
}
routes[path] = querier
}
// Route returns the Querier for a given query route path.
public func route(path: String) -> Querier? {
routes[path]
}
}
}
| 34.857143 | 88 | 0.574795 |
e9bb7841a0a0e912977b04cdf7952577e97223d2 | 506 | //
// ViewController.swift
// MonitorYourApp
//
// Created by siempay on 05/12/2019.
// Copyright (c) 2019 siempay. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 20.24 | 80 | 0.671937 |
f8e9f2dccc98e83d2c81a9380c045239071ff5d4 | 10,330 |
import WebKit
extension MonkeyKing: WKNavigationDelegate {
public func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Swift.Error) {
// Pocket OAuth
if let errorString = (error as NSError).userInfo["ErrorFailingURLStringKey"] as? String, errorString.hasSuffix(":authorizationFinished") {
removeWebView(webView, tuples: (nil, nil, nil))
return
}
// Failed to connect network
activityIndicatorViewAction(webView, stop: true)
addCloseButton()
let detailLabel = UILabel()
detailLabel.text = "无法连接,请检查网络后重试"
detailLabel.textColor = UIColor.gray
detailLabel.translatesAutoresizingMaskIntoConstraints = false
let centerX = NSLayoutConstraint(item: detailLabel, attribute: .centerX, relatedBy: .equal, toItem: webView, attribute: .centerX, multiplier: 1.0, constant: 0.0)
let centerY = NSLayoutConstraint(item: detailLabel, attribute: .centerY, relatedBy: .equal, toItem: webView, attribute: .centerY, multiplier: 1.0, constant: -50.0)
webView.addSubview(detailLabel)
webView.addConstraints([centerX,centerY])
webView.scrollView.alwaysBounceVertical = false
}
public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
activityIndicatorViewAction(webView, stop: true)
addCloseButton()
guard let urlString = webView.url?.absoluteString else { return }
var scriptString = ""
if urlString.contains("getpocket.com") {
scriptString += "document.querySelector('div.toolbar').style.display = 'none';"
scriptString += "document.querySelector('a.extra_action').style.display = 'none';"
scriptString += "var rightButton = $('.toolbarContents div:last-child');"
scriptString += "if (rightButton.html() == 'Log In') {rightButton.click()}"
} else if urlString.contains("api.weibo.com") {
scriptString += "document.querySelector('aside.logins').style.display = 'none';"
}
webView.evaluateJavaScript(scriptString, completionHandler: nil)
}
public func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
guard let url = webView.url else {
webView.stopLoading()
return
}
// twitter access token
for case let .twitter(appID, appKey, redirectURL) in accountSet {
guard url.absoluteString.hasPrefix(redirectURL) else { break }
var parametersString = url.absoluteString
for _ in (0...redirectURL.count) {
parametersString.remove(at: parametersString.startIndex)
}
let params = parametersString.queryStringParameters
guard let token = params["oauth_token"], let verifer = params["oauth_verifier"] else { break }
let accessTokenAPI = "https://api.twitter.com/oauth/access_token"
let parameters = ["oauth_token": token, "oauth_verifier": verifer]
let headerString = Networking.shared.authorizationHeader(for: .post, urlString: accessTokenAPI, appID: appID, appKey: appKey, accessToken: nil, accessTokenSecret: nil, parameters: parameters, isMediaUpload: false)
let oauthHeader = ["Authorization": headerString]
request(accessTokenAPI, method: .post, parameters: nil, encoding: .url, headers: oauthHeader) { [weak self] (responseData, httpResponse, error) in
DispatchQueue.main.async { [weak self] in
self?.removeWebView(webView, tuples: (responseData, httpResponse, error))
}
}
return
}
// QQ Web OAuth
guard url.absoluteString.contains("&access_token=") && url.absoluteString.contains("qq.com") else {
return
}
guard let fragment = url.fragment?.dropFirst(), let newURL = URL(string: "https://qzs.qq.com/?\(String(fragment))") else {
return
}
let queryDictionary = newURL.monkeyking_queryDictionary as [String: Any]
removeWebView(webView, tuples: (queryDictionary, nil, nil))
}
public func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
guard let url = webView.url else { return }
// WeChat OAuth
if url.absoluteString.hasPrefix("wx") {
let queryDictionary = url.monkeyking_queryDictionary
guard let code = queryDictionary["code"] as? String else {
return
}
MonkeyKing.fetchWeChatOAuthInfoByCode(code: code) { [weak self] (info, response, error) in
self?.removeWebView(webView, tuples: (info, response, error))
}
} else {
// Weibo OAuth
for case let .weibo(appID, appKey, redirectURL) in accountSet {
if url.absoluteString.lowercased().hasPrefix(redirectURL) {
webView.stopLoading()
guard let code = url.monkeyking_queryDictionary["code"] as? String else { return }
var accessTokenAPI = "https://api.weibo.com/oauth2/access_token?"
accessTokenAPI += "client_id=" + appID
accessTokenAPI += "&client_secret=" + appKey
accessTokenAPI += "&grant_type=authorization_code"
accessTokenAPI += "&redirect_uri=" + redirectURL
accessTokenAPI += "&code=" + code
activityIndicatorViewAction(webView, stop: false)
request(accessTokenAPI, method: .post) { [weak self] (json, response, error) in
DispatchQueue.main.async { [weak self] in
self?.removeWebView(webView, tuples: (json, response, error))
}
}
}
}
}
}
}
extension MonkeyKing {
class func generateWebView() -> WKWebView {
let webView = WKWebView()
let screenBounds = UIScreen.main.bounds
webView.frame = CGRect(origin: CGPoint(x: 0, y: screenBounds.height),
size: CGSize(width: screenBounds.width, height: screenBounds.height - 20))
webView.navigationDelegate = shared
webView.backgroundColor = UIColor(red: 247/255, green: 247/255, blue: 247/255, alpha: 1.0)
webView.scrollView.backgroundColor = webView.backgroundColor
UIApplication.shared.keyWindow?.addSubview(webView)
return webView
}
class func addWebView(withURLString urlString: String) {
if nil == MonkeyKing.shared.webView {
MonkeyKing.shared.webView = generateWebView()
}
guard let url = URL(string: urlString), let webView = MonkeyKing.shared.webView else { return }
webView.load(URLRequest(url: url))
let activityIndicatorView = UIActivityIndicatorView(frame: CGRect(x: 0.0, y: 0.0, width: 20.0, height: 20.0))
activityIndicatorView.center = CGPoint(x: webView.bounds.midX, y: webView.bounds.midY + 30.0)
activityIndicatorView.activityIndicatorViewStyle = .gray
webView.scrollView.addSubview(activityIndicatorView)
activityIndicatorView.startAnimating()
UIView.animate(withDuration: 0.32, delay: 0.0, options: .curveEaseOut, animations: {
webView.frame.origin.y = 20.0
}, completion: nil)
}
func addCloseButton() {
guard let webView = webView else { return }
let closeButton = CloseButton(type: .custom)
closeButton.frame = CGRect(origin: CGPoint(x: UIScreen.main.bounds.width - 50.0, y: 4.0),
size: CGSize(width: 44.0, height: 44.0))
closeButton.addTarget(self, action: #selector(closeOauthView), for: .touchUpInside)
webView.addSubview(closeButton)
}
@objc func closeOauthView() {
guard let webView = webView else { return }
let error = NSError(domain: "User Cancelled", code: -1, userInfo: nil)
removeWebView(webView, tuples: (nil, nil, error))
}
func removeWebView(_ webView: WKWebView, tuples: ([String: Any]?, URLResponse?, Swift.Error?)?) {
activityIndicatorViewAction(webView, stop: true)
webView.stopLoading()
UIView.animate(withDuration: 0.3, delay: 0.0, options: .curveEaseOut, animations: {
webView.frame.origin.y = UIScreen.main.bounds.height
}, completion: { [weak self] _ in
webView.removeFromSuperview()
MonkeyKing.shared.webView = nil
self?.oauthCompletionHandler?(tuples?.0, tuples?.1, tuples?.2)
})
}
func activityIndicatorViewAction(_ webView: WKWebView, stop: Bool) {
for subview in webView.scrollView.subviews {
if let activityIndicatorView = subview as? UIActivityIndicatorView {
guard stop else {
activityIndicatorView.startAnimating()
return
}
activityIndicatorView.stopAnimating()
}
}
}
}
class CloseButton: UIButton {
override func draw(_ rect: CGRect) {
let circleWidth: CGFloat = 28.0
let circlePathX = (rect.width - circleWidth) / 2.0
let circlePathY = (rect.height - circleWidth) / 2.0
let circlePathRect = CGRect(x: circlePathX, y: circlePathY, width: circleWidth, height: circleWidth)
let circlePath = UIBezierPath(ovalIn: circlePathRect)
UIColor(white: 0.8, alpha: 1.0).setFill()
circlePath.fill()
let xPath = UIBezierPath()
xPath.lineCapStyle = .round
xPath.lineWidth = 3.0
let offset: CGFloat = (bounds.width - circleWidth) / 2.0
xPath.move(to: CGPoint(x: offset + circleWidth / 3.0, y: offset + circleWidth / 3.0))
xPath.addLine(to: CGPoint(x: offset + 2.0 * circleWidth / 3.0, y: offset + 2.0 * circleWidth / 3.0))
xPath.move(to: CGPoint(x: offset + circleWidth / 3.0, y: offset + 2.0 * circleWidth / 3.0))
xPath.addLine(to: CGPoint(x: offset + 2.0 * circleWidth / 3.0, y: offset + circleWidth / 3.0))
UIColor.white.setStroke()
xPath.stroke()
}
}
| 50.637255 | 225 | 0.626718 |
64c5756ecc3677c64dd041b49095e9156bbdb63a | 1,726 | //
// Person.swift
// HKCoure
//
// Created by Sebastian on 2/28/20.
// Copyright © 2020 Sebastian. All rights reserved.
//
import SwiftUI
struct Person {
var uid: String
var email: String?
init(uid: String, email: String?) {
self.uid = uid
self.email = email
}
}
struct PacienteHK {
var cedula: Int64
var estatura: Double
var fechNaci: Date?
var lugar: String?
var motivo: String?
var nombre: String?
var sexo: String?
var telefono: Int64
var tipoSangre: String?
var alergias: String?
var pulso: Int16
var saturacion: Int16
var sintomas: String?
var temperatura: Double
var tension: String?
var triage: Int16
var area: String
var visitas: Int16
var estado: String
init(cedula:Int64, estatura: Double, fechNaci: Date?, lugar:String?, motivo: String?, nombre: String?, sexo: String?, telefono: Int64, tipoSangre: String?, alergias: String?, pulso:Int16, saturacion: Int16, sintomas:String?, temperatura:Double, tension: String?, triaje: Int16, area: String, visitas: Int16, estado: String){
self.cedula=cedula
self.estatura = estatura
self.fechNaci = fechNaci
self.lugar = lugar
self.motivo = motivo
self.nombre = nombre
self.sexo = sexo
self.telefono = telefono
self.tipoSangre = tipoSangre
self.alergias = alergias
self.pulso = pulso
self.saturacion = saturacion
self.sintomas = sintomas
self.temperatura = temperatura
self.tension = tension
self.triage = triaje
self.area = area
self.visitas = visitas
self.estado = estado
}
}
| 25.382353 | 328 | 0.624565 |
218f61e6ea13edd411d9752e8bd016d4775c48ea | 2,104 | //
// RepositoryTableViewCell.swift
// GithubBrowser
//
// Created by Giorgi Khorguani on 7/19/18.
// Copyright © 2018 Giorgi Khorguani. All rights reserved.
//
import UIKit
import SnapKit
class RepositoryTableViewCell: UITableViewCell {
var viewModel: RepositoryCellViewModel? {
didSet {
setupUI()
}
}
lazy var nameLabel: UILabel = {
var label = UILabel()
label.font = UIFont.boldSystemFont(ofSize: 20)
return label
}()
lazy var languageLabelView: UIView = {
var labelView = UIView()
labelView.backgroundColor = UIColor(red:0.00, green:0.75, blue:0.44, alpha:1.0)
labelView.layer.cornerRadius = 20
return labelView
}()
lazy var languageLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 14)
label.textColor = .white
return label
}()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupUI() {
contentView.addSubview(nameLabel)
languageLabelView.addSubview(languageLabel)
contentView.addSubview(languageLabelView)
nameLabel.text = viewModel!.Name
languageLabel.text = viewModel!.Language
nameLabel.snp.makeConstraints { make in
make.left.equalTo(self.contentView).offset(20)
make.centerY.equalTo(self.contentView)
}
languageLabelView.snp.makeConstraints { make in
make.right.equalTo(self.contentView).offset(-20)
make.width.greaterThanOrEqualTo(100)
make.height.greaterThanOrEqualTo(40)
make.centerY.equalTo(self.contentView)
}
languageLabel.snp.makeConstraints { make in
make.center.equalTo(self.languageLabelView)
}
}
}
| 27.324675 | 87 | 0.611692 |
223fd38d3d0be3ca0af511329ad47802a9fdb1d1 | 782 | // Copyright (c) 2019 Razeware LLC
// For full license & permission details, see LICENSE.markdown.
import Foundation
public func medianOfThree<T: Comparable>(_ a: inout [T], low: Int, high: Int) -> Int {
let center = (low + high) / 2
if a[low] > a[center] {
a.swapAt(low, center)
}
if a[low] > a[high] {
a.swapAt(low, high)
}
if a[center] > a[high] {
a.swapAt(center, high)
}
return center
}
public func quickSortMedian<T: Comparable>(_ a: inout [T], low: Int, high: Int) {
if low < high {
let pivotIndex = medianOfThree(&a, low: low, high: high)
a.swapAt(pivotIndex, high)
let pivot = partitionLomuto(&a, low: low, high: high)
quicksortLomuto(&a, low: low, high: pivot - 1)
quicksortLomuto(&a, low: pivot + 1, high: high)
}
}
| 26.965517 | 86 | 0.630435 |
d5d51780ff1dc78b0c06bab0a6dbd1936c64e401 | 1,554 | import Foundation
final class InitBondingSelectValidatorsStartWireframe: SelectValidatorsStartWireframe {
private let state: InitiatedBonding
init(state: InitiatedBonding) {
self.state = state
}
override func proceedToCustomList(
from view: ControllerBackedProtocol?,
validatorList: [SelectedValidatorInfo],
recommendedValidatorList: [SelectedValidatorInfo],
selectedValidatorList: SharedList<SelectedValidatorInfo>,
maxTargets: Int
) {
guard let nextView = CustomValidatorListViewFactory
.createInitiatedBondingView(
for: validatorList,
with: recommendedValidatorList,
selectedValidatorList: selectedValidatorList,
maxTargets: maxTargets,
with: state
) else { return }
view?.controller.navigationController?.pushViewController(
nextView.controller,
animated: true
)
}
override func proceedToRecommendedList(
from view: SelectValidatorsStartViewProtocol?,
validatorList: [SelectedValidatorInfo],
maxTargets: Int
) {
guard let nextView = RecommendedValidatorListViewFactory.createInitiatedBondingView(
for: validatorList,
maxTargets: maxTargets,
with: state
) else {
return
}
view?.controller.navigationController?.pushViewController(
nextView.controller,
animated: true
)
}
}
| 30.470588 | 92 | 0.637709 |
22ccf06d65e9e9add6af74965e312fd1b54ada59 | 4,459 | //
// TwentyfourthViewController.swift
// blista
//
// Created by Falk Rismansanj on 27.06.19.
// Copyright © 2019 Falk Rismansanj. All rights reserved.
//
import UIKit
import Crashlytics
private var viewHasLoaded = false
class TwentyfourthViewController: UIViewController, UIWebViewDelegate {
@IBOutlet weak var webView24: UIWebView!
@IBOutlet weak var activity: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let reachability = Reachability()!
switch reachability.connection {
case .wifi:
Answers.logContentView(withName: "Stundenplan",
contentType: "Stundenplan",
contentId: "stundenplan",
customAttributes: [:])
webView24.loadRequest(URLRequest(url: URL(string: "https://zitrotec.de/stundenplan/display.php")!))
case .cellular:
Answers.logContentView(withName: "Stundenplan",
contentType: "Stundenplan",
contentId: "stundenplan",
customAttributes: [:])
webView24.loadRequest(URLRequest(url: URL(string: "https://zitrotec.de/stundenplan/display.php")!))
case .none:
UIApplication.shared.isNetworkActivityIndicatorVisible = false
activity.stopAnimating()
navigationController?.popViewController(animated: true)
dismiss(animated: true, completion: nil)
let alert = UIAlertView()
alert.title = "Du bist Offline"
alert.message = "Bitte stell eine Internetverbindung her, um diesen Inhalt anzuzeigen."
alert.addButton(withTitle: "OK")
alert.show()
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let reachability = Reachability()!
switch reachability.connection {
case .wifi:
Answers.logContentView(withName: "Stundenplan",
contentType: "Stundenplan",
contentId: "stundenplan",
customAttributes: [:])
if viewHasLoaded == true {
return
} else {
webView24.loadRequest(URLRequest(url: URL(string: "https://zitrotec.de/stundenplan/display.php")!))
}
case .cellular:
Answers.logContentView(withName: "Stundenplan",
contentType: "Stundenplan",
contentId: "stundenplan",
customAttributes: [:])
if viewHasLoaded == true {
return
} else {
webView24.loadRequest(URLRequest(url: URL(string: "https://zitrotec.de/stundenplan/display.php")!))
}
case .none:
UIApplication.shared.isNetworkActivityIndicatorVisible = false
activity.stopAnimating()
navigationController?.popViewController(animated: true)
dismiss(animated: true, completion: nil)
let alert = UIAlertView()
alert.title = "Du bist Offline"
alert.message = "Bitte stell eine Internetverbindung her, um diesen Inhalt anzuzeigen."
alert.addButton(withTitle: "OK")
alert.show()
}
}
func webViewDidStartLoad(_ webView: UIWebView)
{
UIApplication.shared.isNetworkActivityIndicatorVisible = true
activity.startAnimating()
}
func webViewDidFinishLoad(_ webView: UIWebView)
{
UIApplication.shared.isNetworkActivityIndicatorVisible = false
activity.stopAnimating()
viewHasLoaded = true
}
func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
activity.stopAnimating()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 36.252033 | 111 | 0.561112 |
3ada18f7bae7550e09a6a5a433266a798898d349 | 1,004 | //
// CustomDropdownElementResponseCompound.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
#if canImport(AnyCodable)
import AnyCodable
#endif
/** A Generic DropdownElement Object and children to create a complete structure */
public struct CustomDropdownElementResponseCompound: Codable, JSONEncodable, Hashable {
/** The Description of the element */
public var sLabel: String
/** The Value of the element */
public var sValue: String
public init(sLabel: String, sValue: String) {
self.sLabel = sLabel
self.sValue = sValue
}
public enum CodingKeys: String, CodingKey, CaseIterable {
case sLabel
case sValue
}
// Encodable protocol methods
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(sLabel, forKey: .sLabel)
try container.encode(sValue, forKey: .sValue)
}
}
| 25.1 | 87 | 0.696215 |
8ffd495d87caa5946da463b75186c1dde3df9c31 | 3,066 | //
// ModifyFileTool.swift
// CommandLineKit
//
// Created by 赵志丹 on 2019/4/19.
//
import Foundation
import PathKit
import Rainbow
struct ModifyFileTool {
/// 必须为项目的根目录, 需要根据根目录去修改工程文件
let executionPath: Path
let originalStr: String
let replaceStr: String
let extensions: [String]
init(executionPath: String, originalStr: String, replaceStr: String, extensions: [String] = []) {
self.executionPath = Path(executionPath)
self.originalStr = originalStr
self.replaceStr = replaceStr
self.extensions = extensions
}
func searchFile(search: String) {
let rootPath = executionPath
//"/Users/shangp/workspace/compony/ShangpinApp/ShangPin/ShangPin/ShangPin"
let proces = FileSearchProcess(path: rootPath.string, searchStr: search)
let sets = proces.execute()
//print("\(sets)".blue)
let needHandArr = sets.compactMap { $0.components(separatedBy: ":").first }.compactMap({Path($0)})
//print(needHandArr)
/// 这里应该循环
guard let fileName = needHandArr.last else {
return
}
handleModifyFile(file: fileName)
}
func handleModifyFile(file: Path) {
let searchStr = file.lastComponentWithoutExtension
let proces = FileSearchProcess(path: executionPath.string, searchStr: searchStr)
let sets = proces.execute().compactMap({ Path($0) })
print("\(sets)".blue)
let needReplaceStr = searchStr
let replacedStr = needReplaceStr.replacingOccurrences(of: originalStr, with: replaceStr)
var trupes: [ReplaceTrupe] = []
trupes.append((needReplaceStr+".h", replacedStr+".h"))
trupes.append((needReplaceStr+".m", replacedStr+".m"))
trupes.append((needReplaceStr+"*", replacedStr+"*"))
trupes.append((needReplaceStr+".", replacedStr+"."))
trupes.append((needReplaceStr+"$", replacedStr))
sets.forEach { (path) in
let replaceProcess = FileReplaceProcess(path: path.string, replaces: trupes)
let arr = replaceProcess.execute()
print("arr=\(arr)")
}
/**
需要处理的:
1、#import "SPRechargeResultViewController.h"
2、4CFDFF391D781A8300BEDFD5 /* SPRechargeResultViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SPRechargeResultViewController.h; sourceTree = "<group>"; };
3、4CFDFF551D781A8300BEDFD5 /* SPRechargeResultViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 4CFDFF3A1D781A8300BEDFD5 /* SPRechargeResultViewController.m */; };
4、SPRechargeResultViewController *comfirmVC = [[SPRechargeResultViewController alloc] initWithPayConfirmationModel:checkModel];
5、@interface SPRechargeResultViewController ()
6、@implementation SPRechargeResultViewController
7、SPRechargeResultViewController *comfirmVC = SPRechargeResultViewController.new;
*/
// TODO 处理完之后, 修改文件名
// TODO 修改工程文件
}
}
| 36.939759 | 223 | 0.660796 |
76f30a6264314489e618fc95f7534b301f316e24 | 4,611 | //
// LexerTests.swift
// ParsingTests
//
// Created by Nick Lockwood on 03/09/2018.
// Copyright © 2018 Nick Lockwood. All rights reserved.
//
import XCTest
@testable import Parsing
class LexerTests: XCTestCase {
// MARK: identifiers
func testLetters() {
let input = "abc dfe"
let tokens: [Token] = [.identifier("abc"), .identifier("dfe")]
XCTAssertEqual(try tokenize(input), tokens)
}
func testLettersAndNumbers() {
let input = "a1234b"
let tokens: [Token] = [.identifier("a1234b")]
XCTAssertEqual(try tokenize(input), tokens)
}
func testInvalidIdentifier() {
let input = "a123_4b"
XCTAssertThrowsError(try tokenize(input)) { error in
XCTAssertEqual(error as? LexerError, .unrecognizedInput("_4b"))
}
}
// MARK: strings
func testSimpleString() {
let input = "\"abcd\""
let tokens: [Token] = [.string("abcd")]
XCTAssertEqual(try tokenize(input), tokens)
}
func testUnicodeString() {
let input = "\"😂\""
let tokens: [Token] = [.string("😂")]
XCTAssertEqual(try tokenize(input), tokens)
}
func testEmptyString() {
let input = "\"\""
let tokens: [Token] = [.string("")]
XCTAssertEqual(try tokenize(input), tokens)
}
func testStringWithEscapedQuotes() {
let input = "\"\\\"hello\\\"\""
let tokens: [Token] = [.string("\"hello\"")]
XCTAssertEqual(try tokenize(input), tokens)
}
func testStringWithEscapedBackslash() {
let input = "\"foo\\\\bar\""
let tokens: [Token] = [.string("foo\\bar")]
XCTAssertEqual(try tokenize(input), tokens)
}
func testUnterminatedString() {
let input = "\"hello"
XCTAssertThrowsError(try tokenize(input)) { error in
XCTAssertEqual(error as? LexerError, .unrecognizedInput("\"hello"))
}
}
func testUnterminatedEscapedQuote() {
let input = "\"hello\\\""
XCTAssertThrowsError(try tokenize(input)) { error in
XCTAssertEqual(error as? LexerError, .unrecognizedInput("\"hello\\\""))
}
}
// MARK: numbers
func testZero() {
let input = "0"
let tokens: [Token] = [.number(0)]
XCTAssertEqual(try tokenize(input), tokens)
}
func testDigit() {
let input = "5"
let tokens: [Token] = [.number(5)]
XCTAssertEqual(try tokenize(input), tokens)
}
func testMultidigit() {
let input = "50"
let tokens: [Token] = [.number(50)]
XCTAssertEqual(try tokenize(input), tokens)
}
func testLeadingZero() {
let input = "05"
let tokens: [Token] = [.number(5)]
XCTAssertEqual(try tokenize(input), tokens)
}
func testDecimal() {
let input = "0.5"
let tokens: [Token] = [.number(0.5)]
XCTAssertEqual(try tokenize(input), tokens)
}
func testLeadingDecimalPoint() {
let input = ".56"
let tokens: [Token] = [.number(0.56)]
XCTAssertEqual(try tokenize(input), tokens)
}
func testTrailingDecimalPoint() {
let input = "56."
let tokens: [Token] = [.number(56)]
XCTAssertEqual(try tokenize(input), tokens)
}
func testTooManyDecimalPoints() {
let input = "0.5.6"
XCTAssertThrowsError(try tokenize(input)) { error in
XCTAssertEqual(error as? LexerError, .unrecognizedInput("0.5.6"))
}
}
// MARK: operators
func testOperators() {
let input = "a = 4 + b"
let tokens: [Token] = [
.identifier("a"), .assign, .number(4), .plus, .identifier("b"),
]
XCTAssertEqual(try tokenize(input), tokens)
}
// MARK: statements
func testDeclaration() {
let input = """
let foo = 5
let bar = "hello"
let baz = foo
"""
let tokens: [Token] = [
.let, .identifier("foo"), .assign, .number(5),
.let, .identifier("bar"), .assign, .string("hello"),
.let, .identifier("baz"), .assign, .identifier("foo"),
]
XCTAssertEqual(try tokenize(input), tokens)
}
func testPrintStatement() {
let input = """
print foo
print 5
print "hello" + "world"
"""
let tokens: [Token] = [
.print, .identifier("foo"),
.print, .number(5),
.print, .string("hello"), .plus, .string("world"),
]
XCTAssertEqual(try tokenize(input), tokens)
}
}
| 26.80814 | 83 | 0.55129 |
673539342dec0e2e987178948b39bfe7341a8a4d | 286 | //
// Constraints.swift
// XCalendar
//
// Created by Mohammad Yasir on 07/10/21.
//
import SwiftUI
public enum Spacing: CGFloat {
case low = 4
case standard = 8
case small = 12
case medium = 16
case large = 20
case extraLarge = 24
case extreme = 28
}
| 14.3 | 42 | 0.615385 |
d5f65ac4571a2493d92f3dd0c65918eb14d766f5 | 922 |
import Foundation
func fib_dp(n: Int) -> UInt {
precondition(n < 94, "should be less than 94 as it appears to maxed out the Int64's capacity")
var f = [UInt](repeating: 0, count: n + 1)
f[0] = 0
f[1] = 1
for index in 2 ... n {
f[index] = (f[index - 1] + f[index - 2])
}
return f[n]
}
// It appears we do not need to store all the intermediate value for the entire period of execution.
// Because the recurrence depends on two arguments, we only need to retain the last two values we have seen earlier.
func fib_dp2(value: Int) -> UInt {
precondition(value < 94, "should be less than 94 as it appears to maxed out the Int64's capacity")
var back2: UInt = 0 // last two values of f[n]
var back1: UInt = 1
var next: UInt
for _ in 2 ..< value {
next = UInt(back1 + back2)
back2 = back1
back1 = next
}
return back1 + back2
}
print(fib_dp(n: 93))
print(fib_dp2(value: 93))
| 26.342857 | 116 | 0.647505 |
fec539958a585d72317407d79a127fe5b50ebf22 | 5,348 | //
// Configuration+Merging.swift
// SwiftLint
//
// Created by JP Simard on 7/17/17.
// Copyright © 2017 Realm. All rights reserved.
//
import Foundation
import SourceKittenFramework
extension Configuration {
public func configuration(for file: File) -> Configuration {
if let containingDir = file.path?.bridge().deletingLastPathComponent {
return configuration(forPath: containingDir)
}
return self
}
private func configuration(forPath path: String) -> Configuration {
if path == rootDirectory {
return self
}
let pathNSString = path.bridge()
let configurationSearchPath = pathNSString.appendingPathComponent(Configuration.fileName)
// If a configuration exists and it isn't us, load and merge the configurations
if configurationSearchPath != configurationPath &&
FileManager.default.fileExists(atPath: configurationSearchPath) {
let fullPath = pathNSString.absolutePathRepresentation()
let config = Configuration.getCached(atPath: fullPath) ??
Configuration(path: configurationSearchPath, rootPath: fullPath, optional: false, quiet: true)
return merge(with: config)
}
// If we are not at the root path, continue down the tree
if path != rootPath && path != "/" {
return configuration(forPath: pathNSString.deletingLastPathComponent)
}
// If nothing else, return self
return self
}
private var rootDirectory: String? {
guard let rootPath = rootPath else {
return nil
}
var isDirectoryObjC: ObjCBool = false
guard FileManager.default.fileExists(atPath: rootPath, isDirectory: &isDirectoryObjC) else {
return nil
}
let isDirectory: Bool
#if os(Linux)
isDirectory = isDirectoryObjC
#else
isDirectory = isDirectoryObjC.boolValue
#endif
if isDirectory {
return rootPath
} else {
return rootPath.bridge().deletingLastPathComponent
}
}
private struct HashableRule: Hashable {
fileprivate let rule: Rule
fileprivate static func == (lhs: HashableRule, rhs: HashableRule) -> Bool {
// Don't use `isEqualTo` in case its internal implementation changes from
// using the identifier to something else, which could mess up with the `Set`
return type(of: lhs.rule).description.identifier == type(of: rhs.rule).description.identifier
}
fileprivate var hashValue: Int {
return type(of: rule).description.identifier.hashValue
}
}
private func mergingRules(with configuration: Configuration) -> [Rule] {
switch configuration.rulesMode {
case .allEnabled:
// Technically not possible yet as it's not configurable in a .swiftlint.yml file,
// but implemented for completeness
return configuration.rules
case .whitelisted(let whitelistedRules):
// Use an intermediate set to filter out duplicate rules when merging configurations
// (always use the nested rule first if it exists)
return Set(configuration.rules.map(HashableRule.init))
.union(rules.map(HashableRule.init))
.map { $0.rule }
.filter { rule in
return whitelistedRules.contains(type(of: rule).description.identifier)
}
case let .default(disabled, optIn):
// Same here
return Set(
configuration.rules
// Enable rules that are opt-in by the nested configuration
.filter { rule in
return optIn.contains(type(of: rule).description.identifier)
}
.map(HashableRule.init)
)
// And disable rules that are disabled by the nested configuration
.union(
rules.filter { rule in
return !disabled.contains(type(of: rule).description.identifier)
}.map(HashableRule.init)
)
.map { $0.rule }
}
}
internal func merge(with configuration: Configuration) -> Configuration {
return Configuration(
rulesMode: configuration.rulesMode, // Use the rulesMode used to build the merged configuration
included: configuration.included, // Always use the nested included directories
excluded: configuration.excluded, // Always use the nested excluded directories
// The minimum warning threshold if both exist, otherwise the nested,
// and if it doesn't exist try to use the parent one
warningThreshold: warningThreshold.map { warningThreshold in
return min(configuration.warningThreshold ?? .max, warningThreshold)
} ?? configuration.warningThreshold,
reporter: reporter, // Always use the parent reporter
rules: mergingRules(with: configuration),
cachePath: cachePath, // Always use the parent cache path
rootPath: configuration.rootPath
)
}
}
| 39.323529 | 110 | 0.611444 |
22f3f277d832b84286e70f464a06266059463de3 | 1,605 | //
// ParsingTests.swift
// mundraubKitTests
//
// Created by Oliver Krakora on 30.08.20.
// Copyright © 2020 Oliver Ian Krakora. All rights reserved.
//
import XCTest
@testable
import mundraubKit
class ParsingTests: XCTestCase {
func jsonURL(for resource: String) -> URL? {
Bundle(for: Self.self).url(forResource: resource, withExtension: "json")!
}
func data(for resource: String) throws -> Data {
try jsonURL(for: resource).flatMap { try Data(contentsOf: $0) }!
}
func testFilterParsing() throws {
let filters = try data(for: "filters")
try parse(data: filters, type: FilterOptions.self)
}
func testUserParsing() throws {
let users = try data(for: "users")
try parse(data: users, type: ItemResponse.self)
}
func testCideryParsing() throws {
let cideries = try data(for: "cideries")
try parse(data: cideries, type: ItemResponse.self)
}
func testGroupParsing() throws {
let groups = try data(for: "groups")
try parse(data: groups, type: ItemResponse.self)
}
func testBirthTreeParsing() throws {
let birthtrees = try data(for: "birthtrees")
try parse(data: birthtrees, type: ItemResponse.self)
}
func testPlantParsing() throws {
let plants = try data(for: "plants")
try parse(data: plants, type: ItemResponse.self)
}
@discardableResult
func parse<T: Decodable>(data: Data, type: T.Type) throws -> T {
try Decoders.standardJSON.decode(T.self, from: data)
}
}
| 27.672414 | 81 | 0.623676 |
29ee50af6c69c74fb1b9e737a116799c62f287b0 | 1,126 | //
// TurduckenTVUITests.swift
// TurduckenTVUITests
//
// Created by Jeff Kelley on 3/16/17.
// Copyright © 2017 Jeff Kelley. All rights reserved.
//
import XCTest
class TurduckenTVUITests: 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() {
XCTAssertTrue(true)
}
}
| 31.277778 | 182 | 0.657194 |
ef553afb0715aac8c5fdcb44849cec9fcf2cedce | 2,745 | //
// MockDataGenerator.swift
// SampleApp
//
// Created by Matthew Yannascoli on 5/18/16.
//
import Foundation
class MockDataGenerator {
static let Url = NSURL(string: "http://test.someurl.com")!
static let request: NSMutableURLRequest = {
let request = NSMutableURLRequest(URL: MockDataGenerator.Url)
let bodyData = "id=CIW2yQEIo7bJAQjEtskBCP2VygEI7pzKAQ==&someParam=someValue"
let headerData = [
"Accept" : "application/json",
"Accept-Language": "en-us",
"Cache-Control": "max-age=0"
]
request.allHTTPHeaderFields = headerData
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding)
return request
}()
static let response: NSHTTPURLResponse = {
return NSHTTPURLResponse(URL: MockDataGenerator.Url, statusCode: 404, HTTPVersion: nil, headerFields: ["Content-Type":"text/html"])!
}()
static let responseData: NSData = {
let data = "first_name=Leonard&last_name=Nimoy&[email protected]"
return data.dataUsingEncoding(NSUTF8StringEncoding)!
}()
static func generate() {
let queue1 = dispatch_queue_create("AppTestQueue", nil)
dispatch_async(queue1) {
var counter = 0
while true {
sleep(arc4random_uniform(20) + 2)
counter += 1
log.warn(PrettyLog.network(request, response: response, data: responseData), filter: LogFilter.Network.rawValue)
}
}
let queue2 = dispatch_queue_create("AppTestQueue", nil)
dispatch_async(queue2) {
var counter = 0
while true {
sleep(arc4random_uniform(20) + 2)
counter += 1
log.error("Banana Error", filter: LogFilter.Bannana.rawValue)
}
}
let queue3 = dispatch_queue_create("AppTestQueue", nil)
dispatch_async(queue3) {
var counter = 0
while true {
sleep(arc4random_uniform(20) + 2)
counter += 1
log.info("Random Info Random Info Random Info Random Info Random Info Random Info Random Info", filter: LogFilter.Apple.rawValue)
}
}
let queue4 = dispatch_queue_create("AppTestQueue", nil)
dispatch_async(queue4) {
var counter = 0
while true {
sleep(arc4random_uniform(20) + 2)
counter += 1
log.debug("Random Info Random Info Random Info Random Info Random Info Random Info Random Info", filter: LogFilter.Apple.rawValue)
}
}
}
} | 34.746835 | 146 | 0.579599 |
48e054413caef99da77b9908bcbb31d3feed7ac9 | 2,875 | //
// ModelData.swift
// Gifly
//
// Created by 女王様 on 2020/12/16.
//
import Foundation
import Combine
import PhotosUI
import UIKit
final class ModelData: ObservableObject {
// for onchange use
// static func == (lhs: ModelData, rhs: ModelData) -> Bool {
// if lhs.parameters == rhs.parameters
// {
// return true
// }
// print("[!=]")
// return false
// }
// @Published var landmarks: [Landmark] = load("landmarkData.json")
// @Published var profile = Profile.default
@Published var parameters: Parameter
var parametersPrevious: Parameter
// @Published var phassets: [PHAsset]?
// @Published var phasset: PHAsset?
@Published var isGenerating: Bool
@Published var frames: [UIImage]
var category: Categories?
var video: AVAsset?
var gif: [UIImage]?
init() {
parameters = .default
parametersPrevious = .default
isGenerating = false //todo abort all generating
frames = []
category = .none
}
func reload (oftype: PHPickerFilter?) -> Void {
parameters = .default
parametersPrevious = .default
video = nil
gif = nil
isGenerating = false //todo abort all generating
frames = []
category = getCategory(oftype: oftype)
// todo comment test! data!
["1","2","3"]
// ["default"]
.forEach { imageName in
if let img = UIImage(named: imageName) {
frames.append(img)
}
}
}
// var hikes: [Hike] = load("hikeData.json")
// var features: [Landmark] {
// landmarks.filter { $0.isFeatured }
// }
//
// var categories: [String: [Landmark]] {
// Dictionary(grouping: landmarks, by: {
// $0.category.rawValue
// })
// }
private func getCategory(oftype: PHPickerFilter?) -> Categories? {
switch oftype {
case PHPickerFilter.livePhotos:
return .video
case PHPickerFilter.videos:
return .video
case PHPickerFilter.images:
return .gif
default:
return .none
}
}
}
//func load<T: Decodable>(_ filename: String) -> T {
// let data: Data
//
// guard let file = Bundle.main.url(forResource: filename, withExtension: nil)
// else {
// fatalError("Couldn't find \(filename) in main bundle.")
// }
//
// do {
// data = try Data(contentsOf: file)
// } catch {
// fatalError("Couldn't load \(filename) from main bundle:\n\(error)")
// }
//
// do {
// let decoder = JSONDecoder()
// return try decoder.decode(T.self, from: data)
// } catch {
// fatalError("Couldn't parse \(filename) as \(T.self):\n\(error)")
// }
//}
| 24.364407 | 81 | 0.544348 |
abafc0768a47a6e8ee21e3645a80cda99f176bd5 | 7,848 | //
// BLEPeripheralConnection.swift
// Actors
//
// Created by Dario Lencina on 10/26/15.
// Copyright © 2015 dario. All rights reserved.
//
import Foundation
import CoreBluetooth
/**
BLECentral returns a BLEPeripheralConnection OnConnect, the idea is to simplify and provide a more organized
way to interact with CBPeripherals
*/
public class BLEPeripheralConnection : Actor, WithListeners, CBPeripheralDelegate {
/**
Actors that care about this peripheral connection
*/
public var listeners : [ActorRef] = [ActorRef]()
func connected(peripheral : CBPeripheral) -> Receive {
peripheral.delegate = self
return { [unowned self] (msg : Actor.Message) in
switch(msg) {
case let m as DiscoverServices:
peripheral.discoverServices(m.services)
case is AddListener:
self.addListener(sender: msg.sender)
case is PeripheralDidUpdateName:
self.broadcast(msg: msg)
case is DidModifyServices:
self.broadcast(msg: msg)
case is DidReadRSSI:
self.broadcast(msg: msg)
case is DidDiscoverServices:
self.broadcast(msg: msg)
case is DidDiscoverIncludedServicesForService:
self.broadcast(msg: msg)
case is DidDiscoverCharacteristicsForService:
self.broadcast(msg: msg)
case is DidUpdateValueForCharacteristic:
self.broadcast(msg: msg)
case is DidWriteValueForCharacteristic:
self.broadcast(msg: msg)
case is DidUpdateNotificationStateForCharacteristic:
self.broadcast(msg: msg)
case is DidDiscoverDescriptorsForCharacteristic:
self.broadcast(msg: msg)
case is DidUpdateValueForDescriptor:
self.broadcast(msg: msg)
case is DidWriteValueForDescriptor:
self.broadcast(msg: msg)
default:
print("ignored")
}
}
}
/**
This is the message handler when there's no peripheral
- parameter msg : incoming message
*/
override public func receive(msg: Actor.Message) {
switch(msg) {
case let p as SetPeripheral:
self.become(name: "connected", state: self.connected(peripheral: p.peripheral))
default:
super.receive(msg: msg)
}
}
/**
CBPeripheralDelegate forwarded message, this method is exposed through an Actor.Message subclass
*/
public func peripheralDidUpdateName(_ peripheral: CBPeripheral){
this ! PeripheralDidUpdateName(sender: this, peripheral: peripheral)
}
/**
CBPeripheralDelegate forwarded message, this method is exposed through an Actor.Message subclass
*/
public func peripheral(_ peripheral: CBPeripheral, didModifyServices invalidatedServices: [CBService]){
this ! DidModifyServices(sender: this, peripheral: peripheral, invalidatedServices: invalidatedServices)
}
/**
CBPeripheralDelegate forwarded message, this method is exposed through an Actor.Message subclass
*/
public func peripheral(_ peripheral: CBPeripheral, didReadRSSI RSSI: NSNumber, error: Error?){
this ! DidReadRSSI(sender: this, peripheral: peripheral, error: error, RSSI: RSSI)
}
/**
CBPeripheralDelegate forwarded message, this method is exposed through an Actor.Message subclass
*/
public func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?){
if let svcs = peripheral.services {
if svcs.count > 0 {
peripheral.services?.forEach {
print("didDiscoverServices \($0.uuid)")
}
peripheral.services?.forEach({ (service : CBService) in
peripheral.discoverCharacteristics(nil, for: service)
})
this ! DidDiscoverServices(sender: this, peripheral: peripheral, error: error)
} else {
this ! DidDiscoverNoServices(sender: this, peripheral: peripheral, error: error)
}
} else {
this ! DidDiscoverNoServices(sender: this, peripheral: peripheral, error: error)
}
}
/**
CBPeripheralDelegate forwarded message, this method is exposed through an Actor.Message subclass
*/
public func peripheral(_ peripheral: CBPeripheral, didDiscoverIncludedServicesFor service: CBService, error: Error?){
this ! DidDiscoverIncludedServicesForService(sender: this, peripheral: peripheral, service: service, error: error)
}
/**
CBPeripheralDelegate forwarded message, this method is exposed through an Actor.Message subclass
*/
public func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?){
this ! DidDiscoverCharacteristicsForService(sender: this, peripheral: peripheral, service: service, error: error)
}
/**
CBPeripheralDelegate forwarded message, this method is exposed through an Actor.Message subclass
*/
public func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?){
this ! DidUpdateValueForCharacteristic(sender: this, peripheral: peripheral, characteristic: characteristic, error: error)
}
/**
CBPeripheralDelegate forwarded message, this method is exposed through an Actor.Message subclass
*/
public func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?){
this ! DidWriteValueForCharacteristic(sender: this, peripheral: peripheral, characteristic: characteristic, error: error)
}
/**
CBPeripheralDelegate forwarded message, this method is exposed through an Actor.Message subclass
*/
public func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?){
this ! DidUpdateNotificationStateForCharacteristic(sender: this, peripheral: peripheral, characteristic: characteristic, error: error)
}
/**
CBPeripheralDelegate forwarded message, this method is exposed through an Actor.Message subclass
*/
public func peripheral(_ peripheral: CBPeripheral, didDiscoverDescriptorsFor characteristic: CBCharacteristic, error: Error?){
this ! DidDiscoverDescriptorsForCharacteristic(sender: this, peripheral: peripheral, characteristic: characteristic, error: error)
}
/**
CBPeripheralDelegate forwarded message, this method is exposed through an Actor.Message subclass
*/
public func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor descriptor: CBDescriptor, error: Error?){
this ! DidUpdateValueForDescriptor(sender: this, peripheral: peripheral, descriptor: descriptor, error: error)
}
/**
CBPeripheralDelegate forwarded message, this method is exposed through an Actor.Message subclass
*/
public func peripheral(_ peripheral: CBPeripheral, didWriteValueFor descriptor: CBDescriptor, error: Error?){
this ! DidWriteValueForDescriptor(sender: this, peripheral: peripheral, descriptor: descriptor, error: error)
}
deinit {
print("bye")
}
}
| 36.502326 | 142 | 0.639016 |
e4bbd632cce957723b417e65f101ff2e37658d75 | 589 | //
// RAUITestHelperContactSupport.swift
// RideAustinTestUI
//
// Created by Roberto Abreu on 1/11/18.
// Copyright © 2018 RideAustin.com. All rights reserved.
//
import XCTest
class RAUITestHelperContactSupport: RAUITestBaseHelper {
//MARK: Properties
var helpBar: XCUIElement {
return app.otherElements["helpBar"]
}
var contactSupportNavigationBar: XCUIElement {
return app.navigationBars["CONTACT SUPPORT"]
}
var contactSupportMessageTextView: XCUIElement {
return app.textViews["supportMessage"]
}
}
| 20.310345 | 57 | 0.679117 |
e648bab4f7f6e3d4388f4cc5803fd435c778bd5b | 572 | //
// FocusNodeTests.swift
// Tests
//
// Created by Wolfgang Schreurs on 22/06/2019.
// Copyright © 2019 Wolftrail. All rights reserved.
//
import XCTest
import SpriteKit
@testable import Fenris
class FocusNodeTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testFocusNode() {
let strokeColor: SKColor = .yellow
let focusNode = FocusNode(strokeColor: strokeColor)
XCTAssertTrue(focusNode.strokeColor == strokeColor)
}
}
| 19.724138 | 59 | 0.638112 |
2fe42273a00bfffd88842b5cec37b3e59c3b6a78 | 3,270 | //
// Created by Alexey Korolev on 27.06.2018.
// Copyright (c) 2018 Alpha Troya. All rights reserved.
//
import Foundation
import Moya
/// Defines interface for generation string description of the request
public protocol RequestDescriptor {
/**
Method for generating string description of the request
- Parameter request: Request object
- Parameter target: Current Moya target
- Parameter logger: Logger object for printing intermediate log messages
- Returns: String description of the request and target
*/
func description(request: RequestType, target: TargetType, logger: Logger) -> String
}
/**
Descriptor for convert request and target instances for [HTTPie](https://github.com/jakubroztocil/httpie)
tool string representation
*/
public final class HTTPieRequestDescriptor: RequestDescriptor {
/// Descriptor constructor
public init() {}
/**
Method for generating string description of the request
- Parameter request: Request object
- Parameter target: Current Moya target
- Parameter logger: Logger object for printing intermediate log messages
- Returns: String description of the request and target
*/
public func description(request: RequestType, target: TargetType, logger: Logger) -> String {
return target.httpie(request: request, logger: logger)
}
}
private extension TargetType {
func httpie(request: RequestType, logger: Logger) -> String {
var fragments = [
"http",
self.method.rawValue.uppercased(),
self.baseURL.absoluteString + "/" + self.path,
]
if let headers = request.request?.allHTTPHeaderFields {
fragments.append(contentsOf: headers.sorted { $0.key < $1.key }.map { "\($0.key):'\($0.value)'" })
}
switch task {
case .requestPlain:
break
case let .requestParameters(parameters, encoding):
switch encoding {
case _ as URLEncoding:
parameters.map { "\($0.key)==\($0.value)" }.sorted().forEach { fragments.append($0) }
case _ as JSONEncoding:
fragments.insert("echo '\(prettyPrinted(json: parameters))' |", at: 0)
default:
logger.log(with: .warning, "unknown request parameter type \(encoding)")
}
case let .requestJSONEncodable(encodable):
do {
try fragments.insert("echo '\(prettyPrinted(json: encodable.asJSON()))' |", at: 0)
} catch {
logger.log(with: .verbose, "can't encode model object")
}
default:
logger.log(with: .warning, "task description not yet implemented \(task)")
}
return fragments.joined(separator: " ")
}
private func prettyPrinted(json: Any) -> String {
do {
let data = try JSONSerialization.data(withJSONObject: json)
return String(data: data, encoding: .utf8) ?? ""
} catch {
return ""
}
}
}
private extension Encodable {
func asJSON() throws -> Any {
let data = try JSONEncoder().encode(self)
return try JSONSerialization.jsonObject(with: data, options: .allowFragments)
}
}
| 34.787234 | 110 | 0.625382 |
d923d375b4318a357410f6d77f34510eb849cc0c | 3,267 | //
// PopularViewController.swift
// TraVa
//
// Created by Кирилл Прокофьев on 23.12.2021.
//
import Foundation
import UIKit
import SnapKit
final class PopularViewController: UIViewController {
private let networkService = NetworkService()
private let activityIndicator = UIActivityIndicatorView(style: .medium)
private lazy var collectionView: UICollectionView = {
let flowLayout = FlowLayout()
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
collectionView.alwaysBounceVertical = true
collectionView.register(MovieCell.self, forCellWithReuseIdentifier: MovieCell.identifier)
collectionView.delegate = self
collectionView.dataSource = self
return collectionView
}()
private var movies: [Movie]?
func loadData() {
self.activityIndicator.startAnimating()
self.networkService.loadData { (result: Result<MoviesPage, Error>) in
switch result {
case .success(let model):
print("[NETWORK] model is: \(model)")
self.movies = model.results
DispatchQueue.main.async {
self.activityIndicator.stopAnimating()
self.collectionView.reloadData()
}
case .failure(let error):
print("[NETWORK] error is: \(error)")
DispatchQueue.main.async {
self.activityIndicator.stopAnimating()
print("Загрузка закончена с ошибкой \(error.localizedDescription)")
}
}
}
}
override func loadView() {
self.loadData()
self.view = self.collectionView
self.view.addSubview(activityIndicator)
activityIndicator.snp.makeConstraints { maker in
maker.centerX.equalToSuperview()
maker.centerY.equalToSuperview()
}
}
override func viewDidLoad() {
self.navigationController?.navigationBar.prefersLargeTitles = true
self.view.backgroundColor = UIColor.systemBackground
super.viewDidLoad()
self.navigationController?.navigationBar.titleTextAttributes = [.foregroundColor: UIColor(named: "AccentColor") ?? .systemPurple]
self.navigationController?.navigationBar.largeTitleTextAttributes = [.foregroundColor: UIColor(named: "AccentColor") ?? .systemPurple]
self.navigationController?.navigationBar.prefersLargeTitles = true
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.tabBarController?.tabBar.isHidden = false
}
}
extension PopularViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard let movie = self.movies?[indexPath.item] else { return }
let movieVC = MovieViewController(movie: movie)
self.navigationController?.pushViewController(movieVC, animated: true)
}
func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool {
return true
}
}
extension PopularViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
self.movies?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MovieCell.identifier, for: indexPath) as! MovieCell
cell.movie = self.movies?[indexPath.item]
return cell
}
}
| 32.029412 | 136 | 0.771044 |
1d6eba7ce696c324b56f52f1e2a17f1894b3e1ee | 2,754 | /**
* Copyright 2018 IBM Corp. 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
*
* https://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 Dispatch
import Foundation
func main(args: [String: Any]) -> [String: Any] {
/// Retreive required parameters
guard let baseURL = args["services.cloudant.url"] as? String,
let database = args["services.cloudant.database"] as? String else {
print("Error: missing a required parameter for creating a entry in a Cloudant document.")
return ["ok": false]
}
return readAll(url: baseURL, database: database)
}
/// Retrieve all documents from the cloudant db
func readAll(url: String, database: String) -> [String: Any] {
var result: [String: Any] = ["ok": false]
let semaphore = DispatchSemaphore(value: 0)
/// Create URL object from url
guard let endpoint = URL(string: url + "/" + database + "/_all_docs?include_docs=true") else {
print("Error: Failed to create a URL object")
return result
}
/// Construct HTTP Request
var request = URLRequest(url: endpoint)
request.httpMethod = "GET"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
URLSession.shared.dataTask(with: request) { (data: Data?, _, error: Error?) in
defer {
semaphore.signal()
}
if error != nil {
print("Error: Invalid response from Cloudant")
return
}
guard let data = data else {
print("Error: Missing response from Cloudant")
return
}
do {
let json = try JSONSerialization.jsonObject(with: data, options: []) as! [String: Any]
if let error = json["error"] as? String {
print("Error: \(error)")
result = ["ok": false, "error": error]
return
}
result = ["document": json]
} catch let error {
print("Error: Failed to load: \(error.localizedDescription)")
return
}
}.resume()
semaphore.wait(timeout: .distantFuture)
return result
}
| 32.4 | 98 | 0.610022 |
0a91e11722c0bfa54839aadcf99726d70cb8b76b | 75 |
public typealias ap242 = AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF
| 18.75 | 72 | 0.893333 |
62fb397f3748b97310d9ad36c778dcc94a29b9b8 | 495 | //
// BattlegroundsTierDetailWindowController.swift
// HSTracker
//
// Created by Martin BONNIN on 04/01/2020.
// Copyright © 2020 Benjamin Michotte. All rights reserved.
//
import Foundation
class BattlegroundsTierDetailWindowController: OverWindowController {
@IBOutlet weak var detailsView: BattlegroundsTierDetailsView?
override func windowDidLoad() {
super.windowDidLoad()
}
func setTier(tier: Int) {
detailsView?.setTier(tier: tier)
}
}
| 22.5 | 69 | 0.709091 |
69fdabcd4d83751da33f0e65401d75c1287108ea | 628 | //
// Person.swift
// EasyMappingSwiftExample
//
// Created by Denys Telezhkin on 20.07.14.
// Copyright (c) 2014 Denys Telezhkin. All rights reserved.
//
class Person: EKObjectModel {
var name : String!
var email: String!
var car : Car?
var phones: [Phone]!
}
extension Person {
override class func objectMapping() -> EKObjectMapping{
var mapping = EKObjectMapping(objectClass: self)
mapping.mapPropertiesFromArray(["name","email"])
mapping.hasOne(Car.self, forKeyPath: "car")
mapping.hasMany(Phone.self, forKeyPath: "phones")
return mapping
}
}
| 22.428571 | 60 | 0.648089 |
22032f5873a84cbb11dc906246fb0eb7d7c3fd25 | 40,699 | //
// StringExtensions.swift
// EZSwiftExtensions
//
// Created by Goktug Yilmaz on 15/07/15.
// Copyright (c) 2015 Goktug Yilmaz. All rights reserved.
//
// swiftlint:disable line_length
// swiftlint:disable trailing_whitespace
#if os(OSX)
import AppKit
#else
import UIKit
#endif
extension String {
/// EZSE: Init string with a base64 encoded string
init ? (base64: String) {
let pad = String(repeating: "=", count: base64.length % 4)
let base64Padded = base64 + pad
if let decodedData = Data(base64Encoded: base64Padded, options: NSData.Base64DecodingOptions(rawValue: 0)), let decodedString = NSString(data: decodedData, encoding: String.Encoding.utf8.rawValue) {
self.init(decodedString)
return
}
return nil
}
/// EZSE: Converts Date to String
public func toDate(format: String) -> Date? {
let formatter = DateFormatter()
formatter.timeZone = TimeZone(identifier: "GMT")
formatter.dateFormat = format
return formatter.date(from: self)
}
/// EZSE: base64 encoded of string
var base64: String {
let plainData = (self as NSString).data(using: String.Encoding.utf8.rawValue)
let base64String = plainData!.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
return base64String
}
// func localize() -> String {
// return Localize.LOCALIZED_STRING(str: self)
// }
func parseJSON() -> Any? {
let data = self.data(using: String.Encoding.utf8)
let anyObj = try? JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments)
return anyObj
}
/// EZSE: Cut string from integerIndex to the end
public subscript(integerIndex: Int) -> Character {
let index = self.index(startIndex, offsetBy: integerIndex)
return self[index]
}
/// EZSE: Cut string from range
public subscript(integerRange: Range<Int>) -> String {
let start = self.index(startIndex, offsetBy: integerRange.lowerBound)
let end = self.index(startIndex, offsetBy: integerRange.upperBound)
return String(self[start..<end])
}
/// EZSE: Cut string from closedrange
public subscript(integerClosedRange: ClosedRange<Int>) -> String {
return self[integerClosedRange.lowerBound..<(integerClosedRange.upperBound + 1)]
}
/// EZSE: Character count
public var length: Int {
return self.count
}
/// EZSE: Counts number of instances of the input inside String
public func count(_ substring: String) -> Int {
return components(separatedBy: substring).count - 1
}
/// EZSE: Capitalizes first character of String
public mutating func capitalizeFirst() {
guard count > 0 else { return }
self.replaceSubrange(startIndex...startIndex, with: String(self[startIndex]).capitalized)
}
/// EZSE: Capitalizes first character of String, returns a new string
public func capitalizedFirst() -> String {
guard self.count > 0 else { return self }
var result = self
result.replaceSubrange(startIndex...startIndex, with: String(self[startIndex]).capitalized)
return result
}
/// EZSE: Uppercases first 'count' characters of String
public mutating func uppercasePrefix(_ count: Int) {
guard self.count > 0 && count > 0 else { return }
self.replaceSubrange(startIndex..<self.index(startIndex, offsetBy: min(count, length)),
with: String(self[startIndex..<self.index(startIndex, offsetBy: min(count, length))]).uppercased())
}
/// EZSE: Uppercases first 'count' characters of String, returns a new string
public func uppercasedPrefix(_ count: Int) -> String {
guard self.count > 0 && count > 0 else { return self }
var result = self
result.replaceSubrange(startIndex..<self.index(startIndex, offsetBy: min(count, length)),
with: String(self[startIndex..<self.index(startIndex, offsetBy: min(count, length))]).uppercased())
return result
}
/// EZSE: Uppercases last 'count' characters of String
public mutating func uppercaseSuffix(_ count: Int) {
guard self.count > 0 && count > 0 else { return }
self.replaceSubrange(self.index(endIndex, offsetBy: -min(count, length))..<endIndex,
with: String(self[self.index(endIndex, offsetBy: -min(count, length))..<endIndex]).uppercased())
}
/// EZSE: Uppercases last 'count' characters of String, returns a new string
public func uppercasedSuffix(_ count: Int) -> String {
guard self.count > 0 && count > 0 else { return self }
var result = self
result.replaceSubrange(self.index(endIndex, offsetBy: -min(count, length))..<endIndex,
with: String(self[self.index(endIndex, offsetBy: -min(count, length))..<endIndex]).uppercased())
return result
}
/// EZSE: Uppercases string in range 'range' (from range.startIndex to range.endIndex)
public mutating func uppercase(range: CountableRange<Int>) {
let from = max(range.lowerBound, 0), to = min(range.upperBound, length)
guard self.count > 0 && (0..<length).contains(from) else { return }
self.replaceSubrange(self.index(startIndex, offsetBy: from)..<self.index(startIndex, offsetBy: to),
with: String(self[self.index(startIndex, offsetBy: from)..<self.index(startIndex, offsetBy: to)]).uppercased())
}
/// EZSE: Uppercases string in range 'range' (from range.startIndex to range.endIndex), returns new string
public func uppercased(range: CountableRange<Int>) -> String {
let from = max(range.lowerBound, 0), to = min(range.upperBound, length)
guard self.count > 0 && (0..<length).contains(from) else { return self }
var result = self
result.replaceSubrange(self.index(startIndex, offsetBy: from)..<self.index(startIndex, offsetBy: to),
with: String(self[self.index(startIndex, offsetBy: from)..<self.index(startIndex, offsetBy: to)]).uppercased())
return result
}
/// EZSE: Lowercases first character of String
public mutating func lowercaseFirst() {
guard self.count > 0 else { return }
self.replaceSubrange(startIndex...startIndex, with: String(self[startIndex]).lowercased())
}
/// EZSE: Lowercases first character of String, returns a new string
public func lowercasedFirst() -> String {
guard self.count > 0 else { return self }
var result = self
result.replaceSubrange(startIndex...startIndex, with: String(self[startIndex]).lowercased())
return result
}
/// EZSE: Lowercases first 'count' characters of String
public mutating func lowercasePrefix(_ count: Int) {
guard self.count > 0 && count > 0 else { return }
self.replaceSubrange(startIndex..<self.index(startIndex, offsetBy: min(count, length)),
with: String(self[startIndex..<self.index(startIndex, offsetBy: min(count, length))]).lowercased())
}
/// EZSE: Lowercases first 'count' characters of String, returns a new string
public func lowercasedPrefix(_ count: Int) -> String {
guard self.count > 0 && count > 0 else { return self }
var result = self
result.replaceSubrange(startIndex..<self.index(startIndex, offsetBy: min(count, length)),
with: String(self[startIndex..<self.index(startIndex, offsetBy: min(count, length))]).lowercased())
return result
}
/// EZSE: Lowercases last 'count' characters of String
public mutating func lowercaseSuffix(_ count: Int) {
guard self.count > 0 && count > 0 else { return }
self.replaceSubrange(self.index(endIndex, offsetBy: -min(count, length))..<endIndex,
with: String(self[self.index(endIndex, offsetBy: -min(count, length))..<endIndex]).lowercased())
}
/// EZSE: Lowercases last 'count' characters of String, returns a new string
public func lowercasedSuffix(_ count: Int) -> String {
guard self.count > 0 && count > 0 else { return self }
var result = self
result.replaceSubrange(self.index(endIndex, offsetBy: -min(count, length))..<endIndex,
with: String(self[self.index(endIndex, offsetBy: -min(count, length))..<endIndex]).lowercased())
return result
}
/// EZSE: Lowercases string in range 'range' (from range.startIndex to range.endIndex)
public mutating func lowercase(range: CountableRange<Int>) {
let from = max(range.lowerBound, 0), to = min(range.upperBound, length)
guard self.count > 0 && (0..<length).contains(from) else { return }
self.replaceSubrange(self.index(startIndex, offsetBy: from)..<self.index(startIndex, offsetBy: to),
with: String(self[self.index(startIndex, offsetBy: from)..<self.index(startIndex, offsetBy: to)]).lowercased())
}
/// EZSE: Lowercases string in range 'range' (from range.startIndex to range.endIndex), returns new string
public func lowercased(range: CountableRange<Int>) -> String {
let from = max(range.lowerBound, 0), to = min(range.upperBound, length)
guard self.count > 0 && (0..<length).contains(from) else { return self }
var result = self
result.replaceSubrange(self.index(startIndex, offsetBy: from)..<self.index(startIndex, offsetBy: to),
with: String(self[self.index(startIndex, offsetBy: from)..<self.index(startIndex, offsetBy: to)]).lowercased())
return result
}
/// EZSE: Counts whitespace & new lines
@available(*, deprecated, renamed: "isBlank")
public func isOnlyEmptySpacesAndNewLineCharacters() -> Bool {
let characterSet = CharacterSet.whitespacesAndNewlines
let newText = self.trimmingCharacters(in: characterSet)
return newText.isEmpty
}
func size(_ width: CGFloat, font: UIFont, lineBreakMode: NSLineBreakMode?) -> CGSize {
var attrib: [NSAttributedString.Key: Any] = [NSAttributedString.Key.font: font]
if lineBreakMode != nil {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = lineBreakMode!
attrib.updateValue(paragraphStyle, forKey: NSAttributedString.Key.paragraphStyle)
}
var size = CGSize(width: width, height: CGFloat(Double.greatestFiniteMagnitude))
size = (self as NSString).boundingRect(with: size, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes:attrib, context: nil).size
return CGSize(width: ceil(size.width), height: ceil(size.height))
}
func sizeWidth(_ height: CGFloat, font: UIFont, lineBreakMode: NSLineBreakMode?) -> CGSize {
var attrib: [NSAttributedString.Key: Any] = [NSAttributedString.Key.font: font]
if lineBreakMode != nil {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = lineBreakMode!
attrib.updateValue(paragraphStyle, forKey: NSAttributedString.Key.paragraphStyle)
}
var size = CGSize(width: CGFloat(Double.greatestFiniteMagnitude), height:height )
size = (self as NSString).boundingRect(with: size, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes:attrib, context: nil).size
return CGSize(width: ceil(size.width), height: ceil(size.height))
}
public var isValid: Bool {
if isBlank == false && self.length > 0 {
return true
}
return false
}
/// EZSE: Checks if string is empty or consists only of whitespace and newline characters
public var isBlank: Bool {
get {
let trimmed = trimmingCharacters(in: .whitespacesAndNewlines)
return trimmed.isEmpty
}
}
/// EZSE: Trims white space and new line characters
public mutating func trim() -> String {
return self.trimmed()
}
/// EZSE: Trims white space and new line characters, returns a new string
public func trimmed() -> String {
return self.trimmingCharacters(in: .whitespacesAndNewlines)
}
/// EZSE: Position of begining character of substing
public func positionOfSubstring(_ subString: String, caseInsensitive: Bool = false, fromEnd: Bool = false) -> Int {
if subString.isEmpty {
return -1
}
var searchOption = fromEnd ? NSString.CompareOptions.anchored : NSString.CompareOptions.backwards
if caseInsensitive {
searchOption.insert(NSString.CompareOptions.caseInsensitive)
}
if let range = self.range(of: subString, options: searchOption), !range.isEmpty {
return self.distance(from: self.startIndex, to: range.lowerBound)
}
return -1
}
/// SwifterSwift: Sliced string from a start index with length.
///
/// - Parameters:
/// - i: string index the slicing should start from.
/// - length: amount of characters to be sliced after given index.
/// - Returns: sliced substring of length number of characters (if applicable) (example: "Hello World".slicing(from: 6, length: 5) -> "World")
public func slicing(from i: Int, length: Int) -> String? {
guard length >= 0, i >= 0, i < self.count else {
return nil
}
guard i.advanced(by: length) <= self.count else {
return slicing(at: i)
}
guard length > 0 else {
return ""
}
return self[i..<i.advanced(by: length)]
}
/// SwifterSwift: Slice given string from a start index with length (if applicable).
///
/// - Parameters:
/// - i: string index the slicing should start from.
/// - length: amount of characters to be sliced after given index.
public mutating func slice(from i: Int, length: Int) {
if let str = slicing(from: i, length: length) {
self = str
}
}
/// SwifterSwift: Sliced string from a start index to an end index.
///
/// - Parameters:
/// - start: string index the slicing should start from.
/// - end: string index the slicing should end at.
/// - Returns: sliced substring starting from start index, and ends at end index (if applicable) (example: "Hello World".slicing(from: 6, to: 11) -> "World")
public func slicing(from start: Int, to end: Int) -> String? {
guard end >= start else {
return nil
}
return self[start..<end]
}
/// SwifterSwift: Slice given string from a start index to an end index (if applicable).
///
/// - Parameters:
/// - start: string index the slicing should start from.
/// - end: string index the slicing should end at.
public mutating func slice(from start: Int, to end: Int) {
if let str = slicing(from: start, to: end) {
self = str
}
}
/// SwifterSwift: Sliced string from a start index.
///
/// - Parameter i: string index the slicing should start from.
/// - Returns: sliced substring starting from start index (if applicable) (example: "Hello world".slicing(at: 6) -> "world")
public func slicing(at i: Int) -> String? {
guard i < self.count else {
return nil
}
return self[i..<self.count]
}
/// SwifterSwift: Slice given string from a start index (if applicable).
///
/// - Parameter i: string index the slicing should start from.
public mutating func slice(at i: Int) {
if let str = slicing(at: i) {
self = str
}
}
/// EZSE: split string using a spearator string, returns an array of string
public func split(_ separator: String) -> [String] {
return self.components(separatedBy: separator).filter {
!$0.trimmed().isEmpty
}
}
/// EZSE: split string with delimiters, returns an array of string
public func split(_ characters: CharacterSet) -> [String] {
return self.components(separatedBy: characters).filter {
!$0.trimmed().isEmpty
}
}
/// SwifterSwift: Check if string starts with substring.
///
/// - Parameters:
/// - suffix: substring to search if string starts with.
/// - caseSensitive: set true for case sensitive search (default is true).
/// - Returns: true if string starts with substring.
public func starts(with prefix: String, caseSensitive: Bool = true) -> Bool {
if !caseSensitive {
return lowercased().hasPrefix(prefix.lowercased())
}
return hasPrefix(prefix)
}
/// EZSE : Returns count of words in string
public var countofWords: Int {
let regex = try? NSRegularExpression(pattern: "\\w+", options: NSRegularExpression.Options())
return regex?.numberOfMatches(in: self, options: NSRegularExpression.MatchingOptions(), range: NSRange(location: 0, length: self.length)) ?? 0
}
/// EZSE : Returns count of paragraphs in string
public var countofParagraphs: Int {
let regex = try? NSRegularExpression(pattern: "\\n", options: NSRegularExpression.Options())
let str = self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
return (regex?.numberOfMatches(in: str, options: NSRegularExpression.MatchingOptions(), range: NSRange(location:0, length: str.length)) ?? -1) + 1
}
internal func rangeFromNSRange(_ nsRange: NSRange) -> Range<String.Index>? {
let from16 = self.index(self.startIndex, offsetBy: nsRange.location)
let to16 = self.index(from16, offsetBy: nsRange.length)
if let from = String.Index(from16, within: self),
let to = String.Index(to16, within: self) {
return from ..< to
}
return nil
}
/// EZSE: Find matches of regular expression in string
public func matchesForRegexInText(_ regex: String!) -> [String] {
let regex = try? NSRegularExpression(pattern: regex, options: [])
let results = regex?.matches(in: self, options: [], range: NSRange(location: 0, length: self.length)) ?? []
return results.map { self.substring(with: self.rangeFromNSRange($0.range)!) }
}
/// EZSE: Checks if String contains Email
public var isEmail: Bool {
let dataDetector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
let firstMatch = dataDetector?.firstMatch(in: self, options: NSRegularExpression.MatchingOptions.reportCompletion, range: NSRange(location: 0, length: length))
return (firstMatch?.range.location != NSNotFound && firstMatch?.url?.scheme == "mailto")
}
/// SwifterSwift: CamelCase of string.
public var camelCased: String {
let source = lowercased()
if source.contains(" ") {
//let first = source.slicing(from: 0, length: source.index(after: source.startIndex))
//let first = source.substring(to: source.index(after: source.startIndex))
let first = String(source[..<source.index(after: source.startIndex)])
let camel = source.capitalized.replacing(" ", with: "").replacing("\n", with: "")
let rest = String(camel.dropFirst())
return first + rest
}
//let first = source.lowercased().substring(to: source.index(after: source.startIndex))
let first = String(source.lowercased()[..<source.index(after: source.startIndex)])
let rest = String(source.dropFirst())
return first + rest
}
/// SwifterSwift: Check if string contains one or more emojis.
public var containEmoji: Bool {
// http://stackoverflow.com/questions/30757193/find-out-if-character-in-string-is-emoji
for scalar in unicodeScalars {
switch scalar.value {
case 0x3030, 0x00AE, 0x00A9, // Special Characters
0x1D000...0x1F77F, // Emoticons
0x2100...0x27BF, // Misc symbols and Dingbats
0xFE00...0xFE0F, // Variation Selectors
0x1F900...0x1F9FF: // Supplemental Symbols and Pictographs
return true
default:
continue
}
}
return false
}
/// SwifterSwift: First character of string (if applicable).
public var firstCharacter: String? {
guard let first = self.first else {
return nil
}
return String(first)
}
/// SwifterSwift: Check if string contains one or more letters.
public var hasLetters: Bool {
return rangeOfCharacter(from: .letters, options: .numeric, range: nil) != nil
}
/// SwifterSwift: Check if string contains one or more numbers.
public var hasNumbers: Bool {
return rangeOfCharacter(from: .decimalDigits, options: .literal, range: nil) != nil
}
/// SwifterSwift: Check if string contains only letters.
public var isAlphabetic: Bool {
return hasLetters && !hasNumbers
}
/// SwifterSwift: Check if string contains at least one letter and one number.
public var isAlphaNumeric: Bool {
return components(separatedBy: CharacterSet.alphanumerics).joined(separator: "").count == 0 && hasLetters && hasNumbers
}
/// EZSE: Returns if String is a number
public func isNumber() -> Bool {
if let _ = NumberFormatter().number(from: self) {
return true
}
return false
}
/// SwifterSwift: Check if string is a valid URL.
public var isValidUrl: Bool {
//let urlRegEx = "(http|https)://((\\w)*|([0-9]*)|([-|_])*)+([\\.|/]((\\w)*|([0-9]*)|([-|_])*))+"
//let urlRegEx = "((?:http|https)://)?(?:www\\.)?[\\w\\d\\-_]+\\.\\w{2,3}(\\.\\w{2})?(/(?<=/)(?:[\\w\\d\\-./_]+)?)?"
let urlRegEx = "((?:http|https)://)?(?:www\\.)?[-a-zA-Z0-9@:%._\\+~#=]{2,256}\\.[a-z]{2,6}\\b([-a-zA-Z0-9@:%_\\+.~#?&//=]*)"
let predicate = NSPredicate(format: "SELF MATCHES %@", urlRegEx)
return predicate.evaluate(with: self)
}
/// SwifterSwift: Check if string is a valid schemed URL.
public var isValidSchemedUrl: Bool {
guard let url = URL(string: self) else {
return false
}
return url.scheme != nil
}
/// SwifterSwift: Last character of string (if applicable).
public var lastCharacter: String? {
guard let last = self.last else {
return nil
}
return String(last)
}
/// SwifterSwift: Latinized string.
public var latinized: String {
return folding(options: .diacriticInsensitive, locale: Locale.current)
}
/// SwifterSwift: Array of strings separated by new lines.
public var lines: [String] {
var result = [String]()
enumerateLines { line, _ in
result.append(line)
}
return result
}
/// SwifterSwift: The most common character in string.
public var mostCommonCharacter: String {
let mostCommon = withoutSpacesAndNewLines.reduce([Character: Int]()) {
var counts = $0
counts[$1] = ($0[$1] ?? 0) + 1
return counts
}.max { $0.1 < $1.1 }?.0
return mostCommon?.string ?? ""
}
/// SwifterSwift: String without spaces and new lines.
public var withoutSpacesAndNewLines: String {
return replacing(" ", with: "").replacing("\n", with: "")
}
/// SwifterSwift: String by replacing part of string with another string.
///
/// - Parameters:
/// - substring: old substring to find and replace.
/// - newString: new string to insert in old string place.
/// - Returns: string after replacing substring with newString.
public func replacing(_ substring: String, with newString: String) -> String {
return replacingOccurrences(of: substring, with: newString)
}
/// SwifterSwift: Reversed string.
public var reversed: String {
return String(self.reversed())
}
/// EZSE: Extracts URLS from String
public var extractURLs: [URL] {
var urls: [URL] = []
let detector: NSDataDetector?
do {
detector = try NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
} catch _ as NSError {
detector = nil
}
let text = self
if let detector = detector {
detector.enumerateMatches(in: text, options: [], range: NSRange(location: 0, length: text.count), using: {
(result: NSTextCheckingResult?, flags: NSRegularExpression.MatchingFlags, stop: UnsafeMutablePointer<ObjCBool>) -> Void in
if let result = result, let url = result.url {
urls.append(url)
}
})
}
return urls
}
/// EZSE: Checking if String contains input with comparing options
public func contains(_ find: String, compareOption: NSString.CompareOptions) -> Bool {
return self.range(of: find, options: compareOption) != nil
}
/// EZSE: Converts String to Int
public func toInt() -> Int? {
if let num = NumberFormatter().number(from: self) {
return num.intValue
} else {
return nil
}
}
/// EZSE: Converts String to Double
public func toDouble() -> Double? {
if let num = NumberFormatter().number(from: self) {
return num.doubleValue
} else {
return nil
}
}
/// EZSE: Converts String to Float
public func toFloat() -> Float? {
if let num = NumberFormatter().number(from: self) {
return num.floatValue
} else {
return nil
}
}
/// EZSE: Converts String to Bool
public func toBool() -> Bool? {
// let trimmedString = trimmed().lowercased()
// if trimmedString == "true" || trimmedString == "false" {
// return (trimmedString as NSString).boolValue
// }
switch self {
case "True", "true", "yes", "1":
return true
case "False", "false", "no", "0":
return false
default:
return nil
}
}
///EZSE: Returns the first index of the occurency of the character in String
public func getIndexOf(_ char: Character) -> Int? {
for (index, c) in self.enumerated() {
if c == char {
return index
}
}
return nil
}
/// EZSE: Converts String to NSString
public var toNSString: NSString { get { return self as NSString } }
#if os(iOS)
// ///EZSE: Returns bold NSAttributedString
// public func bold() -> NSAttributedString {
// let boldString = NSMutableAttributedString(string: self, attributes: [NSFontAttributeName: UIFont.boldSystemFont(ofSize: UIFont.systemFontSize)])
// return boldString
// }
//
// #endif
//
// ///EZSE: Returns underlined NSAttributedString
// public func underline() -> NSAttributedString {
// let underlineString = NSAttributedString(string: self, attributes: [NSUnderlineStyleAttributeName: NSUnderlineStyle.single.rawValue])
// return underlineString
// }
//
// #if os(iOS)
//
// ///EZSE: Returns italic NSAttributedString
// public func italic() -> NSAttributedString {
// let italicString = NSMutableAttributedString(string: self, attributes: [NSFontAttributeName: UIFont.italicSystemFont(ofSize: UIFont.systemFontSize)])
// return italicString
// }
#endif
#if os(iOS)
///EZSE: Returns hight of rendered string
func height(_ width: CGFloat, font: UIFont, lineBreakMode: NSLineBreakMode?) -> CGFloat {
var attrib: [NSAttributedString.Key: Any] = [NSAttributedString.Key.font: font]
if lineBreakMode != nil {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = lineBreakMode!
attrib.updateValue(paragraphStyle, forKey: NSAttributedString.Key.paragraphStyle)
}
let size = CGSize(width: width, height: CGFloat(Double.greatestFiniteMagnitude))
return ceil((self as NSString).boundingRect(with: size, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes:attrib, context: nil).height)
}
func height(_ width: CGFloat, font: UIFont) -> CGFloat {
let attrib: [NSAttributedString.Key: Any] = [NSAttributedString.Key.font: font]
return height(width, attributes: attrib)
}
func height(_ width: CGFloat, attributes: [NSAttributedString.Key : Any]) -> CGFloat {
let size = CGSize(width: width, height: CGFloat(Double.greatestFiniteMagnitude))
return ceil((self as NSString).boundingRect(with: size, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes:attributes, context: nil).height)
}
func width(_ height: CGFloat, font: UIFont, lineBreakMode: NSLineBreakMode?) -> CGFloat {
var attrib: [NSAttributedString.Key : Any] = [NSAttributedString.Key.font: font]
if lineBreakMode != nil {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = lineBreakMode!
attrib.updateValue(paragraphStyle, forKey: NSAttributedString.Key.paragraphStyle)
}
let size = CGSize(width: CGFloat(Double.greatestFiniteMagnitude), height: height)
return ceil((self as NSString).boundingRect(with: size, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes:attrib, context: nil).width)
}
#endif
///EZSE: Returns NSAttributedString
public func color(_ color: UIColor) -> NSAttributedString {
let colorString = NSMutableAttributedString(string: self, attributes: [NSAttributedString.Key.foregroundColor: color])
return colorString
}
///EZSE: Returns NSAttributedString
public func colorSubString(_ subString: String, color: UIColor) -> NSMutableAttributedString {
var start = 0
var ranges: [NSRange] = []
while true {
let range = (self as NSString).range(of: subString, options: NSString.CompareOptions.literal, range: NSRange(location: start, length: (self as NSString).length - start))
if range.location == NSNotFound {
break
} else {
ranges.append(range)
start = range.location + range.length
}
}
let attrText = NSMutableAttributedString(string: self)
for range in ranges {
attrText.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range)
}
return attrText
}
/// EZSE: Checks if String contains Emoji
public func includesEmoji() -> Bool {
for i in 0...length {
let c: unichar = (self as NSString).character(at: i)
if (0xD800 <= c && c <= 0xDBFF) || (0xDC00 <= c && c <= 0xDFFF) {
return true
}
}
return false
}
#if os(iOS)
/// EZSE: copy string to pasteboard
public func addToPasteboard() {
let pasteboard = UIPasteboard.general
pasteboard.string = self
}
#endif
// EZSE: URL encode a string (percent encoding special chars)
public func urlEncoded() -> String {
return self.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
}
// EZSE: URL encode a string (percent encoding special chars) mutating version
mutating func urlEncode() {
self = urlEncoded()
}
func NSRangeFromRange(range : Range<String.Index>) -> NSRange {
let utf16view = self.utf16
let from = String.UTF16View.Index(range.lowerBound, within: utf16view)!
let to = String.UTF16View.Index(range.upperBound, within: utf16view)!
return NSRange(location: utf16view.distance(from: utf16.startIndex, to: from),
length: utf16view.distance(from: from, to: to))
}
}
extension String {
init(_ value: Float, precision: Int) {
let nFormatter = NumberFormatter()
nFormatter.numberStyle = .decimal
nFormatter.maximumFractionDigits = precision
self = nFormatter.string(from: NSNumber(value: value))!
}
init(_ value: Double, precision: Int) {
let nFormatter = NumberFormatter()
nFormatter.numberStyle = .decimal
nFormatter.maximumFractionDigits = precision
self = nFormatter.string(from: NSNumber(value: value))!
}
}
/// EZSE: Pattern matching of strings via defined functions
public func ~=<T> (pattern: ((T) -> Bool), value: T) -> Bool {
return pattern(value)
}
/// EZSE: Can be used in switch-case
public func hasPrefix(_ prefix: String) -> (_ value: String) -> Bool {
return { (value: String) -> Bool in
value.hasPrefix(prefix)
}
}
/// EZSE: Can be used in switch-case
public func hasSuffix(_ suffix: String) -> (_ value: String) -> Bool {
return { (value: String) -> Bool in
value.hasSuffix(suffix)
}
}
// MARK: - Operators
public extension String {
/// SwifterSwift: Repeat string multiple times.
///
/// - Parameters:
/// - lhs: string to repeat.
/// - rhs: number of times to repeat character.
/// - Returns: new string with given string repeated n times.
static func * (lhs: String, rhs: Int) -> String {
guard rhs > 0 else {
return ""
}
return String(repeating: lhs, count: rhs)
}
/// SwifterSwift: Repeat string multiple times.
///
/// - Parameters:
/// - lhs: number of times to repeat character.
/// - rhs: string to repeat.
/// - Returns: new string with given string repeated n times.
static func * (lhs: Int, rhs: String) -> String {
guard lhs > 0 else {
return ""
}
return String(repeating: rhs, count: lhs)
}
}
// MARK: - NSAttributedString extensions
public extension String {
#if !os(tvOS) && !os(watchOS)
/// SwifterSwift: Bold string.
var bold: NSAttributedString {
#if os(macOS)
return NSMutableAttributedString(string: self, attributes: [NSFontAttributeName: NSFont.boldSystemFont(ofSize: NSFont.systemFontSize())])
#else
return NSMutableAttributedString(string: self, attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: UIFont.systemFontSize)])
#endif
}
#endif
/// SwifterSwift: Underlined string
var underline: NSAttributedString {
return NSAttributedString(string: self, attributes: [NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue])
}
/// SwifterSwift: Strikethrough string.
var strikethrough: NSAttributedString {
return NSAttributedString(string: self, attributes: [NSAttributedString.Key.strikethroughStyle: NSNumber(value: NSUnderlineStyle.single.rawValue as Int)])
}
#if os(iOS)
/// SwifterSwift: Italic string.
var italic: NSAttributedString {
return NSMutableAttributedString(string: self, attributes: [NSAttributedString.Key.font: UIFont.italicSystemFont(ofSize: UIFont.systemFontSize)])
}
#endif
#if os(macOS)
/// SwifterSwift: Add color to string.
///
/// - Parameter color: text color.
/// - Returns: a NSAttributedString versions of string colored with given color.
public func colored(with color: NSColor) -> NSAttributedString {
return NSMutableAttributedString(string: self, attributes: [NSForegroundColorAttributeName: color])
}
#else
/// SwifterSwift: Add color to string.
///
/// - Parameter color: text color.
/// - Returns: a NSAttributedString versions of string colored with given color.
func colored(with color: UIColor) -> NSAttributedString {
return NSMutableAttributedString(string: self, attributes: [NSAttributedString.Key.foregroundColor: color])
}
#endif
}
//MARK: - NSString extensions
public extension String {
/// SwifterSwift: NSString from a string.
var nsString: NSString {
return NSString(string: self)
}
/// SwifterSwift: NSString lastPathComponent.
var lastPathComponent: String {
return (self as NSString).lastPathComponent
}
/// SwifterSwift: NSString pathExtension.
var pathExtension: String {
return (self as NSString).pathExtension
}
/// SwifterSwift: NSString deletingLastPathComponent.
var deletingLastPathComponent: String {
return (self as NSString).deletingLastPathComponent
}
/// SwifterSwift: NSString deletingPathExtension.
var deletingPathExtension: String {
return (self as NSString).deletingPathExtension
}
/// SwifterSwift: NSString pathComponents.
var pathComponents: [String] {
return (self as NSString).pathComponents
}
/// SwifterSwift: NSString appendingPathComponent(str: String)
///
/// - Parameter str: the path component to append to the receiver.
/// - Returns: a new string made by appending aString to the receiver, preceded if necessary by a path separator.
func appendingPathComponent(_ str: String) -> String {
return (self as NSString).appendingPathComponent(str)
}
/// SwifterSwift: NSString appendingPathExtension(str: String)
///
/// - Parameter str: The extension to append to the receiver.
/// - Returns: a new string made by appending to the receiver an extension separator followed by ext (if applicable).
func appendingPathExtension(_ str: String) -> String? {
return (self as NSString).appendingPathExtension(str)
}
}
//MARK: - Size of string
extension String {
func widthOfString(usingFont font: UIFont) -> CGFloat {
let fontAttributes = [NSAttributedString.Key.font: font]
let size = self.size(withAttributes: fontAttributes)
return size.width
}
func heightOfString(usingFont font: UIFont) -> CGFloat {
let fontAttributes = [NSAttributedString.Key.font: font]
let size = self.size(withAttributes: fontAttributes)
return size.height
}
func sizeOfString(usingFont font: UIFont) -> CGSize {
let fontAttributes = [NSAttributedString.Key.font: font]
return self.size(withAttributes: fontAttributes)
}
}
extension String {
func indices(of occurrence: String) -> [Int] {
var indices = [Int]()
var position = startIndex
while let range = range(of: occurrence, range: position..<endIndex) {
let i = distance(from: startIndex,
to: range.lowerBound)
indices.append(i)
let offset = occurrence.distance(from: occurrence.startIndex,
to: occurrence.endIndex) - 1
guard let after = index(range.lowerBound,
offsetBy: offset,
limitedBy: endIndex) else {
break
}
position = index(after: after)
}
return indices
}
func ranges(of searchString: String) -> [Range<String.Index>] {
let _indices = indices(of: searchString)
let count = searchString.count
return _indices.map({ index(startIndex, offsetBy: $0)..<index(startIndex, offsetBy: $0+count) })
}
func nsRange(from range: Range<String.Index>) -> NSRange {
let from = range.lowerBound.samePosition(in: utf16)!
let to = range.upperBound.samePosition(in: utf16)!
return NSRange(location: utf16.distance(from: utf16.startIndex, to: from),
length: utf16.distance(from: from, to: to))
}
}
extension String {
var integer: Int {
return Int(self) ?? 0
}
var secondFromString : Int {
let components: Array = self.components(separatedBy: ":")
let hours = components[0].integer
let minutes = components[1].integer
let seconds = components[2].integer
return Int((hours * 60 * 60) + (minutes * 60) + seconds)
}
}
| 40.018682 | 206 | 0.627313 |
8ae13adb0e1cd77d9dc96bf7178745708ba52e2a | 1,308 | //
// TestHitsTracker.swift
// InstantSearchCore
//
// Created by Vladislav Fitc on 20/12/2019.
// Copyright © 2019 Algolia. All rights reserved.
//
import Foundation
@testable import InstantSearchCore
class TestHitsTracker: HitsAfterSearchTrackable {
var didClick: (((eventName: EventName, indexName: IndexName, objectIDsWithPositions: [(ObjectID, Int)], queryID: QueryID, userToken: UserToken?)) -> Void)?
var didConvert: (((eventName: EventName, indexName: IndexName, objectIDs: [ObjectID], queryID: QueryID, userToken: UserToken?)) -> Void)?
var didView: (((eventName: EventName, indexName: IndexName, objectIDs: [ObjectID], userToken: UserToken?)) -> Void)?
func clickedAfterSearch(eventName: EventName, indexName: IndexName, objectIDsWithPositions: [(ObjectID, Int)], queryID: QueryID, userToken: UserToken?) {
didClick?((eventName, indexName, objectIDsWithPositions, queryID, userToken))
}
func convertedAfterSearch(eventName: EventName, indexName: IndexName, objectIDs: [ObjectID], queryID: QueryID, userToken: UserToken?) {
didConvert?((eventName, indexName, objectIDs, queryID, userToken))
}
func viewed(eventName: EventName, indexName: IndexName, objectIDs: [ObjectID], userToken: UserToken?) {
didView?((eventName, indexName, objectIDs, userToken))
}
}
| 42.193548 | 157 | 0.743884 |
bf7273f8ec224a63c3ede1f355191f3e906bcc75 | 3,307 | //
// Copyright 2020 Swiftkube Project
//
// 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.
//
///
/// Generated by Swiftkube:ModelGen
/// Kubernetes v1.20.9
/// coordination.v1beta1.Lease
///
import Foundation
public extension coordination.v1beta1 {
///
/// Lease defines a lease concept.
///
struct Lease: KubernetesAPIResource, MetadataHavingResource, NamespacedResource,
ReadableResource, ListableResource, CreatableResource, ReplaceableResource, DeletableResource, CollectionDeletableResource
{
///
/// ListableResource.List associated type
///
public typealias List = coordination.v1beta1.LeaseList
///
/// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
///
public let apiVersion: String = "coordination.k8s.io/v1beta1"
///
/// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
///
public let kind: String = "Lease"
///
/// More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
///
public var metadata: meta.v1.ObjectMeta?
///
/// Specification of the Lease. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
///
public var spec: coordination.v1beta1.LeaseSpec?
///
/// Default memberwise initializer
///
public init(
metadata: meta.v1.ObjectMeta? = nil,
spec: coordination.v1beta1.LeaseSpec? = nil
) {
self.metadata = metadata
self.spec = spec
}
}
}
///
/// Codable conformance
///
public extension coordination.v1beta1.Lease {
private enum CodingKeys: String, CodingKey {
case apiVersion = "apiVersion"
case kind = "kind"
case metadata = "metadata"
case spec = "spec"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.metadata = try container.decodeIfPresent(meta.v1.ObjectMeta.self, forKey: .metadata)
self.spec = try container.decodeIfPresent(coordination.v1beta1.LeaseSpec.self, forKey: .spec)
}
func encode(to encoder: Encoder) throws {
var encodingContainer = encoder.container(keyedBy: CodingKeys.self)
try encodingContainer.encode(apiVersion, forKey: .apiVersion)
try encodingContainer.encode(kind, forKey: .kind)
try encodingContainer.encode(metadata, forKey: .metadata)
try encodingContainer.encode(spec, forKey: .spec)
}
}
| 35.180851 | 296 | 0.747808 |
d707f2b94a5e7a7e0c7d0a853c1054252050f7f5 | 8,527 | /*
Copyright (c) 2019, Apple Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder(s) nor the names of any contributors
may be used to endorse or promote products derived from this software without
specific prior written permission. No license is granted to the trademarks of
the copyright holders even if such marks are included in this software.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import Foundation
/// Any store from which types conforming to `OCKAnyCarePlan` can be queried is considered `OCKAnyReadOnlyCarePlanStore`.
public protocol OCKAnyReadOnlyCarePlanStore: OCKAnyResettableStore {
/// The delegate receives callbacks when the contents of the care plan store are modified.
/// In `CareKit` apps, the delegate will be set automatically, and it should not be modified.
var carePlanDelegate: OCKCarePlanStoreDelegate? { get set }
/// `fetchCarePlans` asynchronously retrieves an array of care plans from the store.
///
/// - Parameters:
/// - query: A query used to constrain the values that will be fetched.
/// - callbackQueue: The queue that the completion closure should be called on. In most cases this should be the main queue.
/// - completion: A callback that will fire on the provided callback queue.
func fetchAnyCarePlans(query: OCKAnyCarePlanQuery, callbackQueue: DispatchQueue,
completion: @escaping OCKResultClosure<[OCKAnyCarePlan]>)
// MARK: Singular Methods - Implementation Provided
/// `fetchCarePlan` asynchronously retrieves a single care plans from the store.
///
/// - Parameters:
/// - id: The identifier of the item to be fetched.
/// - callbackQueue: The queue that the completion closure should be called on. In most cases this should be the main queue.
/// - completion: A callback that will fire on the provided callback queue.
func fetchAnyCarePlan(withID id: String, callbackQueue: DispatchQueue, completion: @escaping OCKResultClosure<OCKAnyCarePlan>)
}
/// Any store able to write to one ore more types conforming to `OCKAnyCarePlan` is considered an `OCKAnyCarePlanStore`.
public protocol OCKAnyCarePlanStore: OCKAnyReadOnlyCarePlanStore {
/// `addCarePlans` asynchronously adds an array of care plans to the store.
///
/// - Parameters:
/// - plans: An array of plans to be added to the store.
/// - callbackQueue: The queue that the completion closure should be called on. In most cases this should be the main queue.
/// - completion: A callback that will fire on the provided callback queue.
func addAnyCarePlans(_ plans: [OCKAnyCarePlan], callbackQueue: DispatchQueue, completion: OCKResultClosure<[OCKAnyCarePlan]>?)
/// `updateCarePlans` asynchronously updates an array of care plans in the store.
///
/// - Parameters:
/// - plans: An array of care plans to be updated. The care plans must already exist in the store.
/// - callbackQueue: The queue that the completion closure should be called on. In most cases this should be the main queue.
/// - completion: A callback that will fire on the provided callback queue.
func updateAnyCarePlans(_ plans: [OCKAnyCarePlan], callbackQueue: DispatchQueue, completion: OCKResultClosure<[OCKAnyCarePlan]>?)
/// `deleteCarePlans` asynchronously deletes an array of care plans from the store.
///
/// - Parameters:
/// - plans: An array of care plans to be deleted. The care plans must exist in the store.
/// - callbackQueue: The queue that the completion closure should be called on. In most cases this should be the main queue.
/// - completion: A callback that will fire on the provided callback queue.
func deleteAnyCarePlans(_ plans: [OCKAnyCarePlan], callbackQueue: DispatchQueue, completion: OCKResultClosure<[OCKAnyCarePlan]>?)
// MARK: Singular Methods - Implementation Provided
/// `addAnyCarePlan` asynchronously adds a single care plan to the store.
///
/// - Parameters:
/// - plan: A single plan to be added to the store.
/// - callbackQueue: The queue that the completion closure should be called on. In most cases this should be the main queue.
/// - completion: A callback that will fire on the provided callback queue.
func addAnyCarePlan(_ plan: OCKAnyCarePlan, callbackQueue: DispatchQueue, completion: OCKResultClosure<OCKAnyCarePlan>?)
/// `updateCarePlan` asynchronously updates a single care plan in the store.
///
/// - Parameters:
/// - plan: A single care plan to be updated. The care plans must already exist in the store.
/// - callbackQueue: The queue that the completion closure should be called on. In most cases this should be the main queue.
/// - completion: A callback that will fire on the provided callback queue.
func updateAnyCarePlan(_ plan: OCKAnyCarePlan, callbackQueue: DispatchQueue, completion: OCKResultClosure<OCKAnyCarePlan>?)
/// `deleteCarePlan` asynchronously deletes a single care plan from the store.
///
/// - Parameters:
/// - plans: An single care plan to be deleted. The care plans must exist in the store.
/// - callbackQueue: The queue that the completion closure should be called on. In most cases this should be the main queue.
/// - completion: A callback that will fire on the provided callback queue.
func deleteAnyCarePlan(_ plan: OCKAnyCarePlan, callbackQueue: DispatchQueue, completion: OCKResultClosure<OCKAnyCarePlan>?)
}
// MARK: Singular Methods for OCKAnyReadOnlyCarePlanStore
public extension OCKAnyReadOnlyCarePlanStore {
func fetchAnyCarePlan(withID id: String, callbackQueue: DispatchQueue = .main,
completion: @escaping OCKResultClosure<OCKAnyCarePlan>) {
var query = OCKCarePlanQuery(for: Date())
query.limit = 1
query.extendedSortDescriptors = [.effectiveDate(ascending: true)]
query.ids = [id]
fetchAnyCarePlans(query: query, callbackQueue: callbackQueue, completion:
chooseFirst(then: completion, replacementError: .fetchFailed(reason: "No care plan with matching ID")))
}
}
// MARK: Singular Methods for OCKAnyCarePlanStore
public extension OCKAnyCarePlanStore {
func addAnyCarePlan(_ plan: OCKAnyCarePlan, callbackQueue: DispatchQueue = .main, completion: OCKResultClosure<OCKAnyCarePlan>? = nil) {
addAnyCarePlans([plan], callbackQueue: callbackQueue, completion:
chooseFirst(then: completion, replacementError: .addFailed(reason: "Failed to add care plan")))
}
func updateAnyCarePlan(_ plan: OCKAnyCarePlan, callbackQueue: DispatchQueue = .main, completion: OCKResultClosure<OCKAnyCarePlan>? = nil) {
updateAnyCarePlans([plan], callbackQueue: callbackQueue, completion:
chooseFirst(then: completion, replacementError: .updateFailed(reason: "Failed to update care plan")))
}
func deleteAnyCarePlan(_ plan: OCKAnyCarePlan, callbackQueue: DispatchQueue = .main, completion: OCKResultClosure<OCKAnyCarePlan>? = nil) {
deleteAnyCarePlans([plan], callbackQueue: callbackQueue, completion:
chooseFirst(then: completion, replacementError: .deleteFailed(reason: "Failed to delete care plan")))
}
}
| 57.614865 | 143 | 0.735663 |
6983a8a6833ac8cd06c74cb8293cb269c302d1b0 | 1,493 | // Copyright 2019 Algorand, 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.
//
// Array+View.swift
import UIKit
extension Array where Element: UIView {
func previousView(of view: Element) -> UIView? {
if isFirstView(view) {
return nil
}
guard let index = index(of: view) else {
return nil
}
let previousViewIndex = index - 1
return self[safe: previousViewIndex]
}
func nextView(of view: Element) -> UIView? {
if isLastView(view) {
return nil
}
guard let index = index(of: view) else {
return nil
}
let nextViewIndex = index + 1
return self[safe: nextViewIndex]
}
func isFirstView(_ view: UIView) -> Bool {
return first == view
}
func isLastView(_ view: UIView) -> Bool {
return last == view
}
func index(of view: Element) -> Int? {
return firstIndex(of: view)
}
}
| 25.305085 | 75 | 0.622237 |
230e2a257618371b586ccf9faa07d0dfd0dc0ea1 | 9,886 | import ReactiveSwift
import XCTest
@testable import ComposableArchitecture
final class StoreTests: XCTestCase {
func testEffectDisposablesDeinitialization() {
enum Action {
case triggerDelay
case delayDidComplete
}
let delayedReducer = Reducer<Void, Action, DateScheduler> { _, action, mainQueue in
switch action {
case .triggerDelay:
return Effect(value: .delayDidComplete).delay(1, on: mainQueue)
case .delayDidComplete:
return .none
}
}
let store = Store(
initialState: (),
reducer: delayedReducer,
environment: QueueScheduler.main
)
store.send(.triggerDelay)
store.send(.triggerDelay)
store.send(.triggerDelay)
store.send(.delayDidComplete)
XCTAssertEqual(store.effectDisposables.count, 3)
XCTWaiter().wait(for: [XCTestExpectation()], timeout: 1.1)
XCTAssertEqual(store.effectDisposables.count, 0)
}
func testProducedMapping() {
struct ChildState: Equatable {
var value: Int = 0
}
struct ParentState: Equatable {
var child: ChildState = .init()
}
let store = Store<ParentState, Void>(
initialState: ParentState(),
reducer: Reducer { state, _, _ in
state.child.value += 1
return .none
},
environment: ()
)
let viewStore = ViewStore(store)
var values: [Int] = []
viewStore.produced.child.value.startWithValues { value in
values.append(value)
}
viewStore.send(())
viewStore.send(())
viewStore.send(())
XCTAssertEqual(values, [0, 1, 2, 3])
}
func testScopedStoreReceivesUpdatesFromParent() {
let counterReducer = Reducer<Int, Void, Void> { state, _, _ in
state += 1
return .none
}
let parentStore = Store(initialState: 0, reducer: counterReducer, environment: ())
let parentViewStore = ViewStore(parentStore)
let childStore = parentStore.scope(state: String.init)
var values: [String] = []
childStore.$state.producer
.startWithValues { values.append($0) }
XCTAssertEqual(values, ["0"])
parentViewStore.send(())
XCTAssertEqual(values, ["0", "1"])
}
func testParentStoreReceivesUpdatesFromChild() {
let counterReducer = Reducer<Int, Void, Void> { state, _, _ in
state += 1
return .none
}
let parentStore = Store(initialState: 0, reducer: counterReducer, environment: ())
let childStore = parentStore.scope(state: String.init)
let childViewStore = ViewStore(childStore)
var values: [Int] = []
parentStore.$state.producer
.startWithValues { values.append($0) }
XCTAssertEqual(values, [0])
childViewStore.send(())
XCTAssertEqual(values, [0, 1])
}
func testScopeWithPublisherTransform() {
let counterReducer = Reducer<Int, Int, Void> { state, action, _ in
state = action
return .none
}
let parentStore = Store(initialState: 0, reducer: counterReducer, environment: ())
var outputs: [String] = []
parentStore
.producerScope(state: { $0.map { "\($0)" }.skipRepeats() })
.startWithValues { childStore in
childStore.$state.producer
.startWithValues { outputs.append($0) }
}
parentStore.send(0)
XCTAssertEqual(outputs, ["0"])
parentStore.send(0)
XCTAssertEqual(outputs, ["0"])
parentStore.send(1)
XCTAssertEqual(outputs, ["0", "1"])
parentStore.send(1)
XCTAssertEqual(outputs, ["0", "1"])
parentStore.send(2)
XCTAssertEqual(outputs, ["0", "1", "2"])
}
func testScopeCallCount() {
let counterReducer = Reducer<Int, Void, Void> { state, _, _ in state += 1
return .none
}
var numCalls1 = 0
_ = Store(initialState: 0, reducer: counterReducer, environment: ())
.scope(state: { (count: Int) -> Int in
numCalls1 += 1
return count
})
XCTAssertEqual(numCalls1, 2)
}
func testScopeCallCount2() {
let counterReducer = Reducer<Int, Void, Void> { state, _, _ in
state += 1
return .none
}
var numCalls1 = 0
var numCalls2 = 0
var numCalls3 = 0
let store = Store(initialState: 0, reducer: counterReducer, environment: ())
.scope(state: { (count: Int) -> Int in
numCalls1 += 1
return count
})
.scope(state: { (count: Int) -> Int in
numCalls2 += 1
return count
})
.scope(state: { (count: Int) -> Int in
numCalls3 += 1
return count
})
XCTAssertEqual(numCalls1, 2)
XCTAssertEqual(numCalls2, 2)
XCTAssertEqual(numCalls3, 2)
store.send(())
XCTAssertEqual(numCalls1, 4)
XCTAssertEqual(numCalls2, 5)
XCTAssertEqual(numCalls3, 6)
store.send(())
XCTAssertEqual(numCalls1, 6)
XCTAssertEqual(numCalls2, 8)
XCTAssertEqual(numCalls3, 10)
store.send(())
XCTAssertEqual(numCalls1, 8)
XCTAssertEqual(numCalls2, 11)
XCTAssertEqual(numCalls3, 14)
}
func testSynchronousEffectsSentAfterSinking() {
enum Action {
case tap
case next1
case next2
case end
}
var values: [Int] = []
let counterReducer = Reducer<Void, Action, Void> { state, action, _ in
switch action {
case .tap:
return .merge(
Effect(value: .next1),
Effect(value: .next2),
Effect.fireAndForget { values.append(1) }
)
case .next1:
return .merge(
Effect(value: .end),
Effect.fireAndForget { values.append(2) }
)
case .next2:
return .fireAndForget { values.append(3) }
case .end:
return .fireAndForget { values.append(4) }
}
}
let store = Store(initialState: (), reducer: counterReducer, environment: ())
store.send(.tap)
XCTAssertEqual(values, [1, 2, 3, 4])
}
func testLotsOfSynchronousActions() {
enum Action { case incr, noop }
let reducer = Reducer<Int, Action, ()> { state, action, _ in
switch action {
case .incr:
state += 1
return state >= 100_000 ? Effect(value: .noop) : Effect(value: .incr)
case .noop:
return .none
}
}
let store = Store(initialState: 0, reducer: reducer, environment: ())
store.send(.incr)
XCTAssertEqual(ViewStore(store).state, 100_000)
}
func testPublisherScope() {
let appReducer = Reducer<Int, Bool, Void> { state, action, _ in
state += action ? 1 : 0
return .none
}
let parentStore = Store(initialState: 0, reducer: appReducer, environment: ())
var outputs: [Int] = []
parentStore
.producerScope { $0.skipRepeats() }
.startWithValues { outputs.append($0.$state.value) }
XCTAssertEqual(outputs, [0])
parentStore.send(true)
XCTAssertEqual(outputs, [0, 1])
parentStore.send(false)
XCTAssertEqual(outputs, [0, 1])
parentStore.send(false)
XCTAssertEqual(outputs, [0, 1])
parentStore.send(false)
XCTAssertEqual(outputs, [0, 1])
parentStore.send(false)
XCTAssertEqual(outputs, [0, 1])
}
func testIfLetAfterScope() {
struct AppState {
var count: Int?
}
let appReducer = Reducer<AppState, Int?, Void> { state, action, _ in
state.count = action
return .none
}
let parentStore = Store(initialState: AppState(), reducer: appReducer, environment: ())
// NB: This test needs to hold a strong reference to the emitted stores
var outputs: [Int?] = []
var stores: [Any] = []
parentStore
.scope(state: \.count)
.ifLet(
then: { store in
stores.append(store)
outputs.append(store.state)
},
else: {
outputs.append(nil)
})
XCTAssertEqual(outputs, [nil])
parentStore.send(1)
XCTAssertEqual(outputs, [nil, 1])
parentStore.send(nil)
XCTAssertEqual(outputs, [nil, 1, nil])
parentStore.send(1)
XCTAssertEqual(outputs, [nil, 1, nil, 1])
parentStore.send(nil)
XCTAssertEqual(outputs, [nil, 1, nil, 1, nil])
parentStore.send(1)
XCTAssertEqual(outputs, [nil, 1, nil, 1, nil, 1])
parentStore.send(nil)
XCTAssertEqual(outputs, [nil, 1, nil, 1, nil, 1, nil])
}
func testIfLetTwo() {
let parentStore = Store(
initialState: 0,
reducer: Reducer<Int?, Bool, Void> { state, action, _ in
if action {
state? += 1
return .none
} else {
return Effect(value: true).observe(on: QueueScheduler.main)
}
},
environment: ()
)
parentStore
.ifLet(then: { childStore in
let vs = ViewStore(childStore)
vs
.produced.producer
.startWithValues { _ in }
vs.send(false)
_ = XCTWaiter.wait(for: [.init()], timeout: 0.1)
vs.send(false)
_ = XCTWaiter.wait(for: [.init()], timeout: 0.1)
vs.send(false)
_ = XCTWaiter.wait(for: [.init()], timeout: 0.1)
XCTAssertEqual(vs.state, 3)
})
}
func testActionQueuing() {
let subject = Signal<Void, Never>.pipe()
enum Action: Equatable {
case incrementTapped
case `init`
case doIncrement
}
let store = TestStore(
initialState: 0,
reducer: Reducer<Int, Action, Void> { state, action, _ in
switch action {
case .incrementTapped:
subject.input.send(value: ())
return .none
case .`init`:
return subject.output.producer.map { .doIncrement }
case .doIncrement:
state += 1
return .none
}
},
environment: ()
)
store.send(.`init`)
store.send(.incrementTapped)
store.receive(.doIncrement) {
$0 = 1
}
store.send(.incrementTapped)
store.receive(.doIncrement) {
$0 = 2
}
subject.input.sendCompleted()
}
}
| 24.409877 | 91 | 0.600445 |
0800037ad3d14690bc23561675c444c03ef0401e | 1,345 | //
// CustomTextfield.swift
// ValidationTextField
//
// Created by Nhan Nguyen Le Trong on 10/29/19.
// Copyright © 2019 Nhan Nguyen Le Trong. All rights reserved.
//
import UIKit
protocol CustomTextfieldProtocol: class {
func becomeFirstResponde()
func resignFirstResponder()
}
class CustomTextfield: UITextField, UITextFieldDelegate {
weak var customDelegate: CustomTextfieldProtocol?
/// A Boolean value that determines whether the textfield is being edited or is selected.
open var editingOrSelected: Bool {
return super.isEditing || isSelected
}
// MARK: Responder handling
/**
Attempt the control to become the first responder
- returns: True when successfull becoming the first responder
*/
@discardableResult
override open func becomeFirstResponder() -> Bool {
let result = super.becomeFirstResponder()
customDelegate?.becomeFirstResponde()
return result
}
/**
Attempt the control to resign being the first responder
- returns: True when successfull resigning being the first responder
*/
@discardableResult
override open func resignFirstResponder() -> Bool {
let result = super.resignFirstResponder()
customDelegate?.resignFirstResponder()
return result
}
}
| 25.865385 | 93 | 0.689963 |
56a77ac5611e9ec9e23209452262b4cf47ff127e | 282 | //
// Model.swift
// Helper4Swift_Example
//
// Created by Abdullah Alhaider on 6/18/18.
// Copyright © 2018 CocoaPods. All rights reserved.
//
import Foundation
struct Coin: Codable {
var symbol : String?
var price_usd : String?
var percent_change_7d : String?
}
| 17.625 | 52 | 0.684397 |
33bf16b9c09ec1af6ca565a98587d19621a9023a | 881 | //
// SXPmessageViewController.swift
// weibo
//
// Created by shixinPeng on 16/2/24.
// Copyright © 2016年 shixinPeng. All rights reserved.
//
import UIKit
class SXPmessageViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 24.472222 | 106 | 0.679909 |
7a5eb8b68bcc443791198ceef22a9c75b9fba6d7 | 2,105 | //
// MemeTableViewController.swift
// MemeMe
//
// Created by administrator on 12/6/17.
// Copyright © 2017 administrator. All rights reserved.
//
import UIKit
class MemeTableViewController: UITableViewController {
var memes: [Meme] = []
override func viewDidLoad() {
super.viewDidLoad()
title = "Sent Memes View"
memes = Session.sharedInstance.memes
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
guard memes.count != Session.sharedInstance.memes.count else { return }
memes = Session.sharedInstance.memes
tableView.reloadData()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return memes.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MemeTableViewCell", for: indexPath)
let meme = memes[indexPath.row]
cell.textLabel?.text = meme.topText
cell.imageView?.image = meme.memedImage
cell.detailTextLabel?.text = meme.bottomText
return cell
}
@IBAction func generateMeme(_ sender: Any) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "MemeGeneratorViewControllerID") as! MemeGeneratorViewController
present(vc, animated: true, completion: nil)
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "MemeDetailViewControllerID") as! MemeDetailViewController
vc.memedImage = memes[indexPath.row].memedImage
navigationController?.pushViewController(vc, animated: true)
}
}
| 31.893939 | 134 | 0.685986 |
29e2462c36fad883cfb52f0c21052b9763ab5be0 | 6,075 | //
// Copyright (c) 2018. Uber Technologies
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
extension Int {
var tab: String {
return String(repeating: " ", count: self)
}
}
extension String {
enum SwiftKeywords: String {
case `throws` = "throws"
case `rethrows` = "rethrows"
case `try` = "try"
case `for` = "for"
case `in` = "in"
case `where` = "where"
case `while` = "while"
case `default` = "default"
case `fallthrough` = "fallthrough"
case `do` = "do"
case `switch` = "switch"
}
static let doneInit = "_doneInit"
static let hasBlankInit = "_hasBlankInit"
static let `static` = "static"
static let importSpace = "import "
static public let `class` = "class"
static public let `final` = "final"
static let override = "override"
static let mockType = "protocol"
static let unknownVal = "Unknown"
static let prefix = "prefix"
static let any = "Any"
static let anyObject = "AnyObject"
static let fatalError = "fatalError"
static let available = "available"
static let `open` = "open"
static let initializer = "init"
static let handlerSuffix = "Handler"
static let observableLeftAngleBracket = "Observable<"
static let rxObservableLeftAngleBracket = "RxSwift.Observable<"
static let publishSubject = "PublishSubject"
static let behaviorSubject = "BehaviorSubject"
static let replaySubject = "ReplaySubject"
static let observableEmpty = "Observable.empty()"
static let rxObservableEmpty = "RxSwift.Observable.empty()"
static let `required` = "required"
static let `convenience` = "convenience"
static let closureArrow = "->"
static let moduleColon = "module:"
static let typealiasColon = "typealias:"
static let rxColon = "rx:"
static let varColon = "var:"
static let `typealias` = "typealias"
static let annotationArgDelimiter = ";"
static let subjectSuffix = "Subject"
static let underlyingVarPrefix = "underlying"
static let setCallCountSuffix = "SetCallCount"
static let callCountSuffix = "CallCount"
static let initializerLeftParen = "init("
static let `escaping` = "@escaping"
static let autoclosure = "@autoclosure"
static public let mockAnnotation = "@mockable"
static public let poundIf = "#if "
static public let poundEndIf = "#endif"
static public let headerDoc =
"""
///
/// @Generated by Mockolo
///
"""
var isThrowsOrRethrows: Bool {
return self == SwiftKeywords.throws.rawValue || self == SwiftKeywords.rethrows.rawValue
}
var safeName: String {
if let _ = SwiftKeywords(rawValue: self) {
return "`\(self)`"
}
return self
}
func canBeInitParam(type: String, isStatic: Bool) -> Bool {
return !(isStatic || type == .unknownVal || (type.hasSuffix("?") && type.contains(String.closureArrow)) || isGenerated(type: Type(type)))
}
func isGenerated(type: Type) -> Bool {
return self.hasPrefix(.underlyingVarPrefix) ||
self.hasSuffix(.setCallCountSuffix) ||
self.hasSuffix(.callCountSuffix) ||
self.hasSuffix(.subjectSuffix) ||
self.hasSuffix("SubjectKind") ||
(self.hasSuffix(.handlerSuffix) && type.isOptional)
}
func arguments(with delimiter: String) -> [String: String]? {
let argstr = self
let args = argstr.components(separatedBy: delimiter)
var argsMap = [String: String]()
for item in args {
let keyVal = item.components(separatedBy: "=").map{$0.trimmingCharacters(in: .whitespaces)}
if let k = keyVal.first {
if k.contains(":") {
break
}
if let v = keyVal.last {
argsMap[k] = v
}
}
}
return !argsMap.isEmpty ? argsMap : nil
}
}
let separatorsForDisplay = CharacterSet(charactersIn: "<>[] :,()_-.&@#!{}@+\"\'")
let separatorsForLiterals = CharacterSet(charactersIn: "?<>[] :,()_-.&@#!{}@+\"\'")
extension StringProtocol {
var isNotEmpty: Bool {
return !isEmpty
}
var capitlizeFirstLetter: String {
return prefix(1).capitalized + dropFirst()
}
func shouldParse(with exclusionList: [String]? = nil) -> Bool {
guard hasSuffix(".swift") else { return false }
guard let exlist = exclusionList else { return true }
if let name = components(separatedBy: ".swift").first {
for ex in exlist {
if name.hasSuffix(ex) {
return false
}
}
return true
}
return false
}
var literalComponents: [String] {
return self.components(separatedBy: separatorsForLiterals)
}
var displayableComponents: [String] {
let ret = self.replacingOccurrences(of: "?", with: "Optional")
return ret.components(separatedBy: separatorsForDisplay)
}
var asTestableImport: String {
return "@testable \(self.asImport)"
}
var asImport: String {
return "import \(self)"
}
var moduleName: String? {
guard self.hasPrefix(String.importSpace) else { return nil }
return self.dropFirst(String.importSpace.count).trimmingCharacters(in: .whitespaces)
}
}
| 33.016304 | 146 | 0.607572 |
8760f49526362f9bcf13113d78377fc717d02b71 | 1,708 | //
// DBModel.swift
// todoapi
//
// Created by ito on 1/3/16.
// Copyright © 2016 Yusuke Ito. All rights reserved.
//
import MySQL
extension ConnectionPool {
func createTodoTable() throws {
try execute { conn in
try conn.query("CREATE TABLE `todos` ( " +
"`id` int(11) NOT NULL AUTO_INCREMENT," +
"`title` varchar(256) NOT NULL DEFAULT ''," +
"`done` tinyint(1) NOT NULL DEFAULT '0'," +
"`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP," +
"PRIMARY KEY (`id`)," +
"UNIQUE KEY `id` (`id`)" +
") ENGINE=InnoDB DEFAULT CHARSET=utf8;")
}
}
}
struct Row {
struct Todo: QueryRowResultType, QueryParameterDictionaryType {
let id: Int
let title: String
let done: Bool
let updatedAt: SQLDate
static func decodeRow(r: MySQL.QueryRowResult) throws -> Todo {
return try build(Todo.init)(
r <| "id",
r <| "title",
r <| "done",
r <| "updated_at"
)
}
func queryParameter() throws -> QueryDictionary {
return QueryDictionary([
//"id": // auto increment
"title": title,
"done": done,
"updated_at": updatedAt,
])
}
var json: JSON {
return [
"id": JSON.from(Double(id)),
"title": JSON.from(title),
"done": JSON.from(done),
"timestamp": JSON.from(updatedAt.description)
]
}
}
}
| 29.448276 | 106 | 0.482436 |
75e9b412ca62531546f37cc66ad8bf5fa162dea4 | 18,459 | import Foundation
import XCTest
import VisaCheckoutSDK
class BTVisaCheckout_Tests: XCTestCase {
let mockAPIClient = MockAPIClient(authorization: "development_tokenization_key")!
func testCreateProfile_whenConfigurationFetchErrorOccurs_callsCompletionWithError() {
mockAPIClient.cannedConfigurationResponseError = NSError(domain: "MyError", code: 123, userInfo: nil)
let client = BTVisaCheckoutClient(apiClient: mockAPIClient)
let expecation = expectation(description: "profile error")
client.createProfile { (profile, error) in
let err = error! as NSError
XCTAssertNil(profile)
XCTAssertEqual(err.domain, "MyError")
XCTAssertEqual(err.code, 123)
expecation.fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
}
func testCreateProfile_whenVisaCheckoutIsNotEnabled_callsBackWithError() {
mockAPIClient.cannedConfigurationResponseBody = BTJSON(value: {})
let client = BTVisaCheckoutClient(apiClient: mockAPIClient)
let expecation = expectation(description: "profile error")
client.createProfile { (profile, error) in
let err = error! as NSError
XCTAssertNil(profile)
XCTAssertEqual(err.domain, BTVisaCheckoutErrorDomain)
XCTAssertEqual(err.code, BTVisaCheckoutErrorType.unsupported.rawValue)
expecation.fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
}
func testCreateProfile_whenSuccessful_returnsProfileWithArgs() {
mockAPIClient.cannedConfigurationResponseBody = BTJSON(value: [
"environment": "sandbox",
"visaCheckout": [
"apikey": "API Key",
"externalClientId": "clientExternalId",
"supportedCardTypes": [
"Visa",
"MasterCard",
"American Express",
"Discover"
]
]
])
let client = BTVisaCheckoutClient(apiClient: mockAPIClient)
let expecation = expectation(description: "profile success")
client.createProfile { (profile, error) in
guard let visaProfile = profile as Profile? else {
XCTFail()
return
}
XCTAssertNil(error)
XCTAssertEqual(visaProfile.apiKey, "API Key")
XCTAssertEqual(visaProfile.environment, .sandbox)
XCTAssertEqual(visaProfile.datalevel, DataLevel.full)
XCTAssertEqual(visaProfile.clientId, "clientExternalId")
if let acceptedCardBrands = visaProfile.acceptedCardBrands {
XCTAssertTrue(acceptedCardBrands.count == 4)
} else {
XCTFail()
}
expecation.fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
}
func testTokenize_whenMalformedCheckoutResult_callsCompletionWithError() {
mockAPIClient.cannedConfigurationResponseBody = BTJSON(value: [
"environment": "sandbox",
"visaCheckout": [
"apikey": "API Key",
"externalClientId": "clientExternalId",
"supportedCardTypes": [
"Visa",
"MasterCard",
"American Express",
"Discover"
]
]
])
let client = BTVisaCheckoutClient(apiClient: mockAPIClient)
let expectedErr = NSError(domain: BTVisaCheckoutErrorDomain, code: BTVisaCheckoutErrorType.integration.rawValue, userInfo: [NSLocalizedDescriptionKey: "A valid VisaCheckoutResult is required."])
let malformedCheckoutResults : [(String?, String?, String?)] = [
(callId: nil, encryptedKey: "a", encryptedPaymentData: "b"),
(callId: "a", encryptedKey: nil, encryptedPaymentData: "b"),
(callId: "a", encryptedKey: "b", encryptedPaymentData: nil)
]
malformedCheckoutResults.forEach { (callId, encryptedKey, encryptedPaymentData) in
let expecation = expectation(description: "tokenization error due to malformed CheckoutResult")
client.tokenize(.statusSuccess, callId: callId, encryptedKey: encryptedKey, encryptedPaymentData: encryptedPaymentData) { (nonce, err) in
if nonce != nil {
XCTFail()
return
}
guard let err = err as NSError? else {
XCTFail()
return
}
XCTAssertEqual(err, expectedErr)
expecation.fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
}
}
func testTokenize_whenStatusCodeIndicatesCancellation_callsCompletionWithNilNonceAndError() {
let client = BTVisaCheckoutClient(apiClient: mockAPIClient)
let expectation = self.expectation(description: "Callback invoked")
client.tokenize(.statusUserCancelled, callId: "", encryptedKey: "", encryptedPaymentData: "") { (tokenizedCheckoutResult, error) in
XCTAssertNil(tokenizedCheckoutResult)
XCTAssertNil(error)
expectation.fulfill()
}
self.waitForExpectations(timeout: 1, handler: nil)
}
func testTokenize_whenStatusCodeIndicatesError_callsCompletionWitheError() {
let client = BTVisaCheckoutClient(apiClient: mockAPIClient)
let statusCodes = [
CheckoutResultStatus.statusDuplicateCheckoutAttempt,
CheckoutResultStatus.statusNotConfigured,
CheckoutResultStatus.statusInternalError
]
statusCodes.forEach { statusCode in
let expectation = self.expectation(description: "Callback invoked")
client.tokenize(statusCode, callId: "", encryptedKey: "", encryptedPaymentData: "") { (_, error) in
guard let error = error as NSError? else {
XCTFail()
return
}
XCTAssertEqual(error.domain, BTVisaCheckoutErrorDomain)
XCTAssertEqual(error.code, BTVisaCheckoutErrorType.checkoutUnsuccessful.rawValue)
XCTAssertEqual(error.localizedDescription, "Visa Checkout failed with status code \(statusCode.rawValue)")
expectation.fulfill()
}
self.waitForExpectations(timeout: 1, handler: nil)
}
}
func testTokenize_whenStatusCodeIndicatesCancellation_callsAnalyticsWithCancelled() {
let client = BTVisaCheckoutClient(apiClient: mockAPIClient)
let expectation = self.expectation(description: "Analytic sent")
client.tokenize(.statusUserCancelled, callId: "", encryptedKey: "", encryptedPaymentData: "") { _, _ in
XCTAssertEqual(self.mockAPIClient.postedAnalyticsEvents.last, "ios.visacheckout.result.cancelled")
expectation.fulfill()
}
self.waitForExpectations(timeout: 1, handler: nil)
}
func testTokenize_whenStatusCodeIndicatesError_callsAnalyticsWitheError() {
let client = BTVisaCheckoutClient(apiClient: mockAPIClient)
let statusCodes = [
(statusCode: CheckoutResultStatus.statusDuplicateCheckoutAttempt, analyticEvent: "ios.visacheckout.result.failed.duplicate-checkouts-open"),
(statusCode: CheckoutResultStatus.statusNotConfigured, analyticEvent: "ios.visacheckout.result.failed.not-configured"),
(statusCode: CheckoutResultStatus.statusInternalError, analyticEvent: "ios.visacheckout.result.failed.internal-error"),
]
statusCodes.forEach { (statusCode, analyticEvent) in
let expectation = self.expectation(description: "Analytic sent")
client.tokenize(statusCode, callId: "", encryptedKey: "", encryptedPaymentData: "") { _, _ in
XCTAssertEqual(self.mockAPIClient.postedAnalyticsEvents.last, analyticEvent)
expectation.fulfill()
}
self.waitForExpectations(timeout: 1, handler: nil)
}
}
func testTokenize_whenTokenizationErrorOccurs_callsCompletionWithError() {
mockAPIClient.cannedConfigurationResponseBody = BTJSON(value: [
"environment": "sandbox",
"visaCheckout": [
"apikey": "API Key",
"externalClientId": "clientExternalId",
"supportedCardTypes": [
"Visa",
"MasterCard",
"American Express",
"Discover"
]
]
])
mockAPIClient.cannedHTTPURLResponse = HTTPURLResponse(url: URL(string: "any")!, statusCode: 503, httpVersion: nil, headerFields: nil)
mockAPIClient.cannedResponseError = NSError(domain: "foo", code: 123, userInfo: nil)
let client = BTVisaCheckoutClient(apiClient: mockAPIClient)
let expecation = expectation(description: "tokenization error")
client.tokenize(.statusSuccess, callId: "", encryptedKey: "", encryptedPaymentData: "") { (nonce, err) in
if nonce != nil {
XCTFail()
return
}
guard let err = err as NSError? else {
XCTFail()
return
}
XCTAssertEqual(err, self.mockAPIClient.cannedResponseError)
expecation.fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
}
func testTokenize_whenTokenizationErrorOccurs_sendsAnalyticsEvent() {
mockAPIClient.cannedConfigurationResponseBody = BTJSON(value: [
"environment": "sandbox",
"visaCheckout": [
"apikey": "API Key",
"externalClientId": "clientExternalId",
"supportedCardTypes": [
"Visa",
"MasterCard",
"American Express",
"Discover"
]
]
])
mockAPIClient.cannedHTTPURLResponse = HTTPURLResponse(url: URL(string: "any")!, statusCode: 503, httpVersion: nil, headerFields: nil)
mockAPIClient.cannedResponseError = NSError(domain: "foo", code: 123, userInfo: nil)
let client = BTVisaCheckoutClient(apiClient: mockAPIClient)
let expecation = expectation(description: "tokenization error")
client.tokenize(.statusSuccess, callId: "", encryptedKey: "", encryptedPaymentData: "") { _, _ in
expecation.fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(self.mockAPIClient.postedAnalyticsEvents.last, "ios.visacheckout.tokenize.failed")
}
func testTokenize_whenCalled_makesPOSTRequestToTokenizationEndpoint() {
let client = BTVisaCheckoutClient(apiClient: mockAPIClient)
let expecation = expectation(description: "tokenization success")
client.tokenize(.statusSuccess, callId: "callId", encryptedKey: "encryptedKey", encryptedPaymentData: "encryptedPaymentData") { _, _ in
expecation.fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(self.mockAPIClient.lastPOSTPath, "v1/payment_methods/visa_checkout_cards")
if let visaCheckoutCard = self.mockAPIClient.lastPOSTParameters?["visaCheckoutCard"] as? [String: String] {
XCTAssertEqual(visaCheckoutCard, [
"callId": "callId",
"encryptedKey": "encryptedKey",
"encryptedPaymentData": "encryptedPaymentData"
])
} else {
XCTFail()
return
}
}
func testTokenize_whenMissingPhoneNumber_returnsNilForBothAddresses() {
mockAPIClient.cannedResponseBody = BTJSON(value: [
"visaCheckoutCards":[[
"type": "VisaCheckoutCard",
"nonce": "123456-12345-12345-a-adfa",
"description": "ending in ••11",
"default": false,
"details": [
"cardType": "Visa",
"lastTwo": "11"
],
"shippingAddress": [
"firstName": "BT - shipping",
"lastName": "Test - shipping",
"streetAddress": "123 Townsend St Fl 6 - shipping",
"locality": "San Francisco - shipping",
"region": "CA - shipping",
"postalCode": "94107 - shipping",
"countryCode": "US - shipping"
],
"billingAddress": [
"firstName": "BT - billing",
"lastName": "Test - billing",
"streetAddress": "123 Townsend St Fl 6 - billing",
"locality": "San Francisco - billing",
"region": "CA - billing",
"postalCode": "94107 - billing",
"countryCode": "US - billing"
]
]]
])
let client = BTVisaCheckoutClient(apiClient: mockAPIClient)
let expecation = expectation(description: "tokenization success")
client.tokenize(.statusSuccess, callId: "", encryptedKey: "", encryptedPaymentData: "") { (nonce, error) in
if (error != nil) {
XCTFail()
return
}
guard let nonce = nonce else {
XCTFail()
return
}
XCTAssertNil(nonce.shippingAddress!.phoneNumber)
XCTAssertNil(nonce.billingAddress!.phoneNumber)
expecation.fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
}
func testTokenize_whenTokenizationSuccess_callsAPIClientWithVisaCheckoutCard() {
mockAPIClient.cannedResponseBody = BTJSON(value: [
"visaCheckoutCards":[[
"type": "VisaCheckoutCard",
"nonce": "123456-12345-12345-a-adfa",
"description": "ending in ••11",
"default": false,
"details": [
"cardType": "Visa",
"lastTwo": "11"
],
"shippingAddress": [
"firstName": "BT - shipping",
"lastName": "Test - shipping",
"streetAddress": "123 Townsend St Fl 6 - shipping",
"extendedAddress": "Unit 123 - shipping",
"locality": "San Francisco - shipping",
"region": "CA - shipping",
"postalCode": "94107 - shipping",
"countryCode": "US - shipping",
"phoneNumber": "1234567890 - shipping"
],
"billingAddress": [
"firstName": "BT - billing",
"lastName": "Test - billing",
"streetAddress": "123 Townsend St Fl 6 - billing",
"extendedAddress": "Unit 123 - billing",
"locality": "San Francisco - billing",
"region": "CA - billing",
"postalCode": "94107 - billing",
"countryCode": "US - billing",
"phoneNumber": "1234567890 - billing"
],
"userData": [
"userFirstName": "userFirstName",
"userLastName": "userLastName",
"userFullName": "userFullName",
"userName": "userUserName",
"userEmail": "userEmail"
]
]]
])
let client = BTVisaCheckoutClient(apiClient: mockAPIClient)
let expecation = expectation(description: "tokenization success")
client.tokenize(.statusSuccess, callId: "", encryptedKey: "", encryptedPaymentData: "") { (nonce, error) in
if (error != nil) {
XCTFail()
return
}
guard let nonce = nonce else {
XCTFail()
return
}
XCTAssertEqual(nonce.type, "VisaCheckoutCard")
XCTAssertEqual(nonce.nonce, "123456-12345-12345-a-adfa")
XCTAssertTrue(nonce.cardNetwork == BTCardNetwork.visa)
XCTAssertEqual(nonce.lastTwo, "11")
[(nonce.shippingAddress!, "shipping"), (nonce.billingAddress!, "billing")].forEach { (address, type) in
XCTAssertEqual(address.firstName, "BT - " + type)
XCTAssertEqual(address.lastName, "Test - " + type)
XCTAssertEqual(address.streetAddress, "123 Townsend St Fl 6 - " + type)
XCTAssertEqual(address.extendedAddress, "Unit 123 - " + type)
XCTAssertEqual(address.locality, "San Francisco - " + type)
XCTAssertEqual(address.region, "CA - " + type)
XCTAssertEqual(address.postalCode, "94107 - " + type)
XCTAssertEqual(address.countryCode, "US - " + type)
XCTAssertEqual(address.phoneNumber, "1234567890 - " + type)
}
XCTAssertEqual(nonce.userData!.firstName, "userFirstName")
XCTAssertEqual(nonce.userData!.lastName, "userLastName")
XCTAssertEqual(nonce.userData!.fullName, "userFullName")
XCTAssertEqual(nonce.userData!.username, "userUserName")
XCTAssertEqual(nonce.userData!.email, "userEmail")
expecation.fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
}
func testTokenize_whenTokenizationSuccess_sendsAnalyticEvent() {
mockAPIClient.cannedResponseBody = BTJSON(value: [
"visaCheckoutCards":[[:]]
])
let client = BTVisaCheckoutClient(apiClient: mockAPIClient)
let expecation = expectation(description: "tokenization success")
client.tokenize(.statusSuccess, callId: "", encryptedKey: "", encryptedPaymentData: "") { _, _ in
expecation.fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(self.mockAPIClient.postedAnalyticsEvents.last, "ios.visacheckout.tokenize.succeeded")
}
}
| 41.203125 | 202 | 0.577171 |
e5808d5ac32fb601704feb0084aa41a443702d8f | 3,504 | //
// PlaySoundViewController.swift
// PitchPerfect
//
// Created by 진형탁 on 2017. 1. 1..
// Copyright © 2017년 Boostcamp. All rights reserved.
//
import UIKit
import AVFoundation
class PlaySoundViewController: UIViewController {
@IBOutlet weak var stopButton: UIButton!
@IBOutlet weak var fastButton: UIButton!
@IBOutlet weak var slowButton: UIButton!
@IBOutlet weak var highPitchButton: UIButton!
@IBOutlet weak var lowPitchButton: UIButton!
@IBOutlet weak var echoButton: UIButton!
@IBOutlet weak var reverbButton: UIButton!
@IBOutlet weak var playbackSlider: UISlider!
var recordedAudioURL: URL!
var audioFile: AVAudioFile!
var audioEngine: AVAudioEngine!
var audioPlayerNode: AVAudioPlayerNode!
var sliderTimer = Timer()
var stopTimer: Timer!
var delayInSeconds: Double = 0
enum ButtonType: Int { case fast = 0, slow, highPitch, lowPitch, echo, reverb }
@IBAction func playSoundForButton (_ sender: UIButton) {
switch(ButtonType(rawValue: sender.tag)!) {
case .slow:
playSound(rate: 0.5)
case .fast:
playSound(rate: 1.5)
case .highPitch:
playSound(pitch: 1000)
case .lowPitch:
playSound(pitch: -1000)
case .echo:
playSound(echo: true)
case .reverb:
playSound(reverb: true)
}
configureUI(.playing)
startSliderTimer()
}
@IBAction func stopButtonPressed (_ sender: UIButton) {
stopAudio()
sliderTimer.invalidate()
playbackSlider.value = 0
delayInSeconds = 0
}
override func viewDidLoad() {
super.viewDidLoad()
setupAudio()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
playbackSlider.minimumValue = 0
playbackSlider.isContinuous = true
configureUI(.notPlaying)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// to process when user clicked back button
if (self.isMovingFromParentViewController){
stopAudio()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// fire timer for slider
func startSliderTimer() {
if (!sliderTimer.isValid) {
sliderTimer = Timer.scheduledTimer(timeInterval: delayInSeconds, target: self, selector: #selector(activeSliderTimer(_:)), userInfo: nil, repeats: true)
sliderTimer.fire()
}
}
// change label on view
func activeSliderTimer(_ timer: Timer) {
playbackSlider.value = Float(currentTime())
}
// get play current time
func currentTime() -> TimeInterval {
let nodeTime: AVAudioTime = audioPlayerNode.lastRenderTime!
let playTime: AVAudioTime = audioPlayerNode.playerTime(forNodeTime: nodeTime)!
return Double(Double(playTime.sampleTime) / playTime.sampleRate)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 30.469565 | 164 | 0.642694 |
3ac7e53063063a07e2dc38f3a4f825979d8e4741 | 31,579 |
import UIKit
extension MonkeyKing {
public enum MiniAppType: Int {
case release = 0
case test = 1
case preview = 2
}
/// https://developers.weixin.qq.com/doc/oplatform/Mobile_App/Share_and_Favorites/iOS.html
public enum Media {
case url(URL)
case image(UIImage)
case imageData(Data)
case gif(Data)
case audio(audioURL: URL, linkURL: URL?)
case video(URL)
/// file extension for wechat file share
case file(Data, fileExt: String?)
/**
- url : 含义[兼容低版本的网页链接] 备注[限制长度不超过10KB]
- path: [小程序的页面路径] [小程序页面路径;对于小游戏,可以只传入 query 部分,来实现传参效果,如:传入 "?foo=bar"]
- withShareTicket: 通常开发者希望分享出去的小程序被二次打开时可以获取到更多信息,例如群的标识。可以设置withShareTicket为true,当分享卡片在群聊中被其他用户打开时,可以获取到shareTicket,用于获取更多分享信息。详见小程序获取更多分享信息 ,最低客户端版本要求:6.5.13
- miniprogramType: 小程序的类型,默认正式版,1.8.1及以上版本开发者工具包支持分享开发版和体验版小程序
- userName: 小程序原始ID获取方法:登录小程序管理后台-设置-基本设置-帐号信息
*/
case miniApp(url: URL, path: String, withShareTicket: Bool, type: MiniAppType, userName: String?)
}
public typealias Info = (title: String?, description: String?, thumbnail: UIImage?, media: Media?)
public enum Message {
public enum WeChatSubtype {
case session(info: Info)
case timeline(info: Info)
case favorite(info: Info)
var scene: String {
switch self {
case .session:
return "0"
case .timeline:
return "1"
case .favorite:
return "2"
}
}
var info: Info {
switch self {
case .session(let info):
return info
case .timeline(let info):
return info
case .favorite(let info):
return info
}
}
}
case weChat(WeChatSubtype)
public enum QQSubtype {
case friends(info: Info)
case zone(info: Info)
case favorites(info: Info)
case dataline(info: Info)
var scene: Int {
switch self {
case .friends:
return 0x00
case .zone:
return 0x01
case .favorites:
return 0x08
case .dataline:
return 0x10
}
}
var info: Info {
switch self {
case .friends(let info):
return info
case .zone(let info):
return info
case .favorites(let info):
return info
case .dataline(let info):
return info
}
}
}
case qq(QQSubtype)
public enum WeiboSubtype {
case `default`(info: Info, accessToken: String?)
var info: Info {
switch self {
case .default(let info, _):
return info
}
}
var accessToken: String? {
switch self {
case .default(_, let accessToken):
return accessToken
}
}
}
case weibo(WeiboSubtype)
public enum AlipaySubtype {
case friends(info: Info)
case timeline(info: Info)
var scene: NSNumber {
switch self {
case .friends:
return 0
case .timeline:
return 1
}
}
var info: Info {
switch self {
case .friends(let info):
return info
case .timeline(let info):
return info
}
}
}
case alipay(AlipaySubtype)
public enum TwitterSubtype {
case `default`(info: Info, mediaIDs: [String]?, accessToken: String?, accessTokenSecret: String?)
var info: Info {
switch self {
case .default(let info, _, _, _):
return info
}
}
var mediaIDs: [String]? {
switch self {
case .default(_, let mediaIDs, _, _):
return mediaIDs
}
}
var accessToken: String? {
switch self {
case .default(_, _, let accessToken, _):
return accessToken
}
}
var accessTokenSecret: String? {
switch self {
case .default(_, _, _, let accessTokenSecret):
return accessTokenSecret
}
}
}
case twitter(TwitterSubtype)
public var canBeDelivered: Bool {
switch platform {
case .weibo, .twitter:
return true
default:
return platform.isAppInstalled
}
}
}
private class func fallbackToScheme(url: URL, completionHandler: @escaping DeliverCompletionHandler) {
shared.openURL(url) { succeed in
if succeed {
return
}
completionHandler(.failure(.sdk(.invalidURLScheme)))
}
}
public class func deliver(_ message: Message, completionHandler: @escaping DeliverCompletionHandler) {
guard message.canBeDelivered else {
completionHandler(.failure(.noApp))
return
}
guard let account = shared.accountSet[message.platform] else {
completionHandler(.failure(.noAccount))
return
}
shared.deliverCompletionHandler = completionHandler
shared.payCompletionHandler = nil
shared.oauthCompletionHandler = nil
shared.openSchemeCompletionHandler = nil
let appID = account.appID
switch message {
case .weChat(let type):
var weChatMessageInfo: [String: Any] = [
"scene": type.scene,
"command": "1010",
]
let info = type.info
if let title = info.title {
weChatMessageInfo["title"] = title
}
if let description = info.description {
weChatMessageInfo["description"] = description
}
if let thumbnailImage = info.thumbnail {
weChatMessageInfo["thumbData"] = thumbnailImage.monkeyking_compressedImageData
}
if let media = info.media {
switch media {
case .url(let url):
weChatMessageInfo["objectType"] = "5"
weChatMessageInfo["mediaUrl"] = url.absoluteString
case .image(let image):
weChatMessageInfo["objectType"] = "2"
if let imageData = image.jpegData(compressionQuality: 0.9) {
weChatMessageInfo["fileData"] = imageData
}
case .imageData(let imageData):
weChatMessageInfo["objectType"] = "2"
weChatMessageInfo["fileData"] = imageData
case .gif(let data):
weChatMessageInfo["objectType"] = "8"
weChatMessageInfo["fileData"] = data
case .audio(let audioURL, let linkURL):
weChatMessageInfo["objectType"] = "3"
if let urlString = linkURL?.absoluteString {
weChatMessageInfo["mediaUrl"] = urlString
}
weChatMessageInfo["mediaDataUrl"] = audioURL.absoluteString
case .video(let url):
weChatMessageInfo["objectType"] = "4"
weChatMessageInfo["mediaUrl"] = url.absoluteString
case .miniApp(let url, let path, let withShareTicket, let type, let userName):
if case .weChat(_, _, let miniProgramID, let universalLink) = account {
weChatMessageInfo["objectType"] = "36"
if let hdThumbnailImage = info.thumbnail {
weChatMessageInfo["hdThumbData"] = hdThumbnailImage.monkeyking_resetSizeOfImageData(maxSize: 127 * 1024)
}
weChatMessageInfo["mediaUrl"] = url.absoluteString
weChatMessageInfo["appBrandPath"] = path
weChatMessageInfo["withShareTicket"] = withShareTicket
weChatMessageInfo["miniprogramType"] = type.rawValue
weChatMessageInfo["universalLink"] = universalLink
if let userName = userName {
weChatMessageInfo["appBrandUserName"] = userName
} else if let miniProgramID = miniProgramID {
weChatMessageInfo["appBrandUserName"] = miniProgramID
} else {
fatalError("Missing `miniProgramID`!")
}
}
case .file(let fileData, let fileExt):
weChatMessageInfo["objectType"] = "6"
weChatMessageInfo["fileData"] = fileData
weChatMessageInfo["fileExt"] = fileExt
if let fileExt = fileExt, let title = info.title {
let suffix = ".\(fileExt)"
weChatMessageInfo["title"] = title.hasSuffix(suffix) ? title : title + suffix
}
}
} else { // Text Share
weChatMessageInfo["command"] = "1020"
}
lastMessage = message
shared.setPasteboard(of: appID, with: weChatMessageInfo)
if
let commandUniversalLink = shared.wechatUniversalLink(of: "sendreq"), #available(iOS 10.0, *),
let universalLink = MonkeyKing.shared.accountSet[.weChat]?.universalLink,
let ulURL = URL(string: commandUniversalLink)
{
weChatMessageInfo["universalLink"] = universalLink
weChatMessageInfo["isAutoResend"] = false
shared.openURL(ulURL, options: [.universalLinksOnly: true]) { succeed in
if !succeed, let schemeURL = URL(string: "weixin://app/\(appID)/sendreq/?") {
fallbackToScheme(url: schemeURL, completionHandler: completionHandler)
}
}
} else if let schemeURL = URL(string: "weixin://app/\(appID)/sendreq/?") {
fallbackToScheme(url: schemeURL, completionHandler: completionHandler)
}
case .qq(let type):
let callbackName = appID.monkeyking_qqCallbackName
var qqSchemeURLString = "mqqapi://share/to_fri?"
if let encodedAppDisplayName = Bundle.main.monkeyking_displayName?.monkeyking_base64EncodedString {
qqSchemeURLString += "thirdAppDisplayName=" + encodedAppDisplayName
} else {
qqSchemeURLString += "thirdAppDisplayName=" + "nixApp" // Should not be there
}
qqSchemeURLString += "&version=1&cflag=\(type.scene)"
qqSchemeURLString += "&callback_type=scheme&generalpastboard=1"
qqSchemeURLString += "&callback_name=\(callbackName)"
qqSchemeURLString += "&src_type=app&shareType=0&file_type="
if let media = type.info.media {
func handleNews(with url: URL, mediaType: String?) {
if let thumbnailData = type.info.thumbnail?.monkeyking_compressedImageData {
var dic: [String: Any] = ["previewimagedata": thumbnailData]
if let oldText = UIPasteboard.general.oldText {
dic["pasted_string"] = oldText
}
let data = NSKeyedArchiver.archivedData(withRootObject: dic)
UIPasteboard.general.setData(data, forPasteboardType: "com.tencent.mqq.api.apiLargeData")
}
qqSchemeURLString += mediaType ?? "news"
guard let encodedURLString = url.absoluteString.monkeyking_base64AndURLEncodedString else {
completionHandler(.failure(.sdk(.urlEncodeFailed)))
return
}
qqSchemeURLString += "&url=\(encodedURLString)"
}
switch media {
case .url(let url):
handleNews(with: url, mediaType: "news")
case .image(let image):
guard let imageData = image.jpegData(compressionQuality: 0.9) else {
completionHandler(.failure(.resource(.invalidImageData)))
return
}
var dic: [String: Any] = ["file_data": imageData]
if let thumbnail = type.info.thumbnail, let thumbnailData = thumbnail.jpegData(compressionQuality: 0.9) {
dic["previewimagedata"] = thumbnailData
}
// TODO: handle previewimageUrl string aswell
if let oldText = UIPasteboard.general.oldText {
dic["pasted_string"] = oldText
}
let data = NSKeyedArchiver.archivedData(withRootObject: dic)
UIPasteboard.general.setData(data, forPasteboardType: "com.tencent.mqq.api.apiLargeData")
qqSchemeURLString += "img"
case .imageData(let data), .gif(let data):
var dic: [String: Any] = ["file_data": data]
if let thumbnail = type.info.thumbnail, let thumbnailData = thumbnail.jpegData(compressionQuality: 0.9) {
dic["previewimagedata"] = thumbnailData
}
if let oldText = UIPasteboard.general.oldText {
dic["pasted_string"] = oldText
}
let archivedData = NSKeyedArchiver.archivedData(withRootObject: dic)
UIPasteboard.general.setData(archivedData, forPasteboardType: "com.tencent.mqq.api.apiLargeData")
qqSchemeURLString += "img"
case .audio(let audioURL, _):
handleNews(with: audioURL, mediaType: "audio")
case .video(let url):
handleNews(with: url, mediaType: nil) // No video type, default is news type.
case .file(let fileData, _):
var dic: [String: Any] = ["file_data": fileData]
if let oldText = UIPasteboard.general.oldText {
dic["pasted_string"] = oldText
}
let data = NSKeyedArchiver.archivedData(withRootObject: dic)
UIPasteboard.general.setData(data, forPasteboardType: "com.tencent.mqq.api.apiLargeData")
qqSchemeURLString += "localFile"
if let filename = type.info.description?.monkeyking_urlEncodedString {
qqSchemeURLString += "&fileName=\(filename)"
}
case .miniApp:
fatalError("QQ not supports Mini App type")
}
if let encodedTitle = type.info.title?.monkeyking_base64AndURLEncodedString {
qqSchemeURLString += "&title=\(encodedTitle)"
}
if let encodedDescription = type.info.description?.monkeyking_base64AndURLEncodedString {
qqSchemeURLString += "&objectlocation=pasteboard&description=\(encodedDescription)"
}
qqSchemeURLString += "&sdkv=3.3.9_lite"
} else { // Share Text
// fix #75
switch type {
case .zone:
qqSchemeURLString += "qzone&title="
default:
qqSchemeURLString += "text&file_data="
}
if let encodedDescription = type.info.description?.monkeyking_base64AndURLEncodedString {
qqSchemeURLString += "\(encodedDescription)"
}
}
guard let comps = URLComponents(string: qqSchemeURLString), let url = comps.url else {
completionHandler(.failure(.sdk(.urlEncodeFailed)))
return
}
lastMessage = message
if account.universalLink != nil, var ulComps = URLComponents(string: "https://qm.qq.com/opensdkul/mqqapi/share/to_fri") {
ulComps.query = comps.query
if let token = qqAppSignToken {
ulComps.queryItems?.append(.init(name: "appsign_token", value: token))
}
if let txid = qqAppSignTxid {
ulComps.queryItems?.append(.init(name: "appsign_txid", value: txid))
}
if let ulURL = ulComps.url, #available(iOS 10.0, *) {
shared.openURL(ulURL, options: [.universalLinksOnly: true]) { succeed in
if !succeed {
fallbackToScheme(url: url, completionHandler: completionHandler)
}
}
}
} else {
fallbackToScheme(url: url, completionHandler: completionHandler)
}
case .weibo(let type):
guard !shared.canOpenURL(URL(string: "weibosdk://request")!) else {
// App Share
var messageInfo: [String: Any] = [
"__class": "WBMessageObject",
]
let info = type.info
if let description = info.description {
messageInfo["text"] = description
}
if let media = info.media {
switch media {
case .url(let url):
if let thumbnailData = info.thumbnail?.monkeyking_compressedImageData {
var mediaObject: [String: Any] = [
"__class": "WBWebpageObject",
"objectID": "identifier1",
]
mediaObject["webpageUrl"] = url.absoluteString
mediaObject["title"] = info.title ?? ""
mediaObject["thumbnailData"] = thumbnailData
messageInfo["mediaObject"] = mediaObject
} else {
// Deliver text directly.
let text = info.description ?? ""
messageInfo["text"] = text.isEmpty ? url.absoluteString : text + " " + url.absoluteString
}
case .image(let image):
if let imageData = image.jpegData(compressionQuality: 0.9) {
messageInfo["imageObject"] = ["imageData": imageData]
}
case .imageData(let imageData):
messageInfo["imageObject"] = ["imageData": imageData]
case .gif:
fatalError("Weibo not supports GIF type")
case .audio:
fatalError("Weibo not supports Audio type")
case .video:
fatalError("Weibo not supports Video type")
case .file:
fatalError("Weibo not supports File type")
case .miniApp:
fatalError("Weibo not supports Mini App type")
}
}
let uuidString = UUID().uuidString
let dict: [String: Any] = [
"__class": "WBSendMessageToWeiboRequest",
"message": messageInfo,
"requestID": uuidString,
]
let appData = NSKeyedArchiver.archivedData(
withRootObject: [
"appKey": appID,
"bundleID": Bundle.main.monkeyking_bundleID ?? "",
"universalLink": account.universalLink ?? ""
]
)
let messageData: [[String: Any]] = [
["transferObject": NSKeyedArchiver.archivedData(withRootObject: dict)],
["app": appData],
]
UIPasteboard.general.items = messageData
guard let url = weiboSchemeLink(uuidString: uuidString) else {
completionHandler(.failure(.sdk(.urlEncodeFailed)))
return
}
if account.universalLink != nil,
#available(iOS 10.0, *),
let ulURL = weiboUniversalLink(query: url.query) {
shared.openURL(ulURL, options: [.universalLinksOnly: true]) { succeed in
if !succeed {
fallbackToScheme(url: url, completionHandler: completionHandler)
}
}
} else {
fallbackToScheme(url: url, completionHandler: completionHandler)
}
return
}
// Weibo Web Share
let info = type.info
var parameters = [String: Any]()
guard let accessToken = type.accessToken else {
completionHandler(.failure(.noAccount))
return
}
parameters["access_token"] = accessToken
var status: [String?] = [info.title, info.description]
var mediaType = Media.url(NSURL() as URL)
if let media = info.media {
switch media {
case .url(let url):
status.append(url.absoluteString)
mediaType = Media.url(url)
case .image(let image):
guard let imageData = image.jpegData(compressionQuality: 0.9) else {
completionHandler(.failure(.resource(.invalidImageData)))
return
}
parameters["pic"] = imageData
mediaType = Media.image(image)
case .imageData(let imageData):
parameters["pic"] = imageData
mediaType = Media.imageData(imageData)
case .gif:
fatalError("web Weibo not supports GIF type")
case .audio:
fatalError("web Weibo not supports Audio type")
case .video:
fatalError("web Weibo not supports Video type")
case .file:
fatalError("web Weibo not supports File type")
case .miniApp:
fatalError("web Weibo not supports Mini App type")
}
}
let statusText = status.compactMap { $0 }.joined(separator: " ")
parameters["status"] = statusText
switch mediaType {
case .url:
let urlString = "https://api.weibo.com/2/statuses/share.json"
shared.request(urlString, method: .post, parameters: parameters) { responseData, _, error in
if error != nil {
completionHandler(.failure(.apiRequest(.connectFailed)))
} else if let responseData = responseData, (responseData["idstr"] as? String) == nil {
completionHandler(.failure(shared.buildError(with: responseData, at: .weibo)))
} else {
completionHandler(.success(nil))
}
}
case .image, .imageData:
let urlString = "https://api.weibo.com/2/statuses/share.json"
shared.upload(urlString, parameters: parameters) { responseData, _, error in
if error != nil {
completionHandler(.failure(.apiRequest(.connectFailed)))
} else if let responseData = responseData, (responseData["idstr"] as? String) == nil {
completionHandler(.failure(shared.buildError(with: responseData, at: .weibo)))
} else {
completionHandler(.success(nil))
}
}
case .gif:
fatalError("web Weibo not supports GIF type")
case .audio:
fatalError("web Weibo not supports Audio type")
case .video:
fatalError("web Weibo not supports Video type")
case .file:
fatalError("web Weibo not supports File type")
case .miniApp:
fatalError("web Weibo not supports Mini App type")
}
case .alipay(let type):
let dictionary = createAlipayMessageDictionary(withScene: type.scene, info: type.info, appID: appID)
guard let data = try? PropertyListSerialization.data(fromPropertyList: dictionary, format: .xml, options: .init()) else {
completionHandler(.failure(.sdk(.serializeFailed)))
return
}
UIPasteboard.general.setData(data, forPasteboardType: "com.alipay.openapi.pb.req.\(appID)")
var urlComponents = URLComponents(string: "alipayshare://platformapi/shareService")
urlComponents?.queryItems = [
URLQueryItem(name: "action", value: "sendReq"),
URLQueryItem(name: "shareId", value: appID),
]
guard let url = urlComponents?.url else {
completionHandler(.failure(.sdk(.urlEncodeFailed)))
return
}
shared.openURL(url) { flag in
if flag { return }
completionHandler(.failure(.sdk(.invalidURLScheme)))
}
case .twitter(let type):
// MARK: - Twitter Deliver
guard
let accessToken = type.accessToken,
let accessTokenSecret = type.accessTokenSecret
else {
completionHandler(.failure(.noAccount))
return
}
let info = type.info
var status = [info.title, info.description]
var parameters = [String: Any]()
var mediaType = Media.url(NSURL() as URL)
if let media = info.media {
switch media {
case .url(let url):
status.append(url.absoluteString)
mediaType = Media.url(url)
case .image(let image):
guard let imageData = image.jpegData(compressionQuality: 0.9) else {
completionHandler(.failure(.resource(.invalidImageData)))
return
}
parameters["media"] = imageData
mediaType = Media.image(image)
case .imageData(let imageData):
parameters["media"] = imageData
mediaType = Media.imageData(imageData)
default:
fatalError("web Twitter not supports this type")
}
}
switch mediaType {
case .url:
let statusText = status.compactMap { $0 }.joined(separator: " ")
let updateStatusAPI = "https://api.twitter.com/1.1/statuses/update.json"
var parameters = ["status": statusText]
if let mediaIDs = type.mediaIDs {
parameters["media_ids"] = mediaIDs.joined(separator: ",")
}
if case .twitter(let appID, let appKey, _) = account {
let oauthString = Networking.shared.authorizationHeader(for: .post, urlString: updateStatusAPI, appID: appID, appKey: appKey, accessToken: accessToken, accessTokenSecret: accessTokenSecret, parameters: parameters, isMediaUpload: true)
let headers = ["Authorization": oauthString]
// ref: https://dev.twitter.com/rest/reference/post/statuses/update
let urlString = "\(updateStatusAPI)?\(parameters.urlEncodedQueryString(using: .utf8))"
shared.request(urlString, method: .post, parameters: nil, headers: headers) { responseData, URLResponse, error in
if error != nil {
completionHandler(.failure(.apiRequest(.connectFailed)))
} else {
if let HTTPResponse = URLResponse as? HTTPURLResponse,
HTTPResponse.statusCode == 200 {
completionHandler(.success(nil))
return
}
if let responseData = responseData,
let _ = responseData["errors"] {
completionHandler(.failure(shared.buildError(with: responseData, at: .twitter)))
return
}
completionHandler(.failure(.apiRequest(.unrecognizedError(response: responseData))))
}
}
}
case .image, .imageData:
let uploadMediaAPI = "https://upload.twitter.com/1.1/media/upload.json"
if case .twitter(let appID, let appKey, _) = account {
// ref: https://dev.twitter.com/rest/media/uploading-media#keepinmind
let oauthString = Networking.shared.authorizationHeader(for: .post, urlString: uploadMediaAPI, appID: appID, appKey: appKey, accessToken: accessToken, accessTokenSecret: accessTokenSecret, parameters: nil, isMediaUpload: false)
let headers = ["Authorization": oauthString]
shared.upload(uploadMediaAPI, parameters: parameters, headers: headers) { responseData, URLResponse, error in
if let statusCode = (URLResponse as? HTTPURLResponse)?.statusCode,
statusCode == 200 {
completionHandler(.success(responseData))
return
}
if error != nil {
completionHandler(.failure(.apiRequest(.connectFailed)))
} else {
completionHandler(.failure(.apiRequest(.unrecognizedError(response: responseData))))
}
}
}
default:
fatalError("web Twitter not supports this mediaType")
}
}
}
}
| 45.048502 | 254 | 0.497451 |
bfe5646cfb3d4d0a3748b6f85606cf4ba0858fac | 994 | //
// BaseCloudModel.swift
// KonexiosSDK
//
// Copyright (c) 2017 Arrow Electronics, Inc.
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Apache License 2.0
// which accompanies this distribution, and is available at
// http://apache.org/licenses/LICENSE-2.0
//
// Contributors: Arrow Electronics, Inc.
// Konexios, Inc.
//
open class RequestModel {
open var params: [String: AnyObject] {
preconditionFailure("[RequestModel] - Abstract property: params")
}
var payloadString: String? {
do {
let payloadData = try JSONSerialization.data(withJSONObject: params, options: JSONSerialization.WritingOptions())
return String(data: payloadData, encoding: String.Encoding.utf8)
} catch let error as NSError {
print("[RequestModel] JSON Exception: \(error)")
return nil
}
}
public init() {
}
}
| 29.235294 | 125 | 0.641851 |
1c1c19456bd5edc53335ef75e196b93413699d26 | 5,437 | import TensorFlow
/// A dynamically sized vector.
public struct Vector: Equatable, Differentiable {
public typealias TangentVector = Self
/// The scalars in the vector.
@differentiable public var scalars: [Double] { return scalarsStorage }
/// Derivative for `scalars`.
// This is necessary because we have specified a custom `TangentVector`.
@derivative(of: scalars)
@usableFromInline
func vjpScalars()
-> (value: [Double], pullback: (Array<Double>.DifferentiableView) -> TangentVector)
{
return (scalars, { Vector($0.base) })
}
/// The storage for the scalars.
// This works around the fact that we cannot define custom derivatives for stored properties.
// TODO: Once we can define custom derivatives for stored properties, remove this.
internal var scalarsStorage: [Double]
}
/// Can be losslessly converted to and from a `Vector`.
public protocol VectorConvertible: Differentiable {
@differentiable
init(_ vector: Vector)
@differentiable
var vector: Vector { get }
}
/// Initializers.
extension Vector {
/// Creates a vector with the given `scalars`.
@differentiable
public init(_ scalars: [Double]) {
self.scalarsStorage = scalars
}
/// Derivative for `init`.
// This is necessary because we have specified a custom `TangentVector`.
@derivative(of: init(_:))
@usableFromInline
static func vjpInit(_ scalars: [Double])
-> (value: Vector, pullback: (TangentVector) -> Array<Double>.DifferentiableView)
{
return (Vector(scalars), { Array<Double>.DifferentiableView($0.scalars) })
}
/// Creates a zero vector of the given `dimension`.
public init(zeros dimension: Int) {
self.init(Array(repeating: 0, count: dimension))
}
}
/// Miscellaneous computed properties.
extension Vector {
public var dimension: Int {
return scalarsStorage.count
}
}
/// Arithmetic on elements.
extension Vector {
/// Sum of the elements of `self`.
public func sum() -> Double {
return scalarsStorage.reduce(0, +)
}
/// Vector whose elements are squares of the elements of `self`.
public func squared() -> Self {
return Vector(scalarsStorage.map { $0 * $0 })
}
}
/// Euclidean norms.
extension Vector {
/// Euclidean norm of `self`.
public var norm: Double { squaredNorm.squareRoot() }
/// Square of the Euclidean norm of `self`.
@differentiable
public var squaredNorm: Double { self.squared().sum() }
/// Derivative of `squaredNorm`.
// TODO: This is a custom derivative because derivatives of `map` and
// `reduce` are currently very slow. We can use the automatic derivative for this once
// https://github.com/apple/swift/pull/31704 is available.
@derivative(of: squaredNorm)
@usableFromInline
func vjpSquaredNorm() -> (value: Double, pullback: (Double) -> TangentVector) {
return (
value: squaredNorm,
pullback: { self.scaled(by: 2 * $0) }
)
}
}
/// AdditiveArithmetic conformance.
extension Vector: AdditiveArithmetic {
public static func += (_ lhs: inout Vector, _ rhs: Vector) {
for index in lhs.scalarsStorage.indices {
lhs.scalarsStorage[index] += rhs.scalarsStorage[index]
}
}
public static func + (_ lhs: Vector, _ rhs: Vector) -> Vector {
var result = lhs
result += rhs
return result
}
public static func -= (_ lhs: inout Vector, _ rhs: Vector) {
for index in lhs.scalarsStorage.indices {
lhs.scalarsStorage[index] -= rhs.scalarsStorage[index]
}
}
public static func - (_ lhs: Vector, _ rhs: Vector) -> Vector {
var result = lhs
result -= rhs
return result
}
/// The zero vector.
///
/// Note: "Zero" doesn't make very much sense as a static property on a dynamically sized vector
/// because we don't known the dimension of the zero. However, `AdditiveArithmetic` requires it,
/// so we implement it as reasonably as possible.
public static var zero: Vector {
return Vector([])
}
}
/// VectorProtocol conformance.
extension Vector: VectorProtocol {
public typealias VectorSpaceScalar = Double
public mutating func add(_ x: Double) {
for index in scalarsStorage.indices {
scalarsStorage[index] += x
}
}
public func adding(_ x: Double) -> Vector {
var result = self
result.add(x)
return result
}
public static func += (_ lhs: inout Vector, _ rhs: Double) {
lhs.add(rhs)
}
public mutating func subtract(_ x: Double) {
for index in scalarsStorage.indices {
scalarsStorage[index] -= x
}
}
public func subtracting(_ x: Double) -> Vector {
var result = self
result.subtract(x)
return result
}
public static func -= (_ lhs: inout Vector, _ rhs: Double) {
lhs.subtract(rhs)
}
public mutating func scale(by scalar: Double) {
for index in scalarsStorage.indices {
scalarsStorage[index] *= scalar
}
}
public func scaled(by scalar: Double) -> Vector {
var result = self
result.scale(by: scalar)
return result
}
public static func *= (_ lhs: inout Vector, _ rhs: Double) {
lhs.scale(by: rhs)
}
public static func * (_ lhs: Double, _ rhs: Vector) -> Vector {
return rhs.scaled(by: lhs)
}
}
extension Vector: EuclideanVectorSpace {}
/// Conversion to tensor.
extension Vector {
/// Returns this vector as a `Tensor<Double>`.
public var tensor: Tensor<Double> {
return Tensor(shape: [scalarsStorage.count], scalars: scalarsStorage)
}
}
| 26.651961 | 98 | 0.67574 |
b9cfc309843bfa598322d966bef5852a7e625a13 | 21,998 | //
// Array+Extension.swift
// ZZSwiftKit
//
// Created by GODKILLER on 2019/4/29.
// Copyright © 2019 ZZSwiftKit. All rights reserved.
//
import UIKit
// MARK: - Methods (Integer)
extension Array where Element: Numeric {
/// SwifterSwift: 数组中所有元素的和
///
/// [1, 2, 3, 4, 5].sum() -> 15
///
/// - Returns: sum of the array's elements.
public func sum() -> Element {
var total: Element = 0
for i in 0..<count {
total += self[i]
}
return total
}
}
// MARK: - Methods (FloatingPoint)
extension Array where Element: FloatingPoint {
/// SwifterSwift: 数组中所有元素的平均值
///
/// [1.2, 2.3, 4.5, 3.4, 4.5].average() = 3.18
///
/// - Returns: average of the array's elements.
public func average() -> Element {
guard !isEmpty else { return 0 }
var total: Element = 0
for i in 0..<count {
total += self[i]
}
return total / Element(count)
}
}
// MARK: - Methods
extension Array {
/// SwifterSwift: 元素在给定的索引中,如果它存在
///
/// [1, 2, 3, 4, 5].item(at: 2) -> 3
/// [1.2, 2.3, 4.5, 3.4, 4.5].item(at: 3) -> 3.4
/// ["h", "e", "l", "l", "o"].item(at: 10) -> nil
///
/// - Parameter index: index of element.
/// - Returns: optional element (if exists).
public func item(at index: Int) -> Element? {
guard startIndex..<endIndex ~= index else { return nil }
return self[index]
}
/// SwifterSwift: 在索引位置安全地交换值
///
/// [1, 2, 3, 4, 5].safeSwap(from: 3, to: 0) -> [4, 2, 3, 1, 5]
/// ["h", "e", "l", "l", "o"].safeSwap(from: 1, to: 0) -> ["e", "h", "l", "l", "o"]
///
/// - Parameters:
/// - index: index of first element.
/// - otherIndex: index of other element.
public mutating func safeSwap(from index: Int, to otherIndex: Int) {
guard index != otherIndex,
startIndex..<endIndex ~= index,
startIndex..<endIndex ~= otherIndex else { return }
swapAt(index, otherIndex)
}
/// SwifterSwift: 在索引位置交换值
///
/// [1, 2, 3, 4, 5].swap(from: 3, to: 0) -> [4, 2, 3, 1, 5]
/// ["h", "e", "l", "l", "o"].swap(from: 1, to: 0) -> ["e", "h", "l", "l", "o"]
///
/// - Parameters:
/// - index: index of first element.
/// - otherIndex: index of other element.
public mutating func swap(from index: Int, to otherIndex: Int) {
swapAt(index, otherIndex)
}
/// SwifterSwift: 得到满足条件的第一个索引
///
/// [1, 7, 1, 2, 4, 1, 6].firstIndex { $0 % 2 == 0 } -> 3
///
/// - Parameter condition: condition to evaluate each element against.
/// - Returns: first index where the specified condition evaluates to true. (optional)
public func firstIndex(where condition: (Element) throws -> Bool) rethrows -> Int? {
for (index, value) in lazy.enumerated() {
if try condition(value) { return index }
}
return nil
}
/// SwifterSwift: 得到满足条件的最后一个索引
///
/// [1, 7, 1, 2, 4, 1, 8].lastIndex { $0 % 2 == 0 } -> 6
///
/// - Parameter condition: condition to evaluate each element against.
/// - Returns: last index where the specified condition evaluates to true. (optional)
public func lastIndex(where condition: (Element) throws -> Bool) rethrows -> Int? {
for (index, value) in lazy.enumerated().reversed() {
if try condition(value) { return index }
}
return nil
}
/// SwifterSwift: 获取满足条件的所有指标
///
/// [1, 7, 1, 2, 4, 1, 8].indices(where: { $0 == 1 }) -> [0, 2, 5]
///
/// - Parameter condition: condition to evaluate each element against.
/// - Returns: all indices where the specified condition evaluates to true. (optional)
public func indices(where condition: (Element) throws -> Bool) rethrows -> [Int]? {
var indicies: [Int] = []
for (index, value) in lazy.enumerated() {
if try condition(value) { indicies.append(index) }
}
return indicies.isEmpty ? nil : indicies
}
/// SwifterSwift: 检查数组中的所有元素是否匹配一个条件
///
/// [2, 2, 4].all(matching: {$0 % 2 == 0}) -> true
/// [1,2, 2, 4].all(matching: {$0 % 2 == 0}) -> false
///
/// - Parameter condition: condition to evaluate each element against.
/// - Returns: true when all elements in the array match the specified condition.
public func all(matching condition: (Element) throws -> Bool) rethrows -> Bool {
return try !contains { try !condition($0) }
}
/// SwifterSwift: 检查数组中是否没有元素匹配条件
///
/// [2, 2, 4].none(matching: {$0 % 2 == 0}) -> false
/// [1, 3, 5, 7].none(matching: {$0 % 2 == 0}) -> true
///
/// - Parameter condition: condition to evaluate each element against.
/// - Returns: true when no elements in the array match the specified condition.
public func none(matching condition: (Element) throws -> Bool) rethrows -> Bool {
return try !contains { try condition($0) }
}
/// SwifterSwift: 最后一个满足条件的元素
///
/// [2, 2, 4, 7].last(where: {$0 % 2 == 0}) -> 4
///
/// - Parameter condition: condition to evaluate each element against.
/// - Returns: the last element in the array matching the specified condition. (optional)
public func last(where condition: (Element) throws -> Bool) rethrows -> Element? {
for element in reversed() {
if try condition(element) { return element }
}
return nil
}
/// SwifterSwift: 基于拒绝条件的过滤元素
///
/// [2, 2, 4, 7].reject(where: {$0 % 2 == 0}) -> [7]
///
/// - Parameter condition: to evaluate the exclusion of an element from the array.
/// - Returns: the array with rejected values filtered from it.
public func reject(where condition: (Element) throws -> Bool) rethrows -> [Element] {
return try filter { return try !condition($0) }
}
/// SwifterSwift: 根据条件获取元素计数
///
/// [2, 2, 4, 7].count(where: {$0 % 2 == 0}) -> 3
///
/// - Parameter condition: condition to evaluate each element against.
/// - Returns: number of times the condition evaluated to true.
public func count(where condition: (Element) throws -> Bool) rethrows -> Int {
var count = 0
for element in self {
if try condition(element) { count += 1 }
}
return count
}
/// SwifterSwift: 以相反的顺序遍历集合。(从右到左)
///
/// [0, 2, 4, 7].forEachReversed({ print($0)}) -> //Order of print: 7,4,2,0
///
/// - Parameter body: a closure that takes an element of the array as a parameter.
public func forEachReversed(_ body: (Element) throws -> Void) rethrows {
try reversed().forEach { try body($0) }
}
/// SwifterSwift: 在条件为真的情况下,调用给定的闭包
///
/// [0, 2, 4, 7].forEach(where: {$0 % 2 == 0}, body: { print($0)}) -> //print: 0, 2, 4
///
/// - Parameters:
/// - condition: condition to evaluate each element against.
/// - body: a closure that takes an element of the array as a parameter.
public func forEach(where condition: (Element) throws -> Bool, body: (Element) throws -> Void) rethrows {
for element in self where try condition(element) {
try body(element)
}
}
/// SwifterSwift: 减少数组,同时返回每个临时组合
///
/// [1, 2, 3].accumulate(initial: 0, next: +) -> [1, 3, 6]
///
/// - Parameters:
/// - initial: initial value.
/// - next: closure that combines the accumulating value and next element of the array.
/// - Returns: an array of the final accumulated value and each interim combination.
public func accumulate<U>(initial: U, next: (U, Element) throws -> U) rethrows -> [U] {
var runningTotal = initial
return try map { element in
runningTotal = try next(runningTotal, element)
return runningTotal
}
}
/// SwifterSwift: 在单个操作中过滤和映射
///
/// [1,2,3,4,5].filtered({ $0 % 2 == 0 }, map: { $0.string }) -> ["2", "4"]
///
/// - Parameters:
/// - isIncluded: condition of inclusion to evaluate each element against.
/// - transform: transform element function to evaluate every element.
/// - Returns: Return an filtered and mapped array.
public func filtered<T>(_ isIncluded: (Element) throws -> Bool, map transform: (Element) throws -> T) rethrows -> [T] {
return try compactMap({
if try isIncluded($0) {
return try transform($0)
}
return nil
})
}
/// SwifterSwift: 在条件为真时保存数组元素
///
/// [0, 2, 4, 7].keep( where: {$0 % 2 == 0}) -> [0, 2, 4]
///
/// - Parameter condition: condition to evaluate each element against.
public mutating func keep(while condition: (Element) throws -> Bool) rethrows {
for (index, element) in lazy.enumerated() {
if try !condition(element) {
self = Array(self[startIndex..<index])
break
}
}
}
/// SwifterSwift: 在条件为真时取数组元素
///
/// [0, 2, 4, 7, 6, 8].take( where: {$0 % 2 == 0}) -> [0, 2, 4]
///
/// - Parameter condition: condition to evaluate each element against.
/// - Returns: All elements up until condition evaluates to false.
public func take(while condition: (Element) throws -> Bool) rethrows -> [Element] {
for (index, element) in lazy.enumerated() {
if try !condition(element) {
return Array(self[startIndex..<index])
}
}
return self
}
/// SwifterSwift: 在条件为真时,跳过数组元素
///
/// [0, 2, 4, 7, 6, 8].skip( where: {$0 % 2 == 0}) -> [6, 8]
///
/// - Parameter condition: condition to evaluate each element against.
/// - Returns: All elements after the condition evaluates to false.
public func skip(while condition: (Element) throws-> Bool) rethrows -> [Element] {
for (index, element) in lazy.enumerated() {
if try !condition(element) {
return Array(self[index..<endIndex])
}
}
return [Element]()
}
/// SwifterSwift: 在条件为真的情况下,使用参数切片的数组来调用闭包
///
/// [0, 2, 4, 7].forEach(slice: 2) { print($0) } -> //print: [0, 2], [4, 7]
/// [0, 2, 4, 7, 6].forEach(slice: 2) { print($0) } -> //print: [0, 2], [4, 7], [6]
///
/// - Parameters:
/// - slice: size of array in each interation.
/// - body: a closure that takes an array of slice size as a parameter.
public func forEach(slice: Int, body: ([Element]) throws -> Void) rethrows {
guard slice > 0, !isEmpty else { return }
var value: Int = 0
while value < count {
try body(Array(self[Swift.max(value, startIndex)..<Swift.min(value + slice, endIndex)]))
value += slice
}
}
/// SwifterSwift: 返回数组长度为“size”的数组。如果数组不能被均匀地分割,最后的部分将是其余的元素
///
/// [0, 2, 4, 7].group(by: 2) -> [[0, 2], [4, 7]]
/// [0, 2, 4, 7, 6].group(by: 2) -> [[0, 2], [4, 7], [6]]
///
/// - Parameters:
/// - size: The size of the slices to be returned.
public func group(by size: Int) -> [[Element]]? {
guard size > 0, !isEmpty else { return nil }
var value: Int = 0
var slices: [[Element]] = []
while value < count {
slices.append(Array(self[Swift.max(value, startIndex)..<Swift.min(value + size, endIndex)]))
value += size
}
return slices
}
/// SwifterSwift: 将数组的元素分组到字典中
///
/// [0, 2, 5, 4, 7].groupByKey { $0%2 ? "evens" : "odds" } -> [ "evens" : [0, 2, 4], "odds" : [5, 7] ]
///
/// - Parameter getKey: Clousure to define the key for each element.
/// - Returns: A dictionary with values grouped with keys.
public func groupByKey<K: Hashable>(keyForValue: (_ element: Element) throws -> K) rethrows -> [K: [Element]] {
var group = [K: [Element]]()
for value in self {
let key = try keyForValue(value)
group[key] = (group[key] ?? []) + [value]
}
return group
}
/// SwifterSwift: 根据谓词将数组分成2个数组
///
/// [0, 1, 2, 3, 4, 5].divided { $0 % 2 == 0 } -> ( [0, 2, 4], [1, 3, 5] )
///
/// - Parameter condition: condition to evaluate each element against.
/// - Returns: Two arrays, the first containing the elements for which the specified condition evaluates to true, the second containing the rest.
public func divided(by condition: (Element) throws -> Bool) rethrows -> (matching: [Element], nonMatching: [Element]) {
//Inspired by: http://ruby-doc.org/core-2.5.0/Enumerable.html#method-i-partition
var matching = [Element]()
var nonMatching = [Element]()
for element in self {
if try condition(element) {
matching.append(element)
} else {
nonMatching.append(element)
}
}
return (matching, nonMatching)
}
/// SwifterSwift: 返回给定位置的一个新的旋转数组
///
/// [1, 2, 3, 4].rotated(by: 1) -> [4,1,2,3]
/// [1, 2, 3, 4].rotated(by: 3) -> [2,3,4,1]
/// [1, 2, 3, 4].rotated(by: -1) -> [2,3,4,1]
///
/// - Parameter places: Number of places that the array be rotated. If the value is positive the end becomes the start, if it negative it's that start becom the end.
/// - Returns: The new rotated array
public func rotated(by places: Int) -> [Element] {
guard places != 0 && places < count else {
return self
}
var array: [Element] = self
if places > 0 {
let range = (array.count - places)..<array.endIndex
let slice = array[range]
array.removeSubrange(range)
array.insert(contentsOf: slice, at: 0)
} else {
let range = array.startIndex..<(places * -1)
let slice = array[range]
array.removeSubrange(range)
array.append(contentsOf: slice)
}
return array
}
/// SwifterSwift: 按指定位置旋转数组
///
/// [1, 2, 3, 4].rotate(by: 1) -> [4,1,2,3]
/// [1, 2, 3, 4].rotate(by: 3) -> [2,3,4,1]
/// [1, 2, 3, 4].rotated(by: -1) -> [2,3,4,1]
///
/// - Parameter places: Number of places that the array should be rotated. If the value is positive the end becomes the start, if it negative it's that start becom the end.
public mutating func rotate(by places: Int) {
self = rotated(by: places)
}
/// SwifterSwift: 洗牌数组。(使用Fisher-Yates算法)
///
/// [1, 2, 3, 4, 5].shuffle() // shuffles array
///
mutating func shuffle() {
guard count > 1 else { return }
for index in startIndex..<endIndex - 1 {
let randomIndex = Int(arc4random_uniform(UInt32(endIndex - index))) + index
if index != randomIndex { swapAt(index, randomIndex) }
}
}
/// SwifterSwift: Shuffled version of array. (Using Fisher-Yates Algorithm)
///
/// [1, 2, 3, 4, 5].shuffled // return a shuffled version from given array e.g. [2, 4, 1, 3, 5].
///
/// - Returns: the array with its elements shuffled.
public func shuffled() -> [Element] {
var array = self
array.shuffle()
return array
}
/// SwifterSwift: Return a sorted array based on an optional keypath.
///
/// - Parameter path: Key path to sort. The key path type must be Comparable.
/// - Parameter ascending: If order must be ascending.
/// - Returns: Sorted array based on keyPath.
public func sorted<T: Comparable>(by path: KeyPath<Element, T?>, ascending: Bool = true) -> [Element] {
return sorted(by: { (lhs, rhs) -> Bool in
guard let lhsValue = lhs[keyPath: path], let rhsValue = rhs[keyPath: path] else { return false }
if ascending {
return lhsValue < rhsValue
}
return lhsValue > rhsValue
})
}
/// SwifterSwift: Return a sorted array based on a keypath.
///
/// - Parameter path: Key path to sort. The key path type must be Comparable.
/// - Parameter ascending: If order must be ascending.
/// - Returns: Sorted array based on keyPath.
public func sorted<T: Comparable>(by path: KeyPath<Element, T>, ascending: Bool = true) -> [Element] {
return sorted(by: { (lhs, rhs) -> Bool in
if ascending {
return lhs[keyPath: path] < rhs[keyPath: path]
}
return lhs[keyPath: path] > rhs[keyPath: path]
})
}
/// SwifterSwift: Sort the array based on an optional keypath.
///
/// - Parameter path: Key path to sort. The key path type must be Comparable.
/// - Parameter ascending: If order must be ascending.
public mutating func sort<T: Comparable>(by path: KeyPath<Element, T?>, ascending: Bool = true) {
self = sorted(by: path, ascending: ascending)
}
/// SwifterSwift: Sort the array based on a keypath.
///
/// - Parameter path: Key path to sort. The key path type must be Comparable.
/// - Parameter ascending: If order must be ascending.
mutating func sort<T: Comparable>(by path: KeyPath<Element, T>, ascending: Bool = true) {
self = sorted(by: path, ascending: ascending)
}
}
// MARK: - Methods (Equatable)
extension Array where Element: Equatable {
/// SwifterSwift: Check if array contains an array of elements.
///
/// [1, 2, 3, 4, 5].contains([1, 2]) -> true
/// [1.2, 2.3, 4.5, 3.4, 4.5].contains([2, 6]) -> false
/// ["h", "e", "l", "l", "o"].contains(["l", "o"]) -> true
///
/// - Parameter elements: array of elements to check.
/// - Returns: true if array contains all given items.
public func contains(_ elements: [Element]) -> Bool {
guard !elements.isEmpty else { return true }
var found = true
for element in elements {
if !contains(element) {
found = false
}
}
return found
}
/// SwifterSwift: All indices of specified item.
///
/// [1, 2, 2, 3, 4, 2, 5].indices(of 2) -> [1, 2, 5]
/// [1.2, 2.3, 4.5, 3.4, 4.5].indices(of 2.3) -> [1]
/// ["h", "e", "l", "l", "o"].indices(of "l") -> [2, 3]
///
/// - Parameter item: item to check.
/// - Returns: an array with all indices of the given item.
public func indices(of item: Element) -> [Int] {
var indices: [Int] = []
for index in startIndex..<endIndex where self[index] == item {
indices.append(index)
}
return indices
}
/// SwifterSwift: Remove all instances of an item from array.
///
/// [1, 2, 2, 3, 4, 5].removeAll(2) -> [1, 3, 4, 5]
/// ["h", "e", "l", "l", "o"].removeAll("l") -> ["h", "e", "o"]
///
/// - Parameter item: item to remove.
public mutating func removeAll(_ item: Element) {
self = filter { $0 != item }
}
/// SwifterSwift: Remove all instances contained in items parameter from array.
///
/// [1, 2, 2, 3, 4, 5].removeAll([2,5]) -> [1, 3, 4]
/// ["h", "e", "l", "l", "o"].removeAll(["l", "h"]) -> ["e", "o"]
///
/// - Parameter items: items to remove.
public mutating func removeAll(_ items: [Element]) {
guard !items.isEmpty else { return }
self = filter { !items.contains($0) }
}
/// SwifterSwift: Remove all duplicate elements from Array.
///
/// [1, 2, 2, 3, 4, 5].removeDuplicates() -> [1, 2, 3, 4, 5]
/// ["h", "e", "l", "l", "o"]. removeDuplicates() -> ["h", "e", "l", "o"]
///
public mutating func removeDuplicates() {
self = reduce(into: [Element]()) {
if !$0.contains($1) {
$0.append($1)
}
}
}
/// SwifterSwift: Return array with all duplicate elements removed.
///
/// [1, 1, 2, 2, 3, 3, 3, 4, 5].duplicatesRemoved() -> [1, 2, 3, 4, 5])
/// ["h", "e", "l", "l", "o"].duplicatesRemoved() -> ["h", "e", "l", "o"])
///
/// - Returns: an array of unique elements.
///
public func duplicatesRemoved() -> [Element] {
return reduce(into: [Element]()) {
if !$0.contains($1) {
$0.append($1)
}
}
}
/// SwifterSwift: First index of a given item in an array.
///
/// [1, 2, 2, 3, 4, 2, 5].firstIndex(of: 2) -> 1
/// [1.2, 2.3, 4.5, 3.4, 4.5].firstIndex(of: 6.5) -> nil
/// ["h", "e", "l", "l", "o"].firstIndex(of: "l") -> 2
///
/// - Parameter item: item to check.
/// - Returns: first index of item in array (if exists).
public func firstIndex(of item: Element) -> Int? {
for (index, value) in lazy.enumerated() where value == item {
return index
}
return nil
}
/// SwifterSwift: Last index of element in array.
///
/// [1, 2, 2, 3, 4, 2, 5].lastIndex(of: 2) -> 5
/// [1.2, 2.3, 4.5, 3.4, 4.5].lastIndex(of: 6.5) -> nil
/// ["h", "e", "l", "l", "o"].lastIndex(of: "l") -> 3
///
/// - Parameter item: item to check.
/// - Returns: last index of item in array (if exists).
public func lastIndex(of item: Element) -> Int? {
for (index, value) in lazy.enumerated().reversed() where value == item {
return index
}
return nil
}
}
| 37.03367 | 176 | 0.530048 |
db73bd233c8a393215c1daac761b7c4d1a5238b3 | 904 | //
// AppThirdPartyLibs.swift
// AppProject
//
// Created by Chamira Fernando on 14/03/2017.
// Copyright © 2017 Making Waves. All rights reserved.
//
import Foundation
//import HockeySDK
class AppThirdPartyLibs {
static func integrateAll() {
AppThirdPartyLibs.integrateHockeyApp()
AppThirdPartyLibs.integrateGooleAnalytics()
}
static func integrateHockeyApp() {
fatalError("Uncomment below code and add hockey App Id, make sure you import HockeySDK")
/*let hockeyId = ""
if hockeyId.characters.count == 0 {
fatalError("Hockey app id must be set at above \(#file) \(#line)")
}
BITHockeyManager.shared().configure(withIdentifier: hockeyId)
// Do some additional configuration if needed here
BITHockeyManager.shared().start()
BITHockeyManager.shared().authenticator.authenticateInstallation()
*/
}
static func integrateGooleAnalytics() {
}
}
| 20.545455 | 90 | 0.720133 |
eb9483d34808df98e0bd152cf174562756aa8447 | 19,211 | //
// This is free and unencumbered software released into the public domain.
//
// Anyone is free to copy, modify, publish, use, compile, sell, or
// distribute this software, either in source code form or as a compiled
// binary, for any purpose, commercial or non-commercial, and by any
// means.
//
// In jurisdictions that recognize copyright laws, the author or authors
// of this software dedicate any and all copyright interest in the
// software to the public domain. We make this dedication for the benefit
// of the public at large and to the detriment of our heirs and
// successors. We intend this dedication to be an overt act of
// relinquishment in perpetuity of all present and future rights to this
// software under copyright law.
//
// 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 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.
//
// For more information, please refer to <https://unlicense.org>
//
//
// ActionKit.swift
// RamySDK
//
// Created by Ahmed Ramy on 10/2/20.
// Copyright © 2020 Ahmed Ramy. All rights reserved.
//
import Foundation
import UIKit
public typealias ActionKitVoidClosure = () -> Void
public typealias ActionKitControlClosure = (UIControl) -> Void
public typealias ActionKitGestureClosure = (UIGestureRecognizer) -> Void
public typealias ActionKitBarButtonItemClosure = (UIBarButtonItem) -> Void
public enum ActionKitClosure {
case noParameters(ActionKitVoidClosure)
case withControlParameter(ActionKitControlClosure)
case withGestureParameter(ActionKitGestureClosure)
case withBarButtonItemParameter(ActionKitBarButtonItemClosure)
}
public enum ActionKitControlType: Hashable {
case control(UIControl, UIControl.Event)
case gestureRecognizer(UIGestureRecognizer, String)
case barButtonItem(UIBarButtonItem)
public func hash(into hasher: inout Hasher) {
switch self {
case let .control(control, controlEvent):
hasher.combine(control)
hasher.combine(controlEvent)
case let .gestureRecognizer(recognizer, name):
hasher.combine(recognizer)
hasher.combine(name)
case let .barButtonItem(barButtonItem):
hasher.combine(barButtonItem)
}
}
}
public func == (lhs: ActionKitControlType, rhs: ActionKitControlType) -> Bool {
switch (lhs, rhs) {
case let (.control(lhsControl, lhsControlEvent), .control(rhsControl, rhsControlEvent)):
return lhsControl.hashValue == rhsControl.hashValue && lhsControlEvent.hashValue == rhsControlEvent.hashValue
case let (.gestureRecognizer(lhsRecognizer, lhsName), .gestureRecognizer(rhsRecognizer, rhsName)):
return lhsRecognizer.hashValue == rhsRecognizer.hashValue && lhsName == rhsName
case let (.barButtonItem(lhsBarButtonItem), .barButtonItem(rhsBarButtonItem)):
return lhsBarButtonItem.hashValue == rhsBarButtonItem.hashValue
default:
return false
}
}
public class ActionKitSingleton {
public static let shared: ActionKitSingleton = ActionKitSingleton()
private init() {}
var gestureRecognizerToName = [UIGestureRecognizer: Set<String>]()
var controlToClosureDictionary = [ActionKitControlType: ActionKitClosure]()
}
// MARK: - UIBarButtonItem actions
extension ActionKitSingleton {
func addBarButtonItemClosure(_ barButtonItem: UIBarButtonItem, closure: ActionKitClosure) {
controlToClosureDictionary[.barButtonItem(barButtonItem)] = closure
}
func removeBarButtonItemClosure(_ barButtonItem: UIBarButtonItem) {
controlToClosureDictionary[.barButtonItem(barButtonItem)] = nil
}
@objc(runBarButtonItem:)
func runBarButtonItem(_ item: UIBarButtonItem) {
if let closure = controlToClosureDictionary[.barButtonItem(item)] {
switch closure {
case let .noParameters(voidClosure):
voidClosure()
case let .withBarButtonItemParameter(barButtonItemClosure):
barButtonItemClosure(item)
default:
assertionFailure("Bar button item closure not found, nor void closure")
}
}
}
}
extension UIBarButtonItem {
public func addClosure(_ closure: @escaping ActionKitVoidClosure) {
ActionKitSingleton.shared.addBarButtonItemClosure(self, closure: .noParameters(closure))
}
public func addItemClosure(_ itemClosure: @escaping ActionKitBarButtonItemClosure) {
ActionKitSingleton.shared.addBarButtonItemClosure(self, closure: .withBarButtonItemParameter(itemClosure))
}
public func clearActionKit() {
ActionKitSingleton.shared.removeBarButtonItemClosure(self)
}
@objc public convenience init(
image: UIImage,
landscapeImagePhone: UIImage? = nil,
style: UIBarButtonItem.Style = .plain,
actionClosure: @escaping ActionKitVoidClosure
) {
self.init(image: image,
landscapeImagePhone: landscapeImagePhone,
style: style,
target: ActionKitSingleton.shared,
action: #selector(ActionKitSingleton.runBarButtonItem(_:)))
addClosure(actionClosure)
}
@objc public convenience init(
title: String,
style: UIBarButtonItem.Style = .plain,
actionClosure: @escaping ActionKitVoidClosure
) {
self.init(title: title,
style: style,
target: ActionKitSingleton.shared,
action: #selector(ActionKitSingleton.runBarButtonItem(_:)))
addClosure(actionClosure)
}
@objc public convenience init(
barButtonSystemItem systemItem: UIBarButtonItem.SystemItem,
actionClosure: @escaping ActionKitVoidClosure
) {
self.init(barButtonSystemItem: systemItem,
target: ActionKitSingleton.shared,
action: #selector(ActionKitSingleton.runBarButtonItem(_:)))
addClosure(actionClosure)
}
@nonobjc
public convenience init(
image: UIImage,
landscapeImagePhone: UIImage? = nil,
style: UIBarButtonItem.Style = .plain,
actionClosure: @escaping ActionKitBarButtonItemClosure
) {
self.init(image: image,
landscapeImagePhone: landscapeImagePhone,
style: style,
target: ActionKitSingleton.shared,
action: #selector(ActionKitSingleton.runBarButtonItem(_:)))
addItemClosure(actionClosure)
}
@nonobjc
public convenience init(
title: String,
style: UIBarButtonItem.Style = .plain,
actionClosure: @escaping ActionKitBarButtonItemClosure
) {
self.init(title: title,
style: style,
target: ActionKitSingleton.shared,
action: #selector(ActionKitSingleton.runBarButtonItem(_:)))
addItemClosure(actionClosure)
}
@nonobjc
public convenience init(
barButtonSystemItem systemItem: UIBarButtonItem.SystemItem,
actionClosure: @escaping ActionKitBarButtonItemClosure
) {
self.init(barButtonSystemItem: systemItem,
target: ActionKitSingleton.shared,
action: #selector(ActionKitSingleton.runBarButtonItem(_:)))
addItemClosure(actionClosure)
}
}
// MARK: - UIControl actions
extension ActionKitSingleton {
func removeAction(_ control: UIControl, controlEvent: UIControl.Event) {
control
.removeTarget(ActionKitSingleton.shared, action: ActionKitSingleton.selectorForControlEvent(controlEvent),
for: controlEvent)
controlToClosureDictionary[.control(control, controlEvent)] = nil
}
func addAction(_ control: UIControl, controlEvent: UIControl.Event, closure: ActionKitClosure) {
controlToClosureDictionary[.control(control, controlEvent)] = closure
}
func runControlEventAction(_ control: UIControl, controlEvent: UIControl.Event) {
if let closure = controlToClosureDictionary[.control(control, controlEvent)] {
switch closure {
case let .noParameters(voidClosure):
voidClosure()
case let .withControlParameter(controlClosure):
controlClosure(control)
default:
assertionFailure("Control event closure not found, nor void closure")
}
}
}
@objc(runTouchDownAction:)
func runTouchDownAction(_ control: UIControl) {
runControlEventAction(control, controlEvent: .touchDown)
}
@objc(runTouchDownRepeatAction:)
func runTouchDownRepeatAction(_ control: UIControl) {
runControlEventAction(control, controlEvent: .touchDownRepeat)
}
@objc(runTouchDagInsideAction:)
func runTouchDragInsideAction(_ control: UIControl) {
runControlEventAction(control, controlEvent: .touchDragInside)
}
@objc(runTouchDragOutsideAction:)
func runTouchDragOutsideAction(_ control: UIControl) {
runControlEventAction(control, controlEvent: .touchDragOutside)
}
@objc(runTouchDragEnterAction:)
func runTouchDragEnterAction(_ control: UIControl) {
runControlEventAction(control, controlEvent: .touchDragEnter)
}
@objc(runTouchDragExitAction:)
func runTouchDragExitAction(_ control: UIControl) {
runControlEventAction(control, controlEvent: .touchDragExit)
}
@objc(runTouchUpInsideAction:)
func runTouchUpInsideAction(_ control: UIControl) {
runControlEventAction(control, controlEvent: .touchUpInside)
}
@objc(runTouchUpOutsideAction:)
func runTouchUpOutsideAction(_ control: UIControl) {
runControlEventAction(control, controlEvent: .touchUpOutside)
}
@objc(runTouchCancelAction:)
func runTouchCancelAction(_ control: UIControl) {
runControlEventAction(control, controlEvent: .touchCancel)
}
@objc(runValueChangedAction:)
func runValueChangedAction(_ control: UIControl) {
runControlEventAction(control, controlEvent: .valueChanged)
}
@objc(runPrimaryActionTriggeredAction:)
func runPrimaryActionTriggeredAction(_ control: UIControl) {
runControlEventAction(control, controlEvent: .primaryActionTriggered)
}
@objc(runEditingDidBeginAction:)
func runEditingDidBeginAction(_ control: UIControl) {
runControlEventAction(control, controlEvent: .editingDidBegin)
}
@objc(runEditingChangedAction:)
func runEditingChangedAction(_ control: UIControl) {
runControlEventAction(control, controlEvent: .editingChanged)
}
@objc(runEditingDidEndAction:)
func runEditingDidEndAction(_ control: UIControl) {
runControlEventAction(control, controlEvent: .editingDidEnd)
}
@objc(runEditingDidEndOnExit:)
func runEditingDidEndOnExitAction(_ control: UIControl) {
runControlEventAction(control, controlEvent: .editingDidEndOnExit)
}
@objc(runAllTouchEvents:)
func runAllTouchEventsAction(_ control: UIControl) {
runControlEventAction(control, controlEvent: .allTouchEvents)
}
@objc(runAllEditingEventsAction:)
func runAllEditingEventsAction(_ control: UIControl) {
runControlEventAction(control, controlEvent: .allEditingEvents)
}
@objc(runApplicationReservedAction:)
func runApplicationReservedAction(_ control: UIControl) {
runControlEventAction(control, controlEvent: .applicationReserved)
}
@objc(runSystemReservedAction:)
func runSystemReservedAction(_ control: UIControl) {
runControlEventAction(control, controlEvent: .systemReserved)
}
@objc(runAllEventsAction:)
func runAllEventsAction(_ control: UIControl) {
runControlEventAction(control, controlEvent: .allEvents)
}
@objc(runDefaultAction:)
func runDefaultAction(_ control: UIControl) {
runControlEventAction(control, controlEvent: .init(rawValue: 0))
}
fileprivate static func selectorForControlEvent(_ controlEvent: UIControl.Event) -> Selector {
switch controlEvent {
case .touchDown:
return #selector(ActionKitSingleton.runTouchDownAction(_:))
case .touchDownRepeat:
return #selector(ActionKitSingleton.runTouchDownRepeatAction(_:))
case .touchDragInside:
return #selector(ActionKitSingleton.runTouchDragInsideAction(_:))
case .touchDragOutside:
return #selector(ActionKitSingleton.runTouchDragOutsideAction(_:))
case .touchDragEnter:
return #selector(ActionKitSingleton.runTouchDragEnterAction(_:))
case .touchDragExit:
return #selector(ActionKitSingleton.runTouchDragExitAction(_:))
case .touchUpInside:
return #selector(ActionKitSingleton.runTouchUpInsideAction(_:))
case .touchUpOutside:
return #selector(ActionKitSingleton.runTouchUpOutsideAction(_:))
case .touchCancel:
return #selector(ActionKitSingleton.runTouchCancelAction(_:))
case .valueChanged:
return #selector(ActionKitSingleton.runValueChangedAction(_:))
case .primaryActionTriggered:
return #selector(ActionKitSingleton.runPrimaryActionTriggeredAction(_:))
case .editingDidBegin:
return #selector(ActionKitSingleton.runEditingDidBeginAction(_:))
case .editingChanged:
return #selector(ActionKitSingleton.runEditingChangedAction(_:))
case .editingDidEnd:
return #selector(ActionKitSingleton.runEditingDidEndAction(_:))
case .editingDidEndOnExit:
return #selector(ActionKitSingleton.runEditingDidEndOnExitAction(_:))
case .allTouchEvents:
return #selector(ActionKitSingleton.runAllTouchEventsAction(_:))
case .allEditingEvents:
return #selector(ActionKitSingleton.runAllEditingEventsAction(_:))
case .applicationReserved:
return #selector(ActionKitSingleton.runApplicationReservedAction(_:))
case .systemReserved:
return #selector(ActionKitSingleton.runSystemReservedAction(_:))
case .allEvents:
return #selector(ActionKitSingleton.runAllEventsAction(_:))
default:
return #selector(ActionKitSingleton.runDefaultAction(_:))
}
}
}
extension UIControl.Event: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(rawValue)
}
public static var allValues: [UIControl.Event] {
return [.touchDown, .touchDownRepeat, .touchDragInside, .touchDragOutside, .touchDragEnter,
.touchDragExit, .touchUpInside, .touchUpOutside, .touchCancel, .valueChanged,
.primaryActionTriggered, .editingDidBegin, .editingChanged, .editingDidEnd,
.editingDidEndOnExit, .allTouchEvents, .allEditingEvents, .applicationReserved,
.systemReserved, .allEvents]
}
}
extension UIControl {
open override func removeFromSuperview() {
clearActionKit()
super.removeFromSuperview()
}
public func clearActionKit() {
for eventType in UIControl.Event.allValues {
let closure = ActionKitSingleton.shared.controlToClosureDictionary[.control(self, eventType)]
if closure != nil {
ActionKitSingleton.shared.removeAction(self, controlEvent: eventType)
}
}
}
@objc public func removeControlEvent(_ controlEvent: UIControl.Event) {
ActionKitSingleton.shared.removeAction(self, controlEvent: controlEvent)
}
@objc public func addControlEvent(
_ controlEvent: UIControl.Event,
_ controlClosure: @escaping ActionKitControlClosure
) {
addTarget(ActionKitSingleton.shared, action: ActionKitSingleton.selectorForControlEvent(controlEvent),
for: controlEvent)
ActionKitSingleton.shared
.addAction(self, controlEvent: controlEvent, closure: .withControlParameter(controlClosure))
}
@nonobjc
public func addControlEvent(_ controlEvent: UIControl.Event, _ closure: @escaping ActionKitVoidClosure) {
addTarget(ActionKitSingleton.shared, action: ActionKitSingleton.selectorForControlEvent(controlEvent),
for: controlEvent)
ActionKitSingleton.shared.addAction(self, controlEvent: controlEvent, closure: .noParameters(closure))
}
@nonobjc
public func setControlEvent(_ controlEvent: UIControl.Event, _ closure: @escaping ActionKitVoidClosure) {
removeControlEvent(controlEvent)
addTarget(ActionKitSingleton.shared, action: ActionKitSingleton.selectorForControlEvent(controlEvent),
for: controlEvent)
ActionKitSingleton.shared.addAction(self, controlEvent: controlEvent, closure: .noParameters(closure))
}
}
// MARK: - UIGestureRecognizer actions
extension ActionKitSingleton {
func addGestureClosure(_ gesture: UIGestureRecognizer, name: String, closure: ActionKitClosure) {
let set: Set<String>? = gestureRecognizerToName[gesture]
var newSet: Set<String>
if let nonOptSet = set {
newSet = nonOptSet
} else {
newSet = Set<String>()
}
newSet.insert(name)
gestureRecognizerToName[gesture] = newSet
controlToClosureDictionary[.gestureRecognizer(gesture, name)] = closure
}
func canRemoveGesture(_ gesture: UIGestureRecognizer, _ name: String) -> Bool {
if let _ = controlToClosureDictionary[.gestureRecognizer(gesture, name)] {
return true
} else {
return false
}
}
func removeGesture(_ gesture: UIGestureRecognizer, name: String) {
if canRemoveGesture(gesture, name) {
controlToClosureDictionary[.gestureRecognizer(gesture, name)] = nil
}
}
@objc(runGesture:)
func runGesture(_ gesture: UIGestureRecognizer) {
for gestureName in gestureRecognizerToName[gesture] ?? Set<String>() {
if let closure = controlToClosureDictionary[.gestureRecognizer(gesture, gestureName)] {
switch closure {
case let .noParameters(voidClosure):
voidClosure()
case let .withGestureParameter(gestureClosure):
gestureClosure(gesture)
default:
assertionFailure("Gesture closure not found, nor void closure")
}
}
}
}
}
public extension UIGestureRecognizer {
var actionKitNames: Set<String>? {
get { return ActionKitSingleton.shared.gestureRecognizerToName[self] } set {}
}
}
extension UIGestureRecognizer {
public func clearActionKit() {
let gestureRecognizerNames = ActionKitSingleton.shared.gestureRecognizerToName[self]
ActionKitSingleton.shared.gestureRecognizerToName[self] = nil
for gestureRecognizerName in gestureRecognizerNames ?? Set<String>() {
ActionKitSingleton.shared.removeGesture(self, name: gestureRecognizerName)
}
}
@objc public convenience init(_ name: String = .empty, _ gestureClosure: @escaping ActionKitGestureClosure) {
self.init(target: ActionKitSingleton.shared, action: #selector(ActionKitSingleton.runGesture(_:)))
addClosure(name, gestureClosure: gestureClosure)
}
@nonobjc
public convenience init(_ name: String = .empty, _ closure: @escaping ActionKitVoidClosure) {
self.init(target: ActionKitSingleton.shared, action: #selector(ActionKitSingleton.runGesture(_:)))
addClosure(name, closure: closure)
}
public func addClosure(_ name: String, gestureClosure: @escaping ActionKitGestureClosure) {
ActionKitSingleton.shared.addGestureClosure(self, name: name, closure: .withGestureParameter(gestureClosure))
}
public func addClosure(_ name: String, closure: @escaping ActionKitVoidClosure) {
ActionKitSingleton.shared.addGestureClosure(self, name: name, closure: .noParameters(closure))
}
public func removeClosure(_ name: String) {
ActionKitSingleton.shared.removeGesture(self, name: name)
}
}
| 36.043152 | 113 | 0.745458 |
3869636870637b8fe0ee974cbed8f6f198c2152b | 8,143 | //
// MovieDetailsViewController.swift
// Flicks
//
// Created by Anup Kher on 3/31/17.
// Copyright © 2017 codepath. All rights reserved.
//
import UIKit
import MBProgressHUD
class MovieDetailsViewController: UIViewController {
@IBOutlet weak var bigPosterImageView: UIImageView!
@IBOutlet weak var movieDetailsView: UIView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var releaseDateLabel: UILabel!
@IBOutlet weak var scoreLabel: UILabel!
@IBOutlet weak var runningTimeLabel: UILabel!
@IBOutlet weak var overviewLabel: UILabel!
@IBOutlet weak var scrollView: UIScrollView!
var errorView: ErrorView!
let defaults = UserDefaults.standard
var movieId: Int!
var movie: NSDictionary = [:]
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(colorLiteralRed: 239/255.0, green: 203/255.0, blue: 104/255, alpha: 1.0)
let contentWidth = scrollView.bounds.width
let contentHeight = scrollView.bounds.height * 1.15
scrollView.contentSize = CGSize(width: contentWidth, height: contentHeight)
getMovieDetails(id: movieId)
errorView = ErrorView(frame: CGRect(x: 0, y: 80, width: view.bounds.width, height: 60))
errorView.backgroundColor = UIColor(white: 0.0, alpha: 0.8)
view.addSubview(errorView)
errorView.isHidden = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - TMDB API Helper Methods
func getMovieDetails(id: Int) {
let urlString = "https://api.themoviedb.org/3/movie/\(id)?api_key=0bae87a1c2bc3fd65e17a82fec52d5c7&language=en-US"
let url = URL(string: urlString)
let request = URLRequest(url: url!)
let session = URLSession(configuration: .default, delegate: nil, delegateQueue: OperationQueue.main)
MBProgressHUD.showAdded(to: self.view, animated: true)
let task: URLSessionDataTask = session.dataTask(with: request) {
(data, response, error) in
MBProgressHUD.hide(for: self.view, animated: true)
if let data = data {
self.errorView.isHidden = true
if let movie = try! JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary {
if let posterPath = movie.value(forKeyPath: "poster_path") as? String {
let smallImageRequest = URLRequest(url: URL(string: "https://image.tmdb.org/t/p/w45/\(posterPath)")!)
let largeImageRequest = URLRequest(url: URL(string: "https://image.tmdb.org/t/p/original/\(posterPath)")!)
self.bigPosterImageView.setImageWith(
smallImageRequest,
placeholderImage: nil,
success: { (smallImageRequest, smallImageResponse, smallImage) in
self.errorView.isHidden = true
if (response != nil) {
self.bigPosterImageView.alpha = 0.0
self.bigPosterImageView.image = smallImage
UIView.animate(
withDuration: 0.3,
animations: {
self.bigPosterImageView.alpha = 1.0
}, completion: { (success) in
self.bigPosterImageView.setImageWith(
largeImageRequest,
placeholderImage: smallImage,
success: { (largeImageRequest, largeImageResponse, largeImage) in
self.errorView.isHidden = true
self.bigPosterImageView.image = largeImage
}, failure: { (request, response, error) in
self.errorView.isHidden = false
})
})
} else {
self.bigPosterImageView.image = smallImage
}
}, failure: { (request, response, error) in
self.errorView.isHidden = false
})
}
if let title = movie.value(forKeyPath: "original_title") as? String {
self.navigationItem.title = title
self.titleLabel.text = title
}
if let release = movie.value(forKeyPath: "release_date") as? String {
self.releaseDateLabel.text = self.getFormattedDate(string: release)
}
if let score = movie.value(forKeyPath: "vote_average") as? Float {
if let percentageScore = Int(exactly: (score / 10.0) * 100.0) {
self.scoreLabel.text = "\(percentageScore)%"
}
}
if let running = movie.value(forKeyPath: "runtime") as? Int {
let hours = running / 60
let minutes = running % 60
self.runningTimeLabel.text = "\(hours) hr \(minutes) mins"
}
if let overview = movie.value(forKeyPath: "overview") as? String {
self.overviewLabel.text = overview
self.overviewLabel.sizeToFit()
}
}
}
if let error = error {
print(error)
self.errorView.isHidden = false
}
}
task.resume()
}
func getFormattedDate(string: String) -> String {
var formattedDate = ""
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let calendar = Calendar(identifier: .gregorian)
if let date = dateFormatter.date(from: string) {
let components = calendar.dateComponents([.day, .month, .year], from: date)
if let day = components.day, let month = components.month, let year = components.year {
var fullMonth = ""
switch month {
case 1:
fullMonth = "January"
case 2:
fullMonth = "February"
case 3:
fullMonth = "March"
case 4:
fullMonth = "April"
case 5:
fullMonth = "May"
case 6:
fullMonth = "June"
case 7:
fullMonth = "July"
case 8:
fullMonth = "August"
case 9:
fullMonth = "September"
case 10:
fullMonth = "October"
case 11:
fullMonth = "November"
case 12:
fullMonth = "December"
default:
fullMonth = ""
}
formattedDate = "\(fullMonth) \(day), \(year)"
}
}
return formattedDate
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 41.758974 | 130 | 0.490974 |
cc652d8679468840daac6b3b4e6d5958ec41b0bc | 2,173 | //
// AppDelegate.swift
// YKSearchTextFieldTest
//
// Created by xiezuan on 16/12/20.
// Copyright © 2016年 xz. 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.234043 | 285 | 0.756098 |
1495243507a6e2dfc39df3be9ae7ff2d864336db | 395 | //
// Created by Mengyu Li on 2020/12/25.
//
import Foundation
import MachOParser
/// Architecture-erased protocol for 32/64 ObjC images
protocol ObjcImage {
func getObjectsFromList<Element>(section list: Section?, creator: (Int) -> Element) -> [Element]
func create(offset: Int) -> ObjcClass
func create(offset: Int) -> ObjcCategory
func create(offset: Int) -> ObjcProtocol
}
| 26.333333 | 100 | 0.711392 |
6177723b3aac779bf86ecaf574f409f0226c5817 | 1,755 | //
// SquareStyleViewController.swift
// AutoCompleteTextFieldExample
//
// Created by Jacob Mendelowitz on 11/3/18.
// Copyright © 2018 Jacob Mendelowitz. All rights reserved.
//
import UIKit
import AutoCompleteTextField
class SquareStyleViewController: UIViewController {
@IBOutlet private var autoCompleteTextField: AutoCompleteTextField!
private let dataSource = ["One", "One Two", "One Two Three", "One Two Three Four", "One Two Three Four Five", "One Two Three Four Six"]
override func viewDidLoad() {
super.viewDidLoad()
setupAutoCompleteTextField()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setTransparentNavigationBar(withTint: .black)
navigationItem.setLeftBarButton(
UIBarButtonItem(title: "Back", style: .plain, target: self, action: #selector(backButtonPressed(_:))), animated: false
)
}
private func setupAutoCompleteTextField() {
autoCompleteTextField.load(dataSource: dataSource)
autoCompleteTextField.shouldShowResultList = true
autoCompleteTextField.shouldShowInlineAutoCompletion = true
autoCompleteTextField.maxResultCount = 15
autoCompleteTextField.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 8, height: autoCompleteTextField.frame.height))
autoCompleteTextField.leftViewMode = .always
autoCompleteTextField.rightView = UIView(frame: CGRect(x: 0, y: 0, width: 8, height: autoCompleteTextField.frame.height))
autoCompleteTextField.rightViewMode = .always
}
@objc private func backButtonPressed(_ sender: UIBarButtonItem) {
navigationController?.popViewController(animated: true)
}
}
| 39 | 139 | 0.724786 |
398e7640ae2c7a22ce1d71ccd3230a313740568b | 1,903 | //
// AmberControllerHelper.swift
// TrainBrain
//
// Created by Nikita Arkhipov on 09.10.2017.
// Copyright © 2017 Nikita Arkhipov. All rights reserved.
//
import UIKit
extension AmberPresentable{
public static func instantiate() -> Self{
let sb = UIStoryboard(name: storyboardFile, bundle: nil)
guard let vc = sb.instantiateViewController(withIdentifier: storyboardID) as? Self else { fatalError() }
return vc
}
}
extension UIViewController: AmberPresenter{
public func push(_ viewController: UIViewController, animated: Bool){
navigationController?.pushViewController(viewController, animated: animated)
}
public func embedIn(view: UIView, container: UIViewController){
self.view.frame = view.bounds
container.addChildViewController(self)
view.addSubview(self.view)
didMove(toParentViewController: container)
}
public func show(_ viewController: UIViewController, animated: Bool){
if navigationController != nil { push(viewController, animated: true) }
else { present(viewController, animated: true, completion: nil) }
}
public func close(animated: Bool){
if let nav = navigationController{ nav.popViewController(animated: animated) }
else if parent != nil { unembed() }
else{ dismiss(animated: animated, completion: nil) }
}
public func dismiss(animated: Bool) {
dismiss(animated: animated, completion: nil)
}
public func pop(animated: Bool){
navigationController?.popViewController(animated: animated)
}
public func popToRoot(animated: Bool){
navigationController?.popToRootViewController(animated: animated)
}
private func unembed(){
removeFromParentViewController()
view.removeFromSuperview()
didMove(toParentViewController: nil)
}
}
| 31.716667 | 112 | 0.683132 |
4621477b4ac905725c288bd82816f1efc08d0207 | 924 | //
// File.swift
//
//
// Created by Jesulonimi on 5/1/21.
//
import Foundation
public class DryrunTxnResult :Codable {
public var appCallMessages:[String]?
public var appCallTrace:[DryrunState]?
/**
* Disassembled program line by line.
*/
public var disassembly:[String]?
/**
* Application state delta.
*/
public var globalDelta:[EvalDeltaKeyValue]?
public var localDeltas:[AccountStateDelta]?
public var logicSigMessages:[String]?
public var logicSigTrace: [DryrunState]?
enum CodingKeys:String,CodingKey{
case appCallMessages = "app-call-messages"
case disassembly = "disassembly"
case globalDelta = "global-delta"
case localDeltas = "local-deltas"
case logicSigMessages = "logic-sig-messages"
case logicSigTrace = "logic-sig-trace"
case appCallTrace = "app-call-trace"
}
}
| 18.857143 | 52 | 0.642857 |
9137bd7aa6326cc62571227a93b5c884e43d51a3 | 1,657 | //
// TimeConstants.swift
// WolfFoundation
//
// Created by Wolf McNally on 7/10/17.
//
// 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 let nanosecondsPerSecond = 1_000_000_000.0
public let millisecondsPerSecond = 1_000.0
public let minutesPerHour = 60.0
public let hoursPerDay = 24.0
public let minutesPerDay = minutesPerHour * hoursPerDay
public let daysPerWeek = 7.0
public let oneSecond: TimeInterval = 1.0
public let oneMinute: TimeInterval = 60 * oneSecond
public let oneHour: TimeInterval = oneMinute * minutesPerHour
public let oneDay: TimeInterval = oneMinute * minutesPerDay
| 42.487179 | 82 | 0.767049 |
1cf11c868deb4e5fd8a036ef5e52ef8f6d52a300 | 224 | // RUN: %target-swift-emit-silgen %s -disable-objc-attr-requires-foundation-module -enable-sil-ownership
// REQUIRES: objc_interop
@objc protocol Unrelated {}
@objc class C {}
let c = C()
let unrelated = c as! Unrelated
| 20.363636 | 104 | 0.723214 |
dead41b7d98de900e7738801e3ff1c697d6c1204 | 532 | //
// CAAnimation+Extension.swift
// Demo
//
// Created by 中澤 郁斗 on 2018/05/16.
// Copyright © 2018年 中澤 郁斗. All rights reserved.
//
import QuartzCore
extension CAAnimation {
func configure(delay: Double, duration: Double, timingFunction: TimingFunction, isRemovedOnCompletion: Bool = false) {
self.beginTime = delay
self.duration = duration
self.timingFunction = timingFunction.rawValue
self.fillMode = kCAFillModeForwards
self.isRemovedOnCompletion = isRemovedOnCompletion
}
}
| 26.6 | 122 | 0.703008 |
01fa425768c1a33125652983cd6e89bafe8e6d5b | 1,511 | //
// Email_Login_PageUITests.swift
// Email Login PageUITests
//
// Created by Nguyen Viet Tien on 8/19/20.
// Copyright © 2020 Nguyen Viet Tien. All rights reserved.
//
import XCTest
class Email_Login_PageUITests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// UI tests must launch the application that they test.
let app = XCUIApplication()
app.launch()
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testLaunchPerformance() throws {
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) {
// This measures how long it takes to launch your application.
measure(metrics: [XCTOSSignpostMetric.applicationLaunch]) {
XCUIApplication().launch()
}
}
}
}
| 34.340909 | 182 | 0.665784 |
878808046d0867f883aa0382f61f83a3ac00e7a5 | 221 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
import Foundation
struct B<T where T: P
}
[B( ) ( )
| 24.555556 | 87 | 0.737557 |
c1b7bd69aef264a28b1aa5321241359094bc6771 | 2,570 | //
// EditTable.swift
// MDTableView
//
// Created by Leo on 2017/6/15.
// Copyright © 2017年 Leo Huang. All rights reserved.
//
import UIKit
public protocol EditableRow {
var titleForDeleteConfirmationButton:String? {get}
var editingStyle:UITableViewCell.EditingStyle {get}
var canMove:Bool{ get }
//These are optional
var shouldIndentWhileEditing:Bool { get }
var canEdit:Bool {get}
var editActionsForRowAt:(UITableView, IndexPath)->[UITableViewRowAction]? {get}
}
extension EditableRow{
public var shouldIndentWhileEditing:Bool {return true}
public var canEdit:Bool { return true}
public var canMove:Bool{ return false }
public var editActionsForRowAt:(UITableView, IndexPath)->[UITableViewRowAction]? {
return { (_,_) in
return nil
}
}
}
public protocol Editor{
var editingStyleCommitForRowAt:(UITableView,UITableViewCell.EditingStyle,IndexPath)->Void {get}
//These are optional
var moveRowAtSourceIndexPathToDestinationIndexPath:(UITableView, IndexPath, IndexPath)->Void{ get }
var targetIndexPathForMoveFromTotoProposedIndexPath:(UITableView, IndexPath, IndexPath) ->IndexPath {get}
var willBeginEditingRowAt:(UITableView, IndexPath) -> Void {get}
var didEndEditingRowAt:(UITableView, IndexPath?) -> Void {get}
}
extension Editor{
public var willBeginEditingRowAt:(UITableView, IndexPath) -> Void{
return {(_,_) in}
}
public var didEndEditingRowAt:(UITableView, IndexPath?) -> Void{
return {(_,_) in}
}
public var targetIndexPathForMoveFromTotoProposedIndexPath:(UITableView, IndexPath, IndexPath) ->IndexPath{
return {(_,_,proposedDestinationIndexPath) in
return proposedDestinationIndexPath;
}
}
public var moveRowAtSourceIndexPathToDestinationIndexPath:(UITableView, IndexPath, IndexPath) ->Void{
return {(_,_,proposedDestinationIndexPath) in }
}
}
open class TableEditor:Editor{
public var editingStyleCommitForRowAt: (UITableView, UITableViewCell.EditingStyle, IndexPath) -> Void
public var willBeginEditingRowAt:(UITableView, IndexPath) -> Void
public var didEndEditingRowAt:(UITableView, IndexPath?) -> Void
public var moveRowAtSourceIndexPathToDestinationIndexPath:(UITableView, IndexPath, IndexPath)->Void
public init(){
editingStyleCommitForRowAt = { (_,_,_) in}
moveRowAtSourceIndexPathToDestinationIndexPath = { (_,_,_) in}
willBeginEditingRowAt = {(_,_) in}
didEndEditingRowAt = {(_,_) in}
}
}
| 35.205479 | 111 | 0.71751 |
69f4492b7bb12a9dd00d7fcaafe2935bd5e51114 | 2,174 | import SourceKittenFramework
public struct LastWhereRule: CallPairRule, OptInRule, ConfigurationProviderRule, AutomaticTestableRule {
public var configuration = SeverityConfiguration(.warning)
public init() {}
public static let description = RuleDescription(
identifier: "last_where",
name: "Last Where",
description: "Prefer using `.last(where:)` over `.filter { }.last` in collections.",
kind: .performance,
minSwiftVersion: .fourDotTwo,
nonTriggeringExamples: [
Example("kinds.filter(excludingKinds.contains).isEmpty && kinds.last == .identifier\n"),
Example("myList.last(where: { $0 % 2 == 0 })\n"),
Example("match(pattern: pattern).filter { $0.last == .identifier }\n"),
Example("(myList.filter { $0 == 1 }.suffix(2)).last\n"),
Example("collection.filter(\"stringCol = '3'\").last")
],
triggeringExamples: [
Example("↓myList.filter { $0 % 2 == 0 }.last\n"),
Example("↓myList.filter({ $0 % 2 == 0 }).last\n"),
Example("↓myList.map { $0 + 1 }.filter({ $0 % 2 == 0 }).last\n"),
Example("↓myList.map { $0 + 1 }.filter({ $0 % 2 == 0 }).last?.something()\n"),
Example("↓myList.filter(someFunction).last\n"),
Example("↓myList.filter({ $0 % 2 == 0 })\n.last\n"),
Example("(↓myList.filter { $0 == 1 }).last\n")
]
)
public func validate(file: SwiftLintFile) -> [StyleViolation] {
return validate(file: file,
pattern: "[\\}\\)]\\s*\\.last",
patternSyntaxKinds: [.identifier],
callNameSuffix: ".filter",
severity: configuration.severity) { dictionary in
if !dictionary.substructure.isEmpty {
return true // has a substructure, like a closure
}
guard let bodyRange = dictionary.bodyByteRange else {
return true
}
let syntaxKinds = file.syntaxMap.kinds(inByteRange: bodyRange)
return !syntaxKinds.contains(.string)
}
}
}
| 42.627451 | 104 | 0.550138 |
eb01bab56fa07f0a11f8930377a905405c5f053a | 2,147 | //
// WWExamVC.swift
// WWDC
//
// Created by Maxim Eremenko on 3/26/17.
// Copyright © 2017 Maxim Eremenko. All rights reserved.
//
import UIKit
enum WWExamResult : Int {
case Success
case Fail
}
class WWExamVC: WWChildVC {
let contentView = WWExamView()
let controller = WWExamController()
override func loadView() {
self.view = contentView
}
override func viewDidLoad() {
super.viewDidLoad()
self.configureModule()
}
}
private extension WWExamVC {
func checkRightPage() {
let currentPage = self.controller.currentPage()
let isSwift = currentPage == WWExamType.Swift.rawValue
if isSwift {
self.controller.update(page: currentPage, withResult: .Success)
let delay = WWPhotoCellConstants.animationDuration + 0.3
DispatchBlockAfter(delay: delay, block: {
self.presentLetterController()
})
}
else {
self.controller.update(page: currentPage, withResult: .Fail)
}
}
func presentLetterController() {
let letterVC = WWLetterVC()
letterVC.modalPresentationStyle = .overFullScreen
letterVC.updateWith(nextBlock: {
self.dismiss(animated: true, completion: {
DispatchBlockAfter(delay: 0.3, block: {
WWSceneRouter.current.presentScreenWith(sceneType: .Trip)
})
})
})
self.present(letterVC, animated: true, completion: nil)
}
}
private extension WWExamVC {
func configureModule() {
let models = WWExamBuilder.createExamModels()
self.controller.attach(collectionView: self.contentView.collectionView)
self.controller.updateWith(examModels: models)
self.controller.updateWith { (page: Int) in
self.contentView.update(currentPage: page)
}
self.contentView.update(numberOfPages: models.count)
self.contentView.updateWith {
self.checkRightPage()
}
}
}
| 24.965116 | 79 | 0.59292 |
167e1a2ab13315b7527d04fd4b5e1a5233b55e3c | 1,610 | //
// ID3TrackPositionCreator.swift
//
// Created by Fabrizio Duroni on 08/03/2018.
// 2018 Fabrizio Duroni.
//
import Foundation
class ID3TrackPositionFrameCreator: ID3FrameCreatorsChain {
private let frameCreator: FrameFromStringContentCreator
private var id3FrameConfiguration: ID3FrameConfiguration
init(frameCreator: FrameFromStringContentCreator, id3FrameConfiguration: ID3FrameConfiguration) {
self.frameCreator = frameCreator
self.id3FrameConfiguration = id3FrameConfiguration
}
override func createFrames(id3Tag: ID3Tag, tag: [UInt8]) -> [UInt8] {
if let trackPosition = id3Tag.trackPosition {
let newTag = tag +
frameCreator.createFrame(
frameIdentifier: id3FrameConfiguration.identifierFor(
frameType: .TrackPosition,
version: id3Tag.properties.version
),
version: id3Tag.properties.version,
content: adapt(trackPosition: trackPosition)
)
return super.createFrames(id3Tag: id3Tag, tag: newTag)
}
return super.createFrames(id3Tag: id3Tag, tag: tag)
}
private func adapt(trackPosition: TrackPositionInSet) -> String {
var trackPositionString = String(trackPosition.position)
if let validTotalTracks = trackPosition.totalTracks {
trackPositionString = trackPositionString + "/\(validTotalTracks)"
}
return trackPositionString
}
}
| 37.44186 | 101 | 0.629814 |
edcbe747a25c0d81b94e5240b13543f5cde1e004 | 4,330 | //
// UIView+Anchors.swift
// Pods
//
// Created by Brian Voong on 11/16/16.
//
//
import UIKit
extension UIView {
public func addConstraintsWithFormat(_ format: String, views: UIView...) {
var viewsDictionary = [String: UIView]()
for (index, view) in views.enumerated() {
let key = "v\(index)"
viewsDictionary[key] = view
view.translatesAutoresizingMaskIntoConstraints = false
}
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: format, options: NSLayoutFormatOptions(), metrics: nil, views: viewsDictionary))
}
public func fillSuperview() {
translatesAutoresizingMaskIntoConstraints = false
if let superview = superview {
if #available(iOS 9.0, *) {
leftAnchor.constraint(equalTo: superview.leftAnchor).isActive = true
rightAnchor.constraint(equalTo: superview.rightAnchor).isActive = true
topAnchor.constraint(equalTo: superview.topAnchor).isActive = true
bottomAnchor.constraint(equalTo: superview.bottomAnchor).isActive = true
} else {
// Fallback on earlier versions
}
}
}
@available(iOS 9.0, *)
public func anchor(_ top: NSLayoutYAxisAnchor? = nil, left: NSLayoutXAxisAnchor? = nil, bottom: NSLayoutYAxisAnchor? = nil, right: NSLayoutXAxisAnchor? = nil, topConstant: CGFloat = 0, leftConstant: CGFloat = 0, bottomConstant: CGFloat = 0, rightConstant: CGFloat = 0, widthConstant: CGFloat = 0, heightConstant: CGFloat = 0) {
translatesAutoresizingMaskIntoConstraints = false
_ = anchorWithReturnAnchors(top, left: left, bottom: bottom, right: right, topConstant: topConstant, leftConstant: leftConstant, bottomConstant: bottomConstant, rightConstant: rightConstant, widthConstant: widthConstant, heightConstant: heightConstant)
}
@available(iOS 9.0, *)
public func anchorWithReturnAnchors(_ top: NSLayoutYAxisAnchor? = nil, left: NSLayoutXAxisAnchor? = nil, bottom: NSLayoutYAxisAnchor? = nil, right: NSLayoutXAxisAnchor? = nil, topConstant: CGFloat = 0, leftConstant: CGFloat = 0, bottomConstant: CGFloat = 0, rightConstant: CGFloat = 0, widthConstant: CGFloat = 0, heightConstant: CGFloat = 0) -> [NSLayoutConstraint] {
translatesAutoresizingMaskIntoConstraints = false
var anchors = [NSLayoutConstraint]()
if let top = top {
anchors.append(topAnchor.constraint(equalTo: top, constant: topConstant))
}
if let left = left {
anchors.append(leftAnchor.constraint(equalTo: left, constant: leftConstant))
}
if let bottom = bottom {
anchors.append(bottomAnchor.constraint(equalTo: bottom, constant: -bottomConstant))
}
if let right = right {
anchors.append(rightAnchor.constraint(equalTo: right, constant: -rightConstant))
}
if widthConstant > 0 {
anchors.append(widthAnchor.constraint(equalToConstant: widthConstant))
}
if heightConstant > 0 {
anchors.append(heightAnchor.constraint(equalToConstant: heightConstant))
}
anchors.forEach({$0.isActive = true})
return anchors
}
public func anchorCenterXToSuperview(constant: CGFloat = 0) {
translatesAutoresizingMaskIntoConstraints = false
if #available(iOS 9.0, *) {
if let anchor = superview?.centerXAnchor {
centerXAnchor.constraint(equalTo: anchor, constant: constant).isActive = true
}
} else {
// Fallback on earlier versions
}
}
public func anchorCenterYToSuperview(constant: CGFloat = 0) {
translatesAutoresizingMaskIntoConstraints = false
if #available(iOS 9.0, *) {
if let anchor = superview?.centerYAnchor {
centerYAnchor.constraint(equalTo: anchor, constant: constant).isActive = true
}
} else {
// Fallback on earlier versions
}
}
public func anchorCenterSuperview() {
anchorCenterXToSuperview()
anchorCenterYToSuperview()
}
}
| 40.092593 | 372 | 0.631409 |
91bf57a97dbc3cf23f606e9c1e1669368762ac57 | 8,243 | //
// QRRSBlock.swift
// EFQRCode
//
// Created by Apollo Zhu on 12/27/17.
//
// Copyright (c) 2017 EyreFree <[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.
#if os(iOS) || os(tvOS) || os(macOS)
#else
struct QRRSBlock {
let totalCount: Int
let dataCount: Int
}
extension QRRSBlock {
fileprivate static let RS_BLOCK_TABLE: [[Int]] = [
[1, 26, 19],
[1, 26, 16],
[1, 26, 13],
[1, 26, 9],
[1, 44, 34],
[1, 44, 28],
[1, 44, 22],
[1, 44, 16],
[1, 70, 55],
[1, 70, 44],
[2, 35, 17],
[2, 35, 13],
[1, 100, 80],
[2, 50, 32],
[2, 50, 24],
[4, 25, 9],
[1, 134, 108],
[2, 67, 43],
[2, 33, 15, 2, 34, 16],
[2, 33, 11, 2, 34, 12],
[2, 86, 68],
[4, 43, 27],
[4, 43, 19],
[4, 43, 15],
[2, 98, 78],
[4, 49, 31],
[2, 32, 14, 4, 33, 15],
[4, 39, 13, 1, 40, 14],
[2, 121, 97],
[2, 60, 38, 2, 61, 39],
[4, 40, 18, 2, 41, 19],
[4, 40, 14, 2, 41, 15],
[2, 146, 116],
[3, 58, 36, 2, 59, 37],
[4, 36, 16, 4, 37, 17],
[4, 36, 12, 4, 37, 13],
[2, 86, 68, 2, 87, 69],
[4, 69, 43, 1, 70, 44],
[6, 43, 19, 2, 44, 20],
[6, 43, 15, 2, 44, 16],
[4, 101, 81],
[1, 80, 50, 4, 81, 51],
[4, 50, 22, 4, 51, 23],
[3, 36, 12, 8, 37, 13],
[2, 116, 92, 2, 117, 93],
[6, 58, 36, 2, 59, 37],
[4, 46, 20, 6, 47, 21],
[7, 42, 14, 4, 43, 15],
[4, 133, 107],
[8, 59, 37, 1, 60, 38],
[8, 44, 20, 4, 45, 21],
[12, 33, 11, 4, 34, 12],
[3, 145, 115, 1, 146, 116],
[4, 64, 40, 5, 65, 41],
[11, 36, 16, 5, 37, 17],
[11, 36, 12, 5, 37, 13],
[5, 109, 87, 1, 110, 88],
[5, 65, 41, 5, 66, 42],
[5, 54, 24, 7, 55, 25],
[11, 36, 12],
[5, 122, 98, 1, 123, 99],
[7, 73, 45, 3, 74, 46],
[15, 43, 19, 2, 44, 20],
[3, 45, 15, 13, 46, 16],
[1, 135, 107, 5, 136, 108],
[10, 74, 46, 1, 75, 47],
[1, 50, 22, 15, 51, 23],
[2, 42, 14, 17, 43, 15],
[5, 150, 120, 1, 151, 121],
[9, 69, 43, 4, 70, 44],
[17, 50, 22, 1, 51, 23],
[2, 42, 14, 19, 43, 15],
[3, 141, 113, 4, 142, 114],
[3, 70, 44, 11, 71, 45],
[17, 47, 21, 4, 48, 22],
[9, 39, 13, 16, 40, 14],
[3, 135, 107, 5, 136, 108],
[3, 67, 41, 13, 68, 42],
[15, 54, 24, 5, 55, 25],
[15, 43, 15, 10, 44, 16],
[4, 144, 116, 4, 145, 117],
[17, 68, 42],
[17, 50, 22, 6, 51, 23],
[19, 46, 16, 6, 47, 17],
[2, 139, 111, 7, 140, 112],
[17, 74, 46],
[7, 54, 24, 16, 55, 25],
[34, 37, 13],
[4, 151, 121, 5, 152, 122],
[4, 75, 47, 14, 76, 48],
[11, 54, 24, 14, 55, 25],
[16, 45, 15, 14, 46, 16],
[6, 147, 117, 4, 148, 118],
[6, 73, 45, 14, 74, 46],
[11, 54, 24, 16, 55, 25],
[30, 46, 16, 2, 47, 17],
[8, 132, 106, 4, 133, 107],
[8, 75, 47, 13, 76, 48],
[7, 54, 24, 22, 55, 25],
[22, 45, 15, 13, 46, 16],
[10, 142, 114, 2, 143, 115],
[19, 74, 46, 4, 75, 47],
[28, 50, 22, 6, 51, 23],
[33, 46, 16, 4, 47, 17],
[8, 152, 122, 4, 153, 123],
[22, 73, 45, 3, 74, 46],
[8, 53, 23, 26, 54, 24],
[12, 45, 15, 28, 46, 16],
[3, 147, 117, 10, 148, 118],
[3, 73, 45, 23, 74, 46],
[4, 54, 24, 31, 55, 25],
[11, 45, 15, 31, 46, 16],
[7, 146, 116, 7, 147, 117],
[21, 73, 45, 7, 74, 46],
[1, 53, 23, 37, 54, 24],
[19, 45, 15, 26, 46, 16],
[5, 145, 115, 10, 146, 116],
[19, 75, 47, 10, 76, 48],
[15, 54, 24, 25, 55, 25],
[23, 45, 15, 25, 46, 16],
[13, 145, 115, 3, 146, 116],
[2, 74, 46, 29, 75, 47],
[42, 54, 24, 1, 55, 25],
[23, 45, 15, 28, 46, 16],
[17, 145, 115],
[10, 74, 46, 23, 75, 47],
[10, 54, 24, 35, 55, 25],
[19, 45, 15, 35, 46, 16],
[17, 145, 115, 1, 146, 116],
[14, 74, 46, 21, 75, 47],
[29, 54, 24, 19, 55, 25],
[11, 45, 15, 46, 46, 16],
[13, 145, 115, 6, 146, 116],
[14, 74, 46, 23, 75, 47],
[44, 54, 24, 7, 55, 25],
[59, 46, 16, 1, 47, 17],
[12, 151, 121, 7, 152, 122],
[12, 75, 47, 26, 76, 48],
[39, 54, 24, 14, 55, 25],
[22, 45, 15, 41, 46, 16],
[6, 151, 121, 14, 152, 122],
[6, 75, 47, 34, 76, 48],
[46, 54, 24, 10, 55, 25],
[2, 45, 15, 64, 46, 16],
[17, 152, 122, 4, 153, 123],
[29, 74, 46, 14, 75, 47],
[49, 54, 24, 10, 55, 25],
[24, 45, 15, 46, 46, 16],
[4, 152, 122, 18, 153, 123],
[13, 74, 46, 32, 75, 47],
[48, 54, 24, 14, 55, 25],
[42, 45, 15, 32, 46, 16],
[20, 147, 117, 4, 148, 118],
[40, 75, 47, 7, 76, 48],
[43, 54, 24, 22, 55, 25],
[10, 45, 15, 67, 46, 16],
[19, 148, 118, 6, 149, 119],
[18, 75, 47, 31, 76, 48],
[34, 54, 24, 34, 55, 25],
[20, 45, 15, 61, 46, 16]
]
}
extension QRErrorCorrectLevel {
func getRSBlocksOfType(_ typeNumber: Int) -> [QRRSBlock] {
let rsBlock = getRsBlockTableOfType(typeNumber)
let length = rsBlock.count / 3
var list = [QRRSBlock]()
for i in 0..<length {
let count = rsBlock[i * 3 + 0]
let totalCount = rsBlock[i * 3 + 1]
let dataCount = rsBlock[i * 3 + 2]
for _ in 0..<count {
list.append(QRRSBlock(totalCount: totalCount, dataCount: dataCount))
}
}
return list
}
private func getRsBlockTableOfType(_ typeNumber: Int) -> [Int] {
switch (self) {
case .L:
return QRRSBlock.RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 0]
case .M:
return QRRSBlock.RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 1]
case .Q:
return QRRSBlock.RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 2]
case .H:
return QRRSBlock.RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 3]
}
}
}
#endif
| 35.995633 | 88 | 0.396458 |
f52ba819dcc562a47a8a3c8b6c0f194a0be3a6c1 | 1,649 | //
// Observable.swift
// VKContest
//
// Created by Anton Schukin on 11/11/2018.
// Copyright © 2018 Anton Shchukin. All rights reserved.
//
import Foundation
public class Observable<T> {
private var _value: T
public init(_ value: T) {
self._value = value
}
public var value: T {
get {
return _value
}
set {
self.setValue(newValue)
}
}
public func setValue(_ value: T) {
let oldValue = self._value
self._value = value
for observer in self.observers {
observer.closure(oldValue, self.value)
}
}
public func observe(_ closure: @escaping (_ old: T, _ new: T) -> Void) -> AnyObject {
let observer = Observer(closure: closure)
self.observers.append(observer)
return ObserverWrapper(observer: observer, onDeinit: { [weak self] observer in
self?.removeObserver(observer)
})
}
fileprivate func removeObserver(_ observer: Observer<T>) {
self.observers = self.observers.filter { $0 !== observer }
}
private lazy var observers = [Observer<T>]()
}
private class Observer<T> {
let closure: (_ old: T, _ new: T) -> Void
init (closure: @escaping (_ old: T, _ new: T) -> Void) {
self.closure = closure
}
}
private class ObserverWrapper<T> {
let observer: Observer<T>
let onDeinit: (Observer<T>) -> Void
init(observer: Observer<T>, onDeinit: @escaping (Observer<T>) -> Void) {
self.observer = observer
self.onDeinit = onDeinit
}
deinit {
self.onDeinit(self.observer)
}
}
| 22.902778 | 89 | 0.588235 |
e60edf9febec0fa551578be3d6f0be84db94c4ee | 3,575 | import Combine
import Foundation
public enum HTTPRequestDispatcherError: LocalizedError, FatalError {
case urlSessionError(Error)
case parseError(Error)
case invalidResponse
case serverSideError(Error, HTTPURLResponse)
// MARK: - LocalizedError
public var errorDescription: String? { description }
// MARK: - FatalError
public var description: String {
switch self {
case let .urlSessionError(error):
if let error = error as? LocalizedError {
return error.localizedDescription
} else {
return "Received a session error."
}
case let .parseError(error):
if let error = error as? LocalizedError {
return error.localizedDescription
} else {
return "Error parsing the network response."
}
case .invalidResponse: return "Received unexpected response from the network."
case let .serverSideError(error, response):
let url: URL = response.url!
if let error = error as? LocalizedError {
return """
Error returned by the server:
- URL: \(url.absoluteString)
- Code: \(response.statusCode)
- Description: \(error.localizedDescription)
"""
} else {
return """
Error returned by the server:
- URL: \(url.absoluteString)
- Code: \(response.statusCode)
"""
}
}
}
public var type: ErrorType {
switch self {
case .urlSessionError: return .bug
case .parseError: return .abort
case .invalidResponse: return .bug
case .serverSideError: return .bug
}
}
}
public protocol HTTPRequestDispatching {
func dispatch<T, E: Error>(resource: HTTPResource<T, E>) async throws -> (object: T, response: HTTPURLResponse)
}
public final class HTTPRequestDispatcher: HTTPRequestDispatching {
let session: URLSession
public init(session: URLSession = URLSession.shared) {
self.session = session
}
public func dispatch<T, E: Error>(resource: HTTPResource<T, E>) async throws -> (object: T, response: HTTPURLResponse) {
do {
let (data, response) = try await session.data(for: resource.request())
guard let response = response as? HTTPURLResponse else {
throw HTTPRequestDispatcherError.invalidResponse
}
switch response.statusCode {
case 200 ..< 300:
do {
let object = try resource.parse(data, response)
return (object: object, response: response)
} catch {
throw HTTPRequestDispatcherError.parseError(error)
}
default: // Error
let thrownError: Error
do {
let parsedError = try resource.parseError(data, response)
thrownError = HTTPRequestDispatcherError.serverSideError(parsedError, response)
} catch {
thrownError = HTTPRequestDispatcherError.parseError(error)
}
throw thrownError
}
} catch {
if error is HTTPRequestDispatcherError {
throw error
} else {
throw HTTPRequestDispatcherError.urlSessionError(error)
}
}
}
}
| 34.375 | 124 | 0.558881 |
f79506336968248f03f0413a57835263a3d00843 | 18,320 | //
// CollectCreditCardDataViewController.swift
// Spacy Food
//
// Created by Dima on 18.03.2020.
// Copyright © 2020 Very Good Security. All rights reserved.
//
import Foundation
import UIKit
import VGSCollectSDK
/// An object that store secured card data details
struct SecuredCardData {
/// Sensitive data aliases
let cardNumberAlias: String
let cvcAlias: String
let expDataAlias: String
/// Available Card number details that you can reuse in the app
var cardNumberBin: String = ""
var cardNumberLast4: String = ""
var cardBrand: String = ""
}
/// Your organization <vaultId>
let vaultId = "vaultId"
class CollectCreditCardDataViewController: UIViewController {
@IBOutlet weak var cardDataStackView: UIStackView!
@IBOutlet weak var bluredBackground: UIVisualEffectView!
@IBOutlet weak var containerViewBottomConstraint: NSLayoutConstraint!
@IBOutlet weak var cardFieldsContainerView: UIView!
/// Init VGS Collector
///
/// - Parameters:
///
/// - id: your organization vaultid
/// - environment: your organization environment
///
var collector = VGSCollect(id: vaultId, environment: .sandbox)
// VGSCollectSDK UI Elements
var cardHolderName = VGSTextField()
var cardNumber = VGSCardTextField()
var cardExpDate = VGSExpDateTextField()
var cardCVCNumber = VGSTextField()
var scanController: VGSCardScanController?
// Helpers
var isKeyboardVisible = false
var maxLevel = 0 as CGFloat
var initialTouchPoint = CGPoint.zero
var onCompletion: ((SecuredCardData) -> Void )?
override func viewDidLoad() {
super.viewDidLoad()
/// Add UI elements to ViewController
arrangeTextFields()
/// Setup UI attributes and configuration
setupTextFieldConfigurations()
/// Update and edit payment card brands
updatePaymentCardBrands()
addGestureRecognizer()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
cardFieldsContainerView.addGradient(UIColor.lightBlueColorsSet)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
cardNumber.becomeFirstResponder()
}
// MARK: - Arrange Textfields
private func arrangeTextFields() {
cardDataStackView.addArrangedSubview(cardHolderName)
cardDataStackView.addArrangedSubview(cardNumber)
let scanButton = UIButton()
scanButton.setImage(UIImage(named: "scan_icon.png"), for: .normal)
scanButton.imageView?.contentMode = .scaleAspectFit
scanButton.imageEdgeInsets = .init(top: 5, left: 10, bottom: 5, right: 10)
scanButton.addTarget(self, action: #selector(scan), for: .touchUpInside)
let bottomStackView = UIStackView.init(arrangedSubviews: [cardExpDate, cardCVCNumber, scanButton])
bottomStackView.axis = .horizontal
bottomStackView.alignment = .fill
bottomStackView.distribution = .fillEqually
bottomStackView.spacing = 20
cardDataStackView.addArrangedSubview(bottomStackView)
}
private func setupTextFieldConfigurations() {
let placeholderColor = UIColor(white: 1, alpha: 0.8)
// MARK: - Card Number Field
/// Init card number field configuration with VGSCollect instance.
let cardConfiguration = VGSConfiguration(collector: collector, fieldName: "card_number")
/// Setup field type. For each specific FieldType built-in validation, default text format and other specific attributes will be applied.
cardConfiguration.type = .cardNumber
/// Set input should be .isRequiredValidOnly = true. Then user couldn't send card number that is not valid. VGSCollect.sendData(_:) will return specific VGSError in that case.
cardConfiguration.isRequiredValidOnly = true
/// Set preffered keyboard color
cardConfiguration.keyboardAppearance = .dark
/// Enable unknown card brands validation with Luhn algorithm
cardConfiguration.validationRules = VGSValidationRuleSet(rules: [
VGSValidationRulePaymentCard.init(error: VGSValidationErrorType.cardNumber.rawValue, validateUnknownCardBrand: true)
])
/// Set configuration instance to textfield that will collect card number
cardNumber.configuration = cardConfiguration
/// Setup UI attributes
cardNumber.attributedPlaceholder = NSAttributedString(string: "4111 1111 1111 1111", attributes: [NSAttributedString.Key.foregroundColor: placeholderColor])
// MARK: - Card Expiration Date Field
/// Set expiration data field configuration with same collector but specific fieldName
let expDateConfiguration = VGSConfiguration(collector: collector, fieldName: "card_expirationDate")
/// Set input .isRequired = true if you need textfield input be not empty or nil. Then user couldn't send expiration date that is empty or nil. VGSCollect.sendData(_:) will return specific VGSError in that case.
expDateConfiguration.isRequired = true
expDateConfiguration.type = .expDate
expDateConfiguration.keyboardAppearance = .light
cardExpDate.configuration = expDateConfiguration
/// Add keyboard accessory view on top of UIPicker to handle actions
cardExpDate.keyboardAccessoryView = makeAccessoryView()
cardExpDate.attributedPlaceholder = NSAttributedString(string: "11/22", attributes: [NSAttributedString.Key.foregroundColor: placeholderColor])
cardExpDate.textAlignment = .center
// MARK: - Card CVC Field
/// Set cvc data field configuration with same collector but specific fieldName
let cvcConfiguration = VGSConfiguration(collector: collector, fieldName: "card_cvc")
cvcConfiguration.isRequired = true
cvcConfiguration.type = .cvc
cvcConfiguration.keyboardAppearance = .dark
cardCVCNumber.configuration = cvcConfiguration
cardCVCNumber.isSecureTextEntry = true
cardCVCNumber.attributedPlaceholder = NSAttributedString(string: "CVC", attributes: [NSAttributedString.Key.foregroundColor: placeholderColor])
cardCVCNumber.textAlignment = .center
// MARK: - Card Holder Name Field
/// Set cvc data field configuration with same collector but specific fieldName
let cardHolderConfiguration = VGSConfiguration(collector: collector, fieldName: "cardholder_name")
cardHolderConfiguration.type = .cardHolderName
cardHolderConfiguration.keyboardAppearance = .dark
cardHolderName.configuration = cardHolderConfiguration
cardHolderName.attributedPlaceholder = NSAttributedString(string: "Cardholder Name", attributes: [NSAttributedString.Key.foregroundColor: placeholderColor])
// MARK: - Set Fields UI attributes
collector.textFields.forEach({
$0.textColor = .white
$0.tintColor = .white
$0.font = UIFont.systemFont(ofSize: 22)
$0.padding = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
$0.delegate = self
})
}
/// Update and edit card brands. NOTE: this can be done once in AppDelegate
func updatePaymentCardBrands() {
/// Edit default card brand validation rules
VGSPaymentCards.visa.cardNumberLengths = [16]
VGSPaymentCards.visa.formatPattern = "#### #### #### ####"
/// Add custom brand - Spacy Master. Test with "911 11111111 1111" number.
let customCardBrandModel = VGSCustomPaymentCardModel(name: "Spacy Master",
regex: "^91\\d*$",
formatPattern: "### ######## ####",
cardNumberLengths: [15],
cvcLengths: [3, 4],
checkSumAlgorithm: .luhn,
brandIcon: UIImage(named: "spacy_master"))
VGSPaymentCards.cutomPaymentCardModels.append(customCardBrandModel)
}
//MARK: - Card Scan
@objc func scan() {
/// Init and present card.io scanner. If scanned data is valid it will be set automatically into VGSTextFields, you should implement VGSCardIOScanControllerDelegate for this.
scanController = VGSCardScanController(apiKey: "YOUR_API_KET", delegate: self)
scanController?.presentCardScanner(on: self, animated: true, completion: nil)
}
//MARK: - Send Data
/// Send sensetive data to VGS and get alieses.
@IBAction func save(_ sender: Any) {
/// Before sending data to VGS, you should probably want to check if it's valid.
let notValidFields = collector.textFields.filter({ $0.state.isValid == false })
if notValidFields.count > 0 {
notValidFields.forEach({
$0.borderColor = .red
print($0.state.validationErrors)
})
return
}
/// Also you can grab not sensetive data form CardState attribures
let cardState = cardNumber.state as? CardState
let bin = cardState?.bin ?? ""
let last4 = cardState?.last4 ?? ""
let brand = cardState?.cardBrand.stringValue ?? ""
/// Add any additional data to request
let extraData = ["customData": "customValue",
"cardBrand": brand]
/**
Send data to VGS
For this demo app we send data to our echo server.
The data goes through VGS Inpound proxy, where you have your Routs setup.
When the data reach VGS Inpound proxy, fields with sensitive data will be redacted to aliases, which you can store and use securely later.
Our echo server will return response with same body structure as you send, but fields will have aliases as values instead of original data.
However in your production app on sendData(_:) request, the data will go through VGS Inpound proxy to your backend or any other url that you configure in your Organization vault. It's your backend responsibility to setup response structure.
Check our Documentation to know more about Sending data to VGS: https://www.verygoodsecurity.com/docs/vgs-collect/ios-sdk/submit-data ,
and Inbound connections: https://www.verygoodsecurity.com/docs/guides/inbound-connection
*/
collector.sendData(path: "/post", extraData: extraData, completion: { [weak self](result) in
/// Check response. If success, you should get aliases data that you can use later or store on your backend.
/// If you see raw(not tokenized) data in response - check the Routs configuration for Inbound requests on Dashboard.
switch result {
case .success(let code, let data, _):
print("Success: \(code)")
/// Parse response from echo server
guard let data = data,
let jsonData = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any],
let cardDataDict = jsonData["json"] as? [String: Any],
let cardNumberAlias = cardDataDict["card_number"] as? String,
let cvcAlias = cardDataDict["card_cvc"] as? String,
let expDataAlias = cardDataDict["card_expirationDate"] as? String else {
self?.showAlert(title: "Error", text: "Somethin went wrong!")
return
}
let cardData = SecuredCardData(cardNumberAlias: cardNumberAlias, cvcAlias: cvcAlias, expDataAlias: expDataAlias, cardNumberBin: bin, cardNumberLast4: last4, cardBrand: brand)
self?.onCompletion?(cardData)
self?.dismiss(animated: false, completion: nil)
case .failure(let code, _, _, let error):
switch code {
case 400..<499:
// Wrong request. This also can happend when your Routs not setup yet or your <vaultId> is wrong
self?.showAlert(title: "Error - \(code)", text: "Wrong request!")
case VGSErrorType.inputDataIsNotValid.rawValue:
if let error = error as? VGSError {
self?.showAlert(title: "Error - \(code)", text: "Input data is not valid. Details:\n \(error)")
}
default:
self?.showAlert(title: "Error - \(code)", text: "Somethin went wrong!")
}
print("Failure: \(code)")
}
})
}
}
// MARK: - VGSTextFieldDelegate
/// Handle VGSTextField Delegate funtions
extension CollectCreditCardDataViewController: VGSTextFieldDelegate {
/// Check active vgs textfield's state when editing the field
func vgsTextFieldDidChange(_ textField: VGSTextField) {
textField.borderColor = .white
print(textField.state.description)
}
}
// MARK: - VGSCardIOScanControllerDelegate
/// Handle Card Scanning Delegate
extension CollectCreditCardDataViewController: VGSCardScanControllerDelegate {
/// Set in which VGSTextField scanned data with type should be set. Called after user select Done button, just before userDidFinishScan() delegate.
func textFieldForScannedData(type: CradScanDataType) -> VGSTextField? {
switch type {
case .cardNumber:
return cardNumber
case .expirationDate:
return cardExpDate
case .name:
return cardHolderName
default:
return nil
}
}
/// Handle Cancel button action on Card.io screen
func userDidCancelScan() {
scanController?.dismissCardScanner(animated: true, completion: nil)
}
/// Handle Done button action on Card.io screen
func userDidFinishScan() {
scanController?.dismissCardScanner(animated: true, completion: { [weak self] in
self?.cardCVCNumber.becomeFirstResponder()
})
}
}
// MARK: - Helpers
extension CollectCreditCardDataViewController {
func addGestureRecognizer() {
let gestureRecognizer = UIPanGestureRecognizer(target: self,
action: #selector(panGestureRecognizerHandler(_:)))
self.view.addGestureRecognizer(gestureRecognizer)
}
@IBAction func panGestureRecognizerHandler(_ sender: UIPanGestureRecognizer) {
let touchPoint = sender.location(in: self.view?.window)
switch sender.state {
case .began:
initialTouchPoint = touchPoint
case .changed:
if touchPoint.y - initialTouchPoint.y > 0 {
changeContainerPosition(touchPoint.y - initialTouchPoint.y)
}
self.bluredBackground.alpha = 0.8 * initialTouchPoint.y / touchPoint.y
case .ended, .cancelled:
if touchPoint.y - initialTouchPoint.y > 100 {
self.view.endEditing(true)
UIView.animate(withDuration: 0.1, animations: {
self.containerViewBottomConstraint.constant = -100
self.bluredBackground.alpha = 0
self.view.layoutIfNeeded()
}) { (bool) in
self.dismiss(animated: false, completion: nil)
}
} else {
//to original
containerViewBottomConstraint.constant = maxLevel
view.layoutIfNeeded()
self.bluredBackground.alpha = 0.8
}
default:
return
}
}
@objc func keyboardWillShow(notification: NSNotification) {
guard isKeyboardVisible == false else {
return
}
isKeyboardVisible = true
let userInfo = notification.userInfo
if let info = userInfo, let kbRect = (info[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
let height = kbRect.size.height - 40.0
self.maxLevel = height
self.containerViewBottomConstraint.constant = height
UIView.animate(withDuration: 4, delay: 0, options: .curveEaseOut, animations: {
self.bluredBackground.alpha = 0.9
self.view.layoutIfNeeded()
}, completion: nil)
}
}
func changeContainerPosition(_ delta: CGFloat) {
containerViewBottomConstraint.constant = maxLevel - delta
view.layoutIfNeeded()
}
func makeAccessoryView() -> UIView {
let view = UIView(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 44))
view.backgroundColor = UIColor(red: 0.03, green: 0.04, blue: 0.09, alpha: 0.5)
let doneButton = UIButton(type: .system)
doneButton.setTitle("Next", for: .normal)
doneButton.setTitleColor(.white, for: .normal)
doneButton.addTarget(self, action: #selector(expDateButtonAction), for: .touchUpInside)
view.addSubview(doneButton)
doneButton.translatesAutoresizingMaskIntoConstraints = false
let views = ["button": doneButton]
let h = NSLayoutConstraint.constraints(withVisualFormat: "H:|-(>=15)-[button]-(15)-|",
options: .alignAllCenterY,
metrics: nil,
views: views)
NSLayoutConstraint.activate(h)
let v = NSLayoutConstraint.constraints(withVisualFormat: "V:|[button]|",
options: .alignAllCenterX,
metrics: nil,
views: views)
NSLayoutConstraint.activate(v)
return view
}
@objc func expDateButtonAction() {
self.cardCVCNumber.becomeFirstResponder()
}
}
| 43.72315 | 248 | 0.63226 |
919d5c45b8c257e508ec6d1c79474e47a0658cd7 | 2,011 | /*****************************************************************************************************************************//**
* PROJECT: Executor
* FILENAME: _GCDExecutor.swift
* IDE: AppCode
* AUTHOR: Galen Rhodes
* DATE: July 27, 2021
*
* Permission to use, copy, modify, and distribute this software for any purpose with or without fee is hereby granted, provided
* that the above copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
* CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*//*****************************************************************************************************************************/
import Foundation
import CoreFoundation
import Rubicon
class _GCDExecutor<R>: _ExecutorBase<R> {
private lazy var queue: DispatchQueue = getQueue()
private var current: [Future<R>] = []
override func localShutdown() {
for f in current { f.cancel() }
current.removeAll()
}
func getQueue() -> DispatchQueue { DispatchQueue(label: uuid, qos: .userInitiated, attributes: [ .concurrent ], autoreleaseFrequency: .workItem) }
override func exec(callable c: @escaping Callable<R>) -> Future<R> {
let f = Future<R>(callable: c)
current <+ f
queue.async {
f.execute()
self.remove(f)
}
return f
}
private func remove(_ future: Future<R>) { lock.withLock { current.removeAll { $0 === future } } }
static func == (lhs: _GCDExecutor, rhs: _GCDExecutor) -> Bool { lhs === rhs }
}
| 43.717391 | 150 | 0.593237 |
ac23f0f83d4e5a47caae6135d03188fc7ac56e58 | 6,868 | import KsApi
import Library
import Prelude
import UIKit
internal final class PaymentMethodsViewController: UIViewController, MessageBannerViewControllerPresenting {
private let dataSource = PaymentMethodsDataSource()
private let viewModel: PaymentMethodsViewModelType = PaymentMethodsViewModel()
@IBOutlet private var tableView: UITableView!
fileprivate lazy var editButton: UIBarButtonItem = {
UIBarButtonItem(
title: Strings.discovery_favorite_categories_buttons_edit(),
style: .plain,
target: self,
action: #selector(edit)
)
}()
internal var messageBannerViewController: MessageBannerViewController?
public static func instantiate() -> PaymentMethodsViewController {
return Storyboard.Settings.instantiate(PaymentMethodsViewController.self)
}
override func viewDidLoad() {
super.viewDidLoad()
self.messageBannerViewController = self.configureMessageBannerViewController(on: self)
self.tableView.register(nib: .CreditCardCell)
self.tableView.dataSource = self.dataSource
self.tableView.delegate = self
self.configureHeaderFooterViews()
self.navigationItem.rightBarButtonItem = self.editButton
self.editButton.possibleTitles = [
Strings.discovery_favorite_categories_buttons_edit(),
Strings.Done()
]
self.dataSource.deletionHandler = { [weak self] creditCard in
self?.viewModel.inputs.didDelete(creditCard, visibleCellCount: self?.tableView.visibleCells.count ?? 0)
}
self.viewModel.inputs.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.viewModel.inputs.viewWillAppear()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.tableView.ksr_sizeHeaderFooterViewsToFit()
}
override func bindStyles() {
super.bindStyles()
_ = self
|> settingsViewControllerStyle
|> UIViewController.lens.title %~ { _ in
Strings.Payment_methods()
}
_ = self.tableView
|> tableViewStyle
|> tableViewSeparatorStyle
}
override func bindViewModel() {
super.bindViewModel()
self.editButton.rac.enabled = self.viewModel.outputs.editButtonIsEnabled
self.viewModel.outputs.paymentMethods
.observeForUI()
.observeValues { [weak self] result in
self?.dataSource.load(creditCards: result)
self?.tableView.reloadData()
}
self.viewModel.outputs.reloadData
.observeForUI()
.observeValues { [weak self] in
self?.tableView.reloadData()
}
self.viewModel.outputs.goToAddCardScreenWithIntent
.observeForUI()
.observeValues { [weak self] intent in
self?.goToAddCardScreen(with: intent)
}
self.viewModel.outputs.errorLoadingPaymentMethods
.observeForUI()
.observeValues { [weak self] message in
self?.messageBannerViewController?.showBanner(with: .error, message: message)
}
self.viewModel.outputs.presentBanner
.observeForUI()
.observeValues { [weak self] message in
self?.messageBannerViewController?.showBanner(with: .success, message: message)
}
self.viewModel.outputs.tableViewIsEditing
.observeForUI()
.observeValues { [weak self] isEditing in
self?.tableView.setEditing(isEditing, animated: true)
}
self.viewModel.outputs.showAlert
.observeForControllerAction()
.observeValues { [weak self] message in
self?.present(UIAlertController.genericError(message), animated: true)
}
self.viewModel.outputs.editButtonTitle
.observeForUI()
.observeValues { [weak self] title in
_ = self?.editButton
?|> \.title %~ { _ in title }
}
}
// MARK: - Actions
@objc private func edit() {
self.viewModel.inputs.editButtonTapped()
}
private func goToAddCardScreen(with intent: AddNewCardIntent) {
let vc = AddNewCardViewController.instantiate()
vc.configure(with: intent)
vc.delegate = self
let nav = UINavigationController(rootViewController: vc)
nav.modalPresentationStyle = .formSheet
self.present(nav, animated: true) { self.viewModel.inputs.addNewCardPresented() }
}
// MARK: - Private Helpers
private func configureHeaderFooterViews() {
if let header = SettingsTableViewHeader.fromNib(nib: Nib.SettingsTableViewHeader) {
header.configure(with: Strings.Any_payment_methods_you_saved_to_Kickstarter())
let headerContainer = UIView(frame: .zero)
_ = (header, headerContainer) |> ksr_addSubviewToParent()
self.tableView.tableHeaderView = headerContainer
_ = (header, headerContainer) |> ksr_constrainViewToEdgesInParent()
_ = header.widthAnchor.constraint(equalTo: self.tableView.widthAnchor)
|> \.priority .~ .defaultHigh
|> \.isActive .~ true
}
if let footer = PaymentMethodsFooterView.fromNib(nib: Nib.PaymentMethodsFooterView) {
footer.delegate = self
let footerContainer = UIView(frame: .zero)
_ = (footer, footerContainer) |> ksr_addSubviewToParent()
self.tableView.tableFooterView = footerContainer
_ = (footer, footerContainer) |> ksr_constrainViewToEdgesInParent()
_ = footer.widthAnchor.constraint(equalTo: self.tableView.widthAnchor)
|> \.priority .~ .defaultHigh
|> \.isActive .~ true
}
}
}
extension PaymentMethodsViewController: UITableViewDelegate {
func tableView(_: UITableView, heightForFooterInSection _: Int) -> CGFloat {
return 0.1
}
func tableView(_: UITableView, heightForHeaderInSection _: Int) -> CGFloat {
return 0.1
}
}
extension PaymentMethodsViewController: PaymentMethodsFooterViewDelegate {
internal func paymentMethodsFooterViewDidTapAddNewCardButton(_: PaymentMethodsFooterView) {
self.viewModel.inputs.paymentMethodsFooterViewDidTapAddNewCardButton()
}
}
extension PaymentMethodsViewController: AddNewCardViewControllerDelegate {
func addNewCardViewController(
_: AddNewCardViewController,
didAdd _: GraphUserCreditCard.CreditCard,
withMessage message: String
) {
self.dismiss(animated: true) {
self.viewModel.inputs.addNewCardSucceeded(with: message)
}
}
func addNewCardViewControllerDismissed(_: AddNewCardViewController) {
self.dismiss(animated: true) {
self.viewModel.inputs.addNewCardDismissed()
}
}
}
// MARK: - Styles
private let tableViewStyle: TableViewStyle = { (tableView: UITableView) in
tableView
|> \.backgroundColor .~ UIColor.clear
|> \.rowHeight .~ Styles.grid(11)
|> \.allowsSelection .~ false
}
private let tableViewSeparatorStyle: TableViewStyle = { tableView in
tableView
|> \.separatorStyle .~ .singleLine
|> \.separatorColor .~ .ksr_support_300
|> \.separatorInset .~ .init(left: Styles.grid(2))
}
| 29.350427 | 109 | 0.714182 |
8954253118839c1ec72cedde49254164df3fa479 | 274 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
extension NSSet {
enum S {
let end = [ {
init {
{
}
protocol g {
class d {
var d {
func a {
class
case ,
| 16.117647 | 87 | 0.70438 |
750951eae7096dfd1059e90f83e3d50c29ff3059 | 119 | import XCTest
import BunorHTTPTests
var tests = [XCTestCaseEntry]()
tests += BunorHTTPTests.allTests()
XCTMain(tests) | 17 | 34 | 0.789916 |
f7045c0de8a152a2b5452a8f0ab9198bb4d89acd | 2,588 | //
// ViewController.swift
// LxThroughPointsBezier-Swift
//
import UIKit
class ViewController: UIViewController {
let _curve = UIBezierPath()
let _shapeLayer = CAShapeLayer()
var _pointViewArray = [PointView]()
override func viewDidLoad() {
super.viewDidLoad()
let slider = UISlider()
slider.minimumValue = 0
slider.maximumValue = 1.4
slider.value = 0.7
slider.addTarget(self, action: "sliderValueChanged:", forControlEvents: .ValueChanged)
view.addSubview(slider)
slider.setTranslatesAutoresizingMaskIntoConstraints(false)
let sliderHorizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|-[slider]-|", options: .DirectionLeadingToTrailing, metrics: nil, views: ["slider":slider])
let sliderVerticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|-topMargin-[slider(==sliderHeight)]", options: .DirectionLeadingToTrailing, metrics: ["sliderHeight":6, "topMargin":60], views: ["slider":slider])
view.addConstraints(sliderHorizontalConstraints)
view.addConstraints(sliderVerticalConstraints)
var pointArray = [CGPoint]()
for i in 0 ..< 6 {
let pointView = PointView.aInstance()
pointView.center = CGPoint(x: i * 60 + 30, y: 420)
pointView.dragCallBack = { [unowned self] (pointView: PointView) -> Void in
self.sliderValueChanged(slider)
}
view.addSubview(pointView)
_pointViewArray.append(pointView)
pointArray.append(pointView.center)
}
_curve.moveToPoint(_pointViewArray.first!.center)
_curve.addBezierThrough(points: pointArray)
_shapeLayer.strokeColor = UIColor.blueColor().CGColor
_shapeLayer.fillColor = nil
_shapeLayer.lineWidth = 3
_shapeLayer.path = _curve.CGPath
_shapeLayer.lineCap = kCALineCapRound
view.layer.addSublayer(_shapeLayer)
}
func sliderValueChanged(slider: UISlider) {
_curve.removeAllPoints()
_curve.contractionFactor = CGFloat(slider.value)
_curve.moveToPoint(_pointViewArray.first!.center)
var pointArray = [CGPoint]()
for pointView in _pointViewArray {
pointArray.append(pointView.center)
}
_curve.addBezierThrough(points: pointArray)
_shapeLayer.path = _curve.CGPath
}
}
| 33.61039 | 237 | 0.632148 |
f7655b296e9c5a457da33d9d4f2a9e149f6a90cb | 956 | //
// currency_converterTests.swift
// currency-converterTests
//
// Created by WF | Dimitar Zabaznoski on 1/27/19.
// Copyright © 2019 WebFactory. All rights reserved.
//
import XCTest
@testable import currency_converter
class currency_converterTests: XCTestCase {
override func 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.
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 27.314286 | 111 | 0.669456 |
26ed7ea82d3eac6eda496612acd28e6cc1ecbf66 | 3,357 | //
// AudioChangeViewController.swift
// AudioBox
//
// Created by anker on 2022/2/15.
//
import UIKit
class AudioChangeViewController: UIViewController {
enum State {
case Pause
case Playing
}
@IBOutlet weak var slowButton: UIButton!
@IBOutlet weak var fastButton: UIButton!
@IBOutlet weak var pitchUpButton: UIButton!
@IBOutlet weak var pitchDownButton: UIButton!
@IBOutlet weak var echoButton: UIButton!
@IBOutlet weak var reverbButton: UIButton!
private var magician: AudioMagician = AudioMagician()
private let filePath: URL? = {
let path = Bundle.main.url(forResource: "fascinated", withExtension: "aac")
return path
}()
private var playingButton: UIButton?
private var currentState: State = .Pause {
didSet {
updateUI()
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
private func updateUI() {
let enabled = currentState == .Pause
slowButton.isEnabled = enabled
fastButton.isEnabled = enabled
pitchUpButton.isEnabled = enabled
pitchDownButton.isEnabled = enabled
echoButton.isEnabled = enabled
reverbButton.isEnabled = enabled
playingButton?.isEnabled = true
}
@IBAction func slowButtonDidClick(_ sender: Any) {
playingButton = sender as? UIButton
if currentState == .Pause {
currentState = .Playing
magician.playSound(filePath: filePath!, rate: 0.5)
} else {
currentState = .Pause
magician.stopAudio()
}
}
@IBAction func fastButtonDidClick(_ sender: Any) {
playingButton = sender as? UIButton
if currentState == .Pause {
currentState = .Playing
magician.playSound(filePath: filePath!, rate: 1.5)
} else {
currentState = .Pause
magician.stopAudio()
}
}
@IBAction func pitchUpButtonDidClick(_ sender: Any) {
playingButton = sender as? UIButton
if currentState == .Pause {
currentState = .Playing
magician.playSound(filePath: filePath!, pitch: 1000)
} else {
currentState = .Pause
magician.stopAudio()
}
}
@IBAction func pitchDownButtonDidClick(_ sender: Any) {
playingButton = sender as? UIButton
if currentState == .Pause {
currentState = .Playing
magician.playSound(filePath: filePath!, pitch: -1000)
} else {
currentState = .Pause
magician.stopAudio()
}
}
@IBAction func echoButtonDidClick(_ sender: Any) {
playingButton = sender as? UIButton
if currentState == .Pause {
currentState = .Playing
magician.playSound(filePath: filePath!, echo: true)
} else {
currentState = .Pause
magician.stopAudio()
}
}
@IBAction func reverbButtonDidClick(_ sender: Any) {
playingButton = sender as? UIButton
if currentState == .Pause {
currentState = .Playing
magician.playSound(filePath: filePath!, reverb: true)
} else {
currentState = .Pause
magician.stopAudio()
}
}
}
| 28.692308 | 83 | 0.58594 |
0168b1bdf33aadd0baba15be71a89ad36ad63a8f | 1,695 | //
// ForgotPasswordLocalization.swift
// Travelling
//
// Created by Dimitri Strauneanu on 05/10/2020.
// Copyright (c) 2020 Travelling. All rights reserved.
//
// This file was generated by the Clean Swift Xcode Templates so
// you can apply clean architecture to your iOS and Mac projects,
// see http://clean-swift.com
//
import UIKit
class ForgotPasswordLocalization {
static let shared = ForgotPasswordLocalization()
private init() {
}
struct LocalizedKey {
static let
forgotPasswordTitle = "ForgotPassword.scene.title",
emailTitle = "ForgotPassword.scene.email.title",
sendResetLinkButtonTitle = "ForgotPassword.scene.send.reset.link.button.title",
emailErrorText = "ForgotPassword.scene.email.error.text",
confirmationMessage = "ForgotPassword.scene.confirmation.message",
errorMessage = "ForgotPassword.scene.generic.error.message",
goToMailTitle = "ForgotPassword.scene.go.to.mail.title",
okTitle = "ForgotPassword.scene.ok.title"
}
let forgotPasswordTitle = LocalizedKey.forgotPasswordTitle.localized()
let emailTitle = LocalizedKey.emailTitle.localized()
let sendResetLinkButtonTitle = LocalizedKey.sendResetLinkButtonTitle.localized()
let emailErrorText = LocalizedKey.emailErrorText.localized()
let errorMessage = LocalizedKey.errorMessage.localized()
let goToMailTitle = LocalizedKey.goToMailTitle.localized()
let okTitle = LocalizedKey.okTitle.localized()
func confirmationMessage(email: String) -> String {
return String.localizedStringWithFormat(LocalizedKey.confirmationMessage.localized(), email)
}
}
| 36.847826 | 100 | 0.725664 |
d5df9de37db805c7ef2440eca9c03c54e475f891 | 22,136 | //
// xbBaseAlertView.swift
// FSCycleSwift
//
// Created by huadong on 2022/2/25.
//
import UIKit
import xbTextView
public class xbBaseAlertConfig: NSObject {
/** 弹窗距离屏幕的左右间距*/
public var leftRightMargin: CGFloat = 30.0
/** 标题距离弹窗的左右间距*/
public var leftSpace: CGFloat = 15.0
public var titleTop: CGFloat = 15.0
public var textField_H: CGFloat = 44.0
public var textView_H: CGFloat = 80.0
/** textField, textView 左右距离背景的间距*/
public var textLeftSpace: CGFloat = 10.0
/** 弹窗距离中心Y的间距*/
public var offsetY: CGFloat = 0.0
/** 是否手动来控制弹窗的消失,默认自动消失*/
public var isManualDismiss: Bool = false
/** 是否点击半透明背景弹窗的消失,默认不消失*/
public var isTapDismiss: Bool = false
/** 右上角关闭按钮图标*/
public var closeIconName: String?
public var titleColor: UIColor = xbBaseAlertView.hex(hexString: "#2F343A")
public var titleFont: UIFont = UIFont.systemFont(ofSize: 18.0, weight: .bold)
public var messageColor: UIColor = xbBaseAlertView.hex(hexString: "#333333")
public var messageFont: UIFont = UIFont.systemFont(ofSize: 16.0, weight: .regular)
public var descriptionColor: UIColor = xbBaseAlertView.hex(hexString: "#888888")
public var descriptionFont: UIFont = UIFont.systemFont(ofSize: 14.0, weight: .regular)
public var themeColor: UIColor = xbBaseAlertView.hex(hexString: "#127CF9")
public var actionBtnMainBgColor: UIColor = xbBaseAlertView.hex(hexString: "#127CF9")
public var actionBtnMainColor: UIColor = UIColor.white
public var actionBtnMainFont: UIFont = UIFont.systemFont(ofSize: 16.0, weight: .regular)
public var actionBtnNormalBgColor: UIColor = xbBaseAlertView.hex(hexString: "#eeeeee")
public var actionBtnNormalColor: UIColor = xbBaseAlertView.hex(hexString: "#666666")
public var actionBtnNormalFont: UIFont = UIFont.systemFont(ofSize: 16.0, weight: .regular)
public var placeholderColor: UIColor = xbBaseAlertView.hex(hexString: "#999999")
public var textViewBgColor: UIColor = xbBaseAlertView.hex(hexString: "#f8f8f8")
}
public class xbBaseAlertView: UIView {
private let kWidth = min(UIScreen.main.bounds.size.width, UIScreen.main.bounds.size.height)
private let kHeight = max(UIScreen.main.bounds.size.width, UIScreen.main.bounds.size.height)
private var actionButtons: [UIButton] = []
public typealias kBaseAlertViewButtonsClickedBlock = ((xbBaseAlertView, Int) -> Void)
public typealias kBaseAlertViewTextFieldDidChangedBlock = ((xbBaseAlertView, String) -> Void)
public typealias kBaseAlertViewTextViewDidChangedBlock = ((xbBaseAlertView, String) -> Void)
public typealias kBaseAlertViewCompletedBlock = ((xbBaseAlertView, Bool) -> Void)
private var btnClickedBlock: kBaseAlertViewButtonsClickedBlock?
private var textFieldBlock: kBaseAlertViewTextFieldDidChangedBlock?
private var textViewBlock: kBaseAlertViewTextViewDidChangedBlock?
/** 基本配置, 可自定义配置,也可使用默认配置*/
private var config: xbBaseAlertConfig = xbBaseAlertConfig()
/** 普通弹窗方法*/
public convenience init(configure: xbBaseAlertConfig? = nil, title: String?, message: String?, actionTitles: [String], buttonsClicked: kBaseAlertViewButtonsClickedBlock?){
self.init(configure: configure, title: title, message: message, description: nil, tfPlaceholder: nil, tvPlaceholder: nil, actionTitles: actionTitles, showClose: false, buttonsClicked: buttonsClicked, textFieldDidChanged: nil, textViewDidChanged: nil)
}
/** 普通弹窗方法2 */
public convenience init(configure: xbBaseAlertConfig? = nil, title: String?, message: String?, description: String?, actionTitles: [String], showClose: Bool, buttonsClicked: kBaseAlertViewButtonsClickedBlock?){
self.init(configure: configure, title: title, message: message, description: description, tfPlaceholder: nil, tvPlaceholder: nil, actionTitles: actionTitles, showClose: showClose, buttonsClicked: buttonsClicked, textFieldDidChanged: nil, textViewDidChanged: nil)
}
/** textField 弹窗*/
public convenience init(configure: xbBaseAlertConfig? = nil, title: String?, message: String?, description: String?, tfPlaceholder: String?, actionTitles: [String], showClose: Bool, buttonsClicked: kBaseAlertViewButtonsClickedBlock?, textFieldDidChanged: kBaseAlertViewTextFieldDidChangedBlock?) {
self.init(configure: configure, title: title, message: message, description: description, tfPlaceholder: tfPlaceholder, tvPlaceholder: nil, actionTitles: actionTitles, showClose: showClose, buttonsClicked: buttonsClicked, textFieldDidChanged: textFieldDidChanged, textViewDidChanged: nil)
}
/** textView 弹窗*/
public convenience init(configure: xbBaseAlertConfig? = nil, title: String?, message: String?, description: String?, tvPlaceholder: String?, actionTitles: [String], showClose: Bool, buttonsClicked: kBaseAlertViewButtonsClickedBlock?, textViewDidChanged: kBaseAlertViewTextViewDidChangedBlock?) {
self.init(configure: configure, title: title, message: message, description: description, tfPlaceholder: nil, tvPlaceholder: tvPlaceholder, actionTitles: actionTitles, showClose: showClose, buttonsClicked: buttonsClicked, textFieldDidChanged: nil, textViewDidChanged: textViewDidChanged)
}
/** 通用弹窗方法*/
public init(configure: xbBaseAlertConfig? = nil, title: String?, message: String?, description: String?, tfPlaceholder: String?, tvPlaceholder: String?, actionTitles: [String], showClose: Bool, buttonsClicked: kBaseAlertViewButtonsClickedBlock?, textFieldDidChanged: kBaseAlertViewTextFieldDidChangedBlock?, textViewDidChanged: kBaseAlertViewTextViewDidChangedBlock?) {
self.btnClickedBlock = buttonsClicked
self.textFieldBlock = textFieldDidChanged
self.textViewBlock = textViewDidChanged
if configure != nil {
config = configure!
}
let frame: CGRect = CGRect(x: 0, y: 0, width: kWidth - config.leftRightMargin * 2, height: 0.0)
super.init(frame: frame)
initSettings()
self.closeBtn.isHidden = !showClose
if let closeIcon = config.closeIconName {
self.closeBtn.setImage(UIImage(named: closeIcon), for: .normal)
}
self.titleLabel.text = title
self.messageLabel.text = message
self.desLabel.text = description
if let placeholder = tfPlaceholder {
let holder = NSMutableAttributedString(string: placeholder, attributes: [NSAttributedString.Key.foregroundColor : config.placeholderColor])
self.textField.attributedPlaceholder = holder
}
self.textView.placeholder = tvPlaceholder
if let msg = message {
if (msg.count > 0) {
self.messageLabel.attributedText = xbBaseAlertView.paragraphStyleWith(string: msg, lineSpacing: 3.0, fontSize: config.messageFont.pointSize, alignment: .center)
self.messageLabel.numberOfLines = 0
}
}
if let des = description {
if des.count > 0 {
self.desLabel.attributedText = xbBaseAlertView.paragraphStyleWith(string: des, lineSpacing: 3.0, fontSize: config.descriptionFont.pointSize, alignment: .center)
self.desLabel.numberOfLines = 0
}
}
// 添加操作按钮
for i in 0..<actionTitles.count {
let btn: UIButton = UIButton(type: .custom)
btn.setTitle(actionTitles[i], for: .normal)
btn.setTitleColor(config.actionBtnNormalColor, for: .normal)
btn.titleLabel?.font = config.actionBtnNormalFont
btn.addTarget(self, action: #selector(buttonAction(sender:)), for: .touchUpInside)
btn.tag = 30001 + i
btn.backgroundColor = config.actionBtnNormalBgColor
if (i == actionTitles.count - 1) {
btn.backgroundColor = config.actionBtnMainBgColor
btn.titleLabel?.font = config.actionBtnMainFont
btn.setTitleColor(config.actionBtnMainColor, for: .normal)
}
btn.clipsToBounds = true
btn.layer.cornerRadius = 6.0
self.addSubview(btn)
self.actionButtons.append(btn)
}
updateAllSubviewsFrame()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: UI布局
func initSettings() {
self.backgroundColor = UIColor.white
self.clipsToBounds = true
self.layer.cornerRadius = 6.0
self.frame = CGRect(x: 0, y: 0, width: kWidth - 2 * config.leftRightMargin, height: 0.0)
self.addSubview(self.titleLabel)
self.addSubview(self.messageLabel)
self.addSubview(self.desLabel)
self.addSubview(self.closeBtn)
self.addSubview(self.tfBgView)
self.tfBgView.addSubview(self.textField)
self.addSubview(self.tvBgView)
self.tvBgView.addSubview(self.textView)
NotificationCenter.default.addObserver(self, selector: #selector(textFieldValueChanged(sender:)), name: UITextField.textDidChangeNotification, object: self.textField)
}
func updateAllSubviewsFrame() {
let leftRightMargin: CGFloat = config.leftRightMargin,leftSpace: CGFloat = config.leftSpace
let width: CGFloat = kWidth - leftRightMargin * 2;
let textWidth: CGFloat = width - leftSpace * 2;
self.closeBtn.frame = CGRect(x: width - 40.0, y: 0, width: 40.0, height: 40.0)
var bottomH: CGFloat = 0.0;
self.titleLabel.sizeToFit()
self.titleLabel.frame = CGRect(x: leftSpace, y: config.titleTop, width: textWidth, height: 0.0)
if let title = self.titleLabel.text {
if title.count > 0 {
self.titleLabel.frame = CGRect(x: leftSpace, y: config.titleTop, width: textWidth, height: 30.0)
}
}
bottomH = self.titleLabel.frame.maxY
let style: NSMutableParagraphStyle = NSMutableParagraphStyle()
style.lineSpacing = 3.0
self.messageLabel.sizeToFit()
self.messageLabel.frame = CGRect(x: self.titleLabel.frame.minX, y: bottomH, width: textWidth, height: 0.0)
if let message = self.messageLabel.attributedText?.string {
if message.count > 0 {
let messageH: CGFloat = xbBaseAlertView.textHeight(withAttributedString: self.messageLabel.attributedText!, limitWidth: textWidth)
// 取整 : 大于或等于参数的最近的整数
self.messageLabel.frame = CGRect(x: self.titleLabel.frame.minX, y: bottomH + 15.0, width: textWidth, height: messageH)
}
}
bottomH = self.messageLabel.frame.maxY
self.desLabel.sizeToFit()
self.desLabel.frame = CGRect(x: self.messageLabel.frame.minX, y: bottomH, width: textWidth, height: 0.0)
if let des = self.desLabel.attributedText?.string {
if des.count > 0 {
let desH = xbBaseAlertView.textHeight(withAttributedString: self.desLabel.attributedText!, limitWidth: textWidth)
self.desLabel.frame = CGRect(x: self.messageLabel.frame.minX, y: bottomH + 15.0, width: textWidth, height: desH)
}
}
bottomH = self.desLabel.frame.maxY
self.tfBgView.frame = CGRect(x: self.desLabel.frame.minX, y: bottomH, width: textWidth, height: 0.0)
self.textField.frame = CGRect(x: config.textLeftSpace, y: 0.0, width: self.tfBgView.frame.size.width - config.textLeftSpace * 2, height: 0.0)
if let placeholder = self.textField.placeholder {
if placeholder.count > 0 {
self.tfBgView.frame = CGRect(x: self.desLabel.frame.minX, y: bottomH + 15.0, width: textWidth, height: config.textField_H)
self.textField.frame = CGRect(x: config.textLeftSpace, y: 0.0, width: self.tfBgView.frame.size.width - config.textLeftSpace * 2, height: self.tfBgView.frame.size.height)
bottomH = self.tfBgView.frame.maxY
}
}
self.tvBgView.frame = CGRect(x: self.desLabel.frame.minX, y: bottomH, width: textWidth, height: 0.0)
self.textView.frame = CGRect(x: config.textLeftSpace, y: 0.0, width: self.tvBgView.frame.size.width - config.textLeftSpace * 2, height: 0.0)
if let placeholder = self.textView.placeholder {
if placeholder.count > 0 {
self.tvBgView.frame = CGRect(x: self.desLabel.frame.minX, y: bottomH + 15.0, width: textWidth, height: config.textView_H)
self.textView.frame = CGRect(x: config.textLeftSpace, y: 10.0, width: self.tvBgView.frame.size.width - config.textLeftSpace * 2, height: self.tvBgView.frame.size.height - 20.0)
bottomH = self.tvBgView.frame.maxY
}
}
// 按钮布局
var itemW: CGFloat = width - leftSpace * 2
let itemSpace: CGFloat = 25.0, itemH: CGFloat = 40.0,itemTopMargin: CGFloat = 25.0, itemBottomMargin: CGFloat = 25.0
if (self.actionButtons.count == 1) {
let btn: UIButton = self.actionButtons.first!
btn.frame = CGRect(x: leftSpace, y: bottomH + itemTopMargin, width: itemW, height: itemH)
bottomH = btn.frame.maxY
}else if (self.actionButtons.count > 1) {
itemW = (width - CGFloat(leftSpace * 2) - (CGFloat(self.actionButtons.count - 1) * itemSpace)) / CGFloat(self.actionButtons.count)
for i in 0..<self.actionButtons.count{
let btn: UIButton = self.actionButtons[i]
btn.frame = CGRect(x: leftSpace + (itemW + itemSpace) * CGFloat(i), y: bottomH + itemTopMargin, width: itemW, height: itemH)
bottomH = btn.frame.maxY
}
}
let height: CGFloat = bottomH + itemBottomMargin
self.frame = CGRect(x: (kWidth - width) / 2.0 , y: (kHeight - height) / 2.0 , width: width, height: height)
}
// MARK: 点击事件
@objc func buttonAction(sender: UIButton) {
if !config.isManualDismiss {
self.dismiss()
}
let index = sender.tag - 30000
if let block = self.btnClickedBlock {
block(self, index)
}
}
@objc func textFieldValueChanged(sender: Notification){
if let block = self.textFieldBlock {
block(self, self.textField.text ?? "")
}
}
@objc func tapDismiss() {
if config.isTapDismiss {
dismiss()
}
}
// MARK: 懒加载
lazy var bgMaskView: UIView = {
let bg = UIView(frame: UIScreen.main.bounds)
bg.backgroundColor = UIColor.black.withAlphaComponent(0.3)
let tap = UITapGestureRecognizer(target: self, action: #selector(tapDismiss))
bg.isUserInteractionEnabled = true
bg.addGestureRecognizer(tap)
return bg
}()
lazy var titleLabel: UILabel = {
let label = UILabel.init()
label.text = "温馨提示"
label.textAlignment = .center
label.textColor = config.titleColor
label.font = config.titleFont
return label
}()
lazy var messageLabel: UILabel = {
let label = UILabel.init()
label.text = "一条消息"
label.textAlignment = .center
label.textColor = config.messageColor
label.font = config.messageFont
label.numberOfLines = 0
return label
}()
lazy var desLabel: UILabel = {
let label = UILabel.init()
label.text = "一段描述"
label.textAlignment = .center
label.textColor = config.descriptionColor
label.font = config.descriptionFont
label.numberOfLines = 0
return label
}()
lazy var tfBgView: UIView = {
let bg = UIView()
bg.backgroundColor = config.textViewBgColor
return bg
}()
lazy var textField: UITextField = {
let tf = UITextField()
tf.backgroundColor = UIColor.clear
tf.tintColor = config.themeColor
tf.textColor = config.messageColor
tf.font = config.messageFont
tf.borderStyle = .none
tf.clearButtonMode = .whileEditing
return tf
}()
lazy var tvBgView: UIView = {
let bg = UIView()
bg.backgroundColor = config.textViewBgColor
return bg
}()
lazy var textView: xbTextView = {
let tv = xbTextView()
tv.backgroundColor = UIColor.clear
tv.xb_Delegate = self
tv.font = config.messageFont
tv.tintColor = config.themeColor
tv.textColor = config.messageColor
tv.placeholder = nil
tv.placeholderColor = config.placeholderColor
// tv.maxLength = 20
return tv
}()
lazy var closeBtn: UIButton = {
let btn: UIButton = UIButton(type: .custom)
btn.setImage(UIImage(named: "xbAlert_close_black"), for: .normal)
btn.addTarget(self, action: #selector(buttonAction(sender:)), for: .touchUpInside)
btn.tag = 30000
return btn
}()
}
public extension xbBaseAlertView {
func show(completed: (() -> Void)? = nil) {
guard let window = UIApplication.shared.keyWindow else {
return
}
window.addSubview(self.bgMaskView)
window.addSubview(self)
var center: CGPoint = window.center
center.y += config.offsetY
self.center = center
self.transform = CGAffineTransform(scaleX: 0.6, y: 0.6)
UIView.animate(withDuration: 0.2) {
self.transform = CGAffineTransform(scaleX: 1.1, y: 1.1)
} completion: { finished in
UIView.animate(withDuration: 1.0/15.0) {
self.transform = CGAffineTransform(scaleX: 0.9, y: 0.9)
} completion: { finished in
UIView.animate(withDuration: 1.0/7.5) {
self.transform = CGAffineTransform.identity
} completion: { finished in
if let block = completed{
block()
}
}
}
}
}
func dismiss(completed: (() -> Void)? = nil) {
self.transform = CGAffineTransform.identity
self.bgMaskView.alpha = 1.0
self.alpha = 1.0
UIView.animate(withDuration: 0.25) {
self.bgMaskView.alpha = 0.1
self.alpha = 0.1
self.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
} completion: { finished in
self.bgMaskView.removeFromSuperview()
self.removeFromSuperview()
if let block = completed{
block()
}
}
}
}
extension xbBaseAlertView: xbTextViewDelegate{
public func xb_textViewDidChanged(textView: xbTextView, text: String?) {
if let block = self.textViewBlock {
block(self, self.textView.text)
}
}
public func xb_textViewDidEndEditing(textView: xbTextView, text: String?) {
if let block = self.textViewBlock {
block(self, self.textView.text)
}
}
public func xb_heightWith(textView: xbTextView, textHeight: CGFloat, textViewHeight: CGFloat) {
//debugPrint("textView height = \(textViewHeight)")
}
}
extension xbBaseAlertView {
/** 获取行间距属性字符串*/
static func paragraphStyleWith(string: String ,lineSpacing: CGFloat, fontSize: CGFloat, alignment: NSTextAlignment) -> NSMutableAttributedString {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = lineSpacing
paragraphStyle.alignment = alignment
let attributedText: NSMutableAttributedString = NSMutableAttributedString(string: string, attributes: [NSAttributedString.Key.paragraphStyle : paragraphStyle, NSMutableAttributedString.Key.font : UIFont.systemFont(ofSize: fontSize)])
return attributedText
}
/** 计算属性字符串高度*/
static func textHeight(withAttributedString: NSAttributedString, limitWidth: CGFloat) -> CGFloat{
let rect = withAttributedString.boundingRect(with: CGSize(width: limitWidth, height: 1000), options: [.usesLineFragmentOrigin, .truncatesLastVisibleLine, .usesFontLeading], context: nil)
// 取整 : 大于或等于参数的最近的整数
return ceil(rect.size.height)
}
/** 色值 #F56544 0xF56544 F56544 */
static func hex(hexString:String, alpha:Float = 1.0) -> UIColor{
var cStr = hexString.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased() as NSString;
if(cStr.length < 6){
return UIColor.clear;
}
if(cStr.hasPrefix("0x")) {
cStr = cStr.substring(from: 2) as NSString
}
if(cStr.hasPrefix("#")){
cStr = cStr.substring(from: 1) as NSString
}
if(cStr.length != 6){
return UIColor.clear;
}
let rStr = (cStr as NSString).substring(to: 2)
let gStr = ((cStr as NSString).substring(from: 2) as NSString).substring(to: 2)
let bStr = ((cStr as NSString).substring(from: 4) as NSString).substring(to: 2)
var r : UInt32 = 0x0
var g : UInt32 = 0x0
var b : UInt32 = 0x0
Scanner.init(string: rStr).scanHexInt32(&r);
Scanner.init(string: gStr).scanHexInt32(&g);
Scanner.init(string: bStr).scanHexInt32(&b);
return UIColor.init(red: CGFloat(r)/255.0, green: CGFloat(g)/255.0, blue: CGFloat(b)/255.0, alpha: CGFloat(alpha));
}
}
| 40.174229 | 373 | 0.63006 |
9bd2320af01a33d890379db7a07d7e0e22f34702 | 507 | //
// UIView+NibLoaded.swift
// settlepay-ios-sdk
//
// Created by Yelyzaveta Kartseva on 11.04.2021.
//
import UIKit
import QuickLayout
extension UIView {
@discardableResult
func fromNib<T : UIView>() -> T? {
guard let contentView = BundleHelper.bundle.loadNibNamed(type(of: self).className, owner: self, options: nil)?.first as? T else {
return nil
}
addSubview(contentView)
contentView.fillSuperview()
return contentView
}
}
| 21.125 | 137 | 0.633136 |
21b751d7ba2d795fd59bb8e7c108d553ed4fe74b | 12,294 | //
// UserController.swift
// App
//
// Created by 晋先森 on 2018/5/26.
//
import Vapor
import Crypto
import Authentication
final class UserController: RouteCollection {
private let authController = AuthController()
func boot(router: Router) throws {
let group = router.grouped("users")
// post
group.post(User.self, at: "login", use: loginUserHandler)
group.post(User.self, at: "register", use: registerUserHandler)
group.post(PasswordContainer.self, at: "changePassword", use: changePasswordHandler)
group.post(UserInfoContainer.self, at: "updateInfo", use: updateUserInfoHandler)
group.post("exit", use: exitUserHandler)
// get
group.get("getUserInfo", use: getUserInfoHandler)
group.get("avatar",String.parameter, use: getUserAvatarHandler)
}
}
private extension User {
func user(with digest: BCryptDigest) throws -> User {
return try User(userID: UUID().uuidString,
account: account,
password: digest.hash(password))
}
}
extension UserController {
//MARK: 登录
func loginUserHandler(_ req: Request,user: User) throws -> Future<Response> {
let futureFirst = User.query(on: req).filter(\.account == user.account).first()
return futureFirst.flatMap({ (existingUser) in
guard let existingUser = existingUser else {
return try ResponseJSON<Empty>(status: .userNotExist).encode(for: req)
}
let digest = try req.make(BCryptDigest.self)
guard try digest.verify(user.password,
created: existingUser.password) else {
return try ResponseJSON<Empty>(status: .passwordError).encode(for: req)
}
return try self.authController
.authContainer(for: existingUser, on: req)
.flatMap({ (container) in
var access = AccessContainer(accessToken: container.accessToken)
if !req.environment.isRelease {
access.userID = existingUser.userID
}
return try ResponseJSON<AccessContainer>(status: .ok,
message: "登录成功",
data: access).encode(for: req)
})
})
}
//MARK: 注册
func registerUserHandler(_ req: Request, newUser: User) throws -> Future<Response> {
let futureFirst = User.query(on: req).filter(\.account == newUser.account).first()
return futureFirst.flatMap { existingUser in
guard existingUser == nil else {
return try ResponseJSON<Empty>(status: .userExist).encode(for: req)
}
if newUser.account.isAccount().0 == false {
return try ResponseJSON<Empty>(status: .error,
message: newUser.account.isAccount().1).encode(for: req)
}
if newUser.password.isPassword().0 == false {
return try ResponseJSON<Empty>(status: .error,
message: newUser.password.isPassword().1).encode(for: req)
}
return try newUser
.user(with: req.make(BCryptDigest.self))
.save(on: req)
.flatMap { user in
let logger = try req.make(Logger.self)
logger.warning("New user created: \(user.account)")
return try self.authController
.authContainer(for: user, on: req)
.flatMap({ (container) in
var access = AccessContainer(accessToken: container.accessToken)
if !req.environment.isRelease {
access.userID = user.userID
}
return try ResponseJSON<AccessContainer>(status: .ok,
message: "注册成功",
data: access).encode(for: req)
})
}
}
}
//MARK: 退出登录
func exitUserHandler(_ req: Request) throws -> Future<Response> {
return try req.content.decode(TokenContainer.self).flatMap({ container in
let token = BearerAuthorization(token: container.token)
return AccessToken.authenticate(using: token,
on: req).flatMap({ (existToken) in
guard let existToken = existToken else {
return try ResponseJSON<Empty>(status: .token).encode(for: req)
}
return try self.authController.remokeTokens(userID: existToken.userID,
on: req).flatMap({ _ in
return try ResponseJSON<Empty>(status: .ok,
message: "退出成功").encode(for: req)
})
})
})
}
//MARK: 修改密码
private func changePasswordHandler(_ req: Request,inputContent: PasswordContainer) throws -> Future<Response> {
return User.query(on: req).filter(\.account == inputContent.account).first().flatMap({ (existUser) in
guard let existUser = existUser else {
return try ResponseJSON<Empty>(status: .userNotExist).encode(for: req)
}
let digest = try req.make(BCryptDigest.self)
guard try digest.verify(inputContent.password,
created: existUser.password) else {
return try ResponseJSON<Empty>(status: .passwordError).encode(for: req)
}
if inputContent.newPassword.isPassword().0 == false {
return try ResponseJSON<Empty>(status: .error,
message: inputContent.newPassword.isPassword().1).encode(for: req)
}
var user = existUser
user.password = try req.make(BCryptDigest.self).hash(inputContent.newPassword)
return user.save(on: req).flatMap { newUser in
let logger = try req.make(Logger.self)
logger.info("Password Changed Success: \(newUser.account)")
return try ResponseJSON<Empty>(status: .ok,
message: "修改成功,请重新登录!").encode(for: req)
}
})
}
//MARK: 获取用户信息
func getUserInfoHandler(_ req: Request) throws -> Future<Response> {
guard let token = req.query[String.self,
at: "token"] else {
return try ResponseJSON<Empty>(status: .missesToken).encode(for: req)
}
let bearToken = BearerAuthorization(token: token)
return AccessToken
.authenticate(using: bearToken, on: req)
.flatMap({ (existToken) in
guard let existToken = existToken else {
return try ResponseJSON<Empty>(status: .token).encode(for: req)
}
let futureFirst = UserInfo.query(on: req).filter(\.userID == existToken.userID).first()
return futureFirst.flatMap({ (existInfo) in
guard let existInfo = existInfo else {
return try ResponseJSON<Empty>(status: .error,
message: "用户信息为空").encode(for: req)
}
return try ResponseJSON<UserInfo>(data: existInfo).encode(for: req)
})
})
}
//MARK: 获取头像
func getUserAvatarHandler(_ req: Request) throws -> Future<Response> {
let name = try req.parameters.next(String.self)
let path = try VaporUtils.localRootDir(at: ImagePath.userPic, req: req) + "/" + name
if !FileManager.default.fileExists(atPath: path) {
let json = ResponseJSON<Empty>(status: .error,
message: "Image does not exist")
return try json.encode(for: req)
}
return try req.streamFile(at: path)
}
//MARK: 更新用户信息
func updateUserInfoHandler(_ req: Request,container: UserInfoContainer) throws -> Future<Response> {
let bearToken = BearerAuthorization(token: container.token)
return AccessToken
.authenticate(using: bearToken, on: req)
.flatMap({ (existToken) in
guard let existToken = existToken else {
return try ResponseJSON<Empty>(status: .token).encode(for: req)
}
let futureFirst = UserInfo.query(on: req).filter(\.userID == existToken.userID).first()
return futureFirst.flatMap({ (existInfo) in
var imgName: String?
if let file = container.picImage { //如果上传了图片,就判断下大小,否则就揭过这一茬。
guard file.data.count < ImageMaxByteSize else {
return try ResponseJSON<Empty>(status: .pictureTooBig).encode(for: req)
}
imgName = try VaporUtils.imageName()
let path = try VaporUtils.localRootDir(at: ImagePath.userPic, req: req) + "/" + imgName!
try Data(file.data).write(to: URL(fileURLWithPath: path))
}
var userInfo: UserInfo?
if var existInfo = existInfo { //存在则更新。
userInfo = existInfo.update(with: container)
if let existPicName = existInfo.picName,let imgName = imgName { //移除原来的照片
let path = try VaporUtils.localRootDir(at: ImagePath.userPic, req: req) + "/" + existPicName
try FileManager.default.removeItem(at: URL.init(fileURLWithPath: path))
userInfo?.picName = imgName
} else if userInfo?.picName == nil {
userInfo?.picName = imgName
}
} else {
userInfo = UserInfo(id: nil,
userID: existToken.userID,
age: container.age,
sex: container.sex,
nickName: container.nickName,
phone: container.phone,
birthday: container.birthday,
location: container.location,
picName: imgName)
}
return (userInfo!.save(on: req).flatMap({ (info) in
return try ResponseJSON<Empty>(status: .ok,
message: "Updated successfully!").encode(for: req)
}))
})
})
}
}
fileprivate struct TokenContainer: Content {
var token: String
}
fileprivate struct PasswordContainer: Content {
var account: String
var password: String
var newPassword: String
}
fileprivate struct AccessContainer: Content {
var accessToken: String
var userID:String?
init(accessToken: String,userID: String? = nil) {
self.accessToken = accessToken
self.userID = userID
}
}
struct UserInfoContainer: Content {
var token:String
var age: Int?
var sex: Int?
var nickName: String?
var phone: String?
var birthday: String?
var location: String?
var picImage: File?
}
| 38.782334 | 116 | 0.501383 |
db8f1af10891e0bbc9edf44e17781873a0eaa938 | 753 | //
// AuthenticationTokenResponse.swift
// MovieLister
//
// Created by Ben Scheirman on 11/10/19.
// Copyright © 2019 Fickle Bits. All rights reserved.
//
import Foundation
import SimpleNetworking
struct AuthenticationTokenResponse : Model {
let success: Bool
let expiresAt: Date
let requestToken: String
}
extension AuthenticationTokenResponse {
static var decoder: JSONDecoder {
let decoder = JSONDecoder()
// 2019-11-10 19:02:22 UTC
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
decoder.dateDecodingStrategy = .formatted(dateFormatter)
decoder.keyDecodingStrategy = .convertFromSnakeCase
return decoder
}
}
| 24.290323 | 64 | 0.683931 |
20d1ad4defb2b4f5cb4655a477d1a2b2f09f7fcf | 3,010 | //
// ZLGeneralDefine.swift
// ZLPhotoBrowser
//
// Created by long on 2020/8/11.
//
// Copyright (c) 2020 Long Zhang <[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
let ZLMaxImageWidth: CGFloat = 600
struct ZLLayout {
static let navTitleFont = getFont(17)
static let bottomToolViewH: CGFloat = 55
static let bottomToolBtnH: CGFloat = 34
static let bottomToolTitleFont = getFont(17)
static let bottomToolBtnCornerRadius: CGFloat = 5
static let thumbCollectionViewItemSpacing: CGFloat = 2
static let thumbCollectionViewLineSpacing: CGFloat = 2
}
func zlRGB(_ red: CGFloat, _ green: CGFloat, _ blue: CGFloat) -> UIColor {
return UIColor(red: red / 255, green: green / 255, blue: blue / 255, alpha: 1)
}
func getFont(_ size: CGFloat) -> UIFont {
guard let name = ZLCustomFontDeploy.fontName else {
return UIFont.systemFont(ofSize: size)
}
return UIFont(name: name, size: size) ?? UIFont.systemFont(ofSize: size)
}
func getAppName() -> String {
if let name = Bundle.main.localizedInfoDictionary?["CFBundleDisplayName"] as? String {
return name
}
if let name = Bundle.main.infoDictionary?["CFBundleDisplayName"] as? String {
return name
}
if let name = Bundle.main.infoDictionary?["CFBundleName"] as? String {
return name
}
return "App"
}
func getSpringAnimation() -> CAKeyframeAnimation {
let animate = CAKeyframeAnimation(keyPath: "transform")
animate.duration = 0.3
animate.isRemovedOnCompletion = true
animate.fillMode = .forwards
animate.values = [CATransform3DMakeScale(0.7, 0.7, 1),
CATransform3DMakeScale(1.2, 1.2, 1),
CATransform3DMakeScale(0.8, 0.8, 1),
CATransform3DMakeScale(1, 1, 1)]
return animate
}
func zl_debugPrint(_ message: Any) {
// debugPrint(message)
}
| 32.021277 | 90 | 0.690698 |
edf764130098c174aae8bcd97087bfe805ac4a75 | 6,882 | //
// RestLemmy.swift
// Lemmy-iOS
//
// Created by uuttff8 on 24.10.2020.
// Copyright © 2020 Anton Kuzmin. All rights reserved.
//
import UIKit
private protocol HTTPClientProvider {
func getAuth(url: URL, completion: @escaping ((Result<Data, Error>) -> Void))
func postAuth(url: String, bodyObject: Codable?, completion: @escaping (Result<Data, Error>) -> Void)
func uploadImage(
url: String,
image: UIImage,
filename: String,
completion: @escaping (Result<Data, LemmyGenericError>) -> Void
)
// func genericRequest(url: URL,
// method: String,
// bodyObject: [String: Any]?,
// completion: @escaping (Result<Data, Error>) -> Void)
}
final class HttpLemmyClient: HTTPClientProvider {
func getAuth(url: URL, completion: @escaping ((Result<Data, Error>) -> Void)) {
guard let jwt = LoginData.shared.jwtToken else {
print("JWT token is not provided")
return
}
let config = URLSessionConfiguration.ephemeral
config.waitsForConnectivity = true
config.httpAdditionalHeaders = [ "Cookie": "\(jwt)",
"Accept": "application/json",
"Content-Type": "application/json" ]
let request = URLRequest(url: url)
URLSession(configuration: config,
delegate: nil,
delegateQueue: OperationQueue.current)
.dataTask(with: request) { (data: Data?, _: URLResponse?, error: Error?) in
if let data = data {
completion(.success(data))
} else if let error = error {
completion(.failure(error))
}
}.resume()
}
func postAuth(
url: String,
bodyObject: Codable?,
completion: @escaping (Result<Data, Error>) -> Void
) {
guard let url = URL(string: url) else { return }
guard let jwt = LoginData.shared.jwtToken else {
print("JWT token is not provided")
return
}
guard let jsonBody = try? JSONSerialization.data(withJSONObject: bodyObject?.dictionary ?? [], options: [])
else { return }
let config = URLSessionConfiguration.ephemeral
config.waitsForConnectivity = true
config.httpAdditionalHeaders = [ "Cookie": "\(jwt)",
"Accept": "application/json",
"Content-Type": "application/json"]
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = jsonBody
URLSession(configuration: config,
delegate: INetworkDelegate(),
delegateQueue: OperationQueue.current)
.dataTask(with: request) { (data: Data?, _: URLResponse?, _: Error?) in
if let data = data {
completion(.success(data))
}
}.resume()
}
func uploadImage(
url: String,
image: UIImage,
filename: String,
completion: @escaping (Result<Data, LemmyGenericError>) -> Void
) {
guard let url = URL(string: url) else { return }
guard let jwt = LoginData.shared.jwtToken else {
Logger.commonLog.error("JWT token is not provided")
return
}
let boundary = generateBoundary()
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
let httpBody = createBody(imageToUpload: image, filename: filename, boundary: boundary)
request.httpBody = httpBody
let config = URLSessionConfiguration.default
config.waitsForConnectivity = true
config.httpAdditionalHeaders = [ "Cookie": "jwt=\(jwt)" ]
Logger.log(request: request)
URLSession(configuration: config,
delegate: INetworkDelegate(),
delegateQueue: OperationQueue.current)
.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
Logger.log(data: data, response: (response as? HTTPURLResponse), error: error)
if let data = data {
Logger.commonLog.info(String(data: data, encoding: .utf8))
completion(.success(data))
} else if let error = error {
completion(.failure(.string(error as! String)))
}
}.resume()
}
private func createBody(
imageToUpload: UIImage,
filename: String,
boundary: String
) -> Data {
var body = Data()
let filenameExt = filename.fileExtension
let mimetype = "image/\(filenameExt)"
let filePathKey = "images[]"
guard let imageData = imageToUpload.jpegData(compressionQuality: 1) else { return Data() }
body.append("--\(boundary)\r\n")
body.append("Content-Disposition: form-data; name=\"\(filePathKey)\"; filename=\"\(filename)\"\r\n")
body.append("Content-Type: \(mimetype)\r\n\r\n")
body.append(imageData)
body.append("\r\n")
body.append("--\(boundary)--\r\n")
return body
}
private func generateBoundary() -> String {
"Boundary-\(UUID().uuidString)"
}
}
private class INetworkDelegate: NSObject, URLSessionTaskDelegate {
func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) {
print("\(session) \(task) waiting")
}
}
private extension String {
var fileName: String {
return URL(fileURLWithPath: self).deletingPathExtension().lastPathComponent
}
var fileExtension: String {
return URL(fileURLWithPath: self).pathExtension
}
}
private extension Data {
/// Append string to Data
///
/// Rather than littering my code with calls to `data(using: .utf8)`
/// to convert `String` values to `Data`, this wraps it in a nice convenient little extension to Data.
/// This defaults to converting using UTF-8.
///
/// - parameter string: The string to be added to the `Data`.
mutating func append(_ string: String, using encoding: String.Encoding = .utf8) {
if let data = string.data(using: encoding) {
append(data)
}
}
}
private extension Encodable {
var dictionary: [String: Any]? {
guard let data = try? JSONEncoder().encode(self) else { return nil }
return (try? JSONSerialization.jsonObject(with: data, options: .allowFragments))
.flatMap { $0 as? [String: Any] }
}
}
| 34.93401 | 115 | 0.571781 |
d9c232b47be74429fd9e3121e05b01f9647eb49f | 1,951 | //
// JMPTests.swift
// SwiftNesTests
//
// Created by Tibor Bodecs on 2021. 09. 18..
//
import XCTest
@testable import SwiftNes
final class JMPTests: XCTestCase {
private func testUnchangedRegisterFlags(_ nes: Nes, _ registers: Cpu.Registers) {
XCTAssertEqual(nes.cpu.registers.zeroFlag, registers.zeroFlag)
XCTAssertEqual(nes.cpu.registers.signFlag, registers.signFlag)
XCTAssertEqual(nes.cpu.registers.carryFlag, registers.carryFlag)
XCTAssertEqual(nes.cpu.registers.interruptFlag, registers.interruptFlag)
XCTAssertEqual(nes.cpu.registers.decimalFlag, registers.decimalFlag)
XCTAssertEqual(nes.cpu.registers.breakFlag, registers.breakFlag)
XCTAssertEqual(nes.cpu.registers.overflowFlag, registers.overflowFlag)
}
func testAbsolute() throws {
let nes = Nes()
let registers = nes.cpu.registers
nes.memory.storage[0x00] = nes.cpu.opcode(.jmp, .absolute)
nes.memory.storage[0x01] = 0x11
nes.memory.storage[0x02] = 0x00
let cycles = 3
nes.start(cycles: cycles)
XCTAssertEqual(nes.cpu.totalCycles, cycles)
XCTAssertEqual(nes.cpu.registers.sp, registers.sp)
XCTAssertEqual(nes.cpu.registers.pc, 0x0011)
testUnchangedRegisterFlags(nes, registers)
}
func testIndirect() throws {
let nes = Nes()
let registers = nes.cpu.registers
nes.memory.storage[0x0000] = nes.cpu.opcode(.jmp, .indirect)
nes.memory.storage[0x0001] = 0x11
nes.memory.storage[0x0002] = 0x00
nes.memory.storage[0x0011] = 0x18
nes.memory.storage[0x0012] = 0x00
let cycles = 5
nes.start(cycles: cycles)
XCTAssertEqual(nes.cpu.totalCycles, cycles)
XCTAssertEqual(nes.cpu.registers.sp, registers.sp)
XCTAssertEqual(nes.cpu.registers.pc, 0x0018)
testUnchangedRegisterFlags(nes, registers)
}
}
| 34.839286 | 85 | 0.673501 |
183f61e3bb31fb659e3e026a45834bce84fe7106 | 1,690 | // --------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// --------------------------------------------------------------------------
import AzureCore
import Foundation
// swiftlint:disable superfluous_disable_command
// swiftlint:disable identifier_name
// swiftlint:disable line_length
// swiftlint:disable cyclomatic_complexity
/// The Generic URL.
public struct GenericUrl: Codable {
// MARK: Properties
/// Generic URL value.
public let genericValue: String?
// MARK: Initializers
/// Initialize a `GenericUrl` structure.
/// - Parameters:
/// - genericValue: Generic URL value.
public init(
genericValue: String? = nil
) {
self.genericValue = genericValue
}
// MARK: Codable
enum CodingKeys: String, CodingKey {
case genericValue
}
/// Initialize a `GenericUrl` structure from decoder
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.genericValue = try? container.decode(String.self, forKey: .genericValue)
}
/// Encode a `GenericUrl` structure
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
if genericValue != nil { try? container.encode(genericValue, forKey: .genericValue) }
}
}
| 31.296296 | 93 | 0.631953 |
211858c9af06d7b5a8e61fb4876182b702b17b13 | 759 | //
// SwiftUIView.swift
// ModelViewer
//
// Created by 陈锦明 on 2020/11/24.
//
import SwiftUI
struct SwiftUIView: View {
@EnvironmentObject var globalVariables: GlobalVariables
var body: some View {
VStack(spacing: 15) {
Button(action:{
if let plyUrl = Bundle.main.url(forResource: "Bearded guy", withExtension: "ply"){
globalVariables.renderer.load(ply: plyUrl)
}
}){
Text("Load Demo")
}
}
.lineSpacing(/*@START_MENU_TOKEN@*/10.0/*@END_MENU_TOKEN@*/)
}
}
struct SwiftUIView_Previews: PreviewProvider {
static var previews: some View {
SwiftUIView()
}
}
| 21.685714 | 98 | 0.533597 |
5b15b0a3b0e8d96a231c3c7b8c9ab9a8a8fd7c4e | 1,333 | //
// NodeStackView.swift
// LXSCommons
//
// Created by Alex Rote on 3/5/22.
//
import SwiftUI
/// The Node Stack View is a container that stacks new views on top of the initial content view, using a traditional NavigationView-like approach. The NodeStackView declares an environment object NodeStackNavigationController that can be used to initiate navigation between nodes through the stack.
public struct NodeStackView<InitialView: View>: View {
// Instantiate the navigation stack to the inital view.
@StateObject private var controller = NodeStackNavigationController()
private var content: () -> InitialView
/// Initializes a new Node Stack View with an initial view.
public init(content: @escaping () -> InitialView) {
self.content = content
}
public var body: some View {
GeometryReader { geometry in
VStack(spacing: 0) {
StackBarView(topSafeArea: geometry.safeAreaInsets.top)
StackHost(content: content)
.frame(maxHeight: .infinity)
}
.environmentObject(controller)
.environmentObject(controller.stack)
.environmentObject(controller.details)
.frame(maxHeight: .infinity)
.edgesIgnoringSafeArea(.top)
}
}
}
| 35.078947 | 298 | 0.659415 |
90d1c07c12ff3314e6b4b5bf1fc484669cc00edf | 10,798 | //
// TextField.swift
// PhoneNumberKit
//
// Created by Roy Marmelstein on 07/11/2015.
// Copyright © 2015 Roy Marmelstein. All rights reserved.
//
import Foundation
import UIKit
/// Custom text field that formats phone numbers
open class PhoneNumberTextField: UITextField, UITextFieldDelegate {
let phoneNumberKit = PhoneNumberKit()
/// Override setText so number will be automatically formatted when setting text by code
override open var text: String? {
set {
if newValue != nil {
let formattedNumber = partialFormatter.formatPartial(newValue! as String)
super.text = formattedNumber
}
else {
super.text = newValue
}
}
get {
return super.text
}
}
/// allows text to be set without formatting
open func setTextUnformatted(newValue:String?) {
super.text = newValue
}
/// Override region to set a custom region. Automatically uses the default region code.
public var defaultRegion = PhoneNumberKit.defaultRegionCode() {
didSet {
partialFormatter.defaultRegion = defaultRegion
}
}
public var withPrefix: Bool = true {
didSet {
partialFormatter.withPrefix = withPrefix
if withPrefix == false {
self.keyboardType = UIKeyboardType.numberPad
}
else {
self.keyboardType = UIKeyboardType.phonePad
}
}
}
public var isPartialFormatterEnabled = true
public var maxDigits: Int? {
didSet {
partialFormatter.maxDigits = maxDigits
}
}
let partialFormatter: PartialFormatter
let nonNumericSet: NSCharacterSet = {
var mutableSet = NSMutableCharacterSet.decimalDigit().inverted
mutableSet.remove(charactersIn: PhoneNumberConstants.plusChars)
return mutableSet as NSCharacterSet
}()
weak private var _delegate: UITextFieldDelegate?
override open var delegate: UITextFieldDelegate? {
get {
return _delegate
}
set {
self._delegate = newValue
}
}
//MARK: Status
public var currentRegion: String {
get {
return partialFormatter.currentRegion
}
}
public var nationalNumber: String {
get {
let rawNumber = self.text ?? String()
return partialFormatter.nationalNumber(from: rawNumber)
}
}
public var isValidNumber: Bool {
get {
let rawNumber = self.text ?? String()
do {
let _ = try phoneNumberKit.parse(rawNumber, withRegion: currentRegion)
return true
} catch {
return false
}
}
}
//MARK: Lifecycle
/**
Init with frame
- parameter frame: UITextfield F
- returns: UITextfield
*/
override public init(frame:CGRect)
{
self.partialFormatter = PartialFormatter(phoneNumberKit: phoneNumberKit, defaultRegion: defaultRegion, withPrefix: withPrefix)
super.init(frame:frame)
self.setup()
}
/**
Init with coder
- parameter aDecoder: decoder
- returns: UITextfield
*/
required public init(coder aDecoder: NSCoder) {
self.partialFormatter = PartialFormatter(phoneNumberKit: phoneNumberKit, defaultRegion: defaultRegion, withPrefix: withPrefix)
super.init(coder: aDecoder)!
self.setup()
}
@objc func didBeginEditing() {
drawBorderColor(color: UIColor(red: 0.24, green: 0.71, blue: 0.88, alpha: 1.00))
}
@objc func didEndEditing() {
drawBorderColor(color: UIColor(red: 0.93, green: 0.93, blue: 0.93, alpha: 1.00))
}
fileprivate func drawBorderColor(color: UIColor) {
let border = CALayer()
let width = CGFloat(1.0)
layer.addSublayer(border)
layer.masksToBounds = true
border.borderColor = color.cgColor
border.borderWidth = width
border.frame = CGRect(x: 0, y: frame.size.height - width, width: frame.size.width, height: frame.size.height)
UIView.animate(withDuration: 0.2) {
border.borderColor = color.cgColor
}
}
func setup() {
borderStyle = .none
autocorrectionType = .no
keyboardType = UIKeyboardType.phonePad
delegate = self
addTarget(self, action: #selector(didBeginEditing), for: .editingDidBegin)
addTarget(self, action: #selector(didEndEditing), for: .editingDidEnd)
drawBorderColor(color: UIColor(red: 0.93, green: 0.93, blue: 0.93, alpha: 1.00))
}
// MARK: Phone number formatting
/**
* To keep the cursor position, we find the character immediately after the cursor and count the number of times it repeats in the remaining string as this will remain constant in every kind of editing.
*/
internal struct CursorPosition {
let numberAfterCursor: String
let repetitionCountFromEnd: Int
}
internal func extractCursorPosition() -> CursorPosition? {
var repetitionCountFromEnd = 0
// Check that there is text in the UITextField
guard let text = text, let selectedTextRange = selectedTextRange else {
return nil
}
let textAsNSString = text as NSString
let cursorEnd = offset(from: beginningOfDocument, to: selectedTextRange.end)
// Look for the next valid number after the cursor, when found return a CursorPosition struct
for i in cursorEnd ..< textAsNSString.length {
let cursorRange = NSMakeRange(i, 1)
let candidateNumberAfterCursor: NSString = textAsNSString.substring(with: cursorRange) as NSString
if (candidateNumberAfterCursor.rangeOfCharacter(from: nonNumericSet as CharacterSet).location == NSNotFound) {
for j in cursorRange.location ..< textAsNSString.length {
let candidateCharacter = textAsNSString.substring(with: NSMakeRange(j, 1))
if candidateCharacter == candidateNumberAfterCursor as String {
repetitionCountFromEnd += 1
}
}
return CursorPosition(numberAfterCursor: candidateNumberAfterCursor as String, repetitionCountFromEnd: repetitionCountFromEnd)
}
}
return nil
}
// Finds position of previous cursor in new formatted text
internal func selectionRangeForNumberReplacement(textField: UITextField, formattedText: String) -> NSRange? {
let textAsNSString = formattedText as NSString
var countFromEnd = 0
guard let cursorPosition = extractCursorPosition() else {
return nil
}
for i in stride(from: (textAsNSString.length - 1), through: 0, by: -1) {
let candidateRange = NSMakeRange(i, 1)
let candidateCharacter = textAsNSString.substring(with: candidateRange)
if candidateCharacter == cursorPosition.numberAfterCursor {
countFromEnd += 1
if countFromEnd == cursorPosition.repetitionCountFromEnd {
return candidateRange
}
}
}
return nil
}
open func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// This allows for the case when a user autocompletes a phone number:
if range == NSRange(location: 0, length: 0) && string == " " {
return true
}
guard let text = text else {
return false
}
// allow delegate to intervene
guard _delegate?.textField?(textField, shouldChangeCharactersIn: range, replacementString: string) ?? true else {
return false
}
guard isPartialFormatterEnabled else {
return true
}
let textAsNSString = text as NSString
let changedRange = textAsNSString.substring(with: range) as NSString
let modifiedTextField = textAsNSString.replacingCharacters(in: range, with: string)
let filteredCharacters = modifiedTextField.filter {
return String($0).rangeOfCharacter(from: (textField as! PhoneNumberTextField).nonNumericSet as CharacterSet) == nil
}
let rawNumberString = String(filteredCharacters)
let formattedNationalNumber = partialFormatter.formatPartial(rawNumberString as String)
var selectedTextRange: NSRange?
let nonNumericRange = (changedRange.rangeOfCharacter(from: nonNumericSet as CharacterSet).location != NSNotFound)
if (range.length == 1 && string.isEmpty && nonNumericRange)
{
selectedTextRange = selectionRangeForNumberReplacement(textField: textField, formattedText: modifiedTextField)
textField.text = modifiedTextField
}
else {
selectedTextRange = selectionRangeForNumberReplacement(textField: textField, formattedText: formattedNationalNumber)
textField.text = formattedNationalNumber
}
sendActions(for: .editingChanged)
if let selectedTextRange = selectedTextRange, let selectionRangePosition = textField.position(from: beginningOfDocument, offset: selectedTextRange.location) {
let selectionRange = textField.textRange(from: selectionRangePosition, to: selectionRangePosition)
textField.selectedTextRange = selectionRange
}
return false
}
//MARK: UITextfield Delegate
open func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
return _delegate?.textFieldShouldBeginEditing?(textField) ?? true
}
open func textFieldDidBeginEditing(_ textField: UITextField) {
_delegate?.textFieldDidBeginEditing?(textField)
}
open func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
return _delegate?.textFieldShouldEndEditing?(textField) ?? true
}
open func textFieldDidEndEditing(_ textField: UITextField) {
_delegate?.textFieldDidEndEditing?(textField)
}
open func textFieldShouldClear(_ textField: UITextField) -> Bool {
return _delegate?.textFieldShouldClear?(textField) ?? true
}
open func textFieldShouldReturn(_ textField: UITextField) -> Bool {
return _delegate?.textFieldShouldReturn?(textField) ?? true
}
}
| 35.058442 | 207 | 0.627431 |
3934d3971a3a3547fdae300a03b994ed881609d7 | 14,375 | //
// PageContainer.swift
// famous
//
// Created by zhuxietong on 2016/11/25.
// Copyright © 2016年 zhuxietong. All rights reserved.
//
import UIKit
public protocol PageContainerOffset{
var contentInsetView:UIScrollView?{get}
}
public protocol PageContainer:UIScrollViewDelegate {
var controllers:[UIViewController] {set get}
var menuBar:UIView {get set}
var contentView:UIScrollView {get}
var pageIndex:Int{get set}
func place(menu:UIView,contentView:UIScrollView) -> Void
func select(at index:Int,animated:Bool) -> Void
func reloadPages()
}
public enum Effect {
case new(color:UIColor,scale:CGFloat,opacity:CGFloat)
public var color:UIColor{
get{
switch self {
case .new(color: let color, scale: _, opacity: _):
return color
}
}
}
public var scale:CGFloat{
get{
switch self {
case .new(color: _, scale: let scale, opacity: _):
return scale
}
}
}
public var opacity:CGFloat{
get{
switch self {
case .new(color: _, scale: _, opacity: let opacity):
return opacity
}
}
}
}
open class EffectButton: UIView {
open override var tag: Int{
didSet{
self.button.tag = tag
}
}
public var effect_select:Effect{
return Effect.new(color: self.select_color, scale: 1, opacity: 1)
}
public var effect_normal:Effect{
return Effect.new(color: self.normal_color, scale: 0.9, opacity: 0.5)
}
public var title:String = ""{
didSet{
isSelected = false
self.titleL.text = title
}
}
public var titleL = UILabel()
public var button = UIButton()
public var select_color = UIColor.white
public var normal_color = UIColor.white
required public override init(frame: CGRect) {
super.init(frame: frame)
self.eelay = [
[titleL,[ee.X.Y]],
[button,[ee.T.L.B.R]]
]
titleL.textAlignment = .center
isSelected = false
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func checkProgress(scale:CGFloat,total:Int) {
let value = scale * total.cg_floatValue
if (value < (self.tag.cg_floatValue + 0.5)) && (value > (self.tag.cg_floatValue - 0.5))
{
let sc = 1.0 - (abs(value-self.tag.cg_floatValue))/0.5
self.checkOpenValue(scale: sc)
}
}
public var isSelected:Bool = false{
didSet{
if isSelected{
self.checkOpenValue(scale: 1)
}
else{
self.checkOpenValue(scale: 0)
}
}
}
public func checkOpenValue(scale:CGFloat) {
let select_percen = scale
let normal_percen = 1.0 - select_percen
let size_scale = effect_normal.scale*normal_percen + effect_select.scale*select_percen
let opacity_value = effect_normal.opacity*normal_percen + effect_select.opacity*select_percen
titleL.alpha = opacity_value
let transform = CGAffineTransform(scaleX: size_scale, y: size_scale)
titleL.transform = transform.translatedBy(x: 0, y: 0)
guard let n_colors = effect_normal.color.cgColor.components else{
titleL.textColor = effect_select.color
return
}
guard let s_colors = effect_select.color.cgColor.components else{
titleL.textColor = effect_select.color
return
}
let red = n_colors[0] * normal_percen + s_colors[0] * select_percen
let green = n_colors[1] * normal_percen + s_colors[1] * select_percen
let blue = n_colors[2] * normal_percen + s_colors[2] * select_percen
let opacity = n_colors[3] * normal_percen + s_colors[3] * select_percen
let color = UIColor(red: red, green: green, blue: blue, alpha: opacity)
titleL.textColor = color
}
}
public struct SoSegBarStyle {
public var indicator_width:CGFloat = 60.co
public var indicator_height:CGFloat = 2
public var indicator_color:UIColor = UIColor(shex: "#fff")
public var seg_width:CGFloat = 70
public var normal_color = UIColor(shex: "#aaa")
public var select_color = UIColor(shex: "#fff")
public init() {
}
}
public class SoSegBar:UIView {
public var names = [String]()
public var ui = SoSegBarStyle()
public var indicator = UIView()
public var segClass:EffectButton.Type = EffectButton.self
public var selectActin:((Int)->Void) = {_ in}
public var backgroundView:UIView?{
didSet{
if let bk = backgroundView
{
self.insertSubview(bk, at: 0)
self.eelay = [
[bk,[ee.T.B.L.R]],
]
}
}
}
public var index:Int = 0{
didSet{
if let v = self.viewWithTag(909){
for bt in v.subviews
{
if let a_bt = bt as? UIButton{
if a_bt.tag == index{
a_bt.isSelected = true
}
else{
a_bt.isSelected = false
}
}
}
}
if self.names.count > 0
{
self.updateIndicator(scale: index.cg_floatValue/self.names.count.cg_floatValue)
}
}
}
public func updateIndicator(scale:CGFloat) {
var point = self.indicator.center
let p_x_width = self.names.count.cg_floatValue * ui.seg_width
point.x = (ui.seg_width)/2.0 + p_x_width*scale
indicator.center = point
if let v = self.viewWithTag(909){
for bt in v.subviews
{
if let a_bt = bt as? EffectButton{
a_bt.checkProgress(scale: scale, total: self.names.count)
}
}
}
}
public func update(index:Int) {
// self.index = index
// let scale = index.cg_floatValue/self.names.count.cg_floatValue
// self.updateIndicator(scale: scale)
self.selectActin(index)
}
public func loadItems() {
let sbvs = self.subviews.filter { (one) -> Bool in
return one is EffectButton
}
for s in sbvs{
s.removeFromSuperview()
}
let bts_view = UIView()
bts_view.tag = 909
var pre:UIView?
for (i,name) in names.enumerated(){
if i == 0{
indicator.backgroundColor = ui.indicator_color
bts_view.addSubview(indicator)
indicator.frame = [0,(self.frame.height-ui.indicator_height),ui.seg_width,ui.indicator_height]
}
let bt = segClass.init(frame: [0])
bt.select_color = self.ui.select_color
bt.normal_color = self.ui.normal_color
bt.tag = i
bt.button.addTarget(self, action: #selector(tapSeg(sender:)), for: .touchUpInside)
bts_view.eelay = [
[bt,[ee.T.B,[0,ui.indicator_height/2.0]],Int(ui.seg_width)]
]
if let p = pre
{
bts_view.eelay = [
[bt,[p,ee.R,ee.L],Int(ui.seg_width)]
]
}else{
bts_view.eelay = [
[bt,[ee.L]]
]
}
if i+1 == names.count{
bts_view.eelay = [
[bt,[ee.R]]
]
}
pre = bt
bt.title = name
}
self.eelay = [
[bts_view,[ee.X.Y.B]]
]
}
public func oberveIndex(with scrollView:UIScrollView) {
let scale = scrollView.contentOffset.x/scrollView.contentSize.width
self.updateIndicator(scale: scale)
if scrollView.contentOffset.x.truncatingRemainder(dividingBy: scrollView.frame.width) == 0 {
let currentIndex = Int(scrollView.contentOffset.x / scrollView.frame.width)
self.index = currentIndex
}
}
public func tapSeg(sender:UIButton) {
self.update(index: sender.tag)
}
override public var intrinsicContentSize: CGSize{
return self.frame.size
}
}
open class SoPageController: UIViewController,PageContainer,LoadingPresenter {
public var controllers: [UIViewController] = [UIViewController]()
public var pageIndex: Int = 0{
didSet{
if self.controllers.count > pageIndex{
let ctr = self.controllers[pageIndex]
self.controller = ctr
}
}
}
var controller:UIViewController?{
willSet{
if let ctr = self.controller{
ctr.willMove(toParentViewController: self)
ctr.removeFromParentViewController()
ctr.didMove(toParentViewController: self)
}
if let ctr = newValue{
ctr.willMove(toParentViewController: self)
self.addChildViewController(ctr)
ctr.didMove(toParentViewController: self)
}
}
}
public var menuBar:UIView = SoSegBar()
public var contentView: UIScrollView {
get {
return _contentView
}
}
lazy open var _contentView: UIScrollView = { [unowned self] in
let scrollV = UIScrollView(frame: [0])
scrollV.delegate = self
scrollV.showsVerticalScrollIndicator = false
scrollV.showsHorizontalScrollIndicator = false
scrollV.isPagingEnabled = true
return scrollV
}()
open override func viewDidLoad() {
super.viewDidLoad()
self.ctr_style = CtrStyle.default
self.view.backgroundColor = .white
self.reloadPages()
}
open override func viewWillAppear(_ animated: Bool) {
for on in self.controllers{
on.ctr_style = CtrStyle.transparent_dark
}
super.viewWillAppear(animated)
}
public func reloadPages() {
self.place(menu: menuBar, contentView: contentView)
let sviews = self.contentView.subviews
for v in sviews
{
v.removeFromSuperview()
}
var prev:UIView?
for (i,ctr) in self.controllers.enumerated(){
self.contentView.eelay = [
[ctr.view,[ee.width.height.T.B]]
]
if let p = prev{
self.contentView.eelay = [
[ctr.view,[p,ee.R,ee.L]]
]
}
else{
self.contentView.eelay = [
[ctr.view,[ee.L]]
]
}
if i+1 == controllers.count{
self.contentView.eelay = [
[ctr.view,[ee.R]]
]
}
if let off_ctr = ctr as? PageContainerOffset{
if let off_v = off_ctr.contentInsetView{
off_v.contentInset = UIEdgeInsetsMake(64, 0, 0, 0)
off_v.scrollIndicatorInsets = UIEdgeInsetsMake(64, 0, 0, 0)
}
}
prev = ctr.view
}
(self.menuBar as? SoSegBar)?.names = self.menues
weak var wself = self
(self.menuBar as? SoSegBar)?.selectActin = {
wself?.select(at: $0, animated: true)
}
(menuBar as? SoSegBar)?.loadItems()
self.controller = controllers[0]
(self.menuBar as? SoSegBar)?.index = 0
}
public var menues:[String]{
get{
var ts = [String]()
for obj in self.controllers{
if let t = obj.title
{
ts.append(t)
}
else{
ts.append("item")
}
}
return ts
}
}
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView == contentView{
(self.menuBar as? SoSegBar)?.oberveIndex(with: scrollView)
if scrollView.contentOffset.x.truncatingRemainder(dividingBy: view.frame.width) == 0 {
let currentIndex = Int(scrollView.contentOffset.x / view.frame.width)
self.select(at: currentIndex, animated: false)
}
}
}
open func place(menu: UIView, contentView: UIScrollView) {
menu.frame = [0,0,Swidth,44]
self.navigationItem.titleView = menu
let av = UIView()
jo_contentView.eelay = [
[av,[ee.T.L.R],"0"],
[contentView,[ee.L.B.R],[av,ee.B,ee.T]]
]
}
public func controller(at index: Int) -> UIViewController {
return UIViewController()
}
public func select(at index: Int, animated: Bool) {
if animated{
contentView.setContentOffset([view.frame.width*index.cg_floatValue,0], animated: true)
}
self.pageIndex = index
}
deinit {
}
}
| 25.807899 | 110 | 0.500522 |
3826832e793f042ef5324c204a69d4930311ed0c | 337 | import Foundation
import SwiftUI
extension NSStatusItem {
func update(from response: Pinger.Pong) {
if response.status == .success {
if let speed = response.speed {
button?.image = speed.image
return
}
}
button?.image = response.status.image
}
}
| 19.823529 | 45 | 0.548961 |
8a74c0375ef2a20ee19cb2597059d35b4943a90f | 286 | //
// DataModel.swift
// DataBinding
//
// Created by Jürgen F. Kilian on 06.07.17.
// Copyright © 2017 Kilian IT-Consulting. All rights reserved.
//
import UIKit
class DataModel: NSObject {
var name: String = "my Name"
var value: Float = 0.5
var state: Bool = true
}
| 17.875 | 63 | 0.65035 |
ff069be718b25738ee12ce0a63a44221168e182a | 795 | /*
* Copyright 2018 the original author or authors.
*
* 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 XCTest
class UtilTest: XCTestCase {
public static var allTests = [
("testOk", testOk)
]
func testOk() {
print("hello from UtilTest.")
}
}
| 29.444444 | 75 | 0.700629 |
67d3e6d274353b782350ecc6e9c068bfab681a73 | 1,195 | //
// OldReachability.swift
// Reuse - Repair
//
// This code was created by Leo Dabus
// and referenced via http://stackoverflow.com/questions/30743408/check-for-internet-connection-in-swift-2-ios-9
//
import Foundation
import SystemConfiguration
public class OldReachability {
class func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, UnsafePointer($0))
}
var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0)
if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false {
return false
}
let isReachable = flags == .Reachable
let needsConnection = flags == .ConnectionRequired
return isReachable && !needsConnection
}
} | 34.142857 | 143 | 0.666946 |
385ec72131df3aeea8ed683c5e3b59a0f4eb5007 | 12,010 | //
// SwapToken.WalletView.swift
// p2p_wallet
//
// Created by Chung Tran on 19/08/2021.
//
import Foundation
import RxSwift
import RxCocoa
extension SerumSwapV1 {
class WalletView: BEView {
// MARK: - Nested type
enum WalletType {
case source, destination
}
var wallet: Wallet?
private let disposeBag = DisposeBag()
private let viewModel: SwapTokenViewModelType
private let type: WalletType
private lazy var balanceView = WLBalanceView(forAutoLayout: ())
private lazy var iconImageView = CoinLogoImageView(size: 32, cornerRadius: 16)
private lazy var tokenSymbolLabel = UILabel(text: "TOK", weight: .semibold, textAlignment: .center)
private lazy var maxButton = UILabel(
text: L10n.max.uppercased(),
textSize: 13,
weight: .semibold,
textColor: .textSecondary.onDarkMode(.white)
)
.withContentHuggingPriority(.required, for: .horizontal)
.padding(.init(x: 13.5, y: 8), backgroundColor: .f6f6f8.onDarkMode(.h404040), cornerRadius: 12)
.withContentHuggingPriority(.required, for: .horizontal)
.onTap(self, action: #selector(useAllBalance))
private lazy var amountTextField = TokenAmountTextField(
font: .systemFont(ofSize: 27, weight: .bold),
textColor: .textBlack,
textAlignment: .right,
keyboardType: .decimalPad,
placeholder: "0\(Locale.current.decimalSeparator ?? ".")0",
autocorrectionType: .no/*, rightView: useAllBalanceButton, rightViewMode: .always*/
)
private lazy var equityValueLabel = UILabel(text: "≈ 0.00 \(Defaults.fiat.symbol)", textSize: 13, weight: .medium, textColor: .textSecondary.onDarkMode(.white), textAlignment: .right)
init(viewModel: SwapTokenViewModelType, type: WalletType) {
self.viewModel = viewModel
self.type = type
super.init(frame: .zero)
configureForAutoLayout()
bind()
amountTextField.delegate = self
layer.cornerRadius = 12
layer.masksToBounds = true
layer.borderWidth = 1
layer.borderColor = UIColor.separator.cgColor
}
override func commonInit() {
super.commonInit()
let action: Selector = type == .source ? #selector(chooseSourceWallet): #selector(chooseDestinationWallet)
let balanceView = type == .destination ? balanceView: balanceView
.onTap(self, action: #selector(useAllBalance))
balanceView.tintColor = type == .source ? .h5887ff: .textSecondary.onDarkMode(.white)
let downArrow = UIImageView(width: 11, height: 8, image: .downArrow, tintColor: .a3a5ba)
let stackView = UIStackView(axis: .vertical, spacing: 16, alignment: .fill, distribution: .fill) {
UIStackView(axis: .horizontal, spacing: 16, alignment: .center, distribution: .equalCentering) {
UILabel(text: type == .source ? L10n.from: L10n.to, textSize: 15, weight: .semibold)
balanceView
}
UIStackView(axis: .horizontal, spacing: 8, alignment: .center, distribution: .fill) {
iconImageView
tokenSymbolLabel
.withContentHuggingPriority(.required, for: .horizontal)
downArrow
BEStackViewSpacing(12)
maxButton
amountTextField
}
BEStackViewSpacing(0)
equityValueLabel
}
if type == .destination {
maxButton.isHidden = true
}
addSubview(stackView)
stackView.autoPinEdgesToSuperviewEdges(with: .init(all: 16))
// for increasing touchable area
let chooseWalletView = UIView(forAutoLayout: ())
.onTap(self, action: action)
addSubview(chooseWalletView)
chooseWalletView.autoPinEdge(.leading, to: .leading, of: iconImageView)
chooseWalletView.autoPinEdge(.trailing, to: .trailing, of: downArrow)
chooseWalletView.autoPinEdge(.top, to: .top, of: iconImageView, withOffset: -10)
chooseWalletView.autoPinEdge(.bottom, to: .bottom, of: iconImageView, withOffset: 10)
}
private func bind() {
// subjects
let walletDriver: Driver<Wallet?>
let textFieldKeydownEvent: (Double) -> AnalyticsEvent
let equityValueLabelDriver: Driver<String?>
let balanceTextDriver: Driver<String?>
let inputSubject: PublishRelay<String?>
let outputDriver: Driver<Double?>
switch type {
case .source:
walletDriver = viewModel.sourceWalletDriver
textFieldKeydownEvent = {amount in
.swapTokenAAmountKeydown(sum: amount)
}
equityValueLabelDriver = Driver.combineLatest(
viewModel.inputAmountDriver,
viewModel.sourceWalletDriver
)
.map {amount, wallet in
if let wallet = wallet {
let value = amount * wallet.priceInCurrentFiat
return "≈ \(value.toString(maximumFractionDigits: 9)) \(Defaults.fiat.symbol)"
} else {
return L10n.selectCurrency
}
}
inputSubject = viewModel.inputAmountSubject
outputDriver = viewModel.inputAmountDriver
// use all balance
viewModel.useAllBalanceDidTapSignal
.map {$0?.toString(maximumFractionDigits: 9, groupingSeparator: "")}
.emit(onNext: {[weak self] in
// write text without notifying
self?.amountTextField.text = $0
self?.viewModel.inputAmountSubject.accept($0)
})
.disposed(by: disposeBag)
// available amount
balanceTextDriver = Driver.combineLatest(
viewModel.availableAmountDriver,
viewModel.sourceWalletDriver
)
.map {amount, wallet -> String? in
guard let amount = amount else {return nil}
return amount.toString(maximumFractionDigits: 9) + " " + wallet?.token.symbol
}
viewModel.errorDriver
.map {$0 == L10n.insufficientFunds || $0 == L10n.amountIsNotValid}
.map {$0 ? UIColor.alert: UIColor.h5887ff}
.drive(balanceView.rx.tintColor)
.disposed(by: disposeBag)
Driver.combineLatest(
viewModel.inputAmountDriver,
viewModel.sourceWalletDriver
)
.map {$0 != nil || $1 == nil}
.drive(maxButton.rx.isHidden)
.disposed(by: disposeBag)
case .destination:
walletDriver = viewModel.destinationWalletDriver
textFieldKeydownEvent = {amount in
.swapTokenBAmountKeydown(sum: amount)
}
equityValueLabelDriver = Driver.combineLatest(
viewModel.estimatedAmountDriver,
viewModel.destinationWalletDriver
)
.map {minReceiveAmount, wallet -> String? in
guard let symbol = wallet?.token.symbol,
let minReceiveAmount = minReceiveAmount?.toString(maximumFractionDigits: 9)
else {return nil}
return L10n.receiveAtLeast + ": " + minReceiveAmount + " " + symbol
}
inputSubject = viewModel.estimatedAmountSubject
outputDriver = viewModel.estimatedAmountDriver
balanceTextDriver = viewModel.destinationWalletDriver
.map { wallet -> String? in
if let amount = wallet?.amount?.toString(maximumFractionDigits: 9) {
return amount + " " + "\(wallet?.token.symbol ?? "")"
}
return nil
}
}
// wallet
walletDriver
.drive(onNext: { [weak self] wallet in
self?.setUp(wallet: wallet)
})
.disposed(by: disposeBag)
// balance text
balanceTextDriver
.drive(balanceView.balanceLabel.rx.text)
.disposed(by: disposeBag)
balanceTextDriver.map {$0 == nil}
.drive(balanceView.walletView.rx.isHidden)
.disposed(by: disposeBag)
// analytics
amountTextField.rx.controlEvent([.editingDidEnd])
.asObservable()
.subscribe(onNext: { [weak self] _ in
guard let amount = self?.amountTextField.text?.double else {return}
let event = textFieldKeydownEvent(amount)
self?.viewModel.log(event)
})
.disposed(by: disposeBag)
// equity value label
equityValueLabelDriver
.drive(equityValueLabel.rx.text)
.disposed(by: disposeBag)
// input amount
amountTextField.rx.text
.filter {[weak self] _ in self?.amountTextField.isFirstResponder == true}
.distinctUntilChanged()
.bind(to: inputSubject)
.disposed(by: disposeBag)
outputDriver
.map {$0?.toString(maximumFractionDigits: 9, groupingSeparator: "")}
.filter {[weak self] _ in self?.amountTextField.isFirstResponder == false}
.drive(amountTextField.rx.text)
.disposed(by: disposeBag)
}
private func setUp(wallet: Wallet?) {
amountTextField.wallet = wallet
iconImageView.setUp(token: wallet?.token, placeholder: .walletPlaceholder)
tokenSymbolLabel.text = wallet?.token.symbol ?? L10n.select
self.wallet = wallet
}
// MARK: - Actions
@objc private func chooseSourceWallet() {
viewModel.navigate(to: .chooseSourceWallet)
}
@objc private func chooseDestinationWallet() {
viewModel.navigate(to: .chooseDestinationWallet)
}
@objc private func useAllBalance() {
viewModel.useAllBalance()
}
}
}
// MARK: - TextField delegate
extension SerumSwapV1.WalletView: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if let textField = textField as? TokenAmountTextField {
return textField.shouldChangeCharactersInRange(range, replacementString: string)
}
return true
}
}
| 41.557093 | 191 | 0.52373 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.